-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommand.go
255 lines (234 loc) · 6.09 KB
/
command.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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
package hush
import (
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
"github.com/pkg/errors"
"mvdan.cc/sh/v3/syntax"
)
const (
homeTilde = "~"
)
type console interface {
Stdout() io.Writer
Stderr() io.Writer
Note() io.Writer
}
func runLine(term console, line string) error {
parser := syntax.NewParser()
var cmdErr error
err := parser.Stmts(strings.NewReader(line), func(stmt *syntax.Stmt) bool {
cmdErr = runCommand(term, line, stmt, false)
return cmdErr == nil
})
if err != nil {
return err
}
if cmdErr != nil {
return cmdErr
}
if parser.Incomplete() {
return errors.New("Incomplete command: Multi-line commands not supported")
}
return nil
}
func evalWord(parts []syntax.WordPart) (string, error) {
s := ""
for ix, part := range parts {
switch part := part.(type) {
case *syntax.Lit:
s += part.Value
if ix == 0 && (s == homeTilde || strings.HasPrefix(s, homeTilde+string(filepath.Separator))) {
homeDir, err := os.UserHomeDir()
if err != nil {
return "", err
}
s = homeDir + s[len(homeTilde):]
}
case *syntax.SglQuoted:
if part.Dollar {
return "", errors.Errorf("Dollar single-quotes not supported: %v", part)
}
s += part.Value
case *syntax.DblQuoted:
if part.Dollar {
return "", errors.Errorf("Dollar single-quotes not supported: %v", part)
}
dblQuoted, err := evalWord(part.Parts)
if err != nil {
return "", err
}
s += dblQuoted
case *syntax.ParamExp:
name := part.Param.Value
if part.Excl || part.Length || part.Width || part.Index != nil || part.Slice != nil || part.Repl != nil || part.Names != 0 || part.Exp != nil {
return "", errors.Errorf("Variable expansion type not supported: %s %v", name, part)
}
s += os.Getenv(name)
case *syntax.CmdSubst, *syntax.ArithmExp, *syntax.ProcSubst, *syntax.ExtGlob:
return "", errors.Errorf("Unrecognized word part type: %T %v", part, part)
default:
return "", errors.Errorf("Unrecognized word part type: %T %v", part, part)
}
}
return s, nil
}
func runCommand(term console, line string, stmt *syntax.Stmt, isPipe bool) error {
switch node := stmt.Cmd.(type) {
case *syntax.CallExpr:
return runCallExpr(term, stmt, node, isPipe)
case *syntax.BinaryCmd:
switch node.Op {
case syntax.AndStmt: // &&
err := runCommand(term, line, node.X, false)
if err != nil {
return err
}
return runCommand(term, line, node.Y, false)
case syntax.OrStmt: // ||
err := runCommand(term, line, node.X, false)
if err == nil {
return nil
}
return runCommand(term, line, node.Y, false)
case syntax.Pipe: // |
r, w, err := os.Pipe()
if err != nil {
return err
}
leftTerm := &redirectconsole{
stdin: getconsoleStdin(term),
stdout: w,
stderr: term.Stderr(),
}
rightTerm := &redirectconsole{
stdin: r,
stdout: term.Stdout(),
stderr: term.Stderr(),
}
errChan := make(chan error, 1)
go func() {
errChan <- runCommand(rightTerm, line, node.Y, true)
}()
err = runCommand(leftTerm, line, node.X, false)
if err != nil {
return err
}
w.Close()
return <-errChan
case syntax.PipeAll: // |&
r, w, err := os.Pipe()
if err != nil {
return err
}
leftTerm := &redirectconsole{
stdin: getconsoleStdin(term),
stdout: w,
stderr: w,
}
rightTerm := &redirectconsole{
stdin: r,
stdout: term.Stdout(),
stderr: term.Stderr(),
}
errChan := make(chan error, 1)
go func() {
errChan <- runCommand(rightTerm, line, node.Y, true)
}()
err = runCommand(leftTerm, line, node.X, false)
if err != nil {
return err
}
return <-errChan
default:
return errors.Errorf("Unknown binary operator: %v", node.Op)
}
case *syntax.TimeClause:
start := time.Now()
err := runCommand(term, line, node.Stmt, false)
duration := time.Since(start)
fmt.Fprintf(term.Stdout(), "\n%s\t %v total\n", formatStmt(line, node.Stmt), duration)
return err
case *syntax.IfClause, *syntax.WhileClause, *syntax.ForClause, *syntax.CaseClause, *syntax.Block, *syntax.Subshell, *syntax.FuncDecl, *syntax.ArithmCmd, *syntax.TestClause, *syntax.DeclClause, *syntax.LetClause, *syntax.CoprocClause:
return errors.Errorf("Unimplemented statement type: %T %v", stmt.Cmd, stmt.Cmd)
default:
return errors.Errorf("Unknown statement type: %T %v", stmt.Cmd, stmt.Cmd)
}
}
func formatStmt(source string, s *syntax.Stmt) string {
return source[s.Pos().Offset():s.End().Offset()]
}
type cmdOptions struct {
Background bool
Pipe bool
}
func runCmd(cmd *exec.Cmd, options cmdOptions) error {
// ensure files are all attached by default. these are assumed to be set up already
if cmd.Stdin == nil || cmd.Stdout == nil || cmd.Stderr == nil {
panic("Standard files not set up")
}
args := []string{cmd.Path}
if len(cmd.Args) > 0 {
args = cmd.Args
}
commandName, args := args[0], args[1:]
builtin, isBuiltin := builtins[commandName]
if options.Pipe || !isBuiltin {
if options.Background {
return cmd.Start()
}
return cmd.Run()
}
var oldKV, unsetKV []string
// override env for builtin
for _, pair := range cmd.Env {
key, value := splitKeyValue(pair)
if oldValue, isSet := os.LookupEnv(key); isSet {
oldKV = append(oldKV, key+"="+oldValue)
} else {
unsetKV = append(unsetKV, key)
}
os.Setenv(key, value)
}
err := builtin(&redirectconsole{
stdin: cmd.Stdin,
stdout: cmd.Stdout,
stderr: cmd.Stderr,
}, args...)
// restore env
for _, pair := range oldKV {
key, value := splitKeyValue(pair)
os.Setenv(key, value)
}
for _, key := range unsetKV {
os.Unsetenv(key)
}
return errors.Wrap(err, commandName)
}
type redirectconsole struct {
stdin io.Reader
stdout, stderr io.Writer
}
func (c *redirectconsole) Stdin() io.Reader {
return c.stdin
}
func (c *redirectconsole) Stdout() io.Writer {
return c.stdout
}
func (c *redirectconsole) Stderr() io.Writer {
return c.stderr
}
func (c *redirectconsole) Note() io.Writer {
return ioutil.Discard
}
func getconsoleStdin(term console) io.Reader {
if stdiner, ok := term.(interface{ Stdin() io.Reader }); ok {
return stdiner.Stdin()
}
return os.Stdin
}