| 1 |
package main |
| 2 |
|
| 3 |
import ( |
| 4 |
"os" |
| 5 |
"path/filepath" |
| 6 |
"runtime" |
| 7 |
"strings" |
| 8 |
) |
| 9 |
|
| 10 |
// The go command runs each toolchain program with the working directory set to |
| 11 |
// the package's source directory, and it gives us no direct statement of GOROOT |
| 12 |
// or GOMODCACHE |
| 13 |
// |
| 14 |
// goroot recovers GOROOT from the path of the tool we were asked to run, which is |
| 15 |
// always $GOROOT/pkg/tool/<goos>_<goarch>/<tool>. |
| 16 |
func goroot(toolPath string) string { |
| 17 |
dir := filepath.Dir(toolPath) // .../pkg/tool/linux_amd64 |
| 18 |
dir = filepath.Dir(dir) // .../pkg/tool |
| 19 |
dir = filepath.Dir(dir) // .../pkg |
| 20 |
if root := filepath.Dir(dir); root != "." { |
| 21 |
return root |
| 22 |
} |
| 23 |
return runtime.GOROOT() |
| 24 |
} |
| 25 |
|
| 26 |
// goModCache resolves GOMODCACHE the same way the go command does. |
| 27 |
func goModCache() string { |
| 28 |
if dir := strings.TrimSpace(os.Getenv("GOMODCACHE")); dir != "" { |
| 29 |
return dir |
| 30 |
} |
| 31 |
gopath := strings.TrimSpace(os.Getenv("GOPATH")) |
| 32 |
if gopath == "" { |
| 33 |
home, err := os.UserHomeDir() |
| 34 |
if err != nil { |
| 35 |
return "" |
| 36 |
} |
| 37 |
gopath = filepath.Join(home, "go") |
| 38 |
} |
| 39 |
// GOPATH is a list; only its first element is written to. |
| 40 |
if i := strings.IndexByte(gopath, os.PathListSeparator); i >= 0 { |
| 41 |
gopath = gopath[:i] |
| 42 |
} |
| 43 |
return filepath.Join(gopath, "pkg", "mod") |
| 44 |
} |
| 45 |
|
| 46 |
// isWorkingTreeSource reports whether path is source the user is working on, as |
| 47 |
// opposed to a downloaded dependency or part of the standard library. |
| 48 |
func isWorkingTreeSource(path string) bool { |
| 49 |
abs, err := filepath.Abs(path) |
| 50 |
if err != nil { |
| 51 |
return false |
| 52 |
} |
| 53 |
for _, external := range []string{goModCache(), goroot(os.Args[1])} { |
| 54 |
if external != "" && isUnder(abs, external) { |
| 55 |
return false |
| 56 |
} |
| 57 |
} |
| 58 |
return true |
| 59 |
} |
| 60 |
|
| 61 |
func isUnder(path, dir string) bool { |
| 62 |
rel, err := filepath.Rel(dir, path) |
| 63 |
if err != nil { |
| 64 |
return false |
| 65 |
} |
| 66 |
return rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) |
| 67 |
} |
| 68 |
|
| 69 |
// moduleRoot finds the directory holding the go.mod that governs the directory dir |
| 70 |
// |
| 71 |
// Returns "" when no go.mod is found, in which case callers fall back to |
| 72 |
// absolute paths. |
| 73 |
func moduleRoot(dir string) string { |
| 74 |
for { |
| 75 |
if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil { |
| 76 |
return dir |
| 77 |
} |
| 78 |
parent := filepath.Dir(dir) |
| 79 |
if parent == dir { |
| 80 |
return "" |
| 81 |
} |
| 82 |
dir = parent |
| 83 |
} |
| 84 |
} |