github.com/ldez/golangci-lint@v1.10.1/pkg/goutils/goutils.go (about) 1 package goutils 2 3 import ( 4 "fmt" 5 "os" 6 "os/exec" 7 "path/filepath" 8 "strings" 9 "sync" 10 11 "github.com/golangci/golangci-lint/pkg/fsutils" 12 ) 13 14 var discoverGoRootOnce sync.Once 15 var discoveredGoRoot string 16 var discoveredGoRootError error 17 18 func DiscoverGoRoot() (string, error) { 19 discoverGoRootOnce.Do(func() { 20 discoveredGoRoot, discoveredGoRootError = discoverGoRootImpl() 21 }) 22 23 return discoveredGoRoot, discoveredGoRootError 24 } 25 26 func discoverGoRootImpl() (string, error) { 27 goroot := os.Getenv("GOROOT") 28 if goroot != "" { 29 return goroot, nil 30 } 31 32 output, err := exec.Command("go", "env", "GOROOT").Output() 33 if err != nil { 34 return "", fmt.Errorf("can't execute go env GOROOT: %s", err) 35 } 36 37 return strings.TrimSpace(string(output)), nil 38 } 39 40 func InGoRoot() (bool, error) { 41 goroot, err := DiscoverGoRoot() 42 if err != nil { 43 return false, err 44 } 45 46 wd, err := fsutils.Getwd() 47 if err != nil { 48 return false, err 49 } 50 51 // TODO: strip, then add slashes 52 return strings.HasPrefix(wd, goroot), nil 53 } 54 55 func IsCgoFilename(f string) bool { 56 return filepath.Base(f) == "C" 57 }