github.com/ActiveState/cli@v0.0.0-20240508170324-6801f60cd051/internal/environment/environment.go (about) 1 package environment 2 3 // This package may NOT depend on failures (directly or indirectly) 4 5 import ( 6 "errors" 7 "go/build" 8 "os" 9 "path/filepath" 10 "runtime" 11 "strings" 12 ) 13 14 // GetRootPath returns the root path of the library we're under 15 func GetRootPath() (string, error) { 16 pathsep := string(os.PathSeparator) 17 18 _, file, _, ok := runtime.Caller(0) 19 if !ok { 20 return "", errors.New("Could not call Caller(0)") 21 } 22 23 abs := filepath.Dir(file) 24 25 // If we're receiving a relative path resolve it to absolute 26 if abs[0:1] != "/" && abs[1:2] != ":" { 27 gopath := os.Getenv("GOPATH") 28 if gopath == "" { 29 gopath = build.Default.GOPATH 30 } 31 abs = filepath.Join(gopath, "src", abs) 32 } 33 34 // When tests are ran with coverage the location of this file is changed to a temp file, and we have to 35 // adjust accordingly 36 if strings.HasSuffix(abs, "_obj_test") { 37 abs = "" 38 } 39 40 // If we're in a temp _obj we need to account for it in the path 41 if strings.HasSuffix(abs, "_obj") { 42 abs = filepath.Join(abs, "..") 43 } 44 45 var err error 46 abs, err = filepath.Abs(filepath.Join(abs, "..", "..")) 47 48 if err != nil { 49 return "", err 50 } 51 52 return abs + pathsep, nil 53 } 54 55 // GetRootPathUnsafe returns the root path or panics if it cannot be found (hence the unsafe) 56 func GetRootPathUnsafe() string { 57 path, err := GetRootPath() 58 if err != nil { 59 panic(err) 60 } 61 return path 62 }