/
main.go
378 lines (321 loc) · 9.21 KB
/
main.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
// 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 main
import (
"errors"
"flag"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strings"
"sync/atomic"
"github.com/rogpeppe/go-internal/goproxytest"
"github.com/rogpeppe/go-internal/gotooltest"
"github.com/rogpeppe/go-internal/testscript"
"github.com/rogpeppe/go-internal/txtar"
)
const (
// goModProxyDir is the special subdirectory in a txtar script's supporting files
// within which we expect to find github.com/rogpeppe/go-internal/goproxytest
// directories.
goModProxyDir = ".gomodproxy"
)
type envVarsFlag struct {
vals []string
}
func (e *envVarsFlag) String() string {
return fmt.Sprintf("%v", e.vals)
}
func (e *envVarsFlag) Set(v string) error {
e.vals = append(e.vals, v)
return nil
}
func main() {
os.Exit(main1())
}
func main1() int {
switch err := mainerr(); err {
case nil:
return 0
case flag.ErrHelp:
return 2
default:
fmt.Fprintln(os.Stderr, err)
return 1
}
}
func mainerr() (retErr error) {
fs := flag.NewFlagSet(os.Args[0], flag.ContinueOnError)
fs.Usage = func() {
mainUsage(os.Stderr)
}
var envVars envVarsFlag
fUpdate := fs.Bool("u", false, "update archive file if a cmp fails")
fWork := fs.Bool("work", false, "print temporary work directory and do not remove when done")
fVerbose := fs.Bool("v", false, "run tests verbosely")
fs.Var(&envVars, "e", "pass through environment variable to script (can appear multiple times)")
if err := fs.Parse(os.Args[1:]); err != nil {
return err
}
td, err := ioutil.TempDir("", "testscript")
if err != nil {
return fmt.Errorf("unable to create temp dir: %v", err)
}
if *fWork {
fmt.Fprintf(os.Stderr, "temporary work directory: %v\n", td)
} else {
defer os.RemoveAll(td)
}
files := fs.Args()
if len(files) == 0 {
files = []string{"-"}
}
// If we are only reading from stdin, -u cannot be specified. It seems a bit
// bizarre to invoke testscript with '-' and a regular file, but hey. In
// that case the -u flag will only apply to the regular file and we assume
// the user knows it.
onlyReadFromStdin := true
for _, f := range files {
if f != "-" {
onlyReadFromStdin = false
}
}
if onlyReadFromStdin && *fUpdate {
return fmt.Errorf("cannot use -u when reading from stdin")
}
tr := testRunner{
update: *fUpdate,
verbose: *fVerbose,
env: envVars.vals,
testWork: *fWork,
}
dirNames := make(map[string]int)
for _, filename := range files {
// TODO make running files concurrent by default? If we do, note we'll need to do
// something smarter with the runner stdout and stderr below
// Derive a name for the directory from the basename of file, making
// uniq by adding a numeric suffix in the case we otherwise end
// up with multiple files with the same basename
dirName := filepath.Base(filename)
count := dirNames[dirName]
dirNames[dirName] = count + 1
if count != 0 {
dirName = fmt.Sprintf("%s%d", dirName, count)
}
runDir := filepath.Join(td, dirName)
if err := os.Mkdir(runDir, 0777); err != nil {
return fmt.Errorf("failed to create a run directory within %v for %v: %v", td, renderFilename(filename), err)
}
if err := tr.run(runDir, filename); err != nil {
return err
}
}
return nil
}
type testRunner struct {
// update denotes that the source testscript archive filename should be
// updated in the case of any cmp failures.
update bool
// verbose indicates the running of the script should be noisy.
verbose bool
// env is the environment that should be set on top of the base
// testscript-defined minimal environment.
env []string
// testWork indicates whether or not temporary working directory trees
// should be left behind. Corresponds exactly to the
// testscript.Params.TestWork field.
testWork bool
}
// run runs the testscript archive located at the path filename, within the
// working directory runDir. filename could be "-" in the case of stdin
func (tr *testRunner) run(runDir, filename string) error {
var ar *txtar.Archive
var err error
mods := filepath.Join(runDir, goModProxyDir)
if err := os.MkdirAll(mods, 0777); err != nil {
return fmt.Errorf("failed to create goModProxy dir: %v", err)
}
if filename == "-" {
byts, err := ioutil.ReadAll(os.Stdin)
if err != nil {
return fmt.Errorf("failed to read from stdin: %v", err)
}
ar = txtar.Parse(byts)
} else {
ar, err = txtar.ParseFile(filename)
}
if err != nil {
return fmt.Errorf("failed to txtar parse %v: %v", renderFilename(filename), err)
}
var script, gomodProxy txtar.Archive
script.Comment = ar.Comment
for _, f := range ar.Files {
fp := filepath.Clean(filepath.FromSlash(f.Name))
parts := strings.Split(fp, string(os.PathSeparator))
if len(parts) > 1 && parts[0] == goModProxyDir {
gomodProxy.Files = append(gomodProxy.Files, f)
} else {
script.Files = append(script.Files, f)
}
}
if txtar.Write(&gomodProxy, runDir); err != nil {
return fmt.Errorf("failed to write .gomodproxy files: %v", err)
}
scriptFile := filepath.Join(runDir, "script.txtar")
if err := ioutil.WriteFile(scriptFile, txtar.Format(&script), 0666); err != nil {
return fmt.Errorf("failed to write script for %v: %v", renderFilename(filename), err)
}
p := testscript.Params{
Dir: runDir,
UpdateScripts: tr.update,
}
if _, err := exec.LookPath("go"); err == nil {
if err := gotooltest.Setup(&p); err != nil {
return fmt.Errorf("failed to setup go tool for %v run: %v", renderFilename(filename), err)
}
}
addSetup := func(f func(env *testscript.Env) error) {
origSetup := p.Setup
p.Setup = func(env *testscript.Env) error {
if origSetup != nil {
if err := origSetup(env); err != nil {
return err
}
}
return f(env)
}
}
if tr.testWork {
addSetup(func(env *testscript.Env) error {
fmt.Fprintf(os.Stderr, "temporary work directory for %s: %s\n", renderFilename(filename), env.WorkDir)
return nil
})
}
if len(gomodProxy.Files) > 0 {
srv, err := goproxytest.NewServer(mods, "")
if err != nil {
return fmt.Errorf("cannot start proxy for %v: %v", renderFilename(filename), err)
}
defer srv.Close()
addSetup(func(env *testscript.Env) error {
// Add GOPROXY after calling the original setup
// so that it overrides any GOPROXY set there.
env.Vars = append(env.Vars,
"GOPROXY="+srv.URL,
"GONOSUMDB=*",
)
return nil
})
}
if len(tr.env) > 0 {
addSetup(func(env *testscript.Env) error {
for _, v := range tr.env {
varName := v
if i := strings.Index(v, "="); i >= 0 {
varName = v[:i]
} else {
v = fmt.Sprintf("%s=%s", v, os.Getenv(v))
}
switch varName {
case "":
return fmt.Errorf("invalid variable name %q", varName)
case "WORK":
return fmt.Errorf("cannot override WORK variable")
}
env.Vars = append(env.Vars, v)
}
return nil
})
}
r := runT{
verbose: tr.verbose,
}
func() {
defer func() {
switch recover() {
case nil, skipRun:
case failedRun:
err = failedRun
default:
panic(fmt.Errorf("unexpected panic: %v [%T]", err, err))
}
}()
testscript.RunT(r, p)
}()
if err != nil {
return fmt.Errorf("error running %v in %v\n", renderFilename(filename), runDir)
}
if tr.update && filename != "-" {
// Parse the (potentially) updated scriptFile as an archive, then merge
// with the original archive, retaining order. Then write the archive
// back to the source file
source, err := ioutil.ReadFile(scriptFile)
if err != nil {
return fmt.Errorf("failed to read from script file %v for -update: %v", scriptFile, err)
}
updatedAr := txtar.Parse(source)
updatedFiles := make(map[string]txtar.File)
for _, f := range updatedAr.Files {
updatedFiles[f.Name] = f
}
for i, f := range ar.Files {
if newF, ok := updatedFiles[f.Name]; ok {
ar.Files[i] = newF
}
}
if err := ioutil.WriteFile(filename, txtar.Format(ar), 0666); err != nil {
return fmt.Errorf("failed to write script back to %v for -update: %v", renderFilename(filename), err)
}
}
return nil
}
var (
failedRun = errors.New("failed run")
skipRun = errors.New("skip")
)
// renderFilename renders filename in error messages, taking into account
// the filename could be the special "-" (stdin)
func renderFilename(filename string) string {
if filename == "-" {
return "<stdin>"
}
return filename
}
// runT implements testscript.T and is used in the call to testscript.Run
type runT struct {
verbose bool
failed int32
}
func (r runT) Skip(is ...interface{}) {
panic(skipRun)
}
func (r runT) Fatal(is ...interface{}) {
r.Log(is...)
r.FailNow()
}
func (r runT) Parallel() {
// No-op for now; we are currently only running a single script in a
// testscript instance.
}
func (r runT) Log(is ...interface{}) {
fmt.Print(is...)
}
func (r runT) FailNow() {
atomic.StoreInt32(&r.failed, 1)
panic(failedRun)
}
func (r runT) Failed() bool {
return atomic.LoadInt32(&r.failed) != 0
}
func (r runT) Run(n string, f func(t testscript.T)) {
// For now we we don't top/tail the run of a subtest. We are currently only
// running a single script in a testscript instance, which means that we
// will only have a single subtest.
f(r)
}
func (r runT) Verbose() bool {
return r.verbose
}