Skip to content

Commit

Permalink
Merge pull request 99designs#941 from vikstrous/qualify-package-path-…
Browse files Browse the repository at this point in the history
…faster

shortcut QualifyPackagePath in go module mode
  • Loading branch information
vektah authored Nov 28, 2019
2 parents e03e97d + 8fdb40c commit 4438942
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
23 changes: 19 additions & 4 deletions internal/code/imports.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,21 +51,21 @@ func NameForDir(dir string) string {
return SanitizePackageName(filepath.Base(dir))
}

// ImportPathForDir takes a path and returns a golang import path for the package
func ImportPathForDir(dir string) (res string) {
// goModuleRoot returns the root of the current go module if there is a go.mod file in the directory tree
// If not, it returns false
func goModuleRoot(dir string) (string, bool) {
dir, err := filepath.Abs(dir)
if err != nil {
panic(err)
}
dir = filepath.ToSlash(dir)

modDir := dir
assumedPart := ""
for {
f, err := ioutil.ReadFile(filepath.Join(modDir, "go.mod"))
if err == nil {
// found it, stop searching
return string(modregex.FindSubmatch(f)[1]) + assumedPart
return string(modregex.FindSubmatch(f)[1]) + assumedPart, true
}

assumedPart = "/" + filepath.Base(modDir) + assumedPart
Expand All @@ -80,6 +80,21 @@ func ImportPathForDir(dir string) (res string) {
}
modDir = parentDir
}
return "", false
}

// ImportPathForDir takes a path and returns a golang import path for the package
func ImportPathForDir(dir string) (res string) {
dir, err := filepath.Abs(dir)
if err != nil {
panic(err)
}
dir = filepath.ToSlash(dir)

modDir, ok := goModuleRoot(dir)
if ok {
return modDir
}

for _, gopath := range gopaths {
if len(gopath) < len(dir) && strings.EqualFold(gopath, dir[0:len(gopath)]) {
Expand Down
5 changes: 5 additions & 0 deletions internal/code/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,11 @@ func NormalizeVendor(pkg string) string {
func QualifyPackagePath(importPath string) string {
wd, _ := os.Getwd()

// in go module mode, the import path doesn't need fixing
if _, ok := goModuleRoot(wd); ok {
return importPath
}

pkg, err := build.Import(importPath, wd, 0)
if err != nil {
return importPath
Expand Down

0 comments on commit 4438942

Please sign in to comment.