forked from rogpeppe/go-internal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmd.go
622 lines (570 loc) · 14.9 KB
/
cmd.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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package testscript
import (
"bufio"
"bytes"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
"fortio.org/testscript/diff"
)
// scriptCmds are the script command implementations.
// Keep list and the implementations below sorted by name.
//
// NOTE: If you make changes here, update doc.go.
var scriptCmds = map[string]func(*TestScript, bool, []string){
"cd": (*TestScript).cmdCd,
"chmod": (*TestScript).cmdChmod,
"cmp": (*TestScript).cmdCmp,
"cmpenv": (*TestScript).cmdCmpenv,
"cp": (*TestScript).cmdCp,
"env": (*TestScript).cmdEnv,
"exec": (*TestScript).cmdExec,
"exists": (*TestScript).cmdExists,
"grep": (*TestScript).cmdGrep,
"mkdir": (*TestScript).cmdMkdir,
"mv": (*TestScript).cmdMv,
"rm": (*TestScript).cmdRm,
"skip": (*TestScript).cmdSkip,
"stderr": (*TestScript).cmdStderr,
"stdin": (*TestScript).cmdStdin,
"stdout": (*TestScript).cmdStdout,
"stop": (*TestScript).cmdStop,
"symlink": (*TestScript).cmdSymlink,
"unix2dos": (*TestScript).cmdUNIX2DOS,
"wait": (*TestScript).cmdWait,
}
// cd changes to a different directory.
func (ts *TestScript) cmdCd(neg bool, args []string) {
if neg {
ts.Fatalf("unsupported: ! cd")
}
if len(args) != 1 {
ts.Fatalf("usage: cd dir")
}
dir := args[0]
if !filepath.IsAbs(dir) {
dir = filepath.Join(ts.cd, dir)
}
info, err := os.Stat(dir)
if os.IsNotExist(err) {
ts.Fatalf("directory %s does not exist", dir)
}
ts.Check(err)
if !info.IsDir() {
ts.Fatalf("%s is not a directory", dir)
}
ts.cd = dir
ts.Logf("%s\n", ts.cd)
}
func (ts *TestScript) cmdChmod(neg bool, args []string) {
if neg {
ts.Fatalf("unsupported: ! chmod")
}
if len(args) != 2 {
ts.Fatalf("usage: chmod perm paths...")
}
perm, err := strconv.ParseUint(args[0], 8, 32)
if err != nil || perm&uint64(os.ModePerm) != perm {
ts.Fatalf("invalid mode: %s", args[0])
}
for _, arg := range args[1:] {
path := arg
if !filepath.IsAbs(path) {
path = filepath.Join(ts.cd, arg)
}
err := os.Chmod(path, os.FileMode(perm))
ts.Check(err)
}
}
// cmp compares two files.
func (ts *TestScript) cmdCmp(neg bool, args []string) {
if len(args) != 2 {
ts.Fatalf("usage: cmp file1 file2")
}
ts.doCmdCmp(neg, args, false)
}
// cmpenv compares two files with environment variable substitution.
func (ts *TestScript) cmdCmpenv(neg bool, args []string) {
if len(args) != 2 {
ts.Fatalf("usage: cmpenv file1 file2")
}
ts.doCmdCmp(neg, args, true)
}
func (ts *TestScript) doCmdCmp(neg bool, args []string, env bool) {
name1, name2 := args[0], args[1]
text1 := ts.ReadFile(name1)
absName2 := ts.MkAbs(name2)
data, err := ioutil.ReadFile(absName2)
ts.Check(err)
text2 := string(data)
if env {
text2 = ts.expand(text2)
}
eq := text1 == text2
if neg {
if eq {
ts.Fatalf("%s and %s do not differ", name1, name2)
}
return // they differ, as expected
}
if eq {
return // they are equal, as expected
}
if ts.params.UpdateScripts && !env {
if scriptFile, ok := ts.scriptFiles[absName2]; ok {
ts.scriptUpdates[scriptFile] = text1
return
}
// The file being compared against isn't in the txtar archive, so don't
// update the script.
}
unifiedDiff := diff.Diff(name1, []byte(text1), name2, []byte(text2))
ts.Logf("%s", unifiedDiff)
ts.Fatalf("%s and %s differ", name1, name2)
}
// cp copies files, maybe eventually directories.
func (ts *TestScript) cmdCp(neg bool, args []string) {
if neg {
ts.Fatalf("unsupported: ! cp")
}
if len(args) < 2 {
ts.Fatalf("usage: cp src... dst")
}
dst := ts.MkAbs(args[len(args)-1])
info, err := os.Stat(dst)
dstDir := err == nil && info.IsDir()
if len(args) > 2 && !dstDir {
ts.Fatalf("cp: destination %s is not a directory", dst)
}
for _, arg := range args[:len(args)-1] {
var (
src string
data []byte
mode os.FileMode
)
switch arg {
case "stdout":
src = arg
data = []byte(ts.stdout)
mode = 0o666
case "stderr":
src = arg
data = []byte(ts.stderr)
mode = 0o666
default:
src = ts.MkAbs(arg)
info, err := os.Stat(src)
ts.Check(err)
mode = info.Mode() & 0o777
data, err = ioutil.ReadFile(src)
ts.Check(err)
}
targ := dst
if dstDir {
targ = filepath.Join(dst, filepath.Base(src))
}
ts.Check(ioutil.WriteFile(targ, data, mode))
}
}
// env displays or adds to the environment.
func (ts *TestScript) cmdEnv(neg bool, args []string) {
if neg {
ts.Fatalf("unsupported: ! env")
}
if len(args) == 0 {
printed := make(map[string]bool) // env list can have duplicates; only print effective value (from envMap) once
for _, kv := range ts.env {
k := envvarname(kv[:strings.Index(kv, "=")])
if !printed[k] {
printed[k] = true
ts.Logf("%s=%s\n", k, ts.envMap[k])
}
}
return
}
for _, env := range args {
i := strings.Index(env, "=")
if i < 0 {
// Display value instead of setting it.
ts.Logf("%s=%s\n", env, ts.Getenv(env))
continue
}
ts.Setenv(env[:i], env[i+1:])
}
}
var backgroundSpecifier = regexp.MustCompile(`^&([a-zA-Z_0-9]+&)?$`)
// exec runs the given command.
func (ts *TestScript) cmdExec(neg bool, args []string) {
if len(args) < 1 || (len(args) == 1 && args[0] == "&") {
ts.Fatalf("usage: exec program [args...] [&]")
}
var err error
if len(args) > 0 && backgroundSpecifier.MatchString(args[len(args)-1]) {
bgName := strings.TrimSuffix(strings.TrimPrefix(args[len(args)-1], "&"), "&")
if ts.findBackground(bgName) != nil {
ts.Fatalf("duplicate background process name %q", bgName)
}
var cmd *exec.Cmd
cmd, err = ts.execBackground(args[0], args[1:len(args)-1]...)
if err == nil {
wait := make(chan struct{})
go func() {
waitOrStop(ts.ctxt, cmd, -1)
close(wait)
}()
ts.background = append(ts.background, backgroundCmd{bgName, cmd, wait, neg})
}
ts.stdout, ts.stderr = "", ""
} else {
ts.stdout, ts.stderr, err = ts.exec(args[0], args[1:]...)
if ts.stdout != "" {
fmt.Fprintf(&ts.log, "[stdout]\n%s", ts.stdout)
}
if ts.stderr != "" {
fmt.Fprintf(&ts.log, "[stderr]\n%s", ts.stderr)
}
if err == nil && neg {
ts.Fatalf("unexpected command success")
}
}
if err != nil {
fmt.Fprintf(&ts.log, "[%v]\n", err)
if ts.ctxt.Err() != nil {
ts.Fatalf("test timed out while running command")
} else if !neg {
ts.Fatalf("unexpected command failure")
}
}
}
// exists checks that the list of files exists.
func (ts *TestScript) cmdExists(neg bool, args []string) {
var readonly bool
if len(args) > 0 && args[0] == "-readonly" {
readonly = true
args = args[1:]
}
if len(args) == 0 {
ts.Fatalf("usage: exists [-readonly] file...")
}
for _, file := range args {
file = ts.MkAbs(file)
info, err := os.Stat(file)
if err == nil && neg {
what := "file"
if info.IsDir() {
what = "directory"
}
ts.Fatalf("%s %s unexpectedly exists", what, file)
}
if err != nil && !neg {
ts.Fatalf("%s does not exist", file)
}
if err == nil && !neg && readonly && info.Mode()&0o222 != 0 {
ts.Fatalf("%s exists but is writable", file)
}
}
}
// mkdir creates directories.
func (ts *TestScript) cmdMkdir(neg bool, args []string) {
if neg {
ts.Fatalf("unsupported: ! mkdir")
}
if len(args) < 1 {
ts.Fatalf("usage: mkdir dir...")
}
for _, arg := range args {
ts.Check(os.MkdirAll(ts.MkAbs(arg), 0o777))
}
}
func (ts *TestScript) cmdMv(neg bool, args []string) {
if neg {
ts.Fatalf("unsupported: ! mv")
}
if len(args) != 2 {
ts.Fatalf("usage: mv old new")
}
ts.Check(os.Rename(ts.MkAbs(args[0]), ts.MkAbs(args[1])))
}
// rm removes files or directories.
func (ts *TestScript) cmdRm(neg bool, args []string) {
if neg {
ts.Fatalf("unsupported: ! rm")
}
if len(args) < 1 {
ts.Fatalf("usage: rm file...")
}
for _, arg := range args {
file := ts.MkAbs(arg)
removeAll(file) // does chmod and then attempts rm
ts.Check(os.RemoveAll(file)) // report error
}
}
// skip marks the test skipped.
func (ts *TestScript) cmdSkip(neg bool, args []string) {
if len(args) > 1 {
ts.Fatalf("usage: skip [msg]")
}
if neg {
ts.Fatalf("unsupported: ! skip")
}
// Before we mark the test as skipped, shut down any background processes and
// make sure they have returned the correct status.
for _, bg := range ts.background {
interruptProcess(bg.cmd.Process)
}
ts.cmdWait(false, nil)
if len(args) == 1 {
ts.t.Skip(args[0])
}
ts.t.Skip()
}
func (ts *TestScript) cmdStdin(neg bool, args []string) {
if neg {
ts.Fatalf("unsupported: ! stdin")
}
if len(args) != 1 {
ts.Fatalf("usage: stdin filename")
}
ts.stdin = ts.ReadFile(args[0])
}
// stdout checks that the last go command standard output matches a regexp.
func (ts *TestScript) cmdStdout(neg bool, args []string) {
scriptMatch(ts, neg, args, ts.stdout, "stdout")
}
// stderr checks that the last go command standard output matches a regexp.
func (ts *TestScript) cmdStderr(neg bool, args []string) {
scriptMatch(ts, neg, args, ts.stderr, "stderr")
}
// grep checks that file content matches a regexp.
// Like stdout/stderr and unlike Unix grep, it accepts Go regexp syntax.
func (ts *TestScript) cmdGrep(neg bool, args []string) {
scriptMatch(ts, neg, args, "", "grep")
}
// stop stops execution of the test (marking it passed).
func (ts *TestScript) cmdStop(neg bool, args []string) {
if neg {
ts.Fatalf("unsupported: ! stop")
}
if len(args) > 1 {
ts.Fatalf("usage: stop [msg]")
}
if len(args) == 1 {
ts.Logf("stop: %s\n", args[0])
} else {
ts.Logf("stop\n")
}
ts.stopped = true
}
// symlink creates a symbolic link.
func (ts *TestScript) cmdSymlink(neg bool, args []string) {
if neg {
ts.Fatalf("unsupported: ! symlink")
}
if len(args) != 3 || args[1] != "->" {
ts.Fatalf("usage: symlink file -> target")
}
// Note that the link target args[2] is not interpreted with MkAbs:
// it will be interpreted relative to the directory file is in.
ts.Check(os.Symlink(args[2], ts.MkAbs(args[0])))
}
// cmdUNIX2DOS converts files from UNIX line endings to DOS line endings.
func (ts *TestScript) cmdUNIX2DOS(neg bool, args []string) {
if neg {
ts.Fatalf("unsupported: ! unix2dos")
}
if len(args) < 1 {
ts.Fatalf("usage: unix2dos paths...")
}
for _, arg := range args {
filename := ts.MkAbs(arg)
data, err := ioutil.ReadFile(filename)
ts.Check(err)
dosData, err := unix2DOS(data)
ts.Check(err)
if err := ioutil.WriteFile(filename, dosData, 0o666); err != nil {
ts.Fatalf("%s: %v", filename, err)
}
}
}
// Tait waits for background commands to exit, setting stderr and stdout to their result.
func (ts *TestScript) cmdWait(neg bool, args []string) {
if len(args) > 1 {
ts.Fatalf("usage: wait [name]")
}
if neg {
ts.Fatalf("unsupported: ! wait")
}
if len(args) > 0 {
ts.waitBackgroundOne(args[0])
} else {
ts.waitBackground(true)
}
}
func (ts *TestScript) waitBackgroundOne(bgName string) {
bg := ts.findBackground(bgName)
if bg == nil {
ts.Fatalf("unknown background process %q", bgName)
}
<-bg.wait
ts.stdout = bg.cmd.Stdout.(*strings.Builder).String()
ts.stderr = bg.cmd.Stderr.(*strings.Builder).String()
if ts.stdout != "" {
fmt.Fprintf(&ts.log, "[stdout]\n%s", ts.stdout)
}
if ts.stderr != "" {
fmt.Fprintf(&ts.log, "[stderr]\n%s", ts.stderr)
}
// Note: ignore bg.neg, which only takes effect on the non-specific
// wait command.
if bg.cmd.ProcessState.Success() {
if bg.neg {
ts.Fatalf("unexpected command success")
}
} else {
if ts.ctxt.Err() != nil {
ts.Fatalf("test timed out while running command")
} else if !bg.neg {
ts.Fatalf("unexpected command failure")
}
}
// Remove this process from the list of running background processes.
for i := range ts.background {
if bg == &ts.background[i] {
ts.background = append(ts.background[:i], ts.background[i+1:]...)
break
}
}
}
func (ts *TestScript) findBackground(bgName string) *backgroundCmd {
if bgName == "" {
return nil
}
for i := range ts.background {
bg := &ts.background[i]
if bg.name == bgName {
return bg
}
}
return nil
}
func (ts *TestScript) waitBackground(checkStatus bool) {
var stdouts, stderrs []string
for _, bg := range ts.background {
<-bg.wait
args := append([]string{filepath.Base(bg.cmd.Args[0])}, bg.cmd.Args[1:]...)
fmt.Fprintf(&ts.log, "[background] %s: %v\n", strings.Join(args, " "), bg.cmd.ProcessState)
cmdStdout := bg.cmd.Stdout.(*strings.Builder).String()
if cmdStdout != "" {
fmt.Fprintf(&ts.log, "[stdout]\n%s", cmdStdout)
stdouts = append(stdouts, cmdStdout)
}
cmdStderr := bg.cmd.Stderr.(*strings.Builder).String()
if cmdStderr != "" {
fmt.Fprintf(&ts.log, "[stderr]\n%s", cmdStderr)
stderrs = append(stderrs, cmdStderr)
}
if !checkStatus {
continue
}
if bg.cmd.ProcessState.Success() {
if bg.neg {
ts.Fatalf("unexpected command success")
}
} else {
if ts.ctxt.Err() != nil {
ts.Fatalf("test timed out while running command")
} else if !bg.neg {
ts.Fatalf("unexpected command failure")
}
}
}
ts.stdout = strings.Join(stdouts, "")
ts.stderr = strings.Join(stderrs, "")
ts.background = nil
}
// scriptMatch implements both stdout and stderr.
func scriptMatch(ts *TestScript, neg bool, args []string, text, name string) {
n := 0
if len(args) >= 1 && strings.HasPrefix(args[0], "-count=") {
if neg {
ts.Fatalf("cannot use -count= with negated match")
}
var err error
n, err = strconv.Atoi(args[0][len("-count="):])
if err != nil {
ts.Fatalf("bad -count=: %v", err)
}
if n < 1 {
ts.Fatalf("bad -count=: must be at least 1")
}
args = args[1:]
}
extraUsage := ""
want := 1
if name == "grep" {
extraUsage = " file"
want = 2
}
if len(args) != want {
ts.Fatalf("usage: %s [-count=N] 'pattern'%s", name, extraUsage)
}
pattern := args[0]
re, err := regexp.Compile(`(?m)` + pattern)
ts.Check(err)
isGrep := name == "grep"
if isGrep {
name = args[1] // for error messages
data, err := ioutil.ReadFile(ts.MkAbs(args[1]))
ts.Check(err)
text = string(data)
}
if neg {
if re.MatchString(text) {
if isGrep {
ts.Logf("[%s]\n%s\n", name, text)
}
ts.Fatalf("unexpected match for %#q found in %s: %s", pattern, name, re.FindString(text))
}
} else {
if !re.MatchString(text) {
if isGrep {
ts.Logf("[%s]\n%s\n", name, text)
}
ts.Fatalf("no match for %#q found in %s", pattern, name)
}
if n > 0 {
count := len(re.FindAllString(text, -1))
if count != n {
if isGrep {
ts.Logf("[%s]\n%s\n", name, text)
}
ts.Fatalf("have %d matches for %#q, want %d", count, pattern, n)
}
}
}
}
// unix2DOS returns data with UNIX line endings converted to DOS line endings.
func unix2DOS(data []byte) ([]byte, error) {
sb := &strings.Builder{}
s := bufio.NewScanner(bytes.NewReader(data))
for s.Scan() {
if _, err := sb.Write(s.Bytes()); err != nil {
return nil, err
}
if _, err := sb.WriteString("\r\n"); err != nil {
return nil, err
}
}
if err := s.Err(); err != nil {
return nil, err
}
return []byte(sb.String()), nil
}