-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcmd_unix.go
More file actions
100 lines (85 loc) · 2.14 KB
/
cmd_unix.go
File metadata and controls
100 lines (85 loc) · 2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
//go:build !windows
// +build !windows
package sip
import (
"fmt"
"io"
"os"
"os/exec"
"syscall"
xpty "github.com/charmbracelet/x/xpty"
)
// cmdPlatformPty holds platform-specific PTY resources for command execution.
type cmdPlatformPty struct {
pty xpty.Pty
cmd *exec.Cmd
}
// newCmdPlatformPty creates a new PTY and spawns the command on Unix systems.
func newCmdPlatformPty(name string, args []string, dir string, cols, rows int) (*cmdPlatformPty, error) {
ptyInstance, err := xpty.NewPty(cols, rows)
if err != nil {
return nil, fmt.Errorf("failed to open PTY: %w", err)
}
// Set up command
cmd := exec.Command(name, args...)
cmd.Dir = dir
cmd.Env = append(os.Environ(),
"TERM=xterm-256color",
"COLORTERM=truecolor",
)
// Set up the command to use the PTY as controlling terminal
cmd.SysProcAttr = &syscall.SysProcAttr{
Setsid: true, // Create new session
Setctty: true, // Set controlling terminal
Ctty: 0, // Use stdin (which will be the PTY slave)
}
// Start the command with PTY
if err := ptyInstance.Start(cmd); err != nil {
_ = ptyInstance.Close()
return nil, fmt.Errorf("failed to start command: %w", err)
}
return &cmdPlatformPty{
pty: ptyInstance,
cmd: cmd,
}, nil
}
// Close closes the PTY and waits for the command to exit.
func (p *cmdPlatformPty) Close() error {
if p.pty != nil {
_ = p.pty.Close()
}
if p.cmd != nil && p.cmd.Process != nil {
_ = p.cmd.Process.Kill()
_ = p.cmd.Wait()
}
return nil
}
// Resize resizes the PTY.
func (p *cmdPlatformPty) Resize(cols, rows int) error {
if p.pty != nil {
return p.pty.Resize(cols, rows)
}
return nil
}
// OutputReader returns an io.Reader for reading command output.
func (p *cmdPlatformPty) OutputReader() io.Reader {
return p.pty
}
// InputWriter returns an io.Writer for writing command input.
func (p *cmdPlatformPty) InputWriter() io.Writer {
return p.pty
}
// Wait waits for the command to exit.
func (p *cmdPlatformPty) Wait() error {
if p.cmd != nil {
return p.cmd.Wait()
}
return nil
}
// Process returns the underlying process.
func (p *cmdPlatformPty) Process() *os.Process {
if p.cmd != nil {
return p.cmd.Process
}
return nil
}