-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathtoolchain.go
356 lines (307 loc) · 11.2 KB
/
toolchain.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
package toolchain
import (
"bufio"
"encoding/json"
"io"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/github/codeql-go/extractor/util"
)
var V1_14 = util.NewSemVer("v1.14.0")
var V1_16 = util.NewSemVer("v1.16.0")
var V1_18 = util.NewSemVer("v1.18.0")
var V1_21 = util.NewSemVer("v1.21.0")
// Check if Go is installed in the environment.
func IsInstalled() bool {
_, err := exec.LookPath("go")
return err == nil
}
// The default Go version that is available on a system and a set of all versions
// that we know are installed on the system.
var goVersion = ""
var goVersions = map[util.SemVer]struct{}{}
// Adds an entry to the set of installed Go versions for the normalised `version` number.
func addGoVersion(version util.SemVer) {
goVersions[version] = struct{}{}
}
// Returns the current Go version as returned by 'go version', e.g. go1.14.4
func GetEnvGoVersion() string {
if goVersion == "" {
// Since Go 1.21, running 'go version' in a directory with a 'go.mod' file will attempt to
// download the version of Go specified in there. That may either fail or result in us just
// being told what's already in 'go.mod'. Setting 'GOTOOLCHAIN' to 'local' will force it
// to use the local Go toolchain instead.
cmd := Version()
// If 'GOTOOLCHAIN' is already set, then leave it as is. This allows us to force a specific
// Go version in tests and also allows users to override the system default more generally.
_, hasToolchainVar := os.LookupEnv("GOTOOLCHAIN")
if !hasToolchainVar {
cmd.Env = append(os.Environ(), "GOTOOLCHAIN=local")
}
out, err := cmd.CombinedOutput()
if err != nil {
log.Println(string(out))
log.Fatalf("Unable to run the go command, is it installed?\nError: %s", err.Error())
}
goVersion = parseGoVersion(string(out))
addGoVersion(util.NewSemVer(goVersion))
}
return goVersion
}
// Determines whether, to our knowledge, `version` is available on the current system.
func HasGoVersion(version util.SemVer) bool {
_, found := goVersions[version]
return found
}
// Attempts to install the Go toolchain `version`.
func InstallVersion(workingDir string, version util.SemVer) bool {
// No need to install it if we know that it is already installed.
if HasGoVersion(version) {
return true
}
// Construct a command to invoke `go version` with `GOTOOLCHAIN=go1.N.0` to give
// Go a valid toolchain version to download the toolchain we need; subsequent commands
// should then work even with an invalid version that's still in `go.mod`
toolchainArg := "GOTOOLCHAIN=go" + version.String()[1:]
versionCmd := Version()
versionCmd.Dir = workingDir
versionCmd.Env = append(os.Environ(), toolchainArg)
versionCmd.Stdout = os.Stdout
versionCmd.Stderr = os.Stderr
log.Printf(
"Trying to install Go %s using its canonical representation in `%s`.",
version,
workingDir,
)
// Run the command. If something goes wrong, report it to the log and signal failure
// to the caller.
if versionErr := versionCmd.Run(); versionErr != nil {
log.Printf(
"Failed to invoke `%s go version` in %s: %s\n",
toolchainArg,
versionCmd.Dir,
versionErr.Error(),
)
return false
}
// Add the version to the set of versions that we know are installed and signal
// success to the caller.
addGoVersion(version)
return true
}
// Returns the current Go version in semver format, e.g. v1.14.4
func GetEnvGoSemVer() util.SemVer {
goVersion := GetEnvGoVersion()
if !strings.HasPrefix(goVersion, "go") {
log.Fatalf("Expected 'go version' output of the form 'go1.2.3'; got '%s'", goVersion)
}
return util.NewSemVer(goVersion)
}
// The 'go version' command may output warnings on separate lines before
// the actual version string is printed. This function parses the output
// to retrieve just the version string.
func parseGoVersion(data string) string {
var lastLine string
sc := bufio.NewScanner(strings.NewReader(data))
for sc.Scan() {
lastLine = sc.Text()
}
return strings.Fields(lastLine)[2]
}
// Returns a value indicating whether the system Go toolchain supports workspaces.
func SupportsWorkspaces() bool {
return GetEnvGoSemVer().IsAtLeast(V1_18)
}
// Constructs a `*exec.Cmd` for `go` with the specified arguments.
func GoCommand(arg ...string) *exec.Cmd {
cmd := exec.Command("go", arg...)
util.ApplyProxyEnvVars(cmd)
return cmd
}
// Run `go mod tidy -e` in the directory given by `path`.
func TidyModule(path string) *exec.Cmd {
cmd := GoCommand("mod", "tidy", "-e")
cmd.Dir = path
return cmd
}
// Run `go mod init` in the directory given by `path`.
func InitModule(path string) *exec.Cmd {
moduleName := "codeql/auto-project"
if importpath := util.GetImportPath(); importpath != "" {
// This should be something like `github.com/user/repo`
moduleName = importpath
// If we are not initialising the new module in the root directory of the workspace,
// append the relative path to the module name.
if relPath, err := filepath.Rel(".", path); err != nil && relPath != "." {
moduleName = moduleName + "/" + relPath
}
}
modInit := GoCommand("mod", "init", moduleName)
modInit.Dir = path
return modInit
}
// Constructs a command to run `go mod vendor -e` in the directory given by `path`.
func VendorModule(path string) *exec.Cmd {
modVendor := GoCommand("mod", "vendor", "-e")
modVendor.Dir = path
return modVendor
}
// Constructs a command to run `go version`.
func Version() *exec.Cmd {
version := GoCommand("version")
return version
}
// Runs `go list` with `format`, `patterns`, and `flags` for the respective inputs.
func RunList(format string, patterns []string, flags ...string) (string, error) {
return RunListWithEnv(format, patterns, nil, flags...)
}
// Constructs a `go list` command with `format`, `patterns`, and `flags` for the respective inputs.
func List(format string, patterns []string, flags ...string) *exec.Cmd {
return ListWithEnv(format, patterns, nil, flags...)
}
// Runs `go list`.
func RunListWithEnv(format string, patterns []string, additionalEnv []string, flags ...string) (string, error) {
cmd := ListWithEnv(format, patterns, additionalEnv, flags...)
out, err := cmd.Output()
if err != nil {
if exitErr, ok := err.(*exec.ExitError); ok {
log.Printf("Warning: go list command failed, output below:\nstdout:\n%s\nstderr:\n%s\n", out, exitErr.Stderr)
} else {
log.Printf("Warning: Failed to run go list: %s", err.Error())
}
return "", err
}
return strings.TrimSpace(string(out)), nil
}
// Constructs a `go list` command with `format`, `patterns`, and `flags` for the respective inputs
// and the extra environment variables given by `additionalEnv`.
func ListWithEnv(format string, patterns []string, additionalEnv []string, flags ...string) *exec.Cmd {
args := append([]string{"list", "-e", "-f", format}, flags...)
args = append(args, patterns...)
cmd := GoCommand(args...)
cmd.Env = append(os.Environ(), additionalEnv...)
return cmd
}
// PkgInfo holds package directory and module directory (if any) for a package
type PkgInfo struct {
PkgDir string // the directory directly containing source code of this package
ModDir string // the module directory containing this package, empty if not a module
}
// GetPkgsInfo gets the absolute module and package root directories for the packages matched by the
// patterns `patterns`. It passes to `go list` the flags specified by `flags`. If `includingDeps`
// is true, all dependencies will also be included.
func GetPkgsInfo(patterns []string, includingDeps bool, extractTests bool, flags ...string) (map[string]PkgInfo, error) {
// enable module mode so that we can find a module root if it exists, even if go module support is
// disabled by a build
if includingDeps {
// the flag `-deps` causes all dependencies to be retrieved
flags = append(flags, "-deps")
}
if extractTests {
// Without the `-test` flag, test packages would be omitted from the `go list` output.
flags = append(flags, "-test")
}
// using -json overrides -f format
output, err := RunList("", patterns, append(flags, "-json")...)
if err != nil {
return nil, err
}
// the output of `go list -json` is a stream of json object
type goListPkgInfo struct {
ImportPath string
Dir string
Module *struct {
Dir string
}
}
pkgInfoMapping := make(map[string]PkgInfo)
streamDecoder := json.NewDecoder(strings.NewReader(output))
for {
var pkgInfo goListPkgInfo
decErr := streamDecoder.Decode(&pkgInfo)
if decErr == io.EOF {
break
}
if decErr != nil {
log.Printf("Error decoding output of go list -json: %s", err.Error())
return nil, decErr
}
pkgAbsDir, err := filepath.Abs(pkgInfo.Dir)
if err != nil {
log.Printf("Unable to make package dir %s absolute: %s", pkgInfo.Dir, err.Error())
}
var modAbsDir string
if pkgInfo.Module != nil {
modAbsDir, err = filepath.Abs(pkgInfo.Module.Dir)
if err != nil {
log.Printf("Unable to make module dir %s absolute: %s", pkgInfo.Module.Dir, err.Error())
}
}
pkgInfoMapping[pkgInfo.ImportPath] = PkgInfo{
PkgDir: pkgAbsDir,
ModDir: modAbsDir,
}
if extractTests && strings.Contains(pkgInfo.ImportPath, " [") {
// Assume " [" is the start of a qualifier, and index the package by its base name
baseImportPath := strings.Split(pkgInfo.ImportPath, " [")[0]
pkgInfoMapping[baseImportPath] = pkgInfoMapping[pkgInfo.ImportPath]
}
}
return pkgInfoMapping, nil
}
// GetPkgInfo fills the package info structure for the specified package path.
// It passes the `go list` the flags specified by `flags`.
func GetPkgInfo(pkgpath string, flags ...string) PkgInfo {
return PkgInfo{
PkgDir: GetPkgDir(pkgpath, flags...),
ModDir: GetModDir(pkgpath, flags...),
}
}
// GetModDir gets the absolute directory of the module containing the package with path
// `pkgpath`. It passes the `go list` the flags specified by `flags`.
func GetModDir(pkgpath string, flags ...string) string {
// enable module mode so that we can find a module root if it exists, even if go module support is
// disabled by a build
mod, err := RunListWithEnv("{{.Module}}", []string{pkgpath}, []string{"GO111MODULE=on"}, flags...)
if err != nil || mod == "<nil>" {
// if the command errors or modules aren't being used, return the empty string
return ""
}
modDir, err := RunListWithEnv("{{.Module.Dir}}", []string{pkgpath}, []string{"GO111MODULE=on"}, flags...)
if err != nil {
return ""
}
abs, err := filepath.Abs(modDir)
if err != nil {
log.Printf("Warning: unable to make %s absolute: %s", modDir, err.Error())
return ""
}
return abs
}
// GetPkgDir gets the absolute directory containing the package with path `pkgpath`. It passes the
// `go list` command the flags specified by `flags`.
func GetPkgDir(pkgpath string, flags ...string) string {
pkgDir, err := RunList("{{.Dir}}", []string{pkgpath}, flags...)
if err != nil {
return ""
}
abs, err := filepath.Abs(pkgDir)
if err != nil {
log.Printf("Warning: unable to make %s absolute: %s", pkgDir, err.Error())
return ""
}
return abs
}
// DepErrors checks there are any errors resolving dependencies for `pkgpath`. It passes the `go
// list` command the flags specified by `flags`.
func DepErrors(pkgpath string, flags ...string) bool {
out, err := RunList("{{if .DepsErrors}}error{{else}}{{end}}", []string{pkgpath}, flags...)
if err != nil {
// if go list failed, assume dependencies are broken
return false
}
return out != ""
}