-
Notifications
You must be signed in to change notification settings - Fork 0
/
term.go
98 lines (86 loc) · 1.97 KB
/
term.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
package main
import (
"errors"
"fmt"
"io"
"log"
"os"
"os/exec"
"os/signal"
"syscall"
"github.com/creack/pty"
"golang.org/x/term"
)
type Term struct {
Command *exec.Cmd
BufSize int
}
func (t *Term) Spawn(output chan<- []byte) error {
ptmx, err := pty.Start(t.Command)
if err != nil {
return fmt.Errorf("starting pty: %w", err)
}
defer ptmx.Close()
winch := make(chan os.Signal, 1)
signal.Notify(winch, syscall.SIGWINCH)
defer func() { signal.Stop(winch); close(winch) }()
winch <- syscall.SIGWINCH // initial resize
// TODO: handle sigwinch in select
oldState, err := term.MakeRaw(int(os.Stdin.Fd()))
if err != nil {
return fmt.Errorf("making the terminal raw: %w", err)
}
defer func() {
if err := term.Restore(int(os.Stdin.Fd()), oldState); err != nil {
log.Printf("restoring term state: %s", err)
}
}()
// we don't need stdin where we're going, so we just copy it straight to the pty
stdinPumpErrors := make(chan error)
go func() {
_, err := io.Copy(ptmx, os.Stdin)
if err != nil {
stdinPumpErrors <- err
}
}()
stdoutPumpErrors := pump(output, ptmx, t.BufSize)
for {
select {
case err := <-stdoutPumpErrors:
if errors.Is(err, io.EOF) {
return nil
}
return fmt.Errorf("stdout pump error: %w", err)
case err := <-stdinPumpErrors:
if errors.Is(err, io.EOF) {
return nil
}
return fmt.Errorf("stdin pump error: %w", err)
case <-winch:
if err := pty.InheritSize(os.Stdin, ptmx); err != nil {
return fmt.Errorf("error resizing pty: %w", err)
}
}
}
}
func pump(ch chan<- []byte, r io.Reader, bufSize int) <-chan error {
errCh := make(chan error, 1)
if bufSize == 0 {
errCh <- fmt.Errorf("buffer size too small (0)")
return errCh
}
go func() {
for {
// creating new buf every time so we don't have to wait for old buffer to be processed
buf := make([]byte, bufSize)
_, err := r.Read(buf)
if err != nil {
close(ch)
errCh <- err
return
}
ch <- buf
}
}()
return errCh
}