-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshellCommander.go
181 lines (157 loc) · 3.93 KB
/
shellCommander.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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
/*
Package shellCommander provides a handy way to organize the shell commands to run.
We provide an easy way to mimic the conventional unix-style shell facility -- pipe.
Example:
// First, specify the commands to be piped up.
c1 := NewCommand(NoCleanFn, "ps", "-ef")
c2 := NewCommand(NoCleanFn, "grep", "lantern")
c3 := NewCommand(NoCleanFn, "grep", "-v", "grep")
// Then, create an ordered command sequence with NewPipeCmd().
pc := NewPipeCmd(c1, c2, c3)
// Create a context (used to set timeout etc.), and run the piped commands.
ctx := context.Background()
stdout, stderr, err := pc.Run(ctx)
// Optionally, clean the intermediate result
errc := pc.Clean()
*/
package shellCommander
import (
"bytes"
"errors"
"fmt"
"os/exec"
"golang.org/x/net/context"
)
type Command interface {
Name() string
Params() []string
Clean() error
}
type Cleaner func(Command) error
var (
NoCleanFn = func(c Command) error { return nil }
debug = true
)
type cmd struct {
name string
params []string
cleanfn Cleaner
}
func (this *cmd) Name() string {
return this.name
}
func (this *cmd) Params() []string {
return this.params
}
func (this *cmd) Clean() error {
return this.cleanfn(this)
}
func NewCommand(cleanfn Cleaner, name string, args ...string) Command {
c := &cmd{
name: name,
params: args,
cleanfn: cleanfn,
}
return c
}
type PipeCmd interface {
Run(ctx context.Context) (stdout string, stderr string, err error)
Clean() error
}
func NewPipeCmd(cmds ...Command) PipeCmd {
pc := &pipeCmd{
stdin: &bytes.Buffer{},
stdout: &bytes.Buffer{},
stderr: &bytes.Buffer{},
subCmds: make([]Command, 0),
}
for _, c := range cmds {
pc.subCmds = append(pc.subCmds, c)
}
return pc
}
type pipeCmd struct {
stdin *bytes.Buffer
stdout *bytes.Buffer
stderr *bytes.Buffer
subCmds []Command
}
func (this *pipeCmd) Run(ctx context.Context) (stdout string, stderr string, err error) {
// for k, c := range this.subCmds {
// cmd := exec.Command(c.Name(), c.Params()...)
// // show the command to run
// fmt.Println(cmd.Args)
// stdin, erri := cmd.StdinPipe()
// if erri != nil {
// return "", "", erri
// }
// stdout, erro := cmd.StdoutPipe()
// if erro != nil {
// return "", "", erro
// }
// }
for _, c := range this.subCmds {
this.stdout = &bytes.Buffer{}
this.stderr = &bytes.Buffer{}
cmd := exec.Command(c.Name(), c.Params()...)
cmd.Stdin = this.stdin
cmd.Stdout = this.stdout
cmd.Stderr = this.stderr
// show the command to run
if debug {
fmt.Println(cmd.Args)
}
err = cmd.Start()
if err != nil {
return "", "", err
}
tchan := make(chan int, 1)
go func() {
err = cmd.Wait()
if err != nil {
tchan <- 0
}
tchan <- 1
}()
select {
case i := <-tchan:
if i == 0 {
return "", "", err
}
case <-ctx.Done():
err := cmd.Process.Kill()
if err != nil {
return "", "", err
}
return "", "", ctx.Err()
}
// fmt.Println(this.stdout.String())
this.stdin = cmd.Stdout.(*bytes.Buffer)
}
return this.stdout.String(), this.stderr.String(), nil
}
func (this *pipeCmd) Clean() error {
var errc error
for _, c := range this.subCmds {
if err := c.Clean(); err != nil {
if errc != nil {
errc = errors.New(errc.Error() + "\n" + err.Error())
} else {
errc = errors.New(err.Error())
}
}
}
return errc
}
/*******************************************************************************************************************
********************************************** shortcuts ************************************************************
*******************************************************************************************************************/
func RunCmd(cmdline string) (string, string, error) {
splits := strings.Split(cmdline, " ")
name := splits[0]
args := splits[1:]
cmd := NewCommand(NoCleanFn, name, args...)
pipe := NewPipeCmd(cmd)
ctx := context.Background()
return pipe.Run(ctx)
}