From 0ee35918971027a4e4efaeaab70e812eaf1bfa99 Mon Sep 17 00:00:00 2001 From: James Nugent Date: Fri, 28 Jul 2017 15:13:56 -0500 Subject: [PATCH] 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. --- parser/parser.go | 6 ++++++ parser/parser_unix.go | 9 +++++++++ parser/parser_windows.go | 9 +++++++++ 3 files changed, 24 insertions(+) diff --git a/parser/parser.go b/parser/parser.go index 1c0b94c..5bd06e9 100644 --- a/parser/parser.go +++ b/parser/parser.go @@ -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 +} diff --git a/parser/parser_unix.go b/parser/parser_unix.go index a1b9d84..09b20a2 100644 --- a/parser/parser_unix.go +++ b/parser/parser_unix.go @@ -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 { diff --git a/parser/parser_windows.go b/parser/parser_windows.go index 64974aa..2d741a5 100644 --- a/parser/parser_windows.go +++ b/parser/parser_windows.go @@ -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 {