Skip to content

Commit e908c9f

Browse files
authored
fix:(go) run go mod tidy before parsing (cloudwego#18)
1 parent 8544a9d commit e908c9f

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

lang/golang/parser/parser.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,15 @@
1515
package parser
1616

1717
import (
18+
"bytes"
1819
"fmt"
1920
"go/ast"
2021
"go/parser"
2122
"go/token"
2223
"go/types"
2324
"io/fs"
2425
"os"
26+
"os/exec"
2527
"path/filepath"
2628
"regexp"
2729
"strings"
@@ -142,6 +144,15 @@ func (p *GoParser) ParseRepo() (Repository, error) {
142144

143145
func (p *GoParser) ParseModule(mod *Module, dir string) (err error) {
144146
filepath.Walk(dir, func(path string, info fs.FileInfo, e error) error {
147+
// run go mod tidy before parse
148+
cmd := exec.Command("go", "mod", "tidy")
149+
cmd.Dir = dir
150+
buf := bytes.NewBuffer(nil)
151+
cmd.Stderr = buf
152+
if err := cmd.Run(); err != nil {
153+
return fmt.Errorf("run go mod tidy failed in %s: %v", dir, buf.String())
154+
}
155+
145156
if info != nil && info.IsDir() && filepath.Base(path) == ".git" {
146157
return filepath.SkipDir
147158
}

lang/golang/parser/pkg.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@ func (p *GoParser) loadPackages(mod *Module, dir string, pkgPath PkgPath) (err e
151151
if mm := p.repo.Modules[mod.Name]; mm != nil && (*mm).Packages[pkgPath] != nil {
152152
return nil
153153
}
154-
fmt.Fprintf(os.Stderr, "[loadPackages] mod: %s, dir: %s, pkgPath: %s", mod.Name, dir, pkgPath)
154+
fmt.Fprintf(os.Stderr, "[loadPackages] mod: %s, dir: %s, pkgPath: %s\n", mod.Name, dir, pkgPath)
155155
fset := token.NewFileSet()
156156
loadCount++
157157
// slow-path: load packages in the dir, including sub pakcages
@@ -181,6 +181,10 @@ func (p *GoParser) loadPackages(mod *Module, dir string, pkgPath PkgPath) (err e
181181
}
182182
next_file:
183183
for idx, file := range pkg.Syntax {
184+
if idx >= len(pkg.GoFiles) {
185+
fmt.Fprintf(os.Stderr, "skip file %s by loader\n", file.Name)
186+
continue
187+
}
184188
filePath := pkg.GoFiles[idx]
185189
for _, exclude := range p.exclues {
186190
if exclude.MatchString(filePath) {

0 commit comments

Comments
 (0)