Skip to content
This repository was archived by the owner on Jun 6, 2022. It is now read-only.

Commit

Permalink
Use authoritative parser to find import comments
Browse files Browse the repository at this point in the history
Fixes #55.

Signed-off-by: Tim Waugh <[email protected]>
  • Loading branch information
twaugh committed Sep 21, 2018
1 parent 8591a88 commit 4fd15b7
Showing 1 changed file with 18 additions and 41 deletions.
59 changes: 18 additions & 41 deletions backvendor/gosource.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
package backvendor // import "github.com/release-engineering/backvendor/backvendor"

import (
"bufio"
"go/build"
"os"
"path"
"path/filepath"
Expand Down Expand Up @@ -187,52 +187,29 @@ func findImportComment(src *GoSource) (string, error) {
if err != nil {
return err
}
if info.IsDir() {
if info.Name() != "." &&
strings.HasPrefix(info.Name(), ".") {
return filepath.SkipDir
}
if info.Name() == "vendor" || info.Name() == "testdata" {
return filepath.SkipDir
}
if !info.IsDir() {
return nil
}
if !strings.HasSuffix(info.Name(), ".go") {
return nil
if info.Name() != "." &&
strings.HasPrefix(info.Name(), ".") {
return filepath.SkipDir
}
r, err := os.Open(pth)
if err != nil {
return err
switch info.Name() {
case "vendor", "testdata":
return filepath.SkipDir
}
defer r.Close()
scanner := bufio.NewScanner(bufio.NewReader(r))
for scanner.Scan() {
line := scanner.Text()
fields := strings.Fields(line)
if len(fields) < 5 {
continue
}
if fields[0] == "//" || fields[0] == "/*" {
continue
}
if fields[0] != "package" {
return nil
}
if fields[2] != "/*" && fields[2] != "//" {
return nil
}
if fields[3] != "import" {
return nil
}
pth := fields[4]
if len(pth) < 3 {
return nil
}
if pth[0] != '"' ||
pth[len(pth)-1] != '"' {

pkg, err := build.ImportDir(pth, build.ImportComment)
if err != nil {
if _, ok := err.(*build.NoGoError); ok {
return nil
}
importPath = pth[1 : len(pth)-1]
return err
}
if pkg.ImportComment != "" {
importPath = pkg.ImportComment
log.Debugf("found import path from import comment: %s",
importPath)
return errFound
}
return nil
Expand Down

0 comments on commit 4fd15b7

Please sign in to comment.