-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwatcher.go
115 lines (104 loc) · 2.11 KB
/
watcher.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
103
104
105
106
107
108
109
110
111
112
113
114
115
package main
import (
"io"
"os"
"strings"
"time"
)
const (
EventCtrlC = -2
EventTimeOut = -1
)
type Watcher struct {
ch <-chan string
lastline string
ctrlc <-chan struct{}
}
func NewWatcher(pty io.ReadWriter) *Watcher {
pipeline := make(chan string, 1024)
ctrlc := make(chan struct{}, 100)
go func() {
for {
var buffer [1024]byte
n, _ := os.Stdin.Read(buffer[:])
B := buffer[:n]
for i, b := range B {
if b == '\x03' {
ctrlc <- struct{}{}
return
} else if b == '\x08' {
// On CMD.exe, Ctrl-H removes all input text.
// ( The reason is unknown )
// Therefore, replace Ctrl-H to Backspace-key
buffer[i] = '\x7F'
}
}
pty.Write(B)
}
}()
go func() {
for {
var buffer [1024]byte
n, err := pty.Read(buffer[:])
if err != nil {
close(pipeline)
return
}
// If the code below spends a lot of time,
// It hangs up to io.Copy(pty, os.Stdin)
// The reason is unknown.
b := buffer[:n]
os.Stdout.Write(b)
pipeline <- string(b)
}
}()
return &Watcher{ch: pipeline, ctrlc: ctrlc}
}
func (W *Watcher) checkWords(token string, words []string) int {
W.lastline += token
for i, word := range words {
if pos := strings.Index(W.lastline, word); pos >= 0 {
W.lastline = W.lastline[pos+len(word):]
return i
}
}
newLinePos := strings.LastIndexByte(W.lastline, '\n')
if newLinePos >= 0 {
W.lastline = W.lastline[newLinePos+1:]
}
return -1
}
func (W *Watcher) Expect(words ...string) int {
if found := W.checkWords("", words); found >= 0 {
return found
}
for {
select {
case token := <-W.ch:
if found := W.checkWords(token, words); found >= 0 {
return found
}
case <-W.ctrlc:
return EventCtrlC
}
}
}
func (W *Watcher) ExpectWithTimeout(d time.Duration, words ...string) int {
if found := W.checkWords("", words); found >= 0 {
return found
}
timer := time.NewTimer(d)
defer timer.Stop()
for {
select {
case token := <-W.ch:
if found := W.checkWords(token, words); found >= 0 {
return found
}
case <-timer.C:
return EventTimeOut
case <-W.ctrlc:
return EventCtrlC
}
}
}