-
Notifications
You must be signed in to change notification settings - Fork 0
/
shell.go
87 lines (68 loc) · 1.77 KB
/
shell.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
package expect
import (
"fmt"
"strings"
)
type ShellExpect struct {
process *ExpectProcess
promptString string
Debug bool
}
func NewShellExpect(expect *ExpectProcess, prompt string) *ShellExpect {
return &ShellExpect{
process: expect,
promptString: prompt,
}
}
// Init synchronize the prompt detection by expecting the initial prompt.
func (c *ShellExpect) Init() error {
line, err := c.process.Line()
if err != nil {
return err
}
// First line should be the prompt, but can be prepended with terminal initialization chars.
if strings.HasSuffix(norm(line), norm(c.promptString)) {
c.debugLine("Found initial prompt\n")
return nil
}
return fmt.Errorf("expected initial prompt, got %q", line)
}
func (c *ShellExpect) Run(command string) ([]string, error) {
command = strings.TrimSuffix(command, "\n") + "\n"
err := c.process.Send(command)
if err != nil {
return nil, fmt.Errorf("sending command %q: %w", command, err)
}
output, err := c.waitPrompt()
if err != nil {
return nil, fmt.Errorf("waiting prompt after command %q: %w", command, err)
}
return output, nil
}
func (c *ShellExpect) waitPrompt() ([]string, error) {
var output []string
c.debugLine("Waiting for the prompt")
for {
line, err := c.process.Line()
if err != nil {
return nil, fmt.Errorf("expecting output: %w", err)
}
if norm(line) == norm(c.promptString) {
c.debugLine("Received prompt")
return output, nil
}
c.debugLine(fmt.Sprintf("Received output: %q", line))
output = append(output, trim(norm(line)))
}
}
func (c *ShellExpect) debugLine(line string) {
if c.Debug {
fmt.Println(strings.TrimSuffix(line, "\n"))
}
}
func norm(s string) string {
return strings.Replace(s, "\r", "", -1)
}
func trim(s string) string {
return strings.TrimSuffix(s, "\n")
}