-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstreams.go
94 lines (80 loc) · 2.12 KB
/
streams.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
package forge
import (
"io"
"os"
"github.com/moby/term"
)
// DefaultDetachKeys are the default key combinations
// to use when detaching from a Container that has
// been attached to.
const DefaultDetachKeys = "ctrl-d"
// Streams represents streams to and from a process
// inside of a Container.
type Streams struct {
*Drains
In io.Reader
DetachKeys string
}
// StdStreams returns a Streams consisting of os.Stdin,
// os.Stdout and os.Stderr.
func StdStreams() *Streams {
return &Streams{
In: os.Stdin,
Drains: StdDrains(),
DetachKeys: DefaultDetachKeys,
}
}
// StdTerminalStreams creates a Streams with os.Stdin, os.Stdout and os.Stderr
// made raw and a restore function to return them to their previous state.
// For use with attaching to a shell inside of a Container.
func StdTerminalStreams() (*Streams, func() error) {
streams, restore, err := TerminalStreams(os.Stdin, os.Stdout, os.Stderr)
if err != nil {
defer restore() //nolint:errcheck
panic(err)
}
return streams, restore
}
// fileDescriptor is an interface to check io.Readers and io.Writers
// against to inspect if they are terminals.
type fileDescriptor interface {
Fd() uintptr
}
// TerminalStreams creates a Streams with each of the given streams
// that is a terminal made raw and a restore function to return
// them to their previous states. For use with attaching to
// a shell inside of a Container.
func TerminalStreams(stdin io.Reader, stdout, stderr io.Writer) (*Streams, func() error, error) {
var (
states = map[uintptr]*term.State{}
restore = func() error {
for fd, state := range states {
if err := term.RestoreTerminal(fd, state); err != nil {
return err
}
delete(states, fd)
}
return nil
}
)
for _, fd := range []any{stdin} {
if fd, ok := fd.(fileDescriptor); ok {
if term.IsTerminal(fd.Fd()) {
state, err := term.MakeRaw(fd.Fd())
if err != nil {
return nil, restore, err
}
states[fd.Fd()] = state
}
}
}
return &Streams{
In: stdin,
Drains: &Drains{
Out: stdout,
Err: stderr,
Tty: true,
},
DetachKeys: DefaultDetachKeys,
}, restore, nil
}