-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoutput-scanner.go
130 lines (117 loc) · 2.48 KB
/
output-scanner.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
// Copyright 2009 Bart de Boer. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package exec
import (
"bufio"
"errors"
"fmt"
"os"
"strconv"
"strings"
)
type OutputScanner struct {
cmd *Cmd
scanner *bufio.Scanner
}
func NewOutputScanner(c *Cmd) *OutputScanner {
return &OutputScanner{
cmd: c,
}
}
func (o *OutputScanner) Start() error {
stdout, err := o.cmd.cmd.StdoutPipe()
if err != nil {
return err
}
// sr.stdoutPipe = stdout
o.cmd.cmd.Stderr = os.Stderr
// stderr, err := sr.cmd.cmd.StderrPipe()
// if err != nil {
// return err
// }
// sr.stderrPipe = stderr
if err := o.cmd.Start(); err != nil {
return err
}
o.scanner = bufio.NewScanner(stdout)
return nil
}
func (o *OutputScanner) Scan() bool {
return o.scanner.Scan()
}
func (o *OutputScanner) Text() string {
return o.scanner.Text()
}
// func (sr *OutputScanner) ErrorOutput() ([]byte, error) {
// return ioutil.ReadAll(sr.stderrPipe)
// }
func (o *OutputScanner) Wait() (int, error) {
return o.cmd.Wait()
}
func (o *OutputScanner) Lines() ([]string, error) {
lines := []string{}
if o.cmd.cmd.Process == nil {
err := o.Start()
if err != nil {
return nil, err
}
}
for o.Scan() {
lines = append(lines, o.Text())
}
// stderrOut, _ := sr.ErrorOutput()
// sr.stderrOut = stderrOut
code, err := o.Wait()
if code > 0 {
return lines, err
}
return lines, nil
}
func (o *OutputScanner) HasLine(line string) (bool, error) {
if o.cmd.cmd.Process == nil {
err := o.Start()
if err == nil {
return false, err
}
}
for o.Scan() {
if strings.Trim(o.Text(), " ") == line {
return true, nil
}
}
if code, err := o.Wait(); code > 0 {
return false, err
}
return false, nil
}
func (o *OutputScanner) Prompt() (string, error) {
options, err := o.Lines()
if err != nil {
return "", err
}
return Select(options)
}
func Select(options []string) (string, error) {
if len(options) == 0 {
return "", errors.New("List of options is empty")
}
for i, l := 0, len(options); i < l; i++ {
fmt.Printf("%3d) %s\n", i+1, options[i])
}
reader := bufio.NewReader(os.Stdin)
fmt.Printf("Enter option: ")
input, err := reader.ReadString('\n')
if err != nil {
return "", err
}
option, err := strconv.ParseInt(strings.Trim(input, " \r\n"), 10, 0)
if err != nil {
return "", err
}
option--
if option >= 0 && int(option) < len(options) {
return options[int(option)], nil
}
return "", errors.New("Invalid option")
}