forked from dhamidi/leader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
terminal.go
102 lines (89 loc) · 2.25 KB
/
terminal.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
package main
import (
"fmt"
"io"
"os"
"syscall"
"github.com/Nerdmaster/terminal"
)
// Terminal is a terminal device.
type Terminal interface {
io.Writer
MakeRaw() error
Restore() error
ReadKey() (rune, error)
}
// TTY represents a TTY and implements Terminal
type TTY struct {
fd int
file *os.File
out io.Writer
originalState *terminal.State
keyReader *terminal.KeyReader
}
// NewTTY returns a terminal connected to /dev/tty.
func NewTTY() (*TTY, error) {
devTTY, err := os.OpenFile("/dev/tty", os.O_RDWR, 0644)
if err != nil {
return nil, fmt.Errorf("NewTTY: %s", err)
}
tty := &TTY{
fd: int(devTTY.Fd()),
out: devTTY,
file: devTTY,
}
tty.keyReader = terminal.NewKeyReader(devTTY)
return tty, nil
}
// File returns the file object connected to this terminal (or nil if
// this terminal is not connected to a file)
func (term *TTY) File() *os.File {
_, connectedToFile := term.out.(*os.File)
if !connectedToFile {
return nil
}
return term.file
}
// MakeRaw puts this terminal into raw mode.
func (term *TTY) MakeRaw() error {
originalState, err := terminal.MakeRaw(term.fd)
if err != nil {
return fmt.Errorf("terminal.GetState: %s", err)
}
term.originalState = originalState
return nil
}
// OutputTo to sets up this terminal to write its output into the provided io.Writer.
func (term *TTY) OutputTo(out io.Writer) *TTY {
term.out = out
return term
}
// InputFrom sets up this terminal to read its input from the provided io.Reader.
func (term *TTY) InputFrom(src io.Reader) *TTY {
term.keyReader = terminal.NewKeyReader(src)
return term
}
// Write implements io.Writer by writing bytes to the underlying terminal.
func (term *TTY) Write(data []byte) (int, error) {
return term.out.Write(data)
}
// Restore restores the original terminal state
func (term *TTY) Restore() error {
if term.originalState == nil {
return nil
}
err := terminal.Restore(term.fd, term.originalState)
if errno, ok := err.(syscall.Errno); ok && errno == 0 {
return nil
}
return err
}
// ReadKey reads a single key code from the terminal
func (term *TTY) ReadKey() (rune, error) {
keypress, err := term.keyReader.ReadKeypress()
ctrlC := rune('\003')
if err != nil {
return ctrlC, nil
}
return keypress.Key, nil
}