-
-
Notifications
You must be signed in to change notification settings - Fork 51
/
command.go
143 lines (126 loc) · 2.6 KB
/
command.go
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
package internal
import (
"context"
"fmt"
"io"
"os"
"os/exec"
"os/signal"
"syscall"
"github.com/oklog/run"
"github.com/olebedev/emitter"
uio "github.com/owenthereal/upterm/io"
"golang.org/x/term"
)
func newCommand(
name string,
args []string,
env []string,
stdin *os.File,
stdout *os.File,
eventEmitter *emitter.Emitter,
writers *uio.MultiWriter,
) *command {
return &command{
name: name,
args: args,
env: env,
stdin: stdin,
stdout: stdout,
eventEmitter: eventEmitter,
writers: writers,
}
}
type command struct {
name string
args []string
env []string
cmd *exec.Cmd
ptmx *pty
stdin *os.File
stdout *os.File
writers *uio.MultiWriter
eventEmitter *emitter.Emitter
ctx context.Context
}
func (c *command) Start(ctx context.Context) (*pty, error) {
c.ctx = ctx
c.cmd = exec.CommandContext(ctx, c.name, c.args...)
c.cmd.Env = append(c.env, os.Environ()...)
var err error
c.ptmx, err = startPty(c.cmd)
if err != nil {
return nil, fmt.Errorf("unable to start pty: %w", err)
}
return c.ptmx, nil
}
func (c *command) Run() error {
// Set stdin in raw mode.
isTty := term.IsTerminal(int(c.stdin.Fd()))
if isTty {
oldState, err := term.MakeRaw(int(c.stdin.Fd()))
if err != nil {
return fmt.Errorf("unable to set terminal to raw mode: %w", err)
}
defer func() { _ = term.Restore(int(c.stdin.Fd()), oldState) }()
}
var g run.Group
if isTty {
// pty
ch := make(chan os.Signal, 1)
signal.Notify(ch, syscall.SIGWINCH)
ch <- syscall.SIGWINCH // Initial resize.
ctx, cancel := context.WithCancel(c.ctx)
tee := terminalEventEmitter{c.eventEmitter}
g.Add(func() error {
for {
select {
case <-ctx.Done():
close(ch)
return ctx.Err()
case <-ch:
h, w, err := getPtysize(c.stdin)
if err != nil {
return err
}
tee.TerminalWindowChanged("local", c.ptmx, w, h)
}
}
}, func(err error) {
tee.TerminalDetached("local", c.ptmx)
cancel()
})
}
{
// input
ctx, cancel := context.WithCancel(c.ctx)
g.Add(func() error {
_, err := io.Copy(c.ptmx, uio.NewContextReader(ctx, c.stdin))
return err
}, func(err error) {
cancel()
})
}
{
// output
if err := c.writers.Append(c.stdout); err != nil {
return err
}
ctx, cancel := context.WithCancel(c.ctx)
g.Add(func() error {
_, err := io.Copy(c.writers, uio.NewContextReader(ctx, c.ptmx))
return ptyError(err)
}, func(err error) {
c.writers.Remove(os.Stdout)
cancel()
})
}
{
g.Add(func() error {
return c.cmd.Wait()
}, func(err error) {
c.ptmx.Close()
})
}
return g.Run()
}