Serge Bazanski | ab4ef13 | 2021-09-24 13:58:13 +0200 | [diff] [blame] | 1 | // gotoolchain provides information about the Go toolchain used on the host by |
| 2 | // rules_go. |
| 3 | package gotoolchain |
| 4 | |
| 5 | import ( |
| 6 | "fmt" |
Serge Bazanski | ae57413 | 2021-12-17 17:28:52 +0100 | [diff] [blame^] | 7 | "os" |
| 8 | "strings" |
Serge Bazanski | ab4ef13 | 2021-09-24 13:58:13 +0200 | [diff] [blame] | 9 | |
| 10 | "github.com/bazelbuild/rules_go/go/tools/bazel" |
| 11 | ) |
| 12 | |
| 13 | func mustRunfile(s string) string { |
Serge Bazanski | ae57413 | 2021-12-17 17:28:52 +0100 | [diff] [blame^] | 14 | // When running as a tool (in a genrule, or a test, etc.), bazel.Runfile |
| 15 | // does not work. However, ${0}.runfiles/$runfile should be present. If so, |
| 16 | // return early and return that. Otherwise, carry on with bazel.Runfile. |
| 17 | // |
| 18 | // TODO(q3k): dig deeper into this and unify with //metropolis/cli/pkg/datafile. |
| 19 | |
| 20 | // Ignore the error, worst case we get an empty string that will make a |
| 21 | // garbage path that won't point to a file. |
| 22 | ex, _ := os.Executable() |
| 23 | rf := ex + ".runfiles" |
| 24 | if _, err := os.Stat(rf); err == nil { |
| 25 | parts := strings.Split(s, "/") |
| 26 | parts[0] = rf |
| 27 | rf = strings.Join(parts, "/") |
| 28 | if _, err := os.Stat(rf); err == nil { |
| 29 | return rf |
| 30 | } |
| 31 | } |
| 32 | |
Serge Bazanski | ab4ef13 | 2021-09-24 13:58:13 +0200 | [diff] [blame] | 33 | res, err := bazel.Runfile(s) |
| 34 | if err != nil { |
| 35 | panic(fmt.Sprintf("runfile %q not found: %v", s, err)) |
| 36 | } |
| 37 | return res |
| 38 | } |
| 39 | |
| 40 | var ( |
| 41 | // Go is a path to the `go` executable. |
| 42 | Go = mustRunfile(`GOTOOL`) |
| 43 | // Root is the GOROOT path. |
| 44 | Root = mustRunfile(`GOROOT`) |
| 45 | ) |