Debian Codegraph @

testscript/exe.go

raw symbols SCIP
1 // Copyright 2018 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package testscript
6
7 import (
8 "io"
9 "log"
10 "os"
11 "path/filepath"
12 "runtime"
13 "strings"
14 )
15
16 // TestingM is implemented by *testing.M. It's defined as an interface
17 // to allow testscript to co-exist with other testing frameworks
18 // that might also wish to call M.Run.
19 type TestingM interface {
20 Run() int
21 }
22
23 // Deprecated: this option is no longer used.
24 func IgnoreMissedCoverage() {}
25
26 // Main should be called within a TestMain function to allow
27 // subcommands to be run in the testscript context.
28 // Main always calls [os.Exit], so it does not return back to the caller.
29 //
30 // The commands map holds the set of command names, each
31 // with an associated run function which may call os.Exit.
32 //
33 // When Run is called, these commands are installed as regular commands in the shell
34 // path, so can be invoked with "exec" or via any other command (for example a shell script).
35 //
36 // For backwards compatibility, the commands declared in the map can be run
37 // without "exec" - that is, "foo" will behave like "exec foo".
38 // This can be disabled with Params.RequireExplicitExec to keep consistency
39 // across test scripts, and to keep separate process executions explicit.
40 func Main(m TestingM, commands map[string]func()) {
41 // Depending on os.Args[0], this is either the top-level execution of
42 // the test binary by "go test", or the execution of one of the provided
43 // commands via "foo" or "exec foo".
44
45 cmdName := filepath.Base(os.Args[0])
46 if runtime.GOOS == "windows" {
47 cmdName = strings.TrimSuffix(cmdName, ".exe")
48 }
49 mainf := commands[cmdName]
50 if mainf == nil {
51 // Unknown command; this is just the top-level execution of the
52 // test binary by "go test".
53 os.Exit(testingMRun(m, commands))
54 }
55 // The command being registered is being invoked, so run it, then exit.
56 os.Args[0] = cmdName
57 mainf()
58 os.Exit(0)
59 }
60
61 // testingMRun exists just so that we can use `defer`, given that [Main] above uses [os.Exit].
62 func testingMRun(m TestingM, commands map[string]func()) int {
63 // Set up all commands in a directory, added in $PATH.
64 tmpdir, err := os.MkdirTemp("", "testscript-main")
65 if err != nil {
66 log.Fatalf("could not set up temporary directory: %v", err)
67 }
68 defer func() {
69 if err := os.RemoveAll(tmpdir); err != nil {
70 log.Fatalf("cannot delete temporary directory: %v", err)
71 }
72 }()
73 bindir := filepath.Join(tmpdir, "bin")
74 if err := os.MkdirAll(bindir, 0o777); err != nil {
75 log.Fatalf("could not set up PATH binary directory: %v", err)
76 }
77 os.Setenv("PATH", bindir+string(filepath.ListSeparator)+os.Getenv("PATH"))
78
79 // We're not in a subcommand.
80 for name := range commands {
81 // Set up this command in the directory we added to $PATH.
82 binfile := filepath.Join(bindir, name)
83 if runtime.GOOS == "windows" {
84 binfile += ".exe"
85 }
86 binpath, err := os.Executable()
87 if err == nil {
88 err = copyBinary(binpath, binfile)
89 }
90 if err != nil {
91 log.Fatalf("could not set up %s in $PATH: %v", name, err)
92 }
93 scriptCmds[name] = func(ts *TestScript, neg bool, args []string) {
94 if ts.params.RequireExplicitExec {
95 ts.Fatalf("use 'exec %s' rather than '%s' (because RequireExplicitExec is enabled)", name, name)
96 }
97 ts.cmdExec(neg, append([]string{name}, args...))
98 }
99 }
100 return m.Run()
101 }
102
103 // Deprecated: use [Main], as the only reason for returning exit codes
104 // was to collect full code coverage, which Go does automatically now:
105 // https://go.dev/blog/integration-test-coverage
106 func RunMain(m TestingM, commands map[string]func() int) (exitCode int) {
107 commands2 := make(map[string]func(), len(commands))
108 for name, fn := range commands {
109 commands2[name] = func() { os.Exit(fn()) }
110 }
111 Main(m, commands2)
112 // Main always calls os.Exit; we assume that all users of RunMain would have simply
113 // called os.Exit with the returned exitCode as well, following the documentation.
114 panic("unreachable")
115 }
116
117 // copyBinary makes a copy of a binary to a new location. It is used as part of
118 // setting up top-level commands in $PATH.
119 //
120 // It does not attempt to use symlinks for two reasons:
121 //
122 // First, some tools like cmd/go's -toolexec will be clever enough to realise
123 // when they're given a symlink, and they will use the symlink target for
124 // executing the program. This breaks testscript, as we depend on os.Args[0] to
125 // know what command to run.
126 //
127 // Second, symlinks might not be available on some environments, so we have to
128 // implement a "full copy" fallback anyway.
129 //
130 // However, we do try to use cloneFile, since that will probably work on most
131 // unix-like setups. Note that "go test" also places test binaries in the
132 // system's temporary directory, like we do.
133 func copyBinary(from, to string) error {
134 if err := cloneFile(from, to); err == nil {
135 return nil
136 }
137 writer, err := os.OpenFile(to, os.O_WRONLY|os.O_CREATE, 0o777)
138 if err != nil {
139 return err
140 }
141 defer writer.Close()
142
143 reader, err := os.Open(from)
144 if err != nil {
145 return err
146 }
147 defer reader.Close()
148
149 _, err = io.Copy(writer, reader)
150 return err
151 }