mod.go (26549B)
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 = goenv["GOMODCACHE"] 170 171 sort.Slice(r.modsByModPath, func(i, j int) bool { 172 count := func(x int) int { 173 return strings.Count(r.modsByModPath[x].Path, "/") 174 } 175 return count(j) < count(i) // descending order 176 }) 177 sort.Slice(r.modsByDir, func(i, j int) bool { 178 count := func(x int) int { 179 return strings.Count(r.modsByDir[x].Dir, string(filepath.Separator)) 180 } 181 return count(j) < count(i) // descending order 182 }) 183 184 r.roots = []gopathwalk.Root{} 185 if goenv["GOROOT"] != "" { // "" happens in tests 186 r.roots = append(r.roots, gopathwalk.Root{Path: filepath.Join(goenv["GOROOT"], "/src"), Type: gopathwalk.RootGOROOT}) 187 } 188 r.mainByDir = make(map[string]*gocommand.ModuleJSON) 189 for _, main := range r.mains { 190 r.roots = append(r.roots, gopathwalk.Root{Path: main.Dir, Type: gopathwalk.RootCurrentModule}) 191 r.mainByDir[main.Dir] = main 192 } 193 if vendorEnabled { 194 r.roots = append(r.roots, gopathwalk.Root{Path: r.dummyVendorMod.Dir, Type: gopathwalk.RootOther}) 195 } else { 196 addDep := func(mod *gocommand.ModuleJSON) { 197 if mod.Replace == nil { 198 // This is redundant with the cache, but we'll skip it cheaply enough 199 // when we encounter it in the module cache scan. 200 // 201 // Including it at a lower index in r.roots than the module cache dir 202 // helps prioritize matches from within existing dependencies. 203 r.roots = append(r.roots, gopathwalk.Root{Path: mod.Dir, Type: gopathwalk.RootModuleCache}) 204 } else { 205 r.roots = append(r.roots, gopathwalk.Root{Path: mod.Dir, Type: gopathwalk.RootOther}) 206 } 207 } 208 // Walk dependent modules before scanning the full mod cache, direct deps first. 209 for _, mod := range r.modsByModPath { 210 if !mod.Indirect && !mod.Main { 211 addDep(mod) 212 } 213 } 214 for _, mod := range r.modsByModPath { 215 if mod.Indirect && !mod.Main { 216 addDep(mod) 217 } 218 } 219 // If provided, share the moduleCacheCache. 220 // 221 // TODO(rfindley): The module cache is immutable. However, the loaded 222 // exports do depend on GOOS and GOARCH. Fortunately, the 223 // ProcessEnv.buildContext does not adjust these from build.DefaultContext 224 // (even though it should). So for now, this is OK to share, but we need to 225 // add logic for handling GOOS/GOARCH. 226 r.moduleCacheCache = moduleCacheCache 227 r.roots = append(r.roots, gopathwalk.Root{Path: r.moduleCacheDir, Type: gopathwalk.RootModuleCache}) 228 } 229 230 r.scannedRoots = map[gopathwalk.Root]bool{} 231 if r.moduleCacheCache == nil { 232 r.moduleCacheCache = NewDirInfoCache() 233 } 234 r.otherCache = NewDirInfoCache() 235 return r, nil 236 } 237 238 func (r *ModuleResolver) initAllMods() error { 239 stdout, err := r.env.invokeGo(context.TODO(), "list", "-m", "-e", "-json", "...") 240 if err != nil { 241 return err 242 } 243 for dec := json.NewDecoder(stdout); dec.More(); { 244 mod := &gocommand.ModuleJSON{} 245 if err := dec.Decode(mod); err != nil { 246 return err 247 } 248 if mod.Dir == "" { 249 r.env.logf("module %v has not been downloaded and will be ignored", mod.Path) 250 // Can't do anything with a module that's not downloaded. 251 continue 252 } 253 // golang/go#36193: the go command doesn't always clean paths. 254 mod.Dir = filepath.Clean(mod.Dir) 255 r.modsByModPath = append(r.modsByModPath, mod) 256 r.modsByDir = append(r.modsByDir, mod) 257 if mod.Main { 258 r.mains = append(r.mains, mod) 259 } 260 } 261 return nil 262 } 263 264 // ClearForNewScan invalidates the last scan. 265 // 266 // It preserves the set of roots, but forgets about the set of directories. 267 // Though it forgets the set of module cache directories, it remembers their 268 // contents, since they are assumed to be immutable. 269 func (r *ModuleResolver) ClearForNewScan() Resolver { 270 <-r.scanSema // acquire r, to guard scannedRoots 271 r2 := &ModuleResolver{ 272 env: r.env, 273 dummyVendorMod: r.dummyVendorMod, 274 moduleCacheDir: r.moduleCacheDir, 275 roots: r.roots, 276 mains: r.mains, 277 mainByDir: r.mainByDir, 278 modsByModPath: r.modsByModPath, 279 280 scanSema: make(chan struct{}, 1), 281 scannedRoots: make(map[gopathwalk.Root]bool), 282 otherCache: NewDirInfoCache(), 283 moduleCacheCache: r.moduleCacheCache, 284 } 285 r2.scanSema <- struct{}{} // r2 must start released 286 // Invalidate root scans. We don't need to invalidate module cache roots, 287 // because they are immutable. 288 // (We don't support a use case where GOMODCACHE is cleaned in the middle of 289 // e.g. a gopls session: the user must restart gopls to get accurate 290 // imports.) 291 // 292 // Scanning for new directories in GOMODCACHE should be handled elsewhere, 293 // via a call to ScanModuleCache. 294 for _, root := range r.roots { 295 if root.Type == gopathwalk.RootModuleCache && r.scannedRoots[root] { 296 r2.scannedRoots[root] = true 297 } 298 } 299 r.scanSema <- struct{}{} // release r 300 return r2 301 } 302 303 // ClearModuleInfo invalidates resolver state that depends on go.mod file 304 // contents (essentially, the output of go list -m -json ...). 305 // 306 // Notably, it does not forget directory contents, which are reset 307 // asynchronously via ClearForNewScan. 308 // 309 // If the ProcessEnv is a GOPATH environment, ClearModuleInfo is a no op. 310 // 311 // TODO(rfindley): move this to a new env.go, consolidating ProcessEnv methods. 312 func (e *ProcessEnv) ClearModuleInfo() { 313 if r, ok := e.resolver.(*ModuleResolver); ok { 314 resolver, err := newModuleResolver(e, e.ModCache) 315 if err != nil { 316 e.resolver = nil 317 e.resolverErr = err 318 return 319 } 320 321 <-r.scanSema // acquire (guards caches) 322 resolver.moduleCacheCache = r.moduleCacheCache 323 resolver.otherCache = r.otherCache 324 r.scanSema <- struct{}{} // release 325 326 e.UpdateResolver(resolver) 327 } 328 } 329 330 // UpdateResolver sets the resolver for the ProcessEnv to use in imports 331 // operations. Only for use with the result of [Resolver.ClearForNewScan]. 332 // 333 // TODO(rfindley): this awkward API is a result of the (arguably) inverted 334 // relationship between configuration and state described in the doc comment 335 // for [ProcessEnv]. 336 func (e *ProcessEnv) UpdateResolver(r Resolver) { 337 e.resolver = r 338 e.resolverErr = nil 339 } 340 341 // findPackage returns the module and directory from within the main modules 342 // and their dependencies that contains the package at the given import path, 343 // or returns nil, "" if no module is in scope. 344 func (r *ModuleResolver) findPackage(importPath string) (*gocommand.ModuleJSON, string) { 345 // This can't find packages in the stdlib, but that's harmless for all 346 // the existing code paths. 347 for _, m := range r.modsByModPath { 348 if !strings.HasPrefix(importPath, m.Path) { 349 continue 350 } 351 pathInModule := importPath[len(m.Path):] 352 pkgDir := filepath.Join(m.Dir, pathInModule) 353 if r.dirIsNestedModule(pkgDir, m) { 354 continue 355 } 356 357 if info, ok := r.cacheLoad(pkgDir); ok { 358 if loaded, err := info.reachedStatus(nameLoaded); loaded { 359 if err != nil { 360 continue // No package in this dir. 361 } 362 return m, pkgDir 363 } 364 if scanned, err := info.reachedStatus(directoryScanned); scanned && err != nil { 365 continue // Dir is unreadable, etc. 366 } 367 // This is slightly wrong: a directory doesn't have to have an 368 // importable package to count as a package for package-to-module 369 // resolution. package main or _test files should count but 370 // don't. 371 // TODO(heschi): fix this. 372 if _, err := r.cachePackageName(info); err == nil { 373 return m, pkgDir 374 } 375 } 376 377 // Not cached. Read the filesystem. 378 pkgFiles, err := os.ReadDir(pkgDir) 379 if err != nil { 380 continue 381 } 382 // A module only contains a package if it has buildable go 383 // files in that directory. If not, it could be provided by an 384 // outer module. See #29736. 385 for _, fi := range pkgFiles { 386 if ok, _ := r.env.matchFile(pkgDir, fi.Name()); ok { 387 return m, pkgDir 388 } 389 } 390 } 391 return nil, "" 392 } 393 394 func (r *ModuleResolver) cacheLoad(dir string) (directoryPackageInfo, bool) { 395 if info, ok := r.moduleCacheCache.Load(dir); ok { 396 return info, ok 397 } 398 return r.otherCache.Load(dir) 399 } 400 401 func (r *ModuleResolver) cacheStore(info directoryPackageInfo) { 402 if info.rootType == gopathwalk.RootModuleCache { 403 r.moduleCacheCache.Store(info.dir, info) 404 } else { 405 r.otherCache.Store(info.dir, info) 406 } 407 } 408 409 // cachePackageName caches the package name for a dir already in the cache. 410 func (r *ModuleResolver) cachePackageName(info directoryPackageInfo) (string, error) { 411 if info.rootType == gopathwalk.RootModuleCache { 412 return r.moduleCacheCache.CachePackageName(info) 413 } 414 return r.otherCache.CachePackageName(info) 415 } 416 417 func (r *ModuleResolver) cacheExports(ctx context.Context, env *ProcessEnv, info directoryPackageInfo) (string, []stdlib.Symbol, error) { 418 if info.rootType == gopathwalk.RootModuleCache { 419 return r.moduleCacheCache.CacheExports(ctx, env, info) 420 } 421 return r.otherCache.CacheExports(ctx, env, info) 422 } 423 424 // findModuleByDir returns the module that contains dir, or nil if no such 425 // module is in scope. 426 func (r *ModuleResolver) findModuleByDir(dir string) *gocommand.ModuleJSON { 427 // This is quite tricky and may not be correct. dir could be: 428 // - a package in the main module. 429 // - a replace target underneath the main module's directory. 430 // - a nested module in the above. 431 // - a replace target somewhere totally random. 432 // - a nested module in the above. 433 // - in the mod cache. 434 // - in /vendor/ in -mod=vendor mode. 435 // - nested module? Dunno. 436 // Rumor has it that replace targets cannot contain other replace targets. 437 // 438 // Note that it is critical here that modsByDir is sorted to have deeper dirs 439 // first. This ensures that findModuleByDir finds the innermost module. 440 // See also golang/go#56291. 441 for _, m := range r.modsByDir { 442 if !strings.HasPrefix(dir, m.Dir) { 443 continue 444 } 445 446 if r.dirIsNestedModule(dir, m) { 447 continue 448 } 449 450 return m 451 } 452 return nil 453 } 454 455 // dirIsNestedModule reports if dir is contained in a nested module underneath 456 // mod, not actually in mod. 457 func (r *ModuleResolver) dirIsNestedModule(dir string, mod *gocommand.ModuleJSON) bool { 458 if !strings.HasPrefix(dir, mod.Dir) { 459 return false 460 } 461 if r.dirInModuleCache(dir) { 462 // Nested modules in the module cache are pruned, 463 // so it cannot be a nested module. 464 return false 465 } 466 if mod != nil && mod == r.dummyVendorMod { 467 // The /vendor pseudomodule is flattened and doesn't actually count. 468 return false 469 } 470 modDir, _ := r.modInfo(dir) 471 if modDir == "" { 472 return false 473 } 474 return modDir != mod.Dir 475 } 476 477 func readModName(modFile string) string { 478 modBytes, err := os.ReadFile(modFile) 479 if err != nil { 480 return "" 481 } 482 return modulePath(modBytes) 483 } 484 485 func (r *ModuleResolver) modInfo(dir string) (modDir, modName string) { 486 if r.dirInModuleCache(dir) { 487 if matches := modCacheRegexp.FindStringSubmatch(dir); len(matches) == 3 { 488 index := strings.Index(dir, matches[1]+"@"+matches[2]) 489 modDir := filepath.Join(dir[:index], matches[1]+"@"+matches[2]) 490 return modDir, readModName(filepath.Join(modDir, "go.mod")) 491 } 492 } 493 for { 494 if info, ok := r.cacheLoad(dir); ok { 495 return info.moduleDir, info.moduleName 496 } 497 f := filepath.Join(dir, "go.mod") 498 info, err := os.Stat(f) 499 if err == nil && !info.IsDir() { 500 return dir, readModName(f) 501 } 502 503 d := filepath.Dir(dir) 504 if len(d) >= len(dir) { 505 return "", "" // reached top of file system, no go.mod 506 } 507 dir = d 508 } 509 } 510 511 func (r *ModuleResolver) dirInModuleCache(dir string) bool { 512 if r.moduleCacheDir == "" { 513 return false 514 } 515 return strings.HasPrefix(dir, r.moduleCacheDir) 516 } 517 518 func (r *ModuleResolver) loadPackageNames(importPaths []string, srcDir string) (map[string]string, error) { 519 names := map[string]string{} 520 for _, path := range importPaths { 521 // TODO(rfindley): shouldn't this use the dirInfoCache? 522 _, packageDir := r.findPackage(path) 523 if packageDir == "" { 524 continue 525 } 526 name, err := packageDirToName(packageDir) 527 if err != nil { 528 continue 529 } 530 names[path] = name 531 } 532 return names, nil 533 } 534 535 func (r *ModuleResolver) scan(ctx context.Context, callback *scanCallback) error { 536 ctx, done := event.Start(ctx, "imports.ModuleResolver.scan") 537 defer done() 538 539 processDir := func(info directoryPackageInfo) { 540 // Skip this directory if we were not able to get the package information successfully. 541 if scanned, err := info.reachedStatus(directoryScanned); !scanned || err != nil { 542 return 543 } 544 pkg, err := r.canonicalize(info) 545 if err != nil { 546 return 547 } 548 if !callback.dirFound(pkg) { 549 return 550 } 551 552 pkg.packageName, err = r.cachePackageName(info) 553 if err != nil { 554 return 555 } 556 if !callback.packageNameLoaded(pkg) { 557 return 558 } 559 560 _, exports, err := r.loadExports(ctx, pkg, false) 561 if err != nil { 562 return 563 } 564 callback.exportsLoaded(pkg, exports) 565 } 566 567 // Start processing everything in the cache, and listen for the new stuff 568 // we discover in the walk below. 569 stop1 := r.moduleCacheCache.ScanAndListen(ctx, processDir) 570 defer stop1() 571 stop2 := r.otherCache.ScanAndListen(ctx, processDir) 572 defer stop2() 573 574 // We assume cached directories are fully cached, including all their 575 // children, and have not changed. We can skip them. 576 skip := func(root gopathwalk.Root, dir string) bool { 577 if r.env.SkipPathInScan != nil && root.Type == gopathwalk.RootCurrentModule { 578 if root.Path == dir { 579 return false 580 } 581 582 if r.env.SkipPathInScan(filepath.Clean(dir)) { 583 return true 584 } 585 } 586 587 info, ok := r.cacheLoad(dir) 588 if !ok { 589 return false 590 } 591 // This directory can be skipped as long as we have already scanned it. 592 // Packages with errors will continue to have errors, so there is no need 593 // to rescan them. 594 packageScanned, _ := info.reachedStatus(directoryScanned) 595 return packageScanned 596 } 597 598 add := func(root gopathwalk.Root, dir string) { 599 r.cacheStore(r.scanDirForPackage(root, dir)) 600 } 601 602 // r.roots and the callback are not necessarily safe to use in the 603 // goroutine below. Process them eagerly. 604 roots := filterRoots(r.roots, callback.rootFound) 605 // We can't cancel walks, because we need them to finish to have a usable 606 // cache. Instead, run them in a separate goroutine and detach. 607 scanDone := make(chan struct{}) 608 go func() { 609 select { 610 case <-ctx.Done(): 611 return 612 case <-r.scanSema: // acquire 613 } 614 defer func() { r.scanSema <- struct{}{} }() // release 615 // We have the lock on r.scannedRoots, and no other scans can run. 616 for _, root := range roots { 617 if ctx.Err() != nil { 618 return 619 } 620 621 if r.scannedRoots[root] { 622 continue 623 } 624 gopathwalk.WalkSkip([]gopathwalk.Root{root}, add, skip, gopathwalk.Options{Logf: r.env.Logf, ModulesEnabled: true}) 625 r.scannedRoots[root] = true 626 } 627 close(scanDone) 628 }() 629 select { 630 case <-ctx.Done(): 631 case <-scanDone: 632 } 633 return nil 634 } 635 636 func (r *ModuleResolver) scoreImportPath(ctx context.Context, path string) float64 { 637 if stdlib.HasPackage(path) { 638 return MaxRelevance 639 } 640 mod, _ := r.findPackage(path) 641 return modRelevance(mod) 642 } 643 644 func modRelevance(mod *gocommand.ModuleJSON) float64 { 645 var relevance float64 646 switch { 647 case mod == nil: // out of scope 648 return MaxRelevance - 4 649 case mod.Indirect: 650 relevance = MaxRelevance - 3 651 case !mod.Main: 652 relevance = MaxRelevance - 2 653 default: 654 relevance = MaxRelevance - 1 // main module ties with stdlib 655 } 656 657 _, versionString, ok := module.SplitPathVersion(mod.Path) 658 if ok { 659 _, after, ok := strings.Cut(versionString, "v") 660 if !ok { 661 return relevance 662 } 663 if versionNumber, err := strconv.ParseFloat(after, 64); err == nil { 664 relevance += versionNumber / 1000 665 } 666 } 667 668 return relevance 669 } 670 671 // canonicalize gets the result of canonicalizing the packages using the results 672 // of initializing the resolver from 'go list -m'. 673 func (r *ModuleResolver) canonicalize(info directoryPackageInfo) (*pkg, error) { 674 // Packages in GOROOT are already canonical, regardless of the std/cmd modules. 675 if info.rootType == gopathwalk.RootGOROOT { 676 return &pkg{ 677 importPathShort: info.nonCanonicalImportPath, 678 dir: info.dir, 679 packageName: path.Base(info.nonCanonicalImportPath), 680 relevance: MaxRelevance, 681 }, nil 682 } 683 684 importPath := info.nonCanonicalImportPath 685 mod := r.findModuleByDir(info.dir) 686 // Check if the directory is underneath a module that's in scope. 687 if mod != nil { 688 // It is. If dir is the target of a replace directive, 689 // our guessed import path is wrong. Use the real one. 690 if mod.Dir == info.dir { 691 importPath = mod.Path 692 } else { 693 dirInMod := info.dir[len(mod.Dir)+len("/"):] 694 importPath = path.Join(mod.Path, filepath.ToSlash(dirInMod)) 695 } 696 } else if !strings.HasPrefix(importPath, info.moduleName) { 697 // The module's name doesn't match the package's import path. It 698 // probably needs a replace directive we don't have. 699 return nil, fmt.Errorf("package in %q is not valid without a replace statement", info.dir) 700 } 701 702 res := &pkg{ 703 importPathShort: importPath, 704 dir: info.dir, 705 relevance: modRelevance(mod), 706 } 707 // We may have discovered a package that has a different version 708 // in scope already. Canonicalize to that one if possible. 709 if _, canonicalDir := r.findPackage(importPath); canonicalDir != "" { 710 res.dir = canonicalDir 711 } 712 return res, nil 713 } 714 715 func (r *ModuleResolver) loadExports(ctx context.Context, pkg *pkg, includeTest bool) (string, []stdlib.Symbol, error) { 716 if info, ok := r.cacheLoad(pkg.dir); ok && !includeTest { 717 return r.cacheExports(ctx, r.env, info) 718 } 719 return loadExportsFromFiles(ctx, r.env, pkg.dir, includeTest) 720 } 721 722 func (r *ModuleResolver) scanDirForPackage(root gopathwalk.Root, dir string) directoryPackageInfo { 723 subdir := "" 724 if prefix := root.Path + string(filepath.Separator); strings.HasPrefix(dir, prefix) { 725 subdir = dir[len(prefix):] 726 } 727 importPath := filepath.ToSlash(subdir) 728 if strings.HasPrefix(importPath, "vendor/") { 729 // Only enter vendor directories if they're explicitly requested as a root. 730 return directoryPackageInfo{ 731 status: directoryScanned, 732 err: fmt.Errorf("unwanted vendor directory"), 733 } 734 } 735 switch root.Type { 736 case gopathwalk.RootCurrentModule: 737 importPath = path.Join(r.mainByDir[root.Path].Path, filepath.ToSlash(subdir)) 738 case gopathwalk.RootModuleCache: 739 matches := modCacheRegexp.FindStringSubmatch(subdir) 740 if len(matches) == 0 { 741 return directoryPackageInfo{ 742 status: directoryScanned, 743 err: fmt.Errorf("invalid module cache path: %v", subdir), 744 } 745 } 746 modPath, err := module.UnescapePath(filepath.ToSlash(matches[1])) 747 if err != nil { 748 r.env.logf("decoding module cache path %q: %v", subdir, err) 749 return directoryPackageInfo{ 750 status: directoryScanned, 751 err: fmt.Errorf("decoding module cache path %q: %v", subdir, err), 752 } 753 } 754 importPath = path.Join(modPath, filepath.ToSlash(matches[3])) 755 } 756 757 modDir, modName := r.modInfo(dir) 758 result := directoryPackageInfo{ 759 status: directoryScanned, 760 dir: dir, 761 rootType: root.Type, 762 nonCanonicalImportPath: importPath, 763 moduleDir: modDir, 764 moduleName: modName, 765 } 766 if root.Type == gopathwalk.RootGOROOT { 767 // stdlib packages are always in scope, despite the confusing go.mod 768 return result 769 } 770 return result 771 } 772 773 // modCacheRegexp splits a path in a module cache into module, module version, and package. 774 var modCacheRegexp = regexp.MustCompile(`(.*)@([^/\\]*)(.*)`) 775 776 var ( 777 slashSlash = []byte("//") 778 moduleStr = []byte("module") 779 ) 780 781 // modulePath returns the module path from the gomod file text. 782 // If it cannot find a module path, it returns an empty string. 783 // It is tolerant of unrelated problems in the go.mod file. 784 // 785 // Copied from cmd/go/internal/modfile. 786 func modulePath(mod []byte) string { 787 for len(mod) > 0 { 788 line := mod 789 mod = nil 790 if i := bytes.IndexByte(line, '\n'); i >= 0 { 791 line, mod = line[:i], line[i+1:] 792 } 793 if i := bytes.Index(line, slashSlash); i >= 0 { 794 line = line[:i] 795 } 796 line = bytes.TrimSpace(line) 797 if !bytes.HasPrefix(line, moduleStr) { 798 continue 799 } 800 line = line[len(moduleStr):] 801 n := len(line) 802 line = bytes.TrimSpace(line) 803 if len(line) == n || len(line) == 0 { 804 continue 805 } 806 807 if line[0] == '"' || line[0] == '`' { 808 p, err := strconv.Unquote(string(line)) 809 if err != nil { 810 return "" // malformed quoted string or multiline module path 811 } 812 return p 813 } 814 815 return string(line) 816 } 817 return "" // missing module path 818 }