-
Notifications
You must be signed in to change notification settings - Fork 0
/
term.go
94 lines (82 loc) · 1.66 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
package governor
import (
"bufio"
"errors"
"io"
"io/fs"
"os"
"golang.org/x/term"
"xorkevin.dev/kerrors"
"xorkevin.dev/kfs"
)
type (
Term interface {
Stdin() io.Reader
Stdout() io.Writer
Stderr() io.Writer
ReadLine() (string, error)
ReadPassword() (string, error)
FS() fs.FS
}
TermConfig struct {
StdinFd int
Stdin io.Reader
Stdout io.Writer
Stderr io.Writer
Fsys fs.FS
}
termClient struct {
stdinfd int
stdin *bufio.Reader
stdout io.Writer
stderr io.Writer
fsys fs.FS
}
)
func newTermClient(config *TermConfig) Term {
if config == nil {
config = &TermConfig{
StdinFd: int(os.Stdin.Fd()),
Stdin: os.Stdin,
Stdout: os.Stdout,
Stderr: os.Stderr,
Fsys: kfs.DirFS("."),
}
}
return &termClient{
stdinfd: config.StdinFd,
stdin: bufio.NewReader(config.Stdin),
stdout: config.Stdout,
stderr: config.Stderr,
fsys: config.Fsys,
}
}
func (c *termClient) Stdin() io.Reader {
return c.stdin
}
func (c *termClient) Stdout() io.Writer {
return c.stdout
}
func (c *termClient) Stderr() io.Writer {
return c.stderr
}
func (c *termClient) ReadLine() (string, error) {
s, err := c.stdin.ReadString('\n')
if err != nil && !errors.Is(err, io.EOF) {
err = kerrors.WithMsg(err, "Failed to read stdin")
}
return s, err
}
func (c *termClient) ReadPassword() (string, error) {
s, err := term.ReadPassword(c.stdinfd)
if err != nil {
return "", kerrors.WithMsg(err, "Failed to read password")
}
if _, err := io.WriteString(c.stderr, "\n"); err != nil {
return "", kerrors.WithMsg(err, "Failed to write newline")
}
return string(s), nil
}
func (c *termClient) FS() fs.FS {
return c.fsys
}