17 "golang.org/x/mod/module"
18 "mvdan.cc/gofumpt/gofumports/internal/gocommand"
19 "mvdan.cc/gofumpt/gofumports/internal/gopathwalk"
22 // ModuleResolver implements resolver for modules using the go command as little
24 type ModuleResolver struct {
27 dummyVendorMod *gocommand.ModuleJSON // If vendoring is enabled, the pseudo-module that represents the /vendor directory.
28 roots []gopathwalk.Root
29 scanSema chan struct{} // scanSema prevents concurrent scans and guards scannedRoots.
30 scannedRoots map[gopathwalk.Root]bool
33 main *gocommand.ModuleJSON
34 modsByModPath []*gocommand.ModuleJSON // All modules, ordered by # of path components in module Path...
35 modsByDir []*gocommand.ModuleJSON // ...or Dir.
37 // moduleCacheCache stores information about the module cache.
38 moduleCacheCache *dirInfoCache
39 otherCache *dirInfoCache
42 func newModuleResolver(e *ProcessEnv) *ModuleResolver {
45 scanSema: make(chan struct{}, 1),
47 r.scanSema <- struct{}{}
51 func (r *ModuleResolver) init() error {
56 inv := gocommand.Invocation{
57 BuildFlags: r.env.BuildFlags,
60 WorkingDir: r.env.WorkingDir,
62 mainMod, vendorEnabled, err := gocommand.VendorEnabled(context.TODO(), inv, r.env.GocmdRunner)
67 if mainMod != nil && vendorEnabled {
68 // Vendor mode is on, so all the non-Main modules are irrelevant,
69 // and we need to search /vendor for everything.
71 r.dummyVendorMod = &gocommand.ModuleJSON{
73 Dir: filepath.Join(mainMod.Dir, "vendor"),
75 r.modsByModPath = []*gocommand.ModuleJSON{mainMod, r.dummyVendorMod}
76 r.modsByDir = []*gocommand.ModuleJSON{mainMod, r.dummyVendorMod}
78 // Vendor mode is off, so run go list -m ... to find everything.
82 if gmc := r.env.Env["GOMODCACHE"]; gmc != "" {
83 r.moduleCacheDir = gmc
85 r.moduleCacheDir = filepath.Join(filepath.SplitList(r.env.gopath())[0], "/pkg/mod")
88 sort.Slice(r.modsByModPath, func(i, j int) bool {
89 count := func(x int) int {
90 return strings.Count(r.modsByModPath[x].Path, "/")
92 return count(j) < count(i) // descending order
94 sort.Slice(r.modsByDir, func(i, j int) bool {
95 count := func(x int) int {
96 return strings.Count(r.modsByDir[x].Dir, "/")
98 return count(j) < count(i) // descending order
101 r.roots = []gopathwalk.Root{
102 {filepath.Join(r.env.goroot(), "/src"), gopathwalk.RootGOROOT},
105 r.roots = append(r.roots, gopathwalk.Root{r.main.Dir, gopathwalk.RootCurrentModule})
108 r.roots = append(r.roots, gopathwalk.Root{r.dummyVendorMod.Dir, gopathwalk.RootOther})
110 addDep := func(mod *gocommand.ModuleJSON) {
111 if mod.Replace == nil {
112 // This is redundant with the cache, but we'll skip it cheaply enough.
113 r.roots = append(r.roots, gopathwalk.Root{mod.Dir, gopathwalk.RootModuleCache})
115 r.roots = append(r.roots, gopathwalk.Root{mod.Dir, gopathwalk.RootOther})
118 // Walk dependent modules before scanning the full mod cache, direct deps first.
119 for _, mod := range r.modsByModPath {
120 if !mod.Indirect && !mod.Main {
124 for _, mod := range r.modsByModPath {
125 if mod.Indirect && !mod.Main {
129 r.roots = append(r.roots, gopathwalk.Root{r.moduleCacheDir, gopathwalk.RootModuleCache})
132 r.scannedRoots = map[gopathwalk.Root]bool{}
133 if r.moduleCacheCache == nil {
134 r.moduleCacheCache = &dirInfoCache{
135 dirs: map[string]*directoryPackageInfo{},
136 listeners: map[*int]cacheListener{},
139 if r.otherCache == nil {
140 r.otherCache = &dirInfoCache{
141 dirs: map[string]*directoryPackageInfo{},
142 listeners: map[*int]cacheListener{},
149 func (r *ModuleResolver) initAllMods() error {
150 stdout, err := r.env.invokeGo(context.TODO(), "list", "-m", "-json", "...")
154 for dec := json.NewDecoder(stdout); dec.More(); {
155 mod := &gocommand.ModuleJSON{}
156 if err := dec.Decode(mod); err != nil {
160 if r.env.Logf != nil {
161 r.env.Logf("module %v has not been downloaded and will be ignored", mod.Path)
163 // Can't do anything with a module that's not downloaded.
166 // golang/go#36193: the go command doesn't always clean paths.
167 mod.Dir = filepath.Clean(mod.Dir)
168 r.modsByModPath = append(r.modsByModPath, mod)
169 r.modsByDir = append(r.modsByDir, mod)
177 func (r *ModuleResolver) ClearForNewScan() {
179 r.scannedRoots = map[gopathwalk.Root]bool{}
180 r.otherCache = &dirInfoCache{
181 dirs: map[string]*directoryPackageInfo{},
182 listeners: map[*int]cacheListener{},
184 r.scanSema <- struct{}{}
187 func (r *ModuleResolver) ClearForNewMod() {
191 moduleCacheCache: r.moduleCacheCache,
192 otherCache: r.otherCache,
193 scanSema: r.scanSema,
196 r.scanSema <- struct{}{}
199 // findPackage returns the module and directory that contains the package at
200 // the given import path, or returns nil, "" if no module is in scope.
201 func (r *ModuleResolver) findPackage(importPath string) (*gocommand.ModuleJSON, string) {
202 // This can't find packages in the stdlib, but that's harmless for all
203 // the existing code paths.
204 for _, m := range r.modsByModPath {
205 if !strings.HasPrefix(importPath, m.Path) {
208 pathInModule := importPath[len(m.Path):]
209 pkgDir := filepath.Join(m.Dir, pathInModule)
210 if r.dirIsNestedModule(pkgDir, m) {
214 if info, ok := r.cacheLoad(pkgDir); ok {
215 if loaded, err := info.reachedStatus(nameLoaded); loaded {
217 continue // No package in this dir.
221 if scanned, err := info.reachedStatus(directoryScanned); scanned && err != nil {
222 continue // Dir is unreadable, etc.
224 // This is slightly wrong: a directory doesn't have to have an
225 // importable package to count as a package for package-to-module
226 // resolution. package main or _test files should count but
228 // TODO(heschi): fix this.
229 if _, err := r.cachePackageName(info); err == nil {
234 // Not cached. Read the filesystem.
235 pkgFiles, err := ioutil.ReadDir(pkgDir)
239 // A module only contains a package if it has buildable go
240 // files in that directory. If not, it could be provided by an
241 // outer module. See #29736.
242 for _, fi := range pkgFiles {
243 if ok, _ := r.env.buildContext().MatchFile(pkgDir, fi.Name()); ok {
251 func (r *ModuleResolver) cacheLoad(dir string) (directoryPackageInfo, bool) {
252 if info, ok := r.moduleCacheCache.Load(dir); ok {
255 return r.otherCache.Load(dir)
258 func (r *ModuleResolver) cacheStore(info directoryPackageInfo) {
259 if info.rootType == gopathwalk.RootModuleCache {
260 r.moduleCacheCache.Store(info.dir, info)
262 r.otherCache.Store(info.dir, info)
266 func (r *ModuleResolver) cacheKeys() []string {
267 return append(r.moduleCacheCache.Keys(), r.otherCache.Keys()...)
270 // cachePackageName caches the package name for a dir already in the cache.
271 func (r *ModuleResolver) cachePackageName(info directoryPackageInfo) (string, error) {
272 if info.rootType == gopathwalk.RootModuleCache {
273 return r.moduleCacheCache.CachePackageName(info)
275 return r.otherCache.CachePackageName(info)
278 func (r *ModuleResolver) cacheExports(ctx context.Context, env *ProcessEnv, info directoryPackageInfo) (string, []string, error) {
279 if info.rootType == gopathwalk.RootModuleCache {
280 return r.moduleCacheCache.CacheExports(ctx, env, info)
282 return r.otherCache.CacheExports(ctx, env, info)
285 // findModuleByDir returns the module that contains dir, or nil if no such
286 // module is in scope.
287 func (r *ModuleResolver) findModuleByDir(dir string) *gocommand.ModuleJSON {
288 // This is quite tricky and may not be correct. dir could be:
289 // - a package in the main module.
290 // - a replace target underneath the main module's directory.
291 // - a nested module in the above.
292 // - a replace target somewhere totally random.
293 // - a nested module in the above.
294 // - in the mod cache.
295 // - in /vendor/ in -mod=vendor mode.
296 // - nested module? Dunno.
297 // Rumor has it that replace targets cannot contain other replace targets.
298 for _, m := range r.modsByDir {
299 if !strings.HasPrefix(dir, m.Dir) {
303 if r.dirIsNestedModule(dir, m) {
312 // dirIsNestedModule reports if dir is contained in a nested module underneath
313 // mod, not actually in mod.
314 func (r *ModuleResolver) dirIsNestedModule(dir string, mod *gocommand.ModuleJSON) bool {
315 if !strings.HasPrefix(dir, mod.Dir) {
318 if r.dirInModuleCache(dir) {
319 // Nested modules in the module cache are pruned,
320 // so it cannot be a nested module.
323 if mod != nil && mod == r.dummyVendorMod {
324 // The /vendor pseudomodule is flattened and doesn't actually count.
327 modDir, _ := r.modInfo(dir)
331 return modDir != mod.Dir
334 func (r *ModuleResolver) modInfo(dir string) (modDir string, modName string) {
335 readModName := func(modFile string) string {
336 modBytes, err := ioutil.ReadFile(modFile)
340 return modulePath(modBytes)
343 if r.dirInModuleCache(dir) {
344 matches := modCacheRegexp.FindStringSubmatch(dir)
345 index := strings.Index(dir, matches[1]+"@"+matches[2])
346 modDir := filepath.Join(dir[:index], matches[1]+"@"+matches[2])
347 return modDir, readModName(filepath.Join(modDir, "go.mod"))
350 if info, ok := r.cacheLoad(dir); ok {
351 return info.moduleDir, info.moduleName
353 f := filepath.Join(dir, "go.mod")
354 info, err := os.Stat(f)
355 if err == nil && !info.IsDir() {
356 return dir, readModName(f)
359 d := filepath.Dir(dir)
360 if len(d) >= len(dir) {
361 return "", "" // reached top of file system, no go.mod
367 func (r *ModuleResolver) dirInModuleCache(dir string) bool {
368 if r.moduleCacheDir == "" {
371 return strings.HasPrefix(dir, r.moduleCacheDir)
374 func (r *ModuleResolver) loadPackageNames(importPaths []string, srcDir string) (map[string]string, error) {
375 if err := r.init(); err != nil {
378 names := map[string]string{}
379 for _, path := range importPaths {
380 _, packageDir := r.findPackage(path)
381 if packageDir == "" {
384 name, err := packageDirToName(packageDir)
393 func (r *ModuleResolver) scan(ctx context.Context, callback *scanCallback) error {
394 if err := r.init(); err != nil {
398 processDir := func(info directoryPackageInfo) {
399 // Skip this directory if we were not able to get the package information successfully.
400 if scanned, err := info.reachedStatus(directoryScanned); !scanned || err != nil {
403 pkg, err := r.canonicalize(info)
408 if !callback.dirFound(pkg) {
411 pkg.packageName, err = r.cachePackageName(info)
416 if !callback.packageNameLoaded(pkg) {
419 _, exports, err := r.loadExports(ctx, pkg, false)
423 callback.exportsLoaded(pkg, exports)
426 // Start processing everything in the cache, and listen for the new stuff
427 // we discover in the walk below.
428 stop1 := r.moduleCacheCache.ScanAndListen(ctx, processDir)
430 stop2 := r.otherCache.ScanAndListen(ctx, processDir)
433 // We assume cached directories are fully cached, including all their
434 // children, and have not changed. We can skip them.
435 skip := func(root gopathwalk.Root, dir string) bool {
436 info, ok := r.cacheLoad(dir)
440 // This directory can be skipped as long as we have already scanned it.
441 // Packages with errors will continue to have errors, so there is no need
443 packageScanned, _ := info.reachedStatus(directoryScanned)
444 return packageScanned
447 // Add anything new to the cache, and process it if we're still listening.
448 add := func(root gopathwalk.Root, dir string) {
449 r.cacheStore(r.scanDirForPackage(root, dir))
452 // r.roots and the callback are not necessarily safe to use in the
453 // goroutine below. Process them eagerly.
454 roots := filterRoots(r.roots, callback.rootFound)
455 // We can't cancel walks, because we need them to finish to have a usable
456 // cache. Instead, run them in a separate goroutine and detach.
457 scanDone := make(chan struct{})
464 defer func() { r.scanSema <- struct{}{} }()
465 // We have the lock on r.scannedRoots, and no other scans can run.
466 for _, root := range roots {
467 if ctx.Err() != nil {
471 if r.scannedRoots[root] {
474 gopathwalk.WalkSkip([]gopathwalk.Root{root}, add, skip, gopathwalk.Options{Logf: r.env.Logf, ModulesEnabled: true})
475 r.scannedRoots[root] = true
486 func (r *ModuleResolver) scoreImportPath(ctx context.Context, path string) int {
487 if _, ok := stdlib[path]; ok {
490 mod, _ := r.findPackage(path)
491 return modRelevance(mod)
494 func modRelevance(mod *gocommand.ModuleJSON) int {
496 case mod == nil: // out of scope
497 return MaxRelevance - 4
499 return MaxRelevance - 3
501 return MaxRelevance - 2
503 return MaxRelevance - 1 // main module ties with stdlib
507 // canonicalize gets the result of canonicalizing the packages using the results
508 // of initializing the resolver from 'go list -m'.
509 func (r *ModuleResolver) canonicalize(info directoryPackageInfo) (*pkg, error) {
510 // Packages in GOROOT are already canonical, regardless of the std/cmd modules.
511 if info.rootType == gopathwalk.RootGOROOT {
513 importPathShort: info.nonCanonicalImportPath,
515 packageName: path.Base(info.nonCanonicalImportPath),
516 relevance: MaxRelevance,
520 importPath := info.nonCanonicalImportPath
521 mod := r.findModuleByDir(info.dir)
522 // Check if the directory is underneath a module that's in scope.
524 // It is. If dir is the target of a replace directive,
525 // our guessed import path is wrong. Use the real one.
526 if mod.Dir == info.dir {
527 importPath = mod.Path
529 dirInMod := info.dir[len(mod.Dir)+len("/"):]
530 importPath = path.Join(mod.Path, filepath.ToSlash(dirInMod))
532 } else if !strings.HasPrefix(importPath, info.moduleName) {
533 // The module's name doesn't match the package's import path. It
534 // probably needs a replace directive we don't have.
535 return nil, fmt.Errorf("package in %q is not valid without a replace statement", info.dir)
539 importPathShort: importPath,
541 relevance: modRelevance(mod),
543 // We may have discovered a package that has a different version
544 // in scope already. Canonicalize to that one if possible.
545 if _, canonicalDir := r.findPackage(importPath); canonicalDir != "" {
546 res.dir = canonicalDir
551 func (r *ModuleResolver) loadExports(ctx context.Context, pkg *pkg, includeTest bool) (string, []string, error) {
552 if err := r.init(); err != nil {
555 if info, ok := r.cacheLoad(pkg.dir); ok && !includeTest {
556 return r.cacheExports(ctx, r.env, info)
558 return loadExportsFromFiles(ctx, r.env, pkg.dir, includeTest)
561 func (r *ModuleResolver) scanDirForPackage(root gopathwalk.Root, dir string) directoryPackageInfo {
563 if dir != root.Path {
564 subdir = dir[len(root.Path)+len("/"):]
566 importPath := filepath.ToSlash(subdir)
567 if strings.HasPrefix(importPath, "vendor/") {
568 // Only enter vendor directories if they're explicitly requested as a root.
569 return directoryPackageInfo{
570 status: directoryScanned,
571 err: fmt.Errorf("unwanted vendor directory"),
575 case gopathwalk.RootCurrentModule:
576 importPath = path.Join(r.main.Path, filepath.ToSlash(subdir))
577 case gopathwalk.RootModuleCache:
578 matches := modCacheRegexp.FindStringSubmatch(subdir)
579 if len(matches) == 0 {
580 return directoryPackageInfo{
581 status: directoryScanned,
582 err: fmt.Errorf("invalid module cache path: %v", subdir),
585 modPath, err := module.UnescapePath(filepath.ToSlash(matches[1]))
587 if r.env.Logf != nil {
588 r.env.Logf("decoding module cache path %q: %v", subdir, err)
590 return directoryPackageInfo{
591 status: directoryScanned,
592 err: fmt.Errorf("decoding module cache path %q: %v", subdir, err),
595 importPath = path.Join(modPath, filepath.ToSlash(matches[3]))
598 modDir, modName := r.modInfo(dir)
599 result := directoryPackageInfo{
600 status: directoryScanned,
603 nonCanonicalImportPath: importPath,
607 if root.Type == gopathwalk.RootGOROOT {
608 // stdlib packages are always in scope, despite the confusing go.mod
614 // modCacheRegexp splits a path in a module cache into module, module version, and package.
615 var modCacheRegexp = regexp.MustCompile(`(.*)@([^/\\]*)(.*)`)
618 slashSlash = []byte("//")
619 moduleStr = []byte("module")
622 // modulePath returns the module path from the gomod file text.
623 // If it cannot find a module path, it returns an empty string.
624 // It is tolerant of unrelated problems in the go.mod file.
626 // Copied from cmd/go/internal/modfile.
627 func modulePath(mod []byte) string {
631 if i := bytes.IndexByte(line, '\n'); i >= 0 {
632 line, mod = line[:i], line[i+1:]
634 if i := bytes.Index(line, slashSlash); i >= 0 {
637 line = bytes.TrimSpace(line)
638 if !bytes.HasPrefix(line, moduleStr) {
641 line = line[len(moduleStr):]
643 line = bytes.TrimSpace(line)
644 if len(line) == n || len(line) == 0 {
648 if line[0] == '"' || line[0] == '`' {
649 p, err := strconv.Unquote(string(line))
651 return "" // malformed quoted string or multiline module path
658 return "" // missing module path