1 // Copyright 2019 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
21 "golang.org/x/mod/module"
22 "golang.org/x/tools/internal/gocommand"
23 "golang.org/x/tools/internal/gopathwalk"
26 // ModuleResolver implements resolver for modules using the go command as little
28 type ModuleResolver struct {
31 dummyVendorMod *gocommand.ModuleJSON // If vendoring is enabled, the pseudo-module that represents the /vendor directory.
32 roots []gopathwalk.Root
33 scanSema chan struct{} // scanSema prevents concurrent scans and guards scannedRoots.
34 scannedRoots map[gopathwalk.Root]bool
37 main *gocommand.ModuleJSON
38 modsByModPath []*gocommand.ModuleJSON // All modules, ordered by # of path components in module Path...
39 modsByDir []*gocommand.ModuleJSON // ...or Dir.
41 // moduleCacheCache stores information about the module cache.
42 moduleCacheCache *dirInfoCache
43 otherCache *dirInfoCache
46 func newModuleResolver(e *ProcessEnv) *ModuleResolver {
49 scanSema: make(chan struct{}, 1),
51 r.scanSema <- struct{}{}
55 func (r *ModuleResolver) init() error {
60 goenv, err := r.env.goEnv()
64 inv := gocommand.Invocation{
65 BuildFlags: r.env.BuildFlags,
66 ModFlag: r.env.ModFlag,
67 ModFile: r.env.ModFile,
70 WorkingDir: r.env.WorkingDir,
72 mainMod, vendorEnabled, err := gocommand.VendorEnabled(context.TODO(), inv, r.env.GocmdRunner)
77 if mainMod != nil && vendorEnabled {
78 // Vendor mode is on, so all the non-Main modules are irrelevant,
79 // and we need to search /vendor for everything.
81 r.dummyVendorMod = &gocommand.ModuleJSON{
83 Dir: filepath.Join(mainMod.Dir, "vendor"),
85 r.modsByModPath = []*gocommand.ModuleJSON{mainMod, r.dummyVendorMod}
86 r.modsByDir = []*gocommand.ModuleJSON{mainMod, r.dummyVendorMod}
88 // Vendor mode is off, so run go list -m ... to find everything.
89 err := r.initAllMods()
90 // We expect an error when running outside of a module with
91 // GO111MODULE=on. Other errors are fatal.
92 if err != nil && !strings.Contains(err.Error(), "working directory is not part of a module") {
97 if gmc := r.env.Env["GOMODCACHE"]; gmc != "" {
98 r.moduleCacheDir = gmc
100 gopaths := filepath.SplitList(goenv["GOPATH"])
101 if len(gopaths) == 0 {
102 return fmt.Errorf("empty GOPATH")
104 r.moduleCacheDir = filepath.Join(gopaths[0], "/pkg/mod")
107 sort.Slice(r.modsByModPath, func(i, j int) bool {
108 count := func(x int) int {
109 return strings.Count(r.modsByModPath[x].Path, "/")
111 return count(j) < count(i) // descending order
113 sort.Slice(r.modsByDir, func(i, j int) bool {
114 count := func(x int) int {
115 return strings.Count(r.modsByDir[x].Dir, "/")
117 return count(j) < count(i) // descending order
120 r.roots = []gopathwalk.Root{
121 {filepath.Join(goenv["GOROOT"], "/src"), gopathwalk.RootGOROOT},
124 r.roots = append(r.roots, gopathwalk.Root{r.main.Dir, gopathwalk.RootCurrentModule})
127 r.roots = append(r.roots, gopathwalk.Root{r.dummyVendorMod.Dir, gopathwalk.RootOther})
129 addDep := func(mod *gocommand.ModuleJSON) {
130 if mod.Replace == nil {
131 // This is redundant with the cache, but we'll skip it cheaply enough.
132 r.roots = append(r.roots, gopathwalk.Root{mod.Dir, gopathwalk.RootModuleCache})
134 r.roots = append(r.roots, gopathwalk.Root{mod.Dir, gopathwalk.RootOther})
137 // Walk dependent modules before scanning the full mod cache, direct deps first.
138 for _, mod := range r.modsByModPath {
139 if !mod.Indirect && !mod.Main {
143 for _, mod := range r.modsByModPath {
144 if mod.Indirect && !mod.Main {
148 r.roots = append(r.roots, gopathwalk.Root{r.moduleCacheDir, gopathwalk.RootModuleCache})
151 r.scannedRoots = map[gopathwalk.Root]bool{}
152 if r.moduleCacheCache == nil {
153 r.moduleCacheCache = &dirInfoCache{
154 dirs: map[string]*directoryPackageInfo{},
155 listeners: map[*int]cacheListener{},
158 if r.otherCache == nil {
159 r.otherCache = &dirInfoCache{
160 dirs: map[string]*directoryPackageInfo{},
161 listeners: map[*int]cacheListener{},
168 func (r *ModuleResolver) initAllMods() error {
169 stdout, err := r.env.invokeGo(context.TODO(), "list", "-m", "-e", "-json", "...")
173 for dec := json.NewDecoder(stdout); dec.More(); {
174 mod := &gocommand.ModuleJSON{}
175 if err := dec.Decode(mod); err != nil {
179 if r.env.Logf != nil {
180 r.env.Logf("module %v has not been downloaded and will be ignored", mod.Path)
182 // Can't do anything with a module that's not downloaded.
185 // golang/go#36193: the go command doesn't always clean paths.
186 mod.Dir = filepath.Clean(mod.Dir)
187 r.modsByModPath = append(r.modsByModPath, mod)
188 r.modsByDir = append(r.modsByDir, mod)
196 func (r *ModuleResolver) ClearForNewScan() {
198 r.scannedRoots = map[gopathwalk.Root]bool{}
199 r.otherCache = &dirInfoCache{
200 dirs: map[string]*directoryPackageInfo{},
201 listeners: map[*int]cacheListener{},
203 r.scanSema <- struct{}{}
206 func (r *ModuleResolver) ClearForNewMod() {
210 moduleCacheCache: r.moduleCacheCache,
211 otherCache: r.otherCache,
212 scanSema: r.scanSema,
215 r.scanSema <- struct{}{}
218 // findPackage returns the module and directory that contains the package at
219 // the given import path, or returns nil, "" if no module is in scope.
220 func (r *ModuleResolver) findPackage(importPath string) (*gocommand.ModuleJSON, string) {
221 // This can't find packages in the stdlib, but that's harmless for all
222 // the existing code paths.
223 for _, m := range r.modsByModPath {
224 if !strings.HasPrefix(importPath, m.Path) {
227 pathInModule := importPath[len(m.Path):]
228 pkgDir := filepath.Join(m.Dir, pathInModule)
229 if r.dirIsNestedModule(pkgDir, m) {
233 if info, ok := r.cacheLoad(pkgDir); ok {
234 if loaded, err := info.reachedStatus(nameLoaded); loaded {
236 continue // No package in this dir.
240 if scanned, err := info.reachedStatus(directoryScanned); scanned && err != nil {
241 continue // Dir is unreadable, etc.
243 // This is slightly wrong: a directory doesn't have to have an
244 // importable package to count as a package for package-to-module
245 // resolution. package main or _test files should count but
247 // TODO(heschi): fix this.
248 if _, err := r.cachePackageName(info); err == nil {
253 // Not cached. Read the filesystem.
254 pkgFiles, err := ioutil.ReadDir(pkgDir)
258 // A module only contains a package if it has buildable go
259 // files in that directory. If not, it could be provided by an
260 // outer module. See #29736.
261 for _, fi := range pkgFiles {
262 if ok, _ := r.env.matchFile(pkgDir, fi.Name()); ok {
270 func (r *ModuleResolver) cacheLoad(dir string) (directoryPackageInfo, bool) {
271 if info, ok := r.moduleCacheCache.Load(dir); ok {
274 return r.otherCache.Load(dir)
277 func (r *ModuleResolver) cacheStore(info directoryPackageInfo) {
278 if info.rootType == gopathwalk.RootModuleCache {
279 r.moduleCacheCache.Store(info.dir, info)
281 r.otherCache.Store(info.dir, info)
285 func (r *ModuleResolver) cacheKeys() []string {
286 return append(r.moduleCacheCache.Keys(), r.otherCache.Keys()...)
289 // cachePackageName caches the package name for a dir already in the cache.
290 func (r *ModuleResolver) cachePackageName(info directoryPackageInfo) (string, error) {
291 if info.rootType == gopathwalk.RootModuleCache {
292 return r.moduleCacheCache.CachePackageName(info)
294 return r.otherCache.CachePackageName(info)
297 func (r *ModuleResolver) cacheExports(ctx context.Context, env *ProcessEnv, info directoryPackageInfo) (string, []string, error) {
298 if info.rootType == gopathwalk.RootModuleCache {
299 return r.moduleCacheCache.CacheExports(ctx, env, info)
301 return r.otherCache.CacheExports(ctx, env, info)
304 // findModuleByDir returns the module that contains dir, or nil if no such
305 // module is in scope.
306 func (r *ModuleResolver) findModuleByDir(dir string) *gocommand.ModuleJSON {
307 // This is quite tricky and may not be correct. dir could be:
308 // - a package in the main module.
309 // - a replace target underneath the main module's directory.
310 // - a nested module in the above.
311 // - a replace target somewhere totally random.
312 // - a nested module in the above.
313 // - in the mod cache.
314 // - in /vendor/ in -mod=vendor mode.
315 // - nested module? Dunno.
316 // Rumor has it that replace targets cannot contain other replace targets.
317 for _, m := range r.modsByDir {
318 if !strings.HasPrefix(dir, m.Dir) {
322 if r.dirIsNestedModule(dir, m) {
331 // dirIsNestedModule reports if dir is contained in a nested module underneath
332 // mod, not actually in mod.
333 func (r *ModuleResolver) dirIsNestedModule(dir string, mod *gocommand.ModuleJSON) bool {
334 if !strings.HasPrefix(dir, mod.Dir) {
337 if r.dirInModuleCache(dir) {
338 // Nested modules in the module cache are pruned,
339 // so it cannot be a nested module.
342 if mod != nil && mod == r.dummyVendorMod {
343 // The /vendor pseudomodule is flattened and doesn't actually count.
346 modDir, _ := r.modInfo(dir)
350 return modDir != mod.Dir
353 func (r *ModuleResolver) modInfo(dir string) (modDir string, modName string) {
354 readModName := func(modFile string) string {
355 modBytes, err := ioutil.ReadFile(modFile)
359 return modulePath(modBytes)
362 if r.dirInModuleCache(dir) {
363 if matches := modCacheRegexp.FindStringSubmatch(dir); len(matches) == 3 {
364 index := strings.Index(dir, matches[1]+"@"+matches[2])
365 modDir := filepath.Join(dir[:index], matches[1]+"@"+matches[2])
366 return modDir, readModName(filepath.Join(modDir, "go.mod"))
370 if info, ok := r.cacheLoad(dir); ok {
371 return info.moduleDir, info.moduleName
373 f := filepath.Join(dir, "go.mod")
374 info, err := os.Stat(f)
375 if err == nil && !info.IsDir() {
376 return dir, readModName(f)
379 d := filepath.Dir(dir)
380 if len(d) >= len(dir) {
381 return "", "" // reached top of file system, no go.mod
387 func (r *ModuleResolver) dirInModuleCache(dir string) bool {
388 if r.moduleCacheDir == "" {
391 return strings.HasPrefix(dir, r.moduleCacheDir)
394 func (r *ModuleResolver) loadPackageNames(importPaths []string, srcDir string) (map[string]string, error) {
395 if err := r.init(); err != nil {
398 names := map[string]string{}
399 for _, path := range importPaths {
400 _, packageDir := r.findPackage(path)
401 if packageDir == "" {
404 name, err := packageDirToName(packageDir)
413 func (r *ModuleResolver) scan(ctx context.Context, callback *scanCallback) error {
414 if err := r.init(); err != nil {
418 processDir := func(info directoryPackageInfo) {
419 // Skip this directory if we were not able to get the package information successfully.
420 if scanned, err := info.reachedStatus(directoryScanned); !scanned || err != nil {
423 pkg, err := r.canonicalize(info)
428 if !callback.dirFound(pkg) {
431 pkg.packageName, err = r.cachePackageName(info)
436 if !callback.packageNameLoaded(pkg) {
439 _, exports, err := r.loadExports(ctx, pkg, false)
443 callback.exportsLoaded(pkg, exports)
446 // Start processing everything in the cache, and listen for the new stuff
447 // we discover in the walk below.
448 stop1 := r.moduleCacheCache.ScanAndListen(ctx, processDir)
450 stop2 := r.otherCache.ScanAndListen(ctx, processDir)
453 // We assume cached directories are fully cached, including all their
454 // children, and have not changed. We can skip them.
455 skip := func(root gopathwalk.Root, dir string) bool {
456 info, ok := r.cacheLoad(dir)
460 // This directory can be skipped as long as we have already scanned it.
461 // Packages with errors will continue to have errors, so there is no need
463 packageScanned, _ := info.reachedStatus(directoryScanned)
464 return packageScanned
467 // Add anything new to the cache, and process it if we're still listening.
468 add := func(root gopathwalk.Root, dir string) {
469 r.cacheStore(r.scanDirForPackage(root, dir))
472 // r.roots and the callback are not necessarily safe to use in the
473 // goroutine below. Process them eagerly.
474 roots := filterRoots(r.roots, callback.rootFound)
475 // We can't cancel walks, because we need them to finish to have a usable
476 // cache. Instead, run them in a separate goroutine and detach.
477 scanDone := make(chan struct{})
484 defer func() { r.scanSema <- struct{}{} }()
485 // We have the lock on r.scannedRoots, and no other scans can run.
486 for _, root := range roots {
487 if ctx.Err() != nil {
491 if r.scannedRoots[root] {
494 gopathwalk.WalkSkip([]gopathwalk.Root{root}, add, skip, gopathwalk.Options{Logf: r.env.Logf, ModulesEnabled: true})
495 r.scannedRoots[root] = true
506 func (r *ModuleResolver) scoreImportPath(ctx context.Context, path string) float64 {
507 if _, ok := stdlib[path]; ok {
510 mod, _ := r.findPackage(path)
511 return modRelevance(mod)
514 func modRelevance(mod *gocommand.ModuleJSON) float64 {
515 var relevance float64
517 case mod == nil: // out of scope
518 return MaxRelevance - 4
520 relevance = MaxRelevance - 3
522 relevance = MaxRelevance - 2
524 relevance = MaxRelevance - 1 // main module ties with stdlib
527 _, versionString, ok := module.SplitPathVersion(mod.Path)
529 index := strings.Index(versionString, "v")
533 if versionNumber, err := strconv.ParseFloat(versionString[index+1:], 64); err == nil {
534 relevance += versionNumber / 1000
541 // canonicalize gets the result of canonicalizing the packages using the results
542 // of initializing the resolver from 'go list -m'.
543 func (r *ModuleResolver) canonicalize(info directoryPackageInfo) (*pkg, error) {
544 // Packages in GOROOT are already canonical, regardless of the std/cmd modules.
545 if info.rootType == gopathwalk.RootGOROOT {
547 importPathShort: info.nonCanonicalImportPath,
549 packageName: path.Base(info.nonCanonicalImportPath),
550 relevance: MaxRelevance,
554 importPath := info.nonCanonicalImportPath
555 mod := r.findModuleByDir(info.dir)
556 // Check if the directory is underneath a module that's in scope.
558 // It is. If dir is the target of a replace directive,
559 // our guessed import path is wrong. Use the real one.
560 if mod.Dir == info.dir {
561 importPath = mod.Path
563 dirInMod := info.dir[len(mod.Dir)+len("/"):]
564 importPath = path.Join(mod.Path, filepath.ToSlash(dirInMod))
566 } else if !strings.HasPrefix(importPath, info.moduleName) {
567 // The module's name doesn't match the package's import path. It
568 // probably needs a replace directive we don't have.
569 return nil, fmt.Errorf("package in %q is not valid without a replace statement", info.dir)
573 importPathShort: importPath,
575 relevance: modRelevance(mod),
577 // We may have discovered a package that has a different version
578 // in scope already. Canonicalize to that one if possible.
579 if _, canonicalDir := r.findPackage(importPath); canonicalDir != "" {
580 res.dir = canonicalDir
585 func (r *ModuleResolver) loadExports(ctx context.Context, pkg *pkg, includeTest bool) (string, []string, error) {
586 if err := r.init(); err != nil {
589 if info, ok := r.cacheLoad(pkg.dir); ok && !includeTest {
590 return r.cacheExports(ctx, r.env, info)
592 return loadExportsFromFiles(ctx, r.env, pkg.dir, includeTest)
595 func (r *ModuleResolver) scanDirForPackage(root gopathwalk.Root, dir string) directoryPackageInfo {
597 if dir != root.Path {
598 subdir = dir[len(root.Path)+len("/"):]
600 importPath := filepath.ToSlash(subdir)
601 if strings.HasPrefix(importPath, "vendor/") {
602 // Only enter vendor directories if they're explicitly requested as a root.
603 return directoryPackageInfo{
604 status: directoryScanned,
605 err: fmt.Errorf("unwanted vendor directory"),
609 case gopathwalk.RootCurrentModule:
610 importPath = path.Join(r.main.Path, filepath.ToSlash(subdir))
611 case gopathwalk.RootModuleCache:
612 matches := modCacheRegexp.FindStringSubmatch(subdir)
613 if len(matches) == 0 {
614 return directoryPackageInfo{
615 status: directoryScanned,
616 err: fmt.Errorf("invalid module cache path: %v", subdir),
619 modPath, err := module.UnescapePath(filepath.ToSlash(matches[1]))
621 if r.env.Logf != nil {
622 r.env.Logf("decoding module cache path %q: %v", subdir, err)
624 return directoryPackageInfo{
625 status: directoryScanned,
626 err: fmt.Errorf("decoding module cache path %q: %v", subdir, err),
629 importPath = path.Join(modPath, filepath.ToSlash(matches[3]))
632 modDir, modName := r.modInfo(dir)
633 result := directoryPackageInfo{
634 status: directoryScanned,
637 nonCanonicalImportPath: importPath,
641 if root.Type == gopathwalk.RootGOROOT {
642 // stdlib packages are always in scope, despite the confusing go.mod
648 // modCacheRegexp splits a path in a module cache into module, module version, and package.
649 var modCacheRegexp = regexp.MustCompile(`(.*)@([^/\\]*)(.*)`)
652 slashSlash = []byte("//")
653 moduleStr = []byte("module")
656 // modulePath returns the module path from the gomod file text.
657 // If it cannot find a module path, it returns an empty string.
658 // It is tolerant of unrelated problems in the go.mod file.
660 // Copied from cmd/go/internal/modfile.
661 func modulePath(mod []byte) string {
665 if i := bytes.IndexByte(line, '\n'); i >= 0 {
666 line, mod = line[:i], line[i+1:]
668 if i := bytes.Index(line, slashSlash); i >= 0 {
671 line = bytes.TrimSpace(line)
672 if !bytes.HasPrefix(line, moduleStr) {
675 line = line[len(moduleStr):]
677 line = bytes.TrimSpace(line)
678 if len(line) == n || len(line) == 0 {
682 if line[0] == '"' || line[0] == '`' {
683 p, err := strconv.Unquote(string(line))
685 return "" // malformed quoted string or multiline module path
692 return "" // missing module path