golang.org/x/build@v0.0.0-20240506185731-218518f32b70/internal/basedir/basedir.go (about) 1 // Copyright 2017 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 basedir finds templates and static files associated with a binary. 6 package basedir 7 8 import ( 9 "bytes" 10 "os" 11 "os/exec" 12 "path/filepath" 13 "runtime" 14 "strings" 15 ) 16 17 // Find locates a directory for the given package. 18 // pkg should be the directory that contains the templates and/or static directories. 19 // If pkg cannot be found, an empty string will be returned. 20 func Find(pkg string) string { 21 cmd := exec.Command("go", "list", "-e", "-f", "{{.Dir}}", pkg) 22 if out, err := cmd.Output(); err == nil && len(out) > 0 { 23 return string(bytes.TrimRight(out, "\r\n")) 24 } 25 gopath := os.Getenv("GOPATH") 26 if gopath == "" { 27 gopath = defaultGOPATH() 28 } 29 if gopath != "" { 30 for _, dir := range strings.Split(gopath, ":") { 31 p := filepath.Join(dir, pkg) 32 if _, err := os.Stat(p); err == nil { 33 return p 34 } 35 } 36 } 37 return "" 38 } 39 40 // Copied from go/build/build.go 41 func defaultGOPATH() string { 42 env := "HOME" 43 if runtime.GOOS == "windows" { 44 env = "USERPROFILE" 45 } else if runtime.GOOS == "plan9" { 46 env = "home" 47 } 48 if home := os.Getenv(env); home != "" { 49 def := filepath.Join(home, "go") 50 if filepath.Clean(def) == filepath.Clean(runtime.GOROOT()) { 51 // Don't set the default GOPATH to GOROOT, 52 // as that will trigger warnings from the go tool. 53 return "" 54 } 55 return def 56 } 57 return "" 58 }