Debian Codegraph @

internal/imports/mod.go

raw symbols SCIP
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.
4
5 package imports
6
7 import (
8 "bytes"
9 "context"
10 "encoding/json"
11 "fmt"
12 "os"
13 "path"
14 "path/filepath"
15 "regexp"
16 "slices"
17 "sort"
18 "strconv"
19 "strings"
20
21 "golang.org/x/mod/module"
22 "golang.org/x/tools/internal/event"
23 "golang.org/x/tools/internal/gocommand"
24 "golang.org/x/tools/internal/gopathwalk"
25 "golang.org/x/tools/internal/stdlib"
26 )
27
28 // Notes(rfindley): ModuleResolver appears to be heavily optimized for scanning
29 // as fast as possible, which is desirable for a call to goimports from the
30 // command line, but it doesn't work as well for gopls, where it suffers from
31 // slow startup (golang/go#44863) and intermittent hanging (golang/go#59216),
32 // both caused by populating the cache, albeit in slightly different ways.
33 //
34 // A high level list of TODOs:
35 // - Optimize the scan itself, as there is some redundancy statting and
36 // reading go.mod files.
37 // - Invert the relationship between ProcessEnv and Resolver (see the
38 // docstring of ProcessEnv).
39 // - Make it easier to use an external resolver implementation.
40 //
41 // Smaller TODOs are annotated in the code below.
42
43 // ModuleResolver implements the Resolver interface for a workspace using
44 // modules.
45 //
46 // A goal of the ModuleResolver is to invoke the Go command as little as
47 // possible. To this end, it runs the Go command only for listing module
48 // information (i.e. `go list -m -e -json ...`). Package scanning, the process
49 // of loading package information for the modules, is implemented internally
50 // via the scan method.
51 //
52 // It has two types of state: the state derived from the go command, which
53 // is populated by init, and the state derived from scans, which is populated
54 // via scan. A root is considered scanned if it has been walked to discover
55 // directories. However, if the scan did not require additional information
56 // from the directory (such as package name or exports), the directory
57 // information itself may be partially populated. It will be lazily filled in
58 // as needed by scans, using the scanCallback.
59 type ModuleResolver struct {
60 env *ProcessEnv
61
62 // Module state, populated during construction
63 dummyVendorMod *gocommand.ModuleJSON // if vendoring is enabled, a pseudo-module to represent the /vendor directory
64 moduleCacheDir string // GOMODCACHE, inferred from GOPATH if unset
65 roots []gopathwalk.Root // roots to scan, in approximate order of importance
66 mains []*gocommand.ModuleJSON // main modules
67 mainByDir map[string]*gocommand.ModuleJSON // module information by dir, to join with roots
68 modsByModPath []*gocommand.ModuleJSON // all modules, ordered by # of path components in their module path
69 modsByDir []*gocommand.ModuleJSON // ...or by the number of path components in their Dir.
70
71 // Scanning state, populated by scan
72
73 // scanSema prevents concurrent scans, and guards scannedRoots and the cache
74 // fields below (though the caches themselves are concurrency safe).
75 // Receive to acquire, send to release.
76 scanSema chan struct{}
77 scannedRoots map[gopathwalk.Root]bool // if true, root has been walked
78
79 // Caches of directory info, populated by scans and scan callbacks
80 //
81 // moduleCacheCache stores cached information about roots in the module
82 // cache, which are immutable and therefore do not need to be invalidated.
83 //
84 // otherCache stores information about all other roots (even GOROOT), which
85 // may change.
86 moduleCacheCache *DirInfoCache
87 otherCache *DirInfoCache
88 }
89
90 // newModuleResolver returns a new module-aware goimports resolver.
91 //
92 // Note: use caution when modifying this constructor: changes must also be
93 // reflected in ModuleResolver.ClearForNewScan.
94 func newModuleResolver(e *ProcessEnv, moduleCacheCache *DirInfoCache) (*ModuleResolver, error) {
95 r := &ModuleResolver{
96 env: e,
97 scanSema: make(chan struct{}, 1),
98 }
99 r.scanSema <- struct{}{} // release
100
101 goenv, err := r.env.goEnv()
102 if err != nil {
103 return nil, err
104 }
105
106 // TODO(rfindley): can we refactor to share logic with r.env.invokeGo?
107 inv := gocommand.Invocation{
108 BuildFlags: r.env.BuildFlags,
109 ModFlag: r.env.ModFlag,
110 Env: r.env.env(),
111 Logf: r.env.Logf,
112 WorkingDir: r.env.WorkingDir,
113 }
114
115 vendorEnabled := false
116 var mainModVendor *gocommand.ModuleJSON // for module vendoring
117 var mainModsVendor []*gocommand.ModuleJSON // for workspace vendoring
118
119 goWork := r.env.Env["GOWORK"]
120 if len(goWork) == 0 {
121 // TODO(rfindley): VendorEnabled runs the go command to get GOFLAGS, but
122 // they should be available from the ProcessEnv. Can we avoid the redundant
123 // invocation?
124 vendorEnabled, mainModVendor, err = gocommand.VendorEnabled(context.TODO(), inv, r.env.GocmdRunner)
125 if err != nil {
126 return nil, err
127 }
128 } else {
129 vendorEnabled, mainModsVendor, err = gocommand.WorkspaceVendorEnabled(context.Background(), inv, r.env.GocmdRunner)
130 if err != nil {
131 return nil, err
132 }
133 }
134
135 if vendorEnabled {
136 if mainModVendor != nil {
137 // Module vendor mode is on, so all the non-Main modules are irrelevant,
138 // and we need to search /vendor for everything.
139 r.mains = []*gocommand.ModuleJSON{mainModVendor}
140 r.dummyVendorMod = &gocommand.ModuleJSON{
141 Path: "",
142 Dir: filepath.Join(mainModVendor.Dir, "vendor"),
143 }
144 r.modsByModPath = []*gocommand.ModuleJSON{mainModVendor, r.dummyVendorMod}
145 r.modsByDir = []*gocommand.ModuleJSON{mainModVendor, r.dummyVendorMod}
146 } else {
147 // Workspace vendor mode is on, so all the non-Main modules are irrelevant,
148 // and we need to search /vendor for everything.
149 r.mains = mainModsVendor
150 r.dummyVendorMod = &gocommand.ModuleJSON{
151 Path: "",
152 Dir: filepath.Join(filepath.Dir(goWork), "vendor"),
153 }
154 r.modsByModPath = append(slices.Clone(mainModsVendor), r.dummyVendorMod)
155 r.modsByDir = append(slices.Clone(mainModsVendor), r.dummyVendorMod)
156 }
157 } else {
158 // Vendor mode is off, so run go list -m ... to find everything.
159 err := r.initAllMods()
160 // We expect an error when running outside of a module with
161 // GO111MODULE=on. Other errors are fatal.
162 if err != nil {
163 if errMsg := err.Error(); !strings.Contains(errMsg, "working directory is not part of a module") && !strings.Contains(errMsg, "go.mod file not found") {
164 return nil, err
165 }
166 }
167 }
168
169 r.moduleCacheDir = gomodcacheForEnv(goenv)
170 if r.moduleCacheDir == "" {
171 return nil, fmt.Errorf("cannot resolve GOMODCACHE")
172 }
173
174 sort.Slice(r.modsByModPath, func(i, j int) bool {
175 count := func(x int) int {
176 return strings.Count(r.modsByModPath[x].Path, "/")
177 }
178 return count(j) < count(i) // descending order
179 })
180 sort.Slice(r.modsByDir, func(i, j int) bool {
181 count := func(x int) int {
182 return strings.Count(r.modsByDir[x].Dir, string(filepath.Separator))
183 }
184 return count(j) < count(i) // descending order
185 })
186
187 r.roots = []gopathwalk.Root{}
188 if goenv["GOROOT"] != "" { // "" happens in tests
189 r.roots = append(r.roots, gopathwalk.Root{Path: filepath.Join(goenv["GOROOT"], "/src"), Type: gopathwalk.RootGOROOT})
190 }
191 r.mainByDir = make(map[string]*gocommand.ModuleJSON)
192 for _, main := range r.mains {
193 r.roots = append(r.roots, gopathwalk.Root{Path: main.Dir, Type: gopathwalk.RootCurrentModule})
194 r.mainByDir[main.Dir] = main
195 }
196 if vendorEnabled {
197 r.roots = append(r.roots, gopathwalk.Root{Path: r.dummyVendorMod.Dir, Type: gopathwalk.RootOther})
198 } else {
199 addDep := func(mod *gocommand.ModuleJSON) {
200 if mod.Replace == nil {
201 // This is redundant with the cache, but we'll skip it cheaply enough
202 // when we encounter it in the module cache scan.
203 //
204 // Including it at a lower index in r.roots than the module cache dir
205 // helps prioritize matches from within existing dependencies.
206 r.roots = append(r.roots, gopathwalk.Root{Path: mod.Dir, Type: gopathwalk.RootModuleCache})
207 } else {
208 r.roots = append(r.roots, gopathwalk.Root{Path: mod.Dir, Type: gopathwalk.RootOther})
209 }
210 }
211 // Walk dependent modules before scanning the full mod cache, direct deps first.
212 for _, mod := range r.modsByModPath {
213 if !mod.Indirect && !mod.Main {
214 addDep(mod)
215 }
216 }
217 for _, mod := range r.modsByModPath {
218 if mod.Indirect && !mod.Main {
219 addDep(mod)
220 }
221 }
222 // If provided, share the moduleCacheCache.
223 //
224 // TODO(rfindley): The module cache is immutable. However, the loaded
225 // exports do depend on GOOS and GOARCH. Fortunately, the
226 // ProcessEnv.buildContext does not adjust these from build.DefaultContext
227 // (even though it should). So for now, this is OK to share, but we need to
228 // add logic for handling GOOS/GOARCH.
229 r.moduleCacheCache = moduleCacheCache
230 r.roots = append(r.roots, gopathwalk.Root{Path: r.moduleCacheDir, Type: gopathwalk.RootModuleCache})
231 }
232
233 r.scannedRoots = map[gopathwalk.Root]bool{}
234 if r.moduleCacheCache == nil {
235 r.moduleCacheCache = NewDirInfoCache()
236 }
237 r.otherCache = NewDirInfoCache()
238 return r, nil
239 }
240
241 // gomodcacheForEnv returns the GOMODCACHE value to use based on the given env
242 // map, which must have GOMODCACHE and GOPATH populated.
243 //
244 // TODO(rfindley): this is defensive refactoring.
245 // 1. Is this even relevant anymore? Can't we just read GOMODCACHE.
246 // 2. Use this to separate module cache scanning from other scanning.
247 func gomodcacheForEnv(goenv map[string]string) string {
248 if gmc := goenv["GOMODCACHE"]; gmc != "" {
249 // golang/go#67156: ensure that the module cache is clean, since it is
250 // assumed as a prefix to directories scanned by gopathwalk, which are
251 // themselves clean.
252 return filepath.Clean(gmc)
253 }
254 gopaths := filepath.SplitList(goenv["GOPATH"])
255 if len(gopaths) == 0 {
256 return ""
257 }
258 return filepath.Join(gopaths[0], "/pkg/mod")
259 }
260
261 func (r *ModuleResolver) initAllMods() error {
262 stdout, err := r.env.invokeGo(context.TODO(), "list", "-m", "-e", "-json", "...")
263 if err != nil {
264 return err
265 }
266 for dec := json.NewDecoder(stdout); dec.More(); {
267 mod := &gocommand.ModuleJSON{}
268 if err := dec.Decode(mod); err != nil {
269 return err
270 }
271 if mod.Dir == "" {
272 r.env.logf("module %v has not been downloaded and will be ignored", mod.Path)
273 // Can't do anything with a module that's not downloaded.
274 continue
275 }
276 // golang/go#36193: the go command doesn't always clean paths.
277 mod.Dir = filepath.Clean(mod.Dir)
278 r.modsByModPath = append(r.modsByModPath, mod)
279 r.modsByDir = append(r.modsByDir, mod)
280 if mod.Main {
281 r.mains = append(r.mains, mod)
282 }
283 }
284 return nil
285 }
286
287 // ClearForNewScan invalidates the last scan.
288 //
289 // It preserves the set of roots, but forgets about the set of directories.
290 // Though it forgets the set of module cache directories, it remembers their
291 // contents, since they are assumed to be immutable.
292 func (r *ModuleResolver) ClearForNewScan() Resolver {
293 <-r.scanSema // acquire r, to guard scannedRoots
294 r2 := &ModuleResolver{
295 env: r.env,
296 dummyVendorMod: r.dummyVendorMod,
297 moduleCacheDir: r.moduleCacheDir,
298 roots: r.roots,
299 mains: r.mains,
300 mainByDir: r.mainByDir,
301 modsByModPath: r.modsByModPath,
302
303 scanSema: make(chan struct{}, 1),
304 scannedRoots: make(map[gopathwalk.Root]bool),
305 otherCache: NewDirInfoCache(),
306 moduleCacheCache: r.moduleCacheCache,
307 }
308 r2.scanSema <- struct{}{} // r2 must start released
309 // Invalidate root scans. We don't need to invalidate module cache roots,
310 // because they are immutable.
311 // (We don't support a use case where GOMODCACHE is cleaned in the middle of
312 // e.g. a gopls session: the user must restart gopls to get accurate
313 // imports.)
314 //
315 // Scanning for new directories in GOMODCACHE should be handled elsewhere,
316 // via a call to ScanModuleCache.
317 for _, root := range r.roots {
318 if root.Type == gopathwalk.RootModuleCache && r.scannedRoots[root] {
319 r2.scannedRoots[root] = true
320 }
321 }
322 r.scanSema <- struct{}{} // release r
323 return r2
324 }
325
326 // ClearModuleInfo invalidates resolver state that depends on go.mod file
327 // contents (essentially, the output of go list -m -json ...).
328 //
329 // Notably, it does not forget directory contents, which are reset
330 // asynchronously via ClearForNewScan.
331 //
332 // If the ProcessEnv is a GOPATH environment, ClearModuleInfo is a no op.
333 //
334 // TODO(rfindley): move this to a new env.go, consolidating ProcessEnv methods.
335 func (e *ProcessEnv) ClearModuleInfo() {
336 if r, ok := e.resolver.(*ModuleResolver); ok {
337 resolver, err := newModuleResolver(e, e.ModCache)
338 if err != nil {
339 e.resolver = nil
340 e.resolverErr = err
341 return
342 }
343
344 <-r.scanSema // acquire (guards caches)
345 resolver.moduleCacheCache = r.moduleCacheCache
346 resolver.otherCache = r.otherCache
347 r.scanSema <- struct{}{} // release
348
349 e.UpdateResolver(resolver)
350 }
351 }
352
353 // UpdateResolver sets the resolver for the ProcessEnv to use in imports
354 // operations. Only for use with the result of [Resolver.ClearForNewScan].
355 //
356 // TODO(rfindley): this awkward API is a result of the (arguably) inverted
357 // relationship between configuration and state described in the doc comment
358 // for [ProcessEnv].
359 func (e *ProcessEnv) UpdateResolver(r Resolver) {
360 e.resolver = r
361 e.resolverErr = nil
362 }
363
364 // findPackage returns the module and directory from within the main modules
365 // and their dependencies that contains the package at the given import path,
366 // or returns nil, "" if no module is in scope.
367 func (r *ModuleResolver) findPackage(importPath string) (*gocommand.ModuleJSON, string) {
368 // This can't find packages in the stdlib, but that's harmless for all
369 // the existing code paths.
370 for _, m := range r.modsByModPath {
371 if !strings.HasPrefix(importPath, m.Path) {
372 continue
373 }
374 pathInModule := importPath[len(m.Path):]
375 pkgDir := filepath.Join(m.Dir, pathInModule)
376 if r.dirIsNestedModule(pkgDir, m) {
377 continue
378 }
379
380 if info, ok := r.cacheLoad(pkgDir); ok {
381 if loaded, err := info.reachedStatus(nameLoaded); loaded {
382 if err != nil {
383 continue // No package in this dir.
384 }
385 return m, pkgDir
386 }
387 if scanned, err := info.reachedStatus(directoryScanned); scanned && err != nil {
388 continue // Dir is unreadable, etc.
389 }
390 // This is slightly wrong: a directory doesn't have to have an
391 // importable package to count as a package for package-to-module
392 // resolution. package main or _test files should count but
393 // don't.
394 // TODO(heschi): fix this.
395 if _, err := r.cachePackageName(info); err == nil {
396 return m, pkgDir
397 }
398 }
399
400 // Not cached. Read the filesystem.
401 pkgFiles, err := os.ReadDir(pkgDir)
402 if err != nil {
403 continue
404 }
405 // A module only contains a package if it has buildable go
406 // files in that directory. If not, it could be provided by an
407 // outer module. See #29736.
408 for _, fi := range pkgFiles {
409 if ok, _ := r.env.matchFile(pkgDir, fi.Name()); ok {
410 return m, pkgDir
411 }
412 }
413 }
414 return nil, ""
415 }
416
417 func (r *ModuleResolver) cacheLoad(dir string) (directoryPackageInfo, bool) {
418 if info, ok := r.moduleCacheCache.Load(dir); ok {
419 return info, ok
420 }
421 return r.otherCache.Load(dir)
422 }
423
424 func (r *ModuleResolver) cacheStore(info directoryPackageInfo) {
425 if info.rootType == gopathwalk.RootModuleCache {
426 r.moduleCacheCache.Store(info.dir, info)
427 } else {
428 r.otherCache.Store(info.dir, info)
429 }
430 }
431
432 // cachePackageName caches the package name for a dir already in the cache.
433 func (r *ModuleResolver) cachePackageName(info directoryPackageInfo) (string, error) {
434 if info.rootType == gopathwalk.RootModuleCache {
435 return r.moduleCacheCache.CachePackageName(info)
436 }
437 return r.otherCache.CachePackageName(info)
438 }
439
440 func (r *ModuleResolver) cacheExports(ctx context.Context, env *ProcessEnv, info directoryPackageInfo) (string, []stdlib.Symbol, error) {
441 if info.rootType == gopathwalk.RootModuleCache {
442 return r.moduleCacheCache.CacheExports(ctx, env, info)
443 }
444 return r.otherCache.CacheExports(ctx, env, info)
445 }
446
447 // findModuleByDir returns the module that contains dir, or nil if no such
448 // module is in scope.
449 func (r *ModuleResolver) findModuleByDir(dir string) *gocommand.ModuleJSON {
450 // This is quite tricky and may not be correct. dir could be:
451 // - a package in the main module.
452 // - a replace target underneath the main module's directory.
453 // - a nested module in the above.
454 // - a replace target somewhere totally random.
455 // - a nested module in the above.
456 // - in the mod cache.
457 // - in /vendor/ in -mod=vendor mode.
458 // - nested module? Dunno.
459 // Rumor has it that replace targets cannot contain other replace targets.
460 //
461 // Note that it is critical here that modsByDir is sorted to have deeper dirs
462 // first. This ensures that findModuleByDir finds the innermost module.
463 // See also golang/go#56291.
464 for _, m := range r.modsByDir {
465 if !strings.HasPrefix(dir, m.Dir) {
466 continue
467 }
468
469 if r.dirIsNestedModule(dir, m) {
470 continue
471 }
472
473 return m
474 }
475 return nil
476 }
477
478 // dirIsNestedModule reports if dir is contained in a nested module underneath
479 // mod, not actually in mod.
480 func (r *ModuleResolver) dirIsNestedModule(dir string, mod *gocommand.ModuleJSON) bool {
481 if !strings.HasPrefix(dir, mod.Dir) {
482 return false
483 }
484 if r.dirInModuleCache(dir) {
485 // Nested modules in the module cache are pruned,
486 // so it cannot be a nested module.
487 return false
488 }
489 if mod != nil && mod == r.dummyVendorMod {
490 // The /vendor pseudomodule is flattened and doesn't actually count.
491 return false
492 }
493 modDir, _ := r.modInfo(dir)
494 if modDir == "" {
495 return false
496 }
497 return modDir != mod.Dir
498 }
499
500 func readModName(modFile string) string {
501 modBytes, err := os.ReadFile(modFile)
502 if err != nil {
503 return ""
504 }
505 return modulePath(modBytes)
506 }
507
508 func (r *ModuleResolver) modInfo(dir string) (modDir, modName string) {
509 if r.dirInModuleCache(dir) {
510 if matches := modCacheRegexp.FindStringSubmatch(dir); len(matches) == 3 {
511 index := strings.Index(dir, matches[1]+"@"+matches[2])
512 modDir := filepath.Join(dir[:index], matches[1]+"@"+matches[2])
513 return modDir, readModName(filepath.Join(modDir, "go.mod"))
514 }
515 }
516 for {
517 if info, ok := r.cacheLoad(dir); ok {
518 return info.moduleDir, info.moduleName
519 }
520 f := filepath.Join(dir, "go.mod")
521 info, err := os.Stat(f)
522 if err == nil && !info.IsDir() {
523 return dir, readModName(f)
524 }
525
526 d := filepath.Dir(dir)
527 if len(d) >= len(dir) {
528 return "", "" // reached top of file system, no go.mod
529 }
530 dir = d
531 }
532 }
533
534 func (r *ModuleResolver) dirInModuleCache(dir string) bool {
535 if r.moduleCacheDir == "" {
536 return false
537 }
538 return strings.HasPrefix(dir, r.moduleCacheDir)
539 }
540
541 func (r *ModuleResolver) loadPackageNames(importPaths []string, srcDir string) (map[string]string, error) {
542 names := map[string]string{}
543 for _, path := range importPaths {
544 // TODO(rfindley): shouldn't this use the dirInfoCache?
545 _, packageDir := r.findPackage(path)
546 if packageDir == "" {
547 continue
548 }
549 name, err := packageDirToName(packageDir)
550 if err != nil {
551 continue
552 }
553 names[path] = name
554 }
555 return names, nil
556 }
557
558 func (r *ModuleResolver) scan(ctx context.Context, callback *scanCallback) error {
559 ctx, done := event.Start(ctx, "imports.ModuleResolver.scan")
560 defer done()
561
562 processDir := func(info directoryPackageInfo) {
563 // Skip this directory if we were not able to get the package information successfully.
564 if scanned, err := info.reachedStatus(directoryScanned); !scanned || err != nil {
565 return
566 }
567 pkg, err := r.canonicalize(info)
568 if err != nil {
569 return
570 }
571 if !callback.dirFound(pkg) {
572 return
573 }
574
575 pkg.packageName, err = r.cachePackageName(info)
576 if err != nil {
577 return
578 }
579 if !callback.packageNameLoaded(pkg) {
580 return
581 }
582
583 _, exports, err := r.loadExports(ctx, pkg, false)
584 if err != nil {
585 return
586 }
587 callback.exportsLoaded(pkg, exports)
588 }
589
590 // Start processing everything in the cache, and listen for the new stuff
591 // we discover in the walk below.
592 stop1 := r.moduleCacheCache.ScanAndListen(ctx, processDir)
593 defer stop1()
594 stop2 := r.otherCache.ScanAndListen(ctx, processDir)
595 defer stop2()
596
597 // We assume cached directories are fully cached, including all their
598 // children, and have not changed. We can skip them.
599 skip := func(root gopathwalk.Root, dir string) bool {
600 if r.env.SkipPathInScan != nil && root.Type == gopathwalk.RootCurrentModule {
601 if root.Path == dir {
602 return false
603 }
604
605 if r.env.SkipPathInScan(filepath.Clean(dir)) {
606 return true
607 }
608 }
609
610 info, ok := r.cacheLoad(dir)
611 if !ok {
612 return false
613 }
614 // This directory can be skipped as long as we have already scanned it.
615 // Packages with errors will continue to have errors, so there is no need
616 // to rescan them.
617 packageScanned, _ := info.reachedStatus(directoryScanned)
618 return packageScanned
619 }
620
621 add := func(root gopathwalk.Root, dir string) {
622 r.cacheStore(r.scanDirForPackage(root, dir))
623 }
624
625 // r.roots and the callback are not necessarily safe to use in the
626 // goroutine below. Process them eagerly.
627 roots := filterRoots(r.roots, callback.rootFound)
628 // We can't cancel walks, because we need them to finish to have a usable
629 // cache. Instead, run them in a separate goroutine and detach.
630 scanDone := make(chan struct{})
631 go func() {
632 select {
633 case <-ctx.Done():
634 return
635 case <-r.scanSema: // acquire
636 }
637 defer func() { r.scanSema <- struct{}{} }() // release
638 // We have the lock on r.scannedRoots, and no other scans can run.
639 for _, root := range roots {
640 if ctx.Err() != nil {
641 return
642 }
643
644 if r.scannedRoots[root] {
645 continue
646 }
647 gopathwalk.WalkSkip([]gopathwalk.Root{root}, add, skip, gopathwalk.Options{Logf: r.env.Logf, ModulesEnabled: true})
648 r.scannedRoots[root] = true
649 }
650 close(scanDone)
651 }()
652 select {
653 case <-ctx.Done():
654 case <-scanDone:
655 }
656 return nil
657 }
658
659 func (r *ModuleResolver) scoreImportPath(ctx context.Context, path string) float64 {
660 if stdlib.HasPackage(path) {
661 return MaxRelevance
662 }
663 mod, _ := r.findPackage(path)
664 return modRelevance(mod)
665 }
666
667 func modRelevance(mod *gocommand.ModuleJSON) float64 {
668 var relevance float64
669 switch {
670 case mod == nil: // out of scope
671 return MaxRelevance - 4
672 case mod.Indirect:
673 relevance = MaxRelevance - 3
674 case !mod.Main:
675 relevance = MaxRelevance - 2
676 default:
677 relevance = MaxRelevance - 1 // main module ties with stdlib
678 }
679
680 _, versionString, ok := module.SplitPathVersion(mod.Path)
681 if ok {
682 _, after, ok := strings.Cut(versionString, "v")
683 if !ok {
684 return relevance
685 }
686 if versionNumber, err := strconv.ParseFloat(after, 64); err == nil {
687 relevance += versionNumber / 1000
688 }
689 }
690
691 return relevance
692 }
693
694 // canonicalize gets the result of canonicalizing the packages using the results
695 // of initializing the resolver from 'go list -m'.
696 func (r *ModuleResolver) canonicalize(info directoryPackageInfo) (*pkg, error) {
697 // Packages in GOROOT are already canonical, regardless of the std/cmd modules.
698 if info.rootType == gopathwalk.RootGOROOT {
699 return &pkg{
700 importPathShort: info.nonCanonicalImportPath,
701 dir: info.dir,
702 packageName: path.Base(info.nonCanonicalImportPath),
703 relevance: MaxRelevance,
704 }, nil
705 }
706
707 importPath := info.nonCanonicalImportPath
708 mod := r.findModuleByDir(info.dir)
709 // Check if the directory is underneath a module that's in scope.
710 if mod != nil {
711 // It is. If dir is the target of a replace directive,
712 // our guessed import path is wrong. Use the real one.
713 if mod.Dir == info.dir {
714 importPath = mod.Path
715 } else {
716 dirInMod := info.dir[len(mod.Dir)+len("/"):]
717 importPath = path.Join(mod.Path, filepath.ToSlash(dirInMod))
718 }
719 } else if !strings.HasPrefix(importPath, info.moduleName) {
720 // The module's name doesn't match the package's import path. It
721 // probably needs a replace directive we don't have.
722 return nil, fmt.Errorf("package in %q is not valid without a replace statement", info.dir)
723 }
724
725 res := &pkg{
726 importPathShort: importPath,
727 dir: info.dir,
728 relevance: modRelevance(mod),
729 }
730 // We may have discovered a package that has a different version
731 // in scope already. Canonicalize to that one if possible.
732 if _, canonicalDir := r.findPackage(importPath); canonicalDir != "" {
733 res.dir = canonicalDir
734 }
735 return res, nil
736 }
737
738 func (r *ModuleResolver) loadExports(ctx context.Context, pkg *pkg, includeTest bool) (string, []stdlib.Symbol, error) {
739 if info, ok := r.cacheLoad(pkg.dir); ok && !includeTest {
740 return r.cacheExports(ctx, r.env, info)
741 }
742 return loadExportsFromFiles(ctx, r.env, pkg.dir, includeTest)
743 }
744
745 func (r *ModuleResolver) scanDirForPackage(root gopathwalk.Root, dir string) directoryPackageInfo {
746 subdir := ""
747 if prefix := root.Path + string(filepath.Separator); strings.HasPrefix(dir, prefix) {
748 subdir = dir[len(prefix):]
749 }
750 importPath := filepath.ToSlash(subdir)
751 if strings.HasPrefix(importPath, "vendor/") {
752 // Only enter vendor directories if they're explicitly requested as a root.
753 return directoryPackageInfo{
754 status: directoryScanned,
755 err: fmt.Errorf("unwanted vendor directory"),
756 }
757 }
758 switch root.Type {
759 case gopathwalk.RootCurrentModule:
760 importPath = path.Join(r.mainByDir[root.Path].Path, filepath.ToSlash(subdir))
761 case gopathwalk.RootModuleCache:
762 matches := modCacheRegexp.FindStringSubmatch(subdir)
763 if len(matches) == 0 {
764 return directoryPackageInfo{
765 status: directoryScanned,
766 err: fmt.Errorf("invalid module cache path: %v", subdir),
767 }
768 }
769 modPath, err := module.UnescapePath(filepath.ToSlash(matches[1]))
770 if err != nil {
771 r.env.logf("decoding module cache path %q: %v", subdir, err)
772 return directoryPackageInfo{
773 status: directoryScanned,
774 err: fmt.Errorf("decoding module cache path %q: %v", subdir, err),
775 }
776 }
777 importPath = path.Join(modPath, filepath.ToSlash(matches[3]))
778 }
779
780 modDir, modName := r.modInfo(dir)
781 result := directoryPackageInfo{
782 status: directoryScanned,
783 dir: dir,
784 rootType: root.Type,
785 nonCanonicalImportPath: importPath,
786 moduleDir: modDir,
787 moduleName: modName,
788 }
789 if root.Type == gopathwalk.RootGOROOT {
790 // stdlib packages are always in scope, despite the confusing go.mod
791 return result
792 }
793 return result
794 }
795
796 // modCacheRegexp splits a path in a module cache into module, module version, and package.
797 var modCacheRegexp = regexp.MustCompile(`(.*)@([^/\\]*)(.*)`)
798
799 var (
800 slashSlash = []byte("//")
801 moduleStr = []byte("module")
802 )
803
804 // modulePath returns the module path from the gomod file text.
805 // If it cannot find a module path, it returns an empty string.
806 // It is tolerant of unrelated problems in the go.mod file.
807 //
808 // Copied from cmd/go/internal/modfile.
809 func modulePath(mod []byte) string {
810 for len(mod) > 0 {
811 line := mod
812 mod = nil
813 if i := bytes.IndexByte(line, '\n'); i >= 0 {
814 line, mod = line[:i], line[i+1:]
815 }
816 if i := bytes.Index(line, slashSlash); i >= 0 {
817 line = line[:i]
818 }
819 line = bytes.TrimSpace(line)
820 if !bytes.HasPrefix(line, moduleStr) {
821 continue
822 }
823 line = line[len(moduleStr):]
824 n := len(line)
825 line = bytes.TrimSpace(line)
826 if len(line) == n || len(line) == 0 {
827 continue
828 }
829
830 if line[0] == '"' || line[0] == '`' {
831 p, err := strconv.Unquote(string(line))
832 if err != nil {
833 return "" // malformed quoted string or multiline module path
834 }
835 return p
836 }
837
838 return string(line)
839 }
840 return "" // missing module path
841 }