github.com/joey-fossa/fossa-cli@v0.7.34-0.20190708193710-569f1e8679f0/analyzers/golang/util.go (about) 1 package golang 2 3 import ( 4 "os" 5 "path/filepath" 6 "strings" 7 8 "github.com/pkg/errors" 9 10 "github.com/fossas/fossa-cli/buildtools/gocmd" 11 "github.com/fossas/fossa-cli/pkg" 12 ) 13 14 // Errors that occur while running utilities. 15 var ( 16 ErrNoGOPATH = errors.New("no $GOPATH set") 17 ) 18 19 // Dir returns the absolute path to a Go package. 20 func (a *Analyzer) Dir(importpath string) (string, error) { 21 pkg, err := a.Go.ListOne(importpath, nil) 22 if err != nil { 23 return "", err 24 } 25 return pkg.Dir, nil 26 } 27 28 // ImportPath returns the import path of a package located at the directory. 29 func ImportPath(dir string) (string, error) { 30 if os.Getenv("GOPATH") == "" { 31 return "", ErrNoGOPATH 32 } 33 gopath, err := filepath.Abs(os.Getenv("GOPATH")) 34 if err != nil { 35 return "", errors.Wrap(err, "could not get absolute $GOPATH") 36 } 37 importpath, err := filepath.Rel(filepath.Join(gopath, "src"), dir) 38 if err != nil { 39 return "", errors.Wrap(err, "could not compute import prefix") 40 } 41 return importpath, nil 42 } 43 44 // Unvendor takes a vendorized import path and strips all vendor folder 45 // prefixes. 46 func Unvendor(importpath string) string { 47 sections := strings.Split(importpath, "/vendor/") 48 return sections[len(sections)-1] 49 } 50 51 // VendorParent returns the directory that contains a vendored directory, or "." 52 // if none exists. 53 func VendorParent(dirname string) string { 54 separator := filepath.FromSlash("/vendor/") 55 if !strings.Contains(dirname, separator) { 56 return "." 57 } 58 sections := strings.Split(dirname, separator) 59 return strings.Join(sections[:len(sections)-1], separator) 60 } 61 62 // UnresolvedImport returns the default (non-zero) pkg.Import for an unresolved 63 // gocmd.Package. 64 func UnresolvedImport(gopkg gocmd.Package) pkg.Import { 65 return pkg.Import{ 66 Target: Unvendor(gopkg.ImportPath), 67 Resolved: pkg.ID{ 68 Type: pkg.Go, 69 Name: gopkg.ImportPath, 70 Revision: "", 71 Location: "", 72 }, 73 } 74 }