Detect GOPATH if not specified in $GOPATH

It is no longer required to have the GOPATH environment variable set -
it now defaults to ~/go, but irrespective of whether the value is the
default or not it can be found in the standard output of `go env
GOPATH`.

This commit uses that value if the GOPATH environment variable is not
set.
This commit is contained in:
James Nugent
2017-07-28 15:13:56 -05:00
parent 2f5df55504
commit 0ee3591897
3 changed files with 24 additions and 0 deletions
+6
View File
@@ -4,6 +4,7 @@ import (
"go/ast"
"go/parser"
"go/token"
"os/exec"
"strings"
)
@@ -89,3 +90,8 @@ func (p *Parser) Parse(fname string, isDir bool) error {
}
return nil
}
func getDefaultGoPath() (string, error) {
output, err := exec.Command("go", "env", "GOPATH").Output()
return string(output), err
}
+9
View File
@@ -18,6 +18,15 @@ func getPkgPath(fname string, isDir bool) (string, error) {
fname = path.Join(pwd, fname)
}
gopath := os.Getenv("GOPATH")
if gopath == "" {
var err error
gopath, err = getDefaultGoPath()
if err != nil {
return "", fmt.Errorf("cannot determine GOPATH: %s", err)
}
}
for _, p := range strings.Split(os.Getenv("GOPATH"), ":") {
prefix := path.Join(p, "src") + "/"
if rel := strings.TrimPrefix(fname, prefix); rel != fname {
+9
View File
@@ -22,6 +22,15 @@ func getPkgPath(fname string, isDir bool) (string, error) {
fname = normalizePath(fname)
gopath := os.Getenv("GOPATH")
if gopath == "" {
var err error
gopath, err = getDefaultGoPath()
if err != nil {
return "", fmt.Errorf("cannot determine GOPATH: %s", err)
}
}
for _, p := range strings.Split(os.Getenv("GOPATH"), ";") {
prefix := path.Join(normalizePath(p), "src") + "/"
if rel := strings.TrimPrefix(fname, prefix); rel != fname {