forked from c-bata/go-prompt
-
Notifications
You must be signed in to change notification settings - Fork 2
/
reader_posix.go
74 lines (64 loc) · 1.6 KB
/
reader_posix.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
//go:build !windows
// +build !windows
package prompt
import (
"os"
"syscall"
"github.com/elk-language/go-prompt/term"
"golang.org/x/sys/unix"
)
// PosixReader is a Reader implementation for the POSIX environment.
type PosixReader struct {
fd int
}
// Open should be called before starting input
func (t *PosixReader) Open() error {
in, err := syscall.Open("/dev/tty", syscall.O_RDONLY, 0)
if os.IsNotExist(err) {
in = syscall.Stdin
} else if err != nil {
panic(err)
}
t.fd = in
// Set NonBlocking mode because if syscall.Read block this goroutine, it cannot receive data from stopCh.
if err := syscall.SetNonblock(t.fd, true); err != nil {
return err
}
if err := term.SetRaw(t.fd); err != nil {
return err
}
return nil
}
// Close should be called after stopping input
func (t *PosixReader) Close() error {
if err := term.RestoreFD(t.fd); err != nil {
_ = syscall.Close(t.fd)
return err
}
return syscall.Close(t.fd)
}
// Read returns byte array.
func (t *PosixReader) Read(buff []byte) (int, error) {
return syscall.Read(t.fd, buff)
}
// GetWinSize returns WinSize object to represent width and height of terminal.
func (t *PosixReader) GetWinSize() *WinSize {
ws, err := unix.IoctlGetWinsize(t.fd, unix.TIOCGWINSZ)
if err != nil {
// If this errors, we simply return the default window size as
// it's our best guess.
return &WinSize{
Row: DefRowCount,
Col: DefColCount,
}
}
return &WinSize{
Row: ws.Row,
Col: ws.Col,
}
}
var _ Reader = &PosixReader{}
// NewStdinReader returns Reader object to read from stdin.
func NewStdinReader() *PosixReader {
return &PosixReader{}
}