17 "golang.org/x/mod/module"
18 "golang.org/x/tools/internal/gocommand"
19 "golang.org/x/tools/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 goenv, err := r.env.goEnv()
60 inv := gocommand.Invocation{
61 BuildFlags: r.env.BuildFlags,
62 ModFlag: r.env.ModFlag,
63 ModFile: r.env.ModFile,
66 WorkingDir: r.env.WorkingDir,
68 mainMod, vendorEnabled, err := gocommand.VendorEnabled(context.TODO(), inv, r.env.GocmdRunner)
73 if mainMod != nil && vendorEnabled {
74 // Vendor mode is on, so all the non-Main modules are irrelevant,
75 // and we need to search /vendor for everything.
77 r.dummyVendorMod = &gocommand.ModuleJSON{
79 Dir: filepath.Join(mainMod.Dir, "vendor"),
81 r.modsByModPath = []*gocommand.ModuleJSON{mainMod, r.dummyVendorMod}
82 r.modsByDir = []*gocommand.ModuleJSON{mainMod, r.dummyVendorMod}
84 // Vendor mode is off, so run go list -m ... to find everything.
88 if gmc := r.env.Env["GOMODCACHE"]; gmc != "" {
89 r.moduleCacheDir = gmc
91 r.moduleCacheDir = filepath.Join(filepath.SplitList(goenv["GOPATH"])[0], "/pkg/mod")
94 sort.Slice(r.modsByModPath, func(i, j int) bool {
95 count := func(x int) int {
96 return strings.Count(r.modsByModPath[x].Path, "/")
98 return count(j) < count(i) // descending order
100 sort.Slice(r.modsByDir, func(i, j int) bool {
101 count := func(x int) int {
102 return strings.Count(r.modsByDir[x].Dir, "/")
104 return count(j) < count(i) // descending order
107 r.roots = []gopathwalk.Root{
108 {filepath.Join(goenv["GOROOT"], "/src"), gopathwalk.RootGOROOT},
111 r.roots = append(r.roots, gopathwalk.Root{r.main.Dir, gopathwalk.RootCurrentModule})
114 r.roots = append(r.roots, gopathwalk.Root{r.dummyVendorMod.Dir, gopathwalk.RootOther})
116 addDep := func(mod *gocommand.ModuleJSON) {
117 if mod.Replace == nil {
118 // This is redundant with the cache, but we'll skip it cheaply enough.
119 r.roots = append(r.roots, gopathwalk.Root{mod.Dir, gopathwalk.RootModuleCache})
121 r.roots = append(r.roots, gopathwalk.Root{mod.Dir, gopathwalk.RootOther})
124 // Walk dependent modules before scanning the full mod cache, direct deps first.
125 for _, mod := range r.modsByModPath {
126 if !mod.Indirect && !mod.Main {
130 for _, mod := range r.modsByModPath {
131 if mod.Indirect && !mod.Main {
135 r.roots = append(r.roots, gopathwalk.Root{r.moduleCacheDir, gopathwalk.RootModuleCache})
138 r.scannedRoots = map[gopathwalk.Root]bool{}
139 if r.moduleCacheCache == nil {
140 r.moduleCacheCache = &dirInfoCache{
141 dirs: map[string]*directoryPackageInfo{},
142 listeners: map[*int]cacheListener{},
145 if r.otherCache == nil {
146 r.otherCache = &dirInfoCache{
147 dirs: map[string]*directoryPackageInfo{},
148 listeners: map[*int]cacheListener{},
155 func (r *ModuleResolver) initAllMods() error {
156 stdout, err := r.env.invokeGo(context.TODO(), "list", "-m", "-json", "...")
160 for dec := json.NewDecoder(stdout); dec.More(); {
161 mod := &gocommand.ModuleJSON{}
162 if err := dec.Decode(mod); err != nil {
166 if r.env.Logf != nil {
167 r.env.Logf("module %v has not been downloaded and will be ignored", mod.Path)
169 // Can't do anything with a module that's not downloaded.
172 // golang/go#36193: the go command doesn't always clean paths.
173 mod.Dir = filepath.Clean(mod.Dir)
174 r.modsByModPath = append(r.modsByModPath, mod)
175 r.modsByDir = append(r.modsByDir, mod)
183 func (r *ModuleResolver) ClearForNewScan() {
185 r.scannedRoots = map[gopathwalk.Root]bool{}
186 r.otherCache = &dirInfoCache{
187 dirs: map[string]*directoryPackageInfo{},
188 listeners: map[*int]cacheListener{},
190 r.scanSema <- struct{}{}
193 func (r *ModuleResolver) ClearForNewMod() {
197 moduleCacheCache: r.moduleCacheCache,
198 otherCache: r.otherCache,
199 scanSema: r.scanSema,
202 r.scanSema <- struct{}{}
205 // findPackage returns the module and directory that contains the package at
206 // the given import path, or returns nil, "" if no module is in scope.
207 func (r *ModuleResolver) findPackage(importPath string) (*gocommand.ModuleJSON, string) {
208 // This can't find packages in the stdlib, but that's harmless for all
209 // the existing code paths.
210 for _, m := range r.modsByModPath {
211 if !strings.HasPrefix(importPath, m.Path) {
214 pathInModule := importPath[len(m.Path):]
215 pkgDir := filepath.Join(m.Dir, pathInModule)
216 if r.dirIsNestedModule(pkgDir, m) {
220 if info, ok := r.cacheLoad(pkgDir); ok {
221 if loaded, err := info.reachedStatus(nameLoaded); loaded {
223 continue // No package in this dir.
227 if scanned, err := info.reachedStatus(directoryScanned); scanned && err != nil {
228 continue // Dir is unreadable, etc.
230 // This is slightly wrong: a directory doesn't have to have an
231 // importable package to count as a package for package-to-module
232 // resolution. package main or _test files should count but
234 // TODO(heschi): fix this.
235 if _, err := r.cachePackageName(info); err == nil {
240 // Not cached. Read the filesystem.
241 pkgFiles, err := ioutil.ReadDir(pkgDir)
245 // A module only contains a package if it has buildable go
246 // files in that directory. If not, it could be provided by an
247 // outer module. See #29736.
248 for _, fi := range pkgFiles {
249 if ok, _ := r.env.matchFile(pkgDir, fi.Name()); ok {
257 func (r *ModuleResolver) cacheLoad(dir string) (directoryPackageInfo, bool) {
258 if info, ok := r.moduleCacheCache.Load(dir); ok {
261 return r.otherCache.Load(dir)
264 func (r *ModuleResolver) cacheStore(info directoryPackageInfo) {
265 if info.rootType == gopathwalk.RootModuleCache {
266 r.moduleCacheCache.Store(info.dir, info)
268 r.otherCache.Store(info.dir, info)
272 func (r *ModuleResolver) cacheKeys() []string {
273 return append(r.moduleCacheCache.Keys(), r.otherCache.Keys()...)
276 // cachePackageName caches the package name for a dir already in the cache.
277 func (r *ModuleResolver) cachePackageName(info directoryPackageInfo) (string, error) {
278 if info.rootType == gopathwalk.RootModuleCache {
279 return r.moduleCacheCache.CachePackageName(info)
281 return r.otherCache.CachePackageName(info)
284 func (r *ModuleResolver) cacheExports(ctx context.Context, env *ProcessEnv, info directoryPackageInfo) (string, []string, error) {
285 if info.rootType == gopathwalk.RootModuleCache {
286 return r.moduleCacheCache.CacheExports(ctx, env, info)
288 return r.otherCache.CacheExports(ctx, env, info)
291 // findModuleByDir returns the module that contains dir, or nil if no such
292 // module is in scope.
293 func (r *ModuleResolver) findModuleByDir(dir string) *gocommand.ModuleJSON {
294 // This is quite tricky and may not be correct. dir could be:
295 // - a package in the main module.
296 // - a replace target underneath the main module's directory.
297 // - a nested module in the above.
298 // - a replace target somewhere totally random.
299 // - a nested module in the above.
300 // - in the mod cache.
301 // - in /vendor/ in -mod=vendor mode.
302 // - nested module? Dunno.
303 // Rumor has it that replace targets cannot contain other replace targets.
304 for _, m := range r.modsByDir {
305 if !strings.HasPrefix(dir, m.Dir) {
309 if r.dirIsNestedModule(dir, m) {
318 // dirIsNestedModule reports if dir is contained in a nested module underneath
319 // mod, not actually in mod.
320 func (r *ModuleResolver) dirIsNestedModule(dir string, mod *gocommand.ModuleJSON) bool {
321 if !strings.HasPrefix(dir, mod.Dir) {
324 if r.dirInModuleCache(dir) {
325 // Nested modules in the module cache are pruned,
326 // so it cannot be a nested module.
329 if mod != nil && mod == r.dummyVendorMod {
330 // The /vendor pseudomodule is flattened and doesn't actually count.
333 modDir, _ := r.modInfo(dir)
337 return modDir != mod.Dir
340 func (r *ModuleResolver) modInfo(dir string) (modDir string, modName string) {
341 readModName := func(modFile string) string {
342 modBytes, err := ioutil.ReadFile(modFile)
346 return modulePath(modBytes)
349 if r.dirInModuleCache(dir) {
350 matches := modCacheRegexp.FindStringSubmatch(dir)
351 index := strings.Index(dir, matches[1]+"@"+matches[2])
352 modDir := filepath.Join(dir[:index], matches[1]+"@"+matches[2])
353 return modDir, readModName(filepath.Join(modDir, "go.mod"))
356 if info, ok := r.cacheLoad(dir); ok {
357 return info.moduleDir, info.moduleName
359 f := filepath.Join(dir, "go.mod")
360 info, err := os.Stat(f)
361 if err == nil && !info.IsDir() {
362 return dir, readModName(f)
365 d := filepath.Dir(dir)
366 if len(d) >= len(dir) {
367 return "", "" // reached top of file system, no go.mod
373 func (r *ModuleResolver) dirInModuleCache(dir string) bool {
374 if r.moduleCacheDir == "" {
377 return strings.HasPrefix(dir, r.moduleCacheDir)
380 func (r *ModuleResolver) loadPackageNames(importPaths []string, srcDir string) (map[string]string, error) {
381 if err := r.init(); err != nil {
384 names := map[string]string{}
385 for _, path := range importPaths {
386 _, packageDir := r.findPackage(path)
387 if packageDir == "" {
390 name, err := packageDirToName(packageDir)
399 func (r *ModuleResolver) scan(ctx context.Context, callback *scanCallback) error {
400 if err := r.init(); err != nil {
404 processDir := func(info directoryPackageInfo) {
405 // Skip this directory if we were not able to get the package information successfully.
406 if scanned, err := info.reachedStatus(directoryScanned); !scanned || err != nil {
409 pkg, err := r.canonicalize(info)
414 if !callback.dirFound(pkg) {
417 pkg.packageName, err = r.cachePackageName(info)
422 if !callback.packageNameLoaded(pkg) {
425 _, exports, err := r.loadExports(ctx, pkg, false)
429 callback.exportsLoaded(pkg, exports)
432 // Start processing everything in the cache, and listen for the new stuff
433 // we discover in the walk below.
434 stop1 := r.moduleCacheCache.ScanAndListen(ctx, processDir)
436 stop2 := r.otherCache.ScanAndListen(ctx, processDir)
439 // We assume cached directories are fully cached, including all their
440 // children, and have not changed. We can skip them.
441 skip := func(root gopathwalk.Root, dir string) bool {
442 info, ok := r.cacheLoad(dir)
446 // This directory can be skipped as long as we have already scanned it.
447 // Packages with errors will continue to have errors, so there is no need
449 packageScanned, _ := info.reachedStatus(directoryScanned)
450 return packageScanned
453 // Add anything new to the cache, and process it if we're still listening.
454 add := func(root gopathwalk.Root, dir string) {
455 r.cacheStore(r.scanDirForPackage(root, dir))
458 // r.roots and the callback are not necessarily safe to use in the
459 // goroutine below. Process them eagerly.
460 roots := filterRoots(r.roots, callback.rootFound)
461 // We can't cancel walks, because we need them to finish to have a usable
462 // cache. Instead, run them in a separate goroutine and detach.
463 scanDone := make(chan struct{})
470 defer func() { r.scanSema <- struct{}{} }()
471 // We have the lock on r.scannedRoots, and no other scans can run.
472 for _, root := range roots {
473 if ctx.Err() != nil {
477 if r.scannedRoots[root] {
480 gopathwalk.WalkSkip([]gopathwalk.Root{root}, add, skip, gopathwalk.Options{Logf: r.env.Logf, ModulesEnabled: true})
481 r.scannedRoots[root] = true
492 func (r *ModuleResolver) scoreImportPath(ctx context.Context, path string) float64 {
493 if _, ok := stdlib[path]; ok {
496 mod, _ := r.findPackage(path)
497 return modRelevance(mod)
500 func modRelevance(mod *gocommand.ModuleJSON) float64 {
501 var relevance float64
503 case mod == nil: // out of scope
504 return MaxRelevance - 4
506 relevance = MaxRelevance - 3
508 relevance = MaxRelevance - 2
510 relevance = MaxRelevance - 1 // main module ties with stdlib
513 _, versionString, ok := module.SplitPathVersion(mod.Path)
515 index := strings.Index(versionString, "v")
519 if versionNumber, err := strconv.ParseFloat(versionString[index+1:], 64); err == nil {
520 relevance += versionNumber / 1000
527 // canonicalize gets the result of canonicalizing the packages using the results
528 // of initializing the resolver from 'go list -m'.
529 func (r *ModuleResolver) canonicalize(info directoryPackageInfo) (*pkg, error) {
530 // Packages in GOROOT are already canonical, regardless of the std/cmd modules.
531 if info.rootType == gopathwalk.RootGOROOT {
533 importPathShort: info.nonCanonicalImportPath,
535 packageName: path.Base(info.nonCanonicalImportPath),
536 relevance: MaxRelevance,
540 importPath := info.nonCanonicalImportPath
541 mod := r.findModuleByDir(info.dir)
542 // Check if the directory is underneath a module that's in scope.
544 // It is. If dir is the target of a replace directive,
545 // our guessed import path is wrong. Use the real one.
546 if mod.Dir == info.dir {
547 importPath = mod.Path
549 dirInMod := info.dir[len(mod.Dir)+len("/"):]
550 importPath = path.Join(mod.Path, filepath.ToSlash(dirInMod))
552 } else if !strings.HasPrefix(importPath, info.moduleName) {
553 // The module's name doesn't match the package's import path. It
554 // probably needs a replace directive we don't have.
555 return nil, fmt.Errorf("package in %q is not valid without a replace statement", info.dir)
559 importPathShort: importPath,
561 relevance: modRelevance(mod),
563 // We may have discovered a package that has a different version
564 // in scope already. Canonicalize to that one if possible.
565 if _, canonicalDir := r.findPackage(importPath); canonicalDir != "" {
566 res.dir = canonicalDir
571 func (r *ModuleResolver) loadExports(ctx context.Context, pkg *pkg, includeTest bool) (string, []string, error) {
572 if err := r.init(); err != nil {
575 if info, ok := r.cacheLoad(pkg.dir); ok && !includeTest {
576 return r.cacheExports(ctx, r.env, info)
578 return loadExportsFromFiles(ctx, r.env, pkg.dir, includeTest)
581 func (r *ModuleResolver) scanDirForPackage(root gopathwalk.Root, dir string) directoryPackageInfo {
583 if dir != root.Path {
584 subdir = dir[len(root.Path)+len("/"):]
586 importPath := filepath.ToSlash(subdir)
587 if strings.HasPrefix(importPath, "vendor/") {
588 // Only enter vendor directories if they're explicitly requested as a root.
589 return directoryPackageInfo{
590 status: directoryScanned,
591 err: fmt.Errorf("unwanted vendor directory"),
595 case gopathwalk.RootCurrentModule:
596 importPath = path.Join(r.main.Path, filepath.ToSlash(subdir))
597 case gopathwalk.RootModuleCache:
598 matches := modCacheRegexp.FindStringSubmatch(subdir)
599 if len(matches) == 0 {
600 return directoryPackageInfo{
601 status: directoryScanned,
602 err: fmt.Errorf("invalid module cache path: %v", subdir),
605 modPath, err := module.UnescapePath(filepath.ToSlash(matches[1]))
607 if r.env.Logf != nil {
608 r.env.Logf("decoding module cache path %q: %v", subdir, err)
610 return directoryPackageInfo{
611 status: directoryScanned,
612 err: fmt.Errorf("decoding module cache path %q: %v", subdir, err),
615 importPath = path.Join(modPath, filepath.ToSlash(matches[3]))
618 modDir, modName := r.modInfo(dir)
619 result := directoryPackageInfo{
620 status: directoryScanned,
623 nonCanonicalImportPath: importPath,
627 if root.Type == gopathwalk.RootGOROOT {
628 // stdlib packages are always in scope, despite the confusing go.mod
634 // modCacheRegexp splits a path in a module cache into module, module version, and package.
635 var modCacheRegexp = regexp.MustCompile(`(.*)@([^/\\]*)(.*)`)
638 slashSlash = []byte("//")
639 moduleStr = []byte("module")
642 // modulePath returns the module path from the gomod file text.
643 // If it cannot find a module path, it returns an empty string.
644 // It is tolerant of unrelated problems in the go.mod file.
646 // Copied from cmd/go/internal/modfile.
647 func modulePath(mod []byte) string {
651 if i := bytes.IndexByte(line, '\n'); i >= 0 {
652 line, mod = line[:i], line[i+1:]
654 if i := bytes.Index(line, slashSlash); i >= 0 {
657 line = bytes.TrimSpace(line)
658 if !bytes.HasPrefix(line, moduleStr) {
661 line = line[len(moduleStr):]
663 line = bytes.TrimSpace(line)
664 if len(line) == n || len(line) == 0 {
668 if line[0] == '"' || line[0] == '`' {
669 p, err := strconv.Unquote(string(line))
671 return "" // malformed quoted string or multiline module path
678 return "" // missing module path