1 // Copyright 2018 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.
7 // This file contains the module-mode package loader, as well as some accessory
8 // functions pertaining to the package import graph.
10 // There are two exported entry points into package loading — LoadPackages and
11 // ImportFromFiles — both implemented in terms of loadFromRoots, which itself
12 // manipulates an instance of the loader struct.
14 // Although most of the loading state is maintained in the loader struct,
15 // one key piece - the build list - is a global, so that it can be modified
16 // separate from the loading operation, such as during "go get"
17 // upgrades/downgrades or in "go mod" operations.
18 // TODO(#40775): It might be nice to make the loader take and return
19 // a buildList rather than hard-coding use of the global.
21 // Loading is an iterative process. On each iteration, we try to load the
22 // requested packages and their transitive imports, then try to resolve modules
23 // for any imported packages that are still missing.
25 // The first step of each iteration identifies a set of “root” packages.
26 // Normally the root packages are exactly those matching the named pattern
27 // arguments. However, for the "all" meta-pattern, the final set of packages is
28 // computed from the package import graph, and therefore cannot be an initial
29 // input to loading that graph. Instead, the root packages for the "all" pattern
30 // are those contained in the main module, and allPatternIsRoot parameter to the
31 // loader instructs it to dynamically expand those roots to the full "all"
32 // pattern as loading progresses.
34 // The pkgInAll flag on each loadPkg instance tracks whether that
35 // package is known to match the "all" meta-pattern.
36 // A package matches the "all" pattern if:
37 // - it is in the main module, or
38 // - it is imported by any test in the main module, or
39 // - it is imported by another package in "all", or
40 // - the main module specifies a go version ≤ 1.15, and the package is imported
41 // by a *test of* another package in "all".
43 // When graph pruning is in effect, we want to spot-check the graph-pruning
44 // invariants — which depend on which packages are known to be in "all" — even
45 // when we are only loading individual packages, so we set the pkgInAll flag
46 // regardless of the whether the "all" pattern is a root.
47 // (This is necessary to maintain the “import invariant” described in
48 // https://golang.org/design/36460-lazy-module-loading.)
50 // Because "go mod vendor" prunes out the tests of vendored packages, the
51 // behavior of the "all" pattern with -mod=vendor in Go 1.11–1.15 is the same
52 // as the "all" pattern (regardless of the -mod flag) in 1.16+.
53 // The loader uses the GoVersion parameter to determine whether the "all"
54 // pattern should close over tests (as in Go 1.11–1.15) or stop at only those
55 // packages transitively imported by the packages and tests in the main module
56 // ("all" in Go 1.16+ and "go mod vendor" in Go 1.11+).
58 // Note that it is possible for a loaded package NOT to be in "all" even when we
59 // are loading the "all" pattern. For example, packages that are transitive
60 // dependencies of other roots named on the command line must be loaded, but are
61 // not in "all". (The mod_notall test illustrates this behavior.)
62 // Similarly, if the LoadTests flag is set but the "all" pattern does not close
63 // over test dependencies, then when we load the test of a package that is in
64 // "all" but outside the main module, the dependencies of that test will not
65 // necessarily themselves be in "all". (That configuration does not arise in Go
66 // 1.11–1.15, but it will be possible in Go 1.16+.)
68 // Loading proceeds from the roots, using a parallel work-queue with a limit on
69 // the amount of active work (to avoid saturating disks, CPU cores, and/or
70 // network connections). Each package is added to the queue the first time it is
71 // imported by another package. When we have finished identifying the imports of
72 // a package, we add the test for that package if it is needed. A test may be
74 // - the package matches a root pattern and tests of the roots were requested, or
75 // - the package is in the main module and the "all" pattern is requested
76 // (because the "all" pattern includes the dependencies of tests in the main
78 // - the package is in "all" and the definition of "all" we are using includes
79 // dependencies of tests (as is the case in Go ≤1.15).
81 // After all available packages have been loaded, we examine the results to
82 // identify any requested or imported packages that are still missing, and if
83 // so, which modules we could add to the module graph in order to make the
84 // missing packages available. We add those to the module graph and iterate,
85 // until either all packages resolve successfully or we cannot identify any
86 // module that would resolve any remaining missing package.
88 // If the main module is “tidy” (that is, if "go mod tidy" is a no-op for it)
89 // and all requested packages are in "all", then loading completes in a single
91 // TODO(bcmills): We should also be able to load in a single iteration if the
92 // requested packages all come from modules that are themselves tidy, regardless
93 // of whether those packages are in "all". Today, that requires two iterations
94 // if those packages are not found in existing dependencies of the main module.
113 "cmd/go/internal/base"
114 "cmd/go/internal/cfg"
115 "cmd/go/internal/fsys"
116 "cmd/go/internal/gover"
117 "cmd/go/internal/imports"
118 "cmd/go/internal/modfetch"
119 "cmd/go/internal/modindex"
120 "cmd/go/internal/mvs"
121 "cmd/go/internal/par"
122 "cmd/go/internal/search"
123 "cmd/go/internal/str"
125 "golang.org/x/mod/module"
128 // loaded is the most recently-used package loader.
129 // It holds details about individual packages.
131 // This variable should only be accessed directly in top-level exported
132 // functions. All other functions that require or produce a *loader should pass
133 // or return it as an explicit parameter.
136 // PackageOpts control the behavior of the LoadPackages function.
137 type PackageOpts struct {
138 // GoVersion is the Go version to which the go.mod file should be updated
139 // after packages have been loaded.
141 // An empty GoVersion means to use the Go version already specified in the
142 // main module's go.mod file, or the latest Go version if there is no main
146 // TidyGo, if true, indicates that GoVersion is from the tidy -go= flag.
149 // Tags are the build tags in effect (as interpreted by the
150 // cmd/go/internal/imports package).
151 // If nil, treated as equivalent to imports.Tags().
154 // Tidy, if true, requests that the build list and go.sum file be reduced to
155 // the minimal dependencies needed to reproducibly reload the requested
159 // TidyCompatibleVersion is the oldest Go version that must be able to
160 // reproducibly reload the requested packages.
162 // If empty, the compatible version is the Go version immediately prior to the
163 // 'go' version listed in the go.mod file.
164 TidyCompatibleVersion string
166 // VendorModulesInGOROOTSrc indicates that if we are within a module in
167 // GOROOT/src, packages in the module's vendor directory should be resolved as
168 // actual module dependencies (instead of standard-library packages).
169 VendorModulesInGOROOTSrc bool
171 // ResolveMissingImports indicates that we should attempt to add module
172 // dependencies as needed to resolve imports of packages that are not found.
174 // For commands that support the -mod flag, resolving imports may still fail
175 // if the flag is set to "readonly" (the default) or "vendor".
176 ResolveMissingImports bool
178 // AssumeRootsImported indicates that the transitive dependencies of the root
179 // packages should be treated as if those roots will be imported by the main
181 AssumeRootsImported bool
183 // AllowPackage, if non-nil, is called after identifying the module providing
184 // each package. If AllowPackage returns a non-nil error, that error is set
185 // for the package, and the imports and test of that package will not be
188 // AllowPackage may be invoked concurrently by multiple goroutines,
189 // and may be invoked multiple times for a given package path.
190 AllowPackage func(ctx context.Context, path string, mod module.Version) error
192 // LoadTests loads the test dependencies of each package matching a requested
193 // pattern. If ResolveMissingImports is also true, test dependencies will be
194 // resolved if missing.
197 // UseVendorAll causes the "all" package pattern to be interpreted as if
198 // running "go mod vendor" (or building with "-mod=vendor").
200 // This is a no-op for modules that declare 'go 1.16' or higher, for which this
201 // is the default (and only) interpretation of the "all" pattern in module mode.
204 // AllowErrors indicates that LoadPackages should not terminate the process if
208 // SilencePackageErrors indicates that LoadPackages should not print errors
209 // that occur while matching or loading packages, and should not terminate the
210 // process if such an error occurs.
212 // Errors encountered in the module graph will still be reported.
214 // The caller may retrieve the silenced package errors using the Lookup
215 // function, and matching errors are still populated in the Errs field of the
216 // associated search.Match.)
217 SilencePackageErrors bool
219 // SilenceMissingStdImports indicates that LoadPackages should not print
220 // errors or terminate the process if an imported package is missing, and the
221 // import path looks like it might be in the standard library (perhaps in a
223 SilenceMissingStdImports bool
225 // SilenceNoGoErrors indicates that LoadPackages should not print
226 // imports.ErrNoGo errors.
227 // This allows the caller to invoke LoadPackages (and report other errors)
228 // without knowing whether the requested packages exist for the given tags.
230 // Note that if a requested package does not exist *at all*, it will fail
231 // during module resolution and the error will not be suppressed.
232 SilenceNoGoErrors bool
234 // SilenceUnmatchedWarnings suppresses the warnings normally emitted for
235 // patterns that did not match any packages.
236 SilenceUnmatchedWarnings bool
238 // Resolve the query against this module.
239 MainModule module.Version
242 // LoadPackages identifies the set of packages matching the given patterns and
243 // loads the packages in the import graph rooted at that set.
244 func LoadPackages(ctx context.Context, opts PackageOpts, patterns ...string) (matches []*search.Match, loadedPackages []string) {
245 if opts.Tags == nil {
246 opts.Tags = imports.Tags()
249 patterns = search.CleanPatterns(patterns)
250 matches = make([]*search.Match, 0, len(patterns))
251 allPatternIsRoot := false
252 for _, pattern := range patterns {
253 matches = append(matches, search.NewMatch(pattern))
254 if pattern == "all" {
255 allPatternIsRoot = true
259 updateMatches := func(rs *Requirements, ld *loader) {
260 for _, m := range matches {
263 // Evaluate list of file system directories on first iteration.
265 matchModRoots := modRoots
266 if opts.MainModule != (module.Version{}) {
267 matchModRoots = []string{MainModules.ModRoot(opts.MainModule)}
269 matchLocalDirs(ctx, matchModRoots, m, rs)
272 // Make a copy of the directory list and translate to import paths.
273 // Note that whether a directory corresponds to an import path
274 // changes as the build list is updated, and a directory can change
275 // from not being in the build list to being in it and back as
276 // the exact version of a particular module increases during
277 // the loader iterations.
279 for _, dir := range m.Dirs {
280 pkg, err := resolveLocalPackage(ctx, dir, rs)
282 if !m.IsLiteral() && (err == errPkgIsBuiltin || err == errPkgIsGorootSrc) {
283 continue // Don't include "builtin" or GOROOT/src in wildcard patterns.
286 // If we're outside of a module, ensure that the failure mode
297 m.Pkgs = append(m.Pkgs, pkg)
301 m.Pkgs = []string{m.Pattern()}
303 case strings.Contains(m.Pattern(), "..."):
305 mg, err := rs.Graph(ctx)
307 // The module graph is (or may be) incomplete — perhaps we failed to
308 // load the requirements of some module. This is an error in matching
309 // the patterns to packages, because we may be missing some packages
310 // or we may erroneously match packages in the wrong versions of
311 // modules. However, for cases like 'go list -e', the error should not
312 // necessarily prevent us from loading the packages we could find.
313 m.Errs = append(m.Errs, err)
315 matchPackages(ctx, m, opts.Tags, includeStd, mg.BuildList())
317 case m.Pattern() == "all":
319 // The initial roots are the packages in the main module.
320 // loadFromRoots will expand that to "all".
322 matchModules := MainModules.Versions()
323 if opts.MainModule != (module.Version{}) {
324 matchModules = []module.Version{opts.MainModule}
326 matchPackages(ctx, m, opts.Tags, omitStd, matchModules)
328 // Starting with the packages in the main module,
329 // enumerate the full list of "all".
330 m.Pkgs = ld.computePatternAll()
333 case m.Pattern() == "std" || m.Pattern() == "cmd":
335 m.MatchPackages() // Locate the packages within GOROOT/src.
339 panic(fmt.Sprintf("internal error: modload missing case for pattern %s", m.Pattern()))
344 initialRS := loadModFile(ctx, &opts)
346 ld := loadFromRoots(ctx, loaderParams{
348 requirements: initialRS,
350 allPatternIsRoot: allPatternIsRoot,
352 listRoots: func(rs *Requirements) (roots []string) {
353 updateMatches(rs, nil)
354 for _, m := range matches {
355 roots = append(roots, m.Pkgs...)
361 // One last pass to finalize wildcards.
362 updateMatches(ld.requirements, ld)
364 // List errors in matching patterns (such as directory permission
365 // errors for wildcard patterns).
366 if !ld.SilencePackageErrors {
367 for _, match := range matches {
368 for _, err := range match.Errs {
369 ld.errorf("%v\n", err)
375 if !opts.SilenceUnmatchedWarnings {
376 search.WarnUnmatched(matches)
381 mg, _ := ld.requirements.Graph(ctx)
383 for _, m := range initialRS.rootModules {
385 if ld.requirements.pruning == unpruned {
386 // m is unused if it was dropped from the module graph entirely. If it
387 // was only demoted from direct to indirect, it may still be in use via
388 // a transitive import.
389 unused = mg.Selected(m.Path) == "none"
391 // m is unused if it was dropped from the roots. If it is still present
392 // as a transitive dependency, that transitive dependency is not needed
393 // by any package or test in the main module.
394 _, ok := ld.requirements.rootSelected(m.Path)
398 fmt.Fprintf(os.Stderr, "unused %s\n", m.Path)
403 keep := keepSums(ctx, ld, ld.requirements, loadedZipSumsOnly)
404 if compatDepth := pruningForGoVersion(ld.TidyCompatibleVersion); compatDepth != ld.requirements.pruning {
405 compatRS := newRequirements(compatDepth, ld.requirements.rootModules, ld.requirements.direct)
406 ld.checkTidyCompatibility(ctx, compatRS)
408 for m := range keepSums(ctx, ld, compatRS, loadedZipSumsOnly) {
413 // Update the go.mod file's Go version if necessary.
414 if modFile := ModFile(); modFile != nil && ld.GoVersion != "" {
415 mg, _ := ld.requirements.Graph(ctx)
417 if v := mg.Selected("go"); gover.Compare(ld.GoVersion, v) < 0 {
418 base.Fatalf("go: cannot tidy -go=%v: dependencies require %v", ld.GoVersion, v)
421 modFile.AddGoStmt(ld.GoVersion)
424 if !ExplicitWriteGoMod {
425 modfetch.TrimGoSum(keep)
427 // commitRequirements below will also call WriteGoSum, but the "keep" map
428 // we have here could be strictly larger: commitRequirements only commits
429 // loaded.requirements, but here we may have also loaded (and want to
430 // preserve checksums for) additional entities from compatRS, which are
431 // only needed for compatibility with ld.TidyCompatibleVersion.
432 if err := modfetch.WriteGoSum(ctx, keep, mustHaveCompleteRequirements()); err != nil {
433 base.Fatalf("go: %v", err)
438 // Success! Update go.mod and go.sum (if needed) and return the results.
439 // We'll skip updating if ExplicitWriteGoMod is true (the caller has opted
440 // to call WriteGoMod itself) or if ResolveMissingImports is false (the
441 // command wants to examine the package graph as-is).
443 requirements = loaded.requirements
445 for _, pkg := range ld.pkgs {
447 loadedPackages = append(loadedPackages, pkg.path)
450 sort.Strings(loadedPackages)
452 if !ExplicitWriteGoMod && opts.ResolveMissingImports {
453 if err := commitRequirements(ctx, WriteOpts{}); err != nil {
454 base.Fatalf("go: %v", err)
458 return matches, loadedPackages
461 // matchLocalDirs is like m.MatchDirs, but tries to avoid scanning directories
462 // outside of the standard library and active modules.
463 func matchLocalDirs(ctx context.Context, modRoots []string, m *search.Match, rs *Requirements) {
465 panic(fmt.Sprintf("internal error: resolveLocalDirs on non-local pattern %s", m.Pattern()))
468 if i := strings.Index(m.Pattern(), "..."); i >= 0 {
469 // The pattern is local, but it is a wildcard. Its packages will
470 // only resolve to paths if they are inside of the standard
471 // library, the main module, or some dependency of the main
472 // module. Verify that before we walk the filesystem: a filesystem
473 // walk in a directory like /var or /etc can be very expensive!
474 dir := filepath.Dir(filepath.Clean(m.Pattern()[:i+3]))
476 if !filepath.IsAbs(dir) {
477 absDir = filepath.Join(base.Cwd(), dir)
480 modRoot := findModuleRoot(absDir)
482 for _, mainModuleRoot := range modRoots {
483 if mainModuleRoot == modRoot {
488 if !found && search.InDir(absDir, cfg.GOROOTsrc) == "" && pathInModuleCache(ctx, absDir, rs) == "" {
490 scope := "main module or its selected dependencies"
491 if inWorkspaceMode() {
492 scope = "modules listed in go.work or their selected dependencies"
494 m.AddError(fmt.Errorf("directory prefix %s does not contain %s", base.ShortPath(absDir), scope))
499 m.MatchDirs(modRoots)
502 // resolveLocalPackage resolves a filesystem path to a package path.
503 func resolveLocalPackage(ctx context.Context, dir string, rs *Requirements) (string, error) {
505 if filepath.IsAbs(dir) {
506 absDir = filepath.Clean(dir)
508 absDir = filepath.Join(base.Cwd(), dir)
511 bp, err := cfg.BuildContext.ImportDir(absDir, 0)
512 if err != nil && (bp == nil || len(bp.IgnoredGoFiles) == 0) {
513 // golang.org/issue/32917: We should resolve a relative path to a
514 // package path only if the relative path actually contains the code
517 // If the named directory does not exist or contains no Go files,
518 // the package does not exist.
519 // Other errors may affect package loading, but not resolution.
520 if _, err := fsys.Stat(absDir); err != nil {
521 if os.IsNotExist(err) {
522 // Canonicalize OS-specific errors to errDirectoryNotFound so that error
523 // messages will be easier for users to search for.
524 return "", &fs.PathError{Op: "stat", Path: absDir, Err: errDirectoryNotFound}
528 if _, noGo := err.(*build.NoGoError); noGo {
529 // A directory that does not contain any Go source files — even ignored
530 // ones! — is not a Go package, and we can't resolve it to a package
531 // path because that path could plausibly be provided by some other
534 // Any other error indicates that the package “exists” (at least in the
535 // sense that it cannot exist in any other module), but has some other
536 // problem (such as a syntax error).
541 for _, mod := range MainModules.Versions() {
542 modRoot := MainModules.ModRoot(mod)
543 if modRoot != "" && absDir == modRoot {
544 if absDir == cfg.GOROOTsrc {
545 return "", errPkgIsGorootSrc
547 return MainModules.PathPrefix(mod), nil
551 // Note: The checks for @ here are just to avoid misinterpreting
552 // the module cache directories (formerly GOPATH/src/mod/foo@v1.5.2/bar).
553 // It's not strictly necessary but helpful to keep the checks.
554 var pkgNotFoundErr error
555 pkgNotFoundLongestPrefix := ""
556 for _, mainModule := range MainModules.Versions() {
557 modRoot := MainModules.ModRoot(mainModule)
558 if modRoot != "" && str.HasFilePathPrefix(absDir, modRoot) && !strings.Contains(absDir[len(modRoot):], "@") {
559 suffix := filepath.ToSlash(str.TrimFilePathPrefix(absDir, modRoot))
560 if pkg, found := strings.CutPrefix(suffix, "vendor/"); found {
561 if cfg.BuildMod != "vendor" {
562 return "", fmt.Errorf("without -mod=vendor, directory %s has no package path", absDir)
565 readVendorList(mainModule)
566 if _, ok := vendorPkgModule[pkg]; !ok {
567 return "", fmt.Errorf("directory %s is not a package listed in vendor/modules.txt", absDir)
572 mainModulePrefix := MainModules.PathPrefix(mainModule)
573 if mainModulePrefix == "" {
575 if pkg == "builtin" {
576 // "builtin" is a pseudo-package with a real source file.
577 // It's not included in "std", so it shouldn't resolve from "."
578 // within module "std" either.
579 return "", errPkgIsBuiltin
584 pkg := pathpkg.Join(mainModulePrefix, suffix)
585 if _, ok, err := dirInModule(pkg, mainModulePrefix, modRoot, true); err != nil {
588 // This main module could contain the directory but doesn't. Other main
589 // modules might contain the directory, so wait till we finish the loop
590 // to see if another main module contains directory. But if not,
592 if len(mainModulePrefix) > len(pkgNotFoundLongestPrefix) {
593 pkgNotFoundLongestPrefix = mainModulePrefix
594 pkgNotFoundErr = &PackageNotInModuleError{MainModules: []module.Version{mainModule}, Pattern: pkg}
601 if pkgNotFoundErr != nil {
602 return "", pkgNotFoundErr
605 if sub := search.InDir(absDir, cfg.GOROOTsrc); sub != "" && sub != "." && !strings.Contains(sub, "@") {
606 pkg := filepath.ToSlash(sub)
607 if pkg == "builtin" {
608 return "", errPkgIsBuiltin
613 pkg := pathInModuleCache(ctx, absDir, rs)
615 dirstr := fmt.Sprintf("directory %s", base.ShortPath(absDir))
616 if dirstr == "directory ." {
617 dirstr = "current directory"
619 if inWorkspaceMode() {
620 if mr := findModuleRoot(absDir); mr != "" {
621 return "", fmt.Errorf("%s is contained in a module that is not one of the workspace modules listed in go.work. You can add the module to the workspace using:\n\tgo work use %s", dirstr, base.ShortPath(mr))
623 return "", fmt.Errorf("%s outside modules listed in go.work or their selected dependencies", dirstr)
625 return "", fmt.Errorf("%s outside main module or its selected dependencies", dirstr)
631 errDirectoryNotFound = errors.New("directory not found")
632 errPkgIsGorootSrc = errors.New("GOROOT/src is not an importable package")
633 errPkgIsBuiltin = errors.New(`"builtin" is a pseudo-package, not an importable package`)
636 // pathInModuleCache returns the import path of the directory dir,
637 // if dir is in the module cache copy of a module in our build list.
638 func pathInModuleCache(ctx context.Context, dir string, rs *Requirements) string {
639 tryMod := func(m module.Version) (string, bool) {
640 if gover.IsToolchain(m.Path) {
645 if repl := Replacement(m); repl.Path != "" && repl.Version == "" {
647 if !filepath.IsAbs(root) {
648 root = filepath.Join(replaceRelativeTo(), root)
650 } else if repl.Path != "" {
651 root, err = modfetch.DownloadDir(ctx, repl)
653 root, err = modfetch.DownloadDir(ctx, m)
659 sub := search.InDir(dir, root)
663 sub = filepath.ToSlash(sub)
664 if strings.Contains(sub, "/vendor/") || strings.HasPrefix(sub, "vendor/") || strings.Contains(sub, "@") {
668 return path.Join(m.Path, filepath.ToSlash(sub)), true
671 if rs.pruning == pruned {
672 for _, m := range rs.rootModules {
673 if v, _ := rs.rootSelected(m.Path); v != m.Version {
674 continue // m is a root, but we have a higher root for the same path.
676 if importPath, ok := tryMod(m); ok {
677 // checkMultiplePaths ensures that a module can be used for at most one
678 // requirement, so this must be it.
684 // None of the roots contained dir, or the graph is unpruned (so we don't want
685 // to distinguish between roots and transitive dependencies). Either way,
686 // check the full graph to see if the directory is a non-root dependency.
688 // If the roots are not consistent with the full module graph, the selected
689 // versions of root modules may differ from what we already checked above.
690 // Re-check those paths too.
692 mg, _ := rs.Graph(ctx)
693 var importPath string
694 for _, m := range mg.BuildList() {
696 importPath, found = tryMod(m)
704 // ImportFromFiles adds modules to the build list as needed
705 // to satisfy the imports in the named Go source files.
707 // Errors in missing dependencies are silenced.
709 // TODO(bcmills): Silencing errors seems off. Take a closer look at this and
710 // figure out what the error-reporting actually ought to be.
711 func ImportFromFiles(ctx context.Context, gofiles []string) {
712 rs := LoadModFile(ctx)
714 tags := imports.Tags()
715 imports, testImports, err := imports.ScanFiles(gofiles, tags)
717 base.Fatalf("go: %v", err)
720 loaded = loadFromRoots(ctx, loaderParams{
721 PackageOpts: PackageOpts{
723 ResolveMissingImports: true,
724 SilencePackageErrors: true,
727 listRoots: func(*Requirements) (roots []string) {
728 roots = append(roots, imports...)
729 roots = append(roots, testImports...)
733 requirements = loaded.requirements
735 if !ExplicitWriteGoMod {
736 if err := commitRequirements(ctx, WriteOpts{}); err != nil {
737 base.Fatalf("go: %v", err)
742 // DirImportPath returns the effective import path for dir,
743 // provided it is within a main module, or else returns ".".
744 func (mms *MainModuleSet) DirImportPath(ctx context.Context, dir string) (path string, m module.Version) {
746 return ".", module.Version{}
748 LoadModFile(ctx) // Sets targetPrefix.
750 if !filepath.IsAbs(dir) {
751 dir = filepath.Join(base.Cwd(), dir)
753 dir = filepath.Clean(dir)
756 var longestPrefix string
757 var longestPrefixPath string
758 var longestPrefixVersion module.Version
759 for _, v := range mms.Versions() {
760 modRoot := mms.ModRoot(v)
762 return mms.PathPrefix(v), v
764 if str.HasFilePathPrefix(dir, modRoot) {
765 pathPrefix := MainModules.PathPrefix(v)
766 if pathPrefix > longestPrefix {
767 longestPrefix = pathPrefix
768 longestPrefixVersion = v
769 suffix := filepath.ToSlash(str.TrimFilePathPrefix(dir, modRoot))
770 if strings.HasPrefix(suffix, "vendor/") {
771 longestPrefixPath = strings.TrimPrefix(suffix, "vendor/")
774 longestPrefixPath = pathpkg.Join(mms.PathPrefix(v), suffix)
778 if len(longestPrefix) > 0 {
779 return longestPrefixPath, longestPrefixVersion
782 return ".", module.Version{}
785 // PackageModule returns the module providing the package named by the import path.
786 func PackageModule(path string) module.Version {
787 pkg, ok := loaded.pkgCache.Get(path)
789 return module.Version{}
794 // Lookup returns the source directory, import path, and any loading error for
795 // the package at path as imported from the package in parentDir.
796 // Lookup requires that one of the Load functions in this package has already
798 func Lookup(parentPath string, parentIsStd bool, path string) (dir, realPath string, err error) {
800 panic("Lookup called with empty package path")
804 path = loaded.stdVendor(parentPath, path)
806 pkg, ok := loaded.pkgCache.Get(path)
808 // The loader should have found all the relevant paths.
809 // There are a few exceptions, though:
810 // - during go list without -test, the p.Resolve calls to process p.TestImports and p.XTestImports
811 // end up here to canonicalize the import paths.
812 // - during any load, non-loaded packages like "unsafe" end up here.
813 // - during any load, build-injected dependencies like "runtime/cgo" end up here.
814 // - because we ignore appengine/* in the module loader,
815 // the dependencies of any actual appengine/* library end up here.
816 dir := findStandardImportPath(path)
818 return dir, path, nil
820 return "", "", errMissing
822 return pkg.dir, pkg.path, pkg.err
825 // A loader manages the process of loading information about
826 // the required packages for a particular build,
827 // checking that the packages are available in the module set,
828 // and updating the module set if needed.
832 // allClosesOverTests indicates whether the "all" pattern includes
833 // dependencies of tests outside the main module (as in Go 1.11–1.15).
834 // (Otherwise — as in Go 1.16+ — the "all" pattern includes only the packages
835 // transitively *imported by* the packages and tests in the main module.)
836 allClosesOverTests bool
838 // skipImportModFiles indicates whether we may skip loading go.mod files
839 // for imported packages (as in 'go mod tidy' in Go 1.17–1.20).
840 skipImportModFiles bool
844 // reset on each iteration
846 pkgCache *par.Cache[string, *loadPkg]
847 pkgs []*loadPkg // transitive closure of loaded packages and tests; populated in buildStacks
850 // loaderParams configure the packages loaded by, and the properties reported
851 // by, a loader instance.
852 type loaderParams struct {
854 requirements *Requirements
856 allPatternIsRoot bool // Is the "all" pattern an additional root?
858 listRoots func(rs *Requirements) []string
861 func (ld *loader) reset() {
863 case <-ld.work.Idle():
865 panic("loader.reset when not idle")
869 ld.pkgCache = new(par.Cache[string, *loadPkg])
873 // errorf reports an error via either os.Stderr or base.Errorf,
874 // according to whether ld.AllowErrors is set.
875 func (ld *loader) errorf(format string, args ...any) {
877 fmt.Fprintf(os.Stderr, format, args...)
879 base.Errorf(format, args...)
883 // A loadPkg records information about a single loaded package.
884 type loadPkg struct {
885 // Populated at construction time:
886 path string // import path
889 // Populated at construction time and updated by (*loader).applyPkgFlags:
890 flags atomicLoadPkgFlags
892 // Populated by (*loader).load:
893 mod module.Version // module providing package
894 dir string // directory containing source code
895 err error // error loading package
896 imports []*loadPkg // packages imported by this one
897 testImports []string // test-only imports, saved for use by pkg.test.
899 altMods []module.Version // modules that could have contained the package but did not
901 // Populated by (*loader).pkgTest:
905 // Populated by postprocessing in (*loader).buildStacks:
906 stack *loadPkg // package importing this one in minimal import stack for this pkg
909 // loadPkgFlags is a set of flags tracking metadata about a package.
910 type loadPkgFlags int8
913 // pkgInAll indicates that the package is in the "all" package pattern,
914 // regardless of whether we are loading the "all" package pattern.
916 // When the pkgInAll flag and pkgImportsLoaded flags are both set, the caller
917 // who set the last of those flags must propagate the pkgInAll marking to all
918 // of the imports of the marked package.
920 // A test is marked with pkgInAll if that test would promote the packages it
921 // imports to be in "all" (such as when the test is itself within the main
922 // module, or when ld.allClosesOverTests is true).
923 pkgInAll loadPkgFlags = 1 << iota
925 // pkgIsRoot indicates that the package matches one of the root package
926 // patterns requested by the caller.
928 // If LoadTests is set, then when pkgIsRoot and pkgImportsLoaded are both set,
929 // the caller who set the last of those flags must populate a test for the
930 // package (in the pkg.test field).
932 // If the "all" pattern is included as a root, then non-test packages in "all"
933 // are also roots (and must be marked pkgIsRoot).
936 // pkgFromRoot indicates that the package is in the transitive closure of
937 // imports starting at the roots. (Note that every package marked as pkgIsRoot
938 // is also trivially marked pkgFromRoot.)
941 // pkgImportsLoaded indicates that the imports and testImports fields of a
942 // loadPkg have been populated.
946 // has reports whether all of the flags in cond are set in f.
947 func (f loadPkgFlags) has(cond loadPkgFlags) bool {
948 return f&cond == cond
951 // An atomicLoadPkgFlags stores a loadPkgFlags for which individual flags can be
953 type atomicLoadPkgFlags struct {
957 // update sets the given flags in af (in addition to any flags already set).
959 // update returns the previous flag state so that the caller may determine which
960 // flags were newly-set.
961 func (af *atomicLoadPkgFlags) update(flags loadPkgFlags) (old loadPkgFlags) {
963 old := af.bits.Load()
964 new := old | int32(flags)
965 if new == old || af.bits.CompareAndSwap(old, new) {
966 return loadPkgFlags(old)
971 // has reports whether all of the flags in cond are set in af.
972 func (af *atomicLoadPkgFlags) has(cond loadPkgFlags) bool {
973 return loadPkgFlags(af.bits.Load())&cond == cond
976 // isTest reports whether pkg is a test of another package.
977 func (pkg *loadPkg) isTest() bool {
978 return pkg.testOf != nil
981 // fromExternalModule reports whether pkg was loaded from a module other than
983 func (pkg *loadPkg) fromExternalModule() bool {
984 if pkg.mod.Path == "" {
985 return false // loaded from the standard library, not a module
987 return !MainModules.Contains(pkg.mod.Path)
990 var errMissing = errors.New("cannot find package")
992 // loadFromRoots attempts to load the build graph needed to process a set of
993 // root packages and their dependencies.
995 // The set of root packages is returned by the params.listRoots function, and
996 // expanded to the full set of packages by tracing imports (and possibly tests)
998 func loadFromRoots(ctx context.Context, params loaderParams) *loader {
1000 loaderParams: params,
1001 work: par.NewQueue(runtime.GOMAXPROCS(0)),
1004 if ld.GoVersion == "" {
1005 ld.GoVersion = MainModules.GoVersion()
1007 if ld.Tidy && versionLess(gover.Local(), ld.GoVersion) {
1008 ld.errorf("go: go.mod file indicates go %s, but maximum version supported by tidy is %s\n", ld.GoVersion, gover.Local())
1014 if ld.TidyCompatibleVersion == "" {
1015 ld.TidyCompatibleVersion = gover.Prev(ld.GoVersion)
1016 } else if versionLess(ld.GoVersion, ld.TidyCompatibleVersion) {
1017 // Each version of the Go toolchain knows how to interpret go.mod and
1018 // go.sum files produced by all previous versions, so a compatibility
1019 // version higher than the go.mod version adds nothing.
1020 ld.TidyCompatibleVersion = ld.GoVersion
1023 if gover.Compare(ld.GoVersion, tidyGoModSumVersion) < 0 {
1024 ld.skipImportModFiles = true
1028 if gover.Compare(ld.GoVersion, narrowAllVersion) < 0 && !ld.UseVendorAll {
1029 // The module's go version explicitly predates the change in "all" for graph
1030 // pruning, so continue to use the older interpretation.
1031 ld.allClosesOverTests = true
1035 desiredPruning := pruningForGoVersion(ld.GoVersion)
1036 if ld.requirements.pruning == workspace {
1037 desiredPruning = workspace
1039 ld.requirements, err = convertPruning(ctx, ld.requirements, desiredPruning)
1041 ld.errorf("go: %v\n", err)
1044 if ld.requirements.pruning == unpruned {
1045 // If the module graph does not support pruning, we assume that we will need
1046 // the full module graph in order to load package dependencies.
1048 // This might not be strictly necessary, but it matches the historical
1049 // behavior of the 'go' command and keeps the go.mod file more consistent in
1050 // case of erroneous hand-edits — which are less likely to be detected by
1051 // spot-checks in modules that do not maintain the expanded go.mod
1052 // requirements needed for graph pruning.
1054 ld.requirements, _, err = expandGraph(ctx, ld.requirements)
1056 ld.errorf("go: %v\n", err)
1059 base.ExitIfErrors() // or we will report them again
1064 // Load the root packages and their imports.
1065 // Note: the returned roots can change on each iteration,
1066 // since the expansion of package patterns depends on the
1067 // build list we're using.
1068 rootPkgs := ld.listRoots(ld.requirements)
1070 if ld.requirements.pruning == pruned && cfg.BuildMod == "mod" {
1071 // Before we start loading transitive imports of packages, locate all of
1072 // the root packages and promote their containing modules to root modules
1073 // dependencies. If their go.mod files are tidy (the common case) and the
1074 // set of root packages does not change then we can select the correct
1075 // versions of all transitive imports on the first try and complete
1076 // loading in a single iteration.
1077 changedBuildList := ld.preloadRootModules(ctx, rootPkgs)
1078 if changedBuildList {
1079 // The build list has changed, so the set of root packages may have also
1080 // changed. Start over to pick up the changes. (Preloading roots is much
1081 // cheaper than loading the full import graph, so we would rather pay
1082 // for an extra iteration of preloading than potentially end up
1083 // discarding the result of a full iteration of loading.)
1088 inRoots := map[*loadPkg]bool{}
1089 for _, path := range rootPkgs {
1090 root := ld.pkg(ctx, path, pkgIsRoot)
1092 ld.roots = append(ld.roots, root)
1093 inRoots[root] = true
1097 // ld.pkg adds imported packages to the work queue and calls applyPkgFlags,
1098 // which adds tests (and test dependencies) as needed.
1100 // When all of the work in the queue has completed, we'll know that the
1101 // transitive closure of dependencies has been loaded.
1106 changed, err := ld.updateRequirements(ctx)
1108 ld.errorf("go: %v\n", err)
1112 // Don't resolve missing imports until the module graph has stabilized.
1113 // If the roots are still changing, they may turn out to specify a
1114 // requirement on the missing package(s), and we would rather use a
1115 // version specified by a new root than add a new dependency on an
1116 // unrelated version.
1120 if !ld.ResolveMissingImports || (!HasModRoot() && !allowMissingModuleImports) {
1121 // We've loaded as much as we can without resolving missing imports.
1125 modAddedBy := ld.resolveMissingImports(ctx)
1126 if len(modAddedBy) == 0 {
1127 // The roots are stable, and we've resolved all of the missing packages
1132 toAdd := make([]module.Version, 0, len(modAddedBy))
1133 for m := range modAddedBy {
1134 toAdd = append(toAdd, m)
1136 gover.ModSort(toAdd) // to make errors deterministic
1138 // We ran updateRequirements before resolving missing imports and it didn't
1139 // make any changes, so we know that the requirement graph is already
1140 // consistent with ld.pkgs: we don't need to pass ld.pkgs to updateRoots
1141 // again. (That would waste time looking for changes that we have already
1143 var noPkgs []*loadPkg
1144 // We also know that we're going to call updateRequirements again next
1145 // iteration so we don't need to also update it here. (That would waste time
1146 // computing a "direct" map that we'll have to recompute later anyway.)
1147 direct := ld.requirements.direct
1148 rs, err := updateRoots(ctx, direct, ld.requirements, noPkgs, toAdd, ld.AssumeRootsImported)
1150 // If an error was found in a newly added module, report the package
1151 // import stack instead of the module requirement stack. Packages
1152 // are more descriptive.
1153 if err, ok := err.(*mvs.BuildListError); ok {
1154 if pkg := modAddedBy[err.Module()]; pkg != nil {
1155 ld.errorf("go: %s: %v\n", pkg.stackText(), err.Err)
1159 ld.errorf("go: %v\n", err)
1162 if reflect.DeepEqual(rs.rootModules, ld.requirements.rootModules) {
1163 // Something is deeply wrong. resolveMissingImports gave us a non-empty
1164 // set of modules to add to the graph, but adding those modules had no
1165 // effect — either they were already in the graph, or updateRoots did not
1166 // add them as requested.
1167 panic(fmt.Sprintf("internal error: adding %v to module graph had no effect on root requirements (%v)", toAdd, rs.rootModules))
1169 ld.requirements = rs
1171 base.ExitIfErrors() // TODO(bcmills): Is this actually needed?
1173 // Tidy the build list, if applicable, before we report errors.
1174 // (The process of tidying may remove errors from irrelevant dependencies.)
1176 rs, err := tidyRoots(ctx, ld.requirements, ld.pkgs)
1178 ld.errorf("go: %v\n", err)
1181 if ld.requirements.pruning == pruned {
1182 // We continuously add tidy roots to ld.requirements during loading, so at
1183 // this point the tidy roots should be a subset of the roots of
1184 // ld.requirements, ensuring that no new dependencies are brought inside
1185 // the graph-pruning horizon.
1186 // If that is not the case, there is a bug in the loading loop above.
1187 for _, m := range rs.rootModules {
1188 if v, ok := ld.requirements.rootSelected(m.Path); !ok || v != m.Version {
1189 ld.errorf("go: internal error: a requirement on %v is needed but was not added during package loading\n", m)
1194 ld.requirements = rs
1198 // Report errors, if any.
1199 for _, pkg := range ld.pkgs {
1204 // Add importer information to checksum errors.
1205 if sumErr := (*ImportMissingSumError)(nil); errors.As(pkg.err, &sumErr) {
1206 if importer := pkg.stack; importer != nil {
1207 sumErr.importer = importer.path
1208 sumErr.importerVersion = importer.mod.Version
1209 sumErr.importerIsTest = importer.testOf != nil
1213 if stdErr := (*ImportMissingError)(nil); errors.As(pkg.err, &stdErr) && stdErr.isStd {
1214 // Add importer go version information to import errors of standard
1215 // library packages arising from newer releases.
1216 if importer := pkg.stack; importer != nil {
1217 if v, ok := rawGoVersion.Load(importer.mod); ok && versionLess(gover.Local(), v.(string)) {
1218 stdErr.importerGoVersion = v.(string)
1221 if ld.SilenceMissingStdImports {
1225 if ld.SilencePackageErrors {
1228 if ld.SilenceNoGoErrors && errors.Is(pkg.err, imports.ErrNoGo) {
1232 ld.errorf("%s: %v\n", pkg.stackText(), pkg.err)
1235 ld.checkMultiplePaths()
1239 // versionLess returns whether a < b according to semantic version precedence.
1240 // Both strings are interpreted as go version strings, e.g. "1.19".
1241 func versionLess(a, b string) bool {
1242 return gover.Compare(a, b) < 0
1245 // updateRequirements ensures that ld.requirements is consistent with the
1246 // information gained from ld.pkgs.
1250 // - Modules that provide packages directly imported from the main module are
1251 // marked as direct, and are promoted to explicit roots. If a needed root
1252 // cannot be promoted due to -mod=readonly or -mod=vendor, the importing
1253 // package is marked with an error.
1255 // - If ld scanned the "all" pattern independent of build constraints, it is
1256 // guaranteed to have seen every direct import. Module dependencies that did
1257 // not provide any directly-imported package are then marked as indirect.
1259 // - Root dependencies are updated to their selected versions.
1261 // The "changed" return value reports whether the update changed the selected
1262 // version of any module that either provided a loaded package or may now
1263 // provide a package that was previously unresolved.
1264 func (ld *loader) updateRequirements(ctx context.Context) (changed bool, err error) {
1265 rs := ld.requirements
1267 // direct contains the set of modules believed to provide packages directly
1268 // imported by the main module.
1269 var direct map[string]bool
1271 // If we didn't scan all of the imports from the main module, or didn't use
1272 // imports.AnyTags, then we didn't necessarily load every package that
1273 // contributes “direct” imports — so we can't safely mark existing direct
1274 // dependencies in ld.requirements as indirect-only. Propagate them as direct.
1275 loadedDirect := ld.allPatternIsRoot && reflect.DeepEqual(ld.Tags, imports.AnyTags())
1277 direct = make(map[string]bool)
1279 // TODO(bcmills): It seems like a shame to allocate and copy a map here when
1280 // it will only rarely actually vary from rs.direct. Measure this cost and
1281 // maybe avoid the copy.
1282 direct = make(map[string]bool, len(rs.direct))
1283 for mPath := range rs.direct {
1284 direct[mPath] = true
1288 for _, pkg := range ld.pkgs {
1289 if pkg.mod.Version != "" || !MainModules.Contains(pkg.mod.Path) {
1292 for _, dep := range pkg.imports {
1293 if !dep.fromExternalModule() {
1297 if inWorkspaceMode() {
1298 // In workspace mode / workspace pruning mode, the roots are the main modules
1299 // rather than the main module's direct dependencies. The check below on the selected
1300 // roots does not apply.
1301 if mg, err := rs.Graph(ctx); err != nil {
1303 } else if _, ok := mg.RequiredBy(dep.mod); !ok {
1304 // dep.mod is not an explicit dependency, but needs to be.
1305 // See comment on error returned below.
1306 pkg.err = &DirectImportFromImplicitDependencyError{
1307 ImporterPath: pkg.path,
1308 ImportedPath: dep.path,
1315 if pkg.err == nil && cfg.BuildMod != "mod" {
1316 if v, ok := rs.rootSelected(dep.mod.Path); !ok || v != dep.mod.Version {
1317 // dep.mod is not an explicit dependency, but needs to be.
1318 // Because we are not in "mod" mode, we will not be able to update it.
1319 // Instead, mark the importing package with an error.
1321 // TODO(#41688): The resulting error message fails to include the file
1322 // position of the import statement (because that information is not
1323 // tracked by the module loader). Figure out how to plumb the import
1324 // position through.
1325 pkg.err = &DirectImportFromImplicitDependencyError{
1326 ImporterPath: pkg.path,
1327 ImportedPath: dep.path,
1330 // cfg.BuildMod does not allow us to change dep.mod to be a direct
1331 // dependency, so don't mark it as such.
1336 // dep is a package directly imported by a package or test in the main
1337 // module and loaded from some other module (not the standard library).
1338 // Mark its module as a direct dependency.
1339 direct[dep.mod.Path] = true
1343 var addRoots []module.Version
1345 // When we are tidying a module with a pruned dependency graph, we may need
1346 // to add roots to preserve the versions of indirect, test-only dependencies
1347 // that are upgraded above or otherwise missing from the go.mod files of
1348 // direct dependencies. (For example, the direct dependency might be a very
1349 // stable codebase that predates modules and thus lacks a go.mod file, or
1350 // the author of the direct dependency may have forgotten to commit a change
1351 // to the go.mod file, or may have made an erroneous hand-edit that causes
1352 // it to be untidy.)
1354 // Promoting an indirect dependency to a root adds the next layer of its
1355 // dependencies to the module graph, which may increase the selected
1356 // versions of other modules from which we have already loaded packages.
1357 // So after we promote an indirect dependency to a root, we need to reload
1358 // packages, which means another iteration of loading.
1360 // As an extra wrinkle, the upgrades due to promoting a root can cause
1361 // previously-resolved packages to become unresolved. For example, the
1362 // module providing an unstable package might be upgraded to a version
1363 // that no longer contains that package. If we then resolve the missing
1364 // package, we might add yet another root that upgrades away some other
1365 // dependency. (The tests in mod_tidy_convergence*.txt illustrate some
1366 // particularly worrisome cases.)
1368 // To ensure that this process of promoting, adding, and upgrading roots
1369 // eventually terminates, during iteration we only ever add modules to the
1370 // root set — we only remove irrelevant roots at the very end of
1371 // iteration, after we have already added every root that we plan to need
1372 // in the (eventual) tidy root set.
1374 // Since we do not remove any roots during iteration, even if they no
1375 // longer provide any imported packages, the selected versions of the
1376 // roots can only increase and the set of roots can only expand. The set
1377 // of extant root paths is finite and the set of versions of each path is
1378 // finite, so the iteration *must* reach a stable fixed-point.
1379 tidy, err := tidyRoots(ctx, rs, ld.pkgs)
1383 addRoots = tidy.rootModules
1386 rs, err = updateRoots(ctx, direct, rs, ld.pkgs, addRoots, ld.AssumeRootsImported)
1388 // We don't actually know what even the root requirements are supposed to be,
1389 // so we can't proceed with loading. Return the error to the caller
1393 if rs != ld.requirements && !reflect.DeepEqual(rs.rootModules, ld.requirements.rootModules) {
1394 // The roots of the module graph have changed in some way (not just the
1395 // "direct" markings). Check whether the changes affected any of the loaded
1397 mg, err := rs.Graph(ctx)
1401 for _, pkg := range ld.pkgs {
1402 if pkg.fromExternalModule() && mg.Selected(pkg.mod.Path) != pkg.mod.Version {
1407 // Promoting a module to a root may resolve an import that was
1408 // previously missing (by pulling in a previously-prune dependency that
1409 // provides it) or ambiguous (by promoting exactly one of the
1410 // alternatives to a root and ignoring the second-level alternatives) or
1411 // otherwise errored out (by upgrading from a version that cannot be
1412 // fetched to one that can be).
1414 // Instead of enumerating all of the possible errors, we'll just check
1415 // whether importFromModules returns nil for the package.
1416 // False-positives are ok: if we have a false-positive here, we'll do an
1417 // extra iteration of package loading this time, but we'll still
1418 // converge when the root set stops changing.
1420 // In some sense, we can think of this as ‘upgraded the module providing
1421 // pkg.path from "none" to a version higher than "none"’.
1422 if _, _, _, _, err = importFromModules(ctx, pkg.path, rs, nil, ld.skipImportModFiles); err == nil {
1430 ld.requirements = rs
1434 // resolveMissingImports returns a set of modules that could be added as
1435 // dependencies in order to resolve missing packages from pkgs.
1437 // The newly-resolved packages are added to the addedModuleFor map, and
1438 // resolveMissingImports returns a map from each new module version to
1439 // the first missing package that module would resolve.
1440 func (ld *loader) resolveMissingImports(ctx context.Context) (modAddedBy map[module.Version]*loadPkg) {
1441 type pkgMod struct {
1445 var pkgMods []pkgMod
1446 for _, pkg := range ld.pkgs {
1451 // If we are missing a test, we are also missing its non-test version, and
1452 // we should only add the missing import once.
1455 if !errors.As(pkg.err, new(*ImportMissingError)) {
1456 // Leave other errors for Import or load.Packages to report.
1461 var mod module.Version
1462 ld.work.Add(func() {
1464 mod, err = queryImport(ctx, pkg.path, ld.requirements)
1466 var ime *ImportMissingError
1467 if errors.As(err, &ime) {
1468 for curstack := pkg.stack; curstack != nil; curstack = curstack.stack {
1469 if MainModules.Contains(curstack.mod.Path) {
1470 ime.ImportingMainModule = curstack.mod
1475 // pkg.err was already non-nil, so we can reasonably attribute the error
1476 // for pkg to either the original error or the one returned by
1477 // queryImport. The existing error indicates only that we couldn't find
1478 // the package, whereas the query error also explains why we didn't fix
1479 // the problem — so we prefer the latter.
1483 // err is nil, but we intentionally leave pkg.err non-nil and pkg.mod
1484 // unset: we still haven't satisfied other invariants of a
1485 // successfully-loaded package, such as scanning and loading the imports
1486 // of that package. If we succeed in resolving the new dependency graph,
1487 // the caller can reload pkg and update the error at that point.
1489 // Even then, the package might not be loaded from the version we've
1490 // identified here. The module may be upgraded by some other dependency,
1491 // or by a transitive dependency of mod itself, or — less likely — the
1492 // package may be rejected by an AllowPackage hook or rendered ambiguous
1493 // by some other newly-added or newly-upgraded dependency.
1496 pkgMods = append(pkgMods, pkgMod{pkg: pkg, mod: &mod})
1500 modAddedBy = map[module.Version]*loadPkg{}
1501 for _, pm := range pkgMods {
1502 pkg, mod := pm.pkg, *pm.mod
1507 fmt.Fprintf(os.Stderr, "go: found %s in %s %s\n", pkg.path, mod.Path, mod.Version)
1508 if modAddedBy[mod] == nil {
1509 modAddedBy[mod] = pkg
1516 // pkg locates the *loadPkg for path, creating and queuing it for loading if
1517 // needed, and updates its state to reflect the given flags.
1519 // The imports of the returned *loadPkg will be loaded asynchronously in the
1520 // ld.work queue, and its test (if requested) will also be populated once
1521 // imports have been resolved. When ld.work goes idle, all transitive imports of
1522 // the requested package (and its test, if requested) will have been loaded.
1523 func (ld *loader) pkg(ctx context.Context, path string, flags loadPkgFlags) *loadPkg {
1524 if flags.has(pkgImportsLoaded) {
1525 panic("internal error: (*loader).pkg called with pkgImportsLoaded flag set")
1528 pkg := ld.pkgCache.Do(path, func() *loadPkg {
1532 ld.applyPkgFlags(ctx, pkg, flags)
1534 ld.work.Add(func() { ld.load(ctx, pkg) })
1538 ld.applyPkgFlags(ctx, pkg, flags)
1542 // applyPkgFlags updates pkg.flags to set the given flags and propagate the
1543 // (transitive) effects of those flags, possibly loading or enqueueing further
1544 // packages as a result.
1545 func (ld *loader) applyPkgFlags(ctx context.Context, pkg *loadPkg, flags loadPkgFlags) {
1550 if flags.has(pkgInAll) && ld.allPatternIsRoot && !pkg.isTest() {
1551 // This package matches a root pattern by virtue of being in "all".
1554 if flags.has(pkgIsRoot) {
1555 flags |= pkgFromRoot
1558 old := pkg.flags.update(flags)
1560 if new == old || !new.has(pkgImportsLoaded) {
1561 // We either didn't change the state of pkg, or we don't know anything about
1562 // its dependencies yet. Either way, we can't usefully load its test or
1563 // update its dependencies.
1568 // Check whether we should add (or update the flags for) a test for pkg.
1569 // ld.pkgTest is idempotent and extra invocations are inexpensive,
1570 // so it's ok if we call it more than is strictly necessary.
1573 case ld.allPatternIsRoot && MainModules.Contains(pkg.mod.Path):
1574 // We are loading the "all" pattern, which includes packages imported by
1575 // tests in the main module. This package is in the main module, so we
1576 // need to identify the imports of its test even if LoadTests is not set.
1578 // (We will filter out the extra tests explicitly in computePatternAll.)
1581 case ld.allPatternIsRoot && ld.allClosesOverTests && new.has(pkgInAll):
1582 // This variant of the "all" pattern includes imports of tests of every
1583 // package that is itself in "all", and pkg is in "all", so its test is
1584 // also in "all" (as above).
1587 case ld.LoadTests && new.has(pkgIsRoot):
1588 // LoadTest explicitly requests tests of “the root packages”.
1593 var testFlags loadPkgFlags
1594 if MainModules.Contains(pkg.mod.Path) || (ld.allClosesOverTests && new.has(pkgInAll)) {
1595 // Tests of packages in the main module are in "all", in the sense that
1596 // they cause the packages they import to also be in "all". So are tests
1597 // of packages in "all" if "all" closes over test dependencies.
1598 testFlags |= pkgInAll
1600 ld.pkgTest(ctx, pkg, testFlags)
1604 if new.has(pkgInAll) && !old.has(pkgInAll|pkgImportsLoaded) {
1605 // We have just marked pkg with pkgInAll, or we have just loaded its
1606 // imports, or both. Now is the time to propagate pkgInAll to the imports.
1607 for _, dep := range pkg.imports {
1608 ld.applyPkgFlags(ctx, dep, pkgInAll)
1612 if new.has(pkgFromRoot) && !old.has(pkgFromRoot|pkgImportsLoaded) {
1613 for _, dep := range pkg.imports {
1614 ld.applyPkgFlags(ctx, dep, pkgFromRoot)
1619 // preloadRootModules loads the module requirements needed to identify the
1620 // selected version of each module providing a package in rootPkgs,
1621 // adding new root modules to the module graph if needed.
1622 func (ld *loader) preloadRootModules(ctx context.Context, rootPkgs []string) (changedBuildList bool) {
1623 needc := make(chan map[module.Version]bool, 1)
1624 needc <- map[module.Version]bool{}
1625 for _, path := range rootPkgs {
1627 ld.work.Add(func() {
1628 // First, try to identify the module containing the package using only roots.
1630 // If the main module is tidy and the package is in "all" — or if we're
1631 // lucky — we can identify all of its imports without actually loading the
1632 // full module graph.
1633 m, _, _, _, err := importFromModules(ctx, path, ld.requirements, nil, ld.skipImportModFiles)
1635 var missing *ImportMissingError
1636 if errors.As(err, &missing) && ld.ResolveMissingImports {
1637 // This package isn't provided by any selected module.
1638 // If we can find it, it will be a new root dependency.
1639 m, err = queryImport(ctx, path, ld.requirements)
1642 // We couldn't identify the root module containing this package.
1643 // Leave it unresolved; we will report it during loading.
1648 // The package is in std or cmd. We don't need to change the root set.
1652 v, ok := ld.requirements.rootSelected(m.Path)
1653 if !ok || v != m.Version {
1654 // We found the requested package in m, but m is not a root, so
1655 // loadModGraph will not load its requirements. We need to promote the
1656 // module to a root to ensure that any other packages this package
1657 // imports are resolved from correct dependency versions.
1659 // (This is the “argument invariant” from
1660 // https://golang.org/design/36460-lazy-module-loading.)
1671 return false // No roots to add.
1674 toAdd := make([]module.Version, 0, len(need))
1675 for m := range need {
1676 toAdd = append(toAdd, m)
1678 gover.ModSort(toAdd)
1680 rs, err := updateRoots(ctx, ld.requirements.direct, ld.requirements, nil, toAdd, ld.AssumeRootsImported)
1682 // We are missing some root dependency, and for some reason we can't load
1683 // enough of the module dependency graph to add the missing root. Package
1684 // loading is doomed to fail, so fail quickly.
1685 ld.errorf("go: %v\n", err)
1689 if reflect.DeepEqual(rs.rootModules, ld.requirements.rootModules) {
1690 // Something is deeply wrong. resolveMissingImports gave us a non-empty
1691 // set of modules to add to the graph, but adding those modules had no
1692 // effect — either they were already in the graph, or updateRoots did not
1693 // add them as requested.
1694 panic(fmt.Sprintf("internal error: adding %v to module graph had no effect on root requirements (%v)", toAdd, rs.rootModules))
1697 ld.requirements = rs
1701 // load loads an individual package.
1702 func (ld *loader) load(ctx context.Context, pkg *loadPkg) {
1704 if ld.requirements.pruning == unpruned {
1706 mg, err = ld.requirements.Graph(ctx)
1708 // We already checked the error from Graph in loadFromRoots and/or
1709 // updateRequirements, so we ignored the error on purpose and we should
1710 // keep trying to push past it.
1712 // However, because mg may be incomplete (and thus may select inaccurate
1713 // versions), we shouldn't use it to load packages. Instead, we pass a nil
1714 // *ModuleGraph, which will cause mg to first try loading from only the
1715 // main module and root dependencies.
1721 pkg.mod, modroot, pkg.dir, pkg.altMods, pkg.err = importFromModules(ctx, pkg.path, ld.requirements, mg, ld.skipImportModFiles)
1725 if MainModules.Contains(pkg.mod.Path) {
1726 // Go ahead and mark pkg as in "all". This provides the invariant that a
1727 // package that is *only* imported by other packages in "all" is always
1728 // marked as such before loading its imports.
1730 // We don't actually rely on that invariant at the moment, but it may
1731 // improve efficiency somewhat and makes the behavior a bit easier to reason
1732 // about (by reducing churn on the flag bits of dependencies), and costs
1733 // essentially nothing (these atomic flag ops are essentially free compared
1734 // to scanning source code for imports).
1735 ld.applyPkgFlags(ctx, pkg, pkgInAll)
1737 if ld.AllowPackage != nil {
1738 if err := ld.AllowPackage(ctx, pkg.path, pkg.mod); err != nil {
1743 pkg.inStd = (search.IsStandardImportPath(pkg.path) && search.InDir(pkg.dir, cfg.GOROOTsrc) != "")
1745 var imports, testImports []string
1747 if cfg.BuildContext.Compiler == "gccgo" && pkg.inStd {
1748 // We can't scan standard packages for gccgo.
1751 imports, testImports, err = scanDir(modroot, pkg.dir, ld.Tags)
1758 pkg.imports = make([]*loadPkg, 0, len(imports))
1759 var importFlags loadPkgFlags
1760 if pkg.flags.has(pkgInAll) {
1761 importFlags = pkgInAll
1763 for _, path := range imports {
1765 // Imports from packages in "std" and "cmd" should resolve using
1766 // GOROOT/src/vendor even when "std" is not the main module.
1767 path = ld.stdVendor(pkg.path, path)
1769 pkg.imports = append(pkg.imports, ld.pkg(ctx, path, importFlags))
1771 pkg.testImports = testImports
1773 ld.applyPkgFlags(ctx, pkg, pkgImportsLoaded)
1776 // pkgTest locates the test of pkg, creating it if needed, and updates its state
1777 // to reflect the given flags.
1779 // pkgTest requires that the imports of pkg have already been loaded (flagged
1780 // with pkgImportsLoaded).
1781 func (ld *loader) pkgTest(ctx context.Context, pkg *loadPkg, testFlags loadPkgFlags) *loadPkg {
1783 panic("pkgTest called on a test package")
1786 createdTest := false
1787 pkg.testOnce.Do(func() {
1788 pkg.test = &loadPkg{
1796 ld.applyPkgFlags(ctx, pkg.test, testFlags)
1802 test.imports = make([]*loadPkg, 0, len(pkg.testImports))
1803 var importFlags loadPkgFlags
1804 if test.flags.has(pkgInAll) {
1805 importFlags = pkgInAll
1807 for _, path := range pkg.testImports {
1809 path = ld.stdVendor(test.path, path)
1811 test.imports = append(test.imports, ld.pkg(ctx, path, importFlags))
1813 pkg.testImports = nil
1814 ld.applyPkgFlags(ctx, test, pkgImportsLoaded)
1816 ld.applyPkgFlags(ctx, test, testFlags)
1822 // stdVendor returns the canonical import path for the package with the given
1823 // path when imported from the standard-library package at parentPath.
1824 func (ld *loader) stdVendor(parentPath, path string) string {
1825 if search.IsStandardImportPath(path) {
1829 if str.HasPathPrefix(parentPath, "cmd") {
1830 if !ld.VendorModulesInGOROOTSrc || !MainModules.Contains("cmd") {
1831 vendorPath := pathpkg.Join("cmd", "vendor", path)
1833 if _, err := os.Stat(filepath.Join(cfg.GOROOTsrc, filepath.FromSlash(vendorPath))); err == nil {
1837 } else if !ld.VendorModulesInGOROOTSrc || !MainModules.Contains("std") || str.HasPathPrefix(parentPath, "vendor") {
1838 // If we are outside of the 'std' module, resolve imports from within 'std'
1839 // to the vendor directory.
1841 // Do the same for importers beginning with the prefix 'vendor/' even if we
1842 // are *inside* of the 'std' module: the 'vendor/' packages that resolve
1843 // globally from GOROOT/src/vendor (and are listed as part of 'go list std')
1844 // are distinct from the real module dependencies, and cannot import
1845 // internal packages from the real module.
1847 // (Note that although the 'vendor/' packages match the 'std' *package*
1848 // pattern, they are not part of the std *module*, and do not affect
1849 // 'go mod tidy' and similar module commands when working within std.)
1850 vendorPath := pathpkg.Join("vendor", path)
1851 if _, err := os.Stat(filepath.Join(cfg.GOROOTsrc, filepath.FromSlash(vendorPath))); err == nil {
1856 // Not vendored: resolve from modules.
1860 // computePatternAll returns the list of packages matching pattern "all",
1861 // starting with a list of the import paths for the packages in the main module.
1862 func (ld *loader) computePatternAll() (all []string) {
1863 for _, pkg := range ld.pkgs {
1864 if pkg.flags.has(pkgInAll) && !pkg.isTest() {
1865 all = append(all, pkg.path)
1872 // checkMultiplePaths verifies that a given module path is used as itself
1873 // or as a replacement for another module, but not both at the same time.
1875 // (See https://golang.org/issue/26607 and https://golang.org/issue/34650.)
1876 func (ld *loader) checkMultiplePaths() {
1877 mods := ld.requirements.rootModules
1878 if cached := ld.requirements.graph.Load(); cached != nil {
1879 if mg := cached.mg; mg != nil {
1880 mods = mg.BuildList()
1884 firstPath := map[module.Version]string{}
1885 for _, mod := range mods {
1886 src := resolveReplacement(mod)
1887 if prev, ok := firstPath[src]; !ok {
1888 firstPath[src] = mod.Path
1889 } else if prev != mod.Path {
1890 ld.errorf("go: %s@%s used for two different module paths (%s and %s)\n", src.Path, src.Version, prev, mod.Path)
1895 // checkTidyCompatibility emits an error if any package would be loaded from a
1896 // different module under rs than under ld.requirements.
1897 func (ld *loader) checkTidyCompatibility(ctx context.Context, rs *Requirements) {
1898 suggestUpgrade := false
1899 suggestEFlag := false
1900 suggestFixes := func() {
1902 // The user is explicitly ignoring these errors, so don't bother them with
1907 // We print directly to os.Stderr because this information is advice about
1908 // how to fix errors, not actually an error itself.
1909 // (The actual errors should have been logged already.)
1911 fmt.Fprintln(os.Stderr)
1914 if ld.GoVersion != MainModules.GoVersion() {
1915 goFlag = " -go=" + ld.GoVersion
1919 if ld.TidyCompatibleVersion != gover.Prev(ld.GoVersion) {
1920 compatFlag = " -compat=" + ld.TidyCompatibleVersion
1926 eDesc = ", leaving some packages unresolved"
1929 fmt.Fprintf(os.Stderr, "To upgrade to the versions selected by go %s%s:\n\tgo mod tidy%s -go=%s && go mod tidy%s -go=%s%s\n", ld.TidyCompatibleVersion, eDesc, eFlag, ld.TidyCompatibleVersion, eFlag, ld.GoVersion, compatFlag)
1930 } else if suggestEFlag {
1931 // If some packages are missing but no package is upgraded, then we
1932 // shouldn't suggest upgrading to the Go 1.16 versions explicitly — that
1933 // wouldn't actually fix anything for Go 1.16 users, and *would* break
1934 // something for Go 1.17 users.
1935 fmt.Fprintf(os.Stderr, "To proceed despite packages unresolved in go %s:\n\tgo mod tidy -e%s%s\n", ld.TidyCompatibleVersion, goFlag, compatFlag)
1938 fmt.Fprintf(os.Stderr, "If reproducibility with go %s is not needed:\n\tgo mod tidy%s -compat=%s\n", ld.TidyCompatibleVersion, goFlag, ld.GoVersion)
1940 // TODO(#46141): Populate the linked wiki page.
1941 fmt.Fprintf(os.Stderr, "For other options, see:\n\thttps://golang.org/doc/modules/pruning\n")
1944 mg, err := rs.Graph(ctx)
1946 ld.errorf("go: error loading go %s module graph: %v\n", ld.TidyCompatibleVersion, err)
1951 // Re-resolve packages in parallel.
1953 // We re-resolve each package — rather than just checking versions — to ensure
1954 // that we have fetched module source code (and, importantly, checksums for
1955 // that source code) for all modules that are necessary to ensure that imports
1956 // are unambiguous. That also produces clearer diagnostics, since we can say
1957 // exactly what happened to the package if it became ambiguous or disappeared
1960 // We re-resolve the packages in parallel because this process involves disk
1961 // I/O to check for package sources, and because the process of checking for
1962 // ambiguous imports may require us to download additional modules that are
1963 // otherwise pruned out in Go 1.17 — we don't want to block progress on other
1964 // packages while we wait for a single new download.
1965 type mismatch struct {
1969 mismatchMu := make(chan map[*loadPkg]mismatch, 1)
1970 mismatchMu <- map[*loadPkg]mismatch{}
1971 for _, pkg := range ld.pkgs {
1972 if pkg.mod.Path == "" && pkg.err == nil {
1973 // This package is from the standard library (which does not vary based on
1974 // the module graph).
1979 ld.work.Add(func() {
1980 mod, _, _, _, err := importFromModules(ctx, pkg.path, rs, mg, ld.skipImportModFiles)
1982 mismatches := <-mismatchMu
1983 mismatches[pkg] = mismatch{mod: mod, err: err}
1984 mismatchMu <- mismatches
1990 mismatches := <-mismatchMu
1991 if len(mismatches) == 0 {
1992 // Since we're running as part of 'go mod tidy', the roots of the module
1993 // graph should contain only modules that are relevant to some package in
1994 // the package graph. We checked every package in the package graph and
1995 // didn't find any mismatches, so that must mean that all of the roots of
1996 // the module graph are also consistent.
1998 // If we're wrong, Go 1.16 in -mod=readonly mode will error out with
1999 // "updates to go.mod needed", which would be very confusing. So instead,
2000 // we'll double-check that our reasoning above actually holds — if it
2001 // doesn't, we'll emit an internal error and hopefully the user will report
2003 for _, m := range ld.requirements.rootModules {
2004 if v := mg.Selected(m.Path); v != m.Version {
2005 fmt.Fprintln(os.Stderr)
2006 base.Fatalf("go: internal error: failed to diagnose selected-version mismatch for module %s: go %s selects %s, but go %s selects %s\n\tPlease report this at https://golang.org/issue.", m.Path, ld.GoVersion, m.Version, ld.TidyCompatibleVersion, v)
2012 // Iterate over the packages (instead of the mismatches map) to emit errors in
2013 // deterministic order.
2014 for _, pkg := range ld.pkgs {
2015 mismatch, ok := mismatches[pkg]
2021 // We already did (or will) report an error for the package itself,
2022 // so don't report a duplicate (and more verbose) error for its test.
2023 if _, ok := mismatches[pkg.testOf]; !ok {
2024 base.Fatalf("go: internal error: mismatch recorded for test %s, but not its non-test package", pkg.path)
2030 case mismatch.err != nil:
2031 // pkg resolved successfully, but errors out using the requirements in rs.
2033 // This could occur because the import is provided by a single root (and
2034 // is thus unambiguous in a main module with a pruned module graph) and
2035 // also one or more transitive dependencies (and is ambiguous with an
2038 // It could also occur because some transitive dependency upgrades the
2039 // module that previously provided the package to a version that no
2040 // longer does, or to a version for which the module source code (but
2041 // not the go.mod file in isolation) has a checksum error.
2042 if missing := (*ImportMissingError)(nil); errors.As(mismatch.err, &missing) {
2043 selected := module.Version{
2045 Version: mg.Selected(pkg.mod.Path),
2047 ld.errorf("%s loaded from %v,\n\tbut go %s would fail to locate it in %s\n", pkg.stackText(), pkg.mod, ld.TidyCompatibleVersion, selected)
2049 if ambiguous := (*AmbiguousImportError)(nil); errors.As(mismatch.err, &ambiguous) {
2050 // TODO: Is this check needed?
2052 ld.errorf("%s loaded from %v,\n\tbut go %s would fail to locate it:\n\t%v\n", pkg.stackText(), pkg.mod, ld.TidyCompatibleVersion, mismatch.err)
2057 // Even if we press ahead with the '-e' flag, the older version will
2058 // error out in readonly mode if it thinks the go.mod file contains
2059 // any *explicit* dependency that is not at its selected version,
2060 // even if that dependency is not relevant to any package being loaded.
2062 // We check for that condition here. If all of the roots are consistent
2063 // the '-e' flag suffices, but otherwise we need to suggest an upgrade.
2064 if !suggestUpgrade {
2065 for _, m := range ld.requirements.rootModules {
2066 if v := mg.Selected(m.Path); v != m.Version {
2067 suggestUpgrade = true
2073 case pkg.err != nil:
2074 // pkg had an error in with a pruned module graph (presumably suppressed
2075 // with the -e flag), but the error went away using an unpruned graph.
2077 // This is possible, if, say, the import is unresolved in the pruned graph
2078 // (because the "latest" version of each candidate module either is
2079 // unavailable or does not contain the package), but is resolved in the
2080 // unpruned graph due to a newer-than-latest dependency that is normally
2083 // This could also occur if the source code for the module providing the
2084 // package in the pruned graph has a checksum error, but the unpruned
2085 // graph upgrades that module to a version with a correct checksum.
2087 // pkg.err should have already been logged elsewhere — along with a
2088 // stack trace — so log only the import path and non-error info here.
2089 suggestUpgrade = true
2090 ld.errorf("%s failed to load from any module,\n\tbut go %s would load it from %v\n", pkg.path, ld.TidyCompatibleVersion, mismatch.mod)
2092 case pkg.mod != mismatch.mod:
2093 // The package is loaded successfully by both Go versions, but from a
2094 // different module in each. This could lead to subtle (and perhaps even
2095 // unnoticed!) variations in behavior between builds with different
2097 suggestUpgrade = true
2098 ld.errorf("%s loaded from %v,\n\tbut go %s would select %v\n", pkg.stackText(), pkg.mod, ld.TidyCompatibleVersion, mismatch.mod.Version)
2101 base.Fatalf("go: internal error: mismatch recorded for package %s, but no differences found", pkg.path)
2109 // scanDir is like imports.ScanDir but elides known magic imports from the list,
2110 // so that we do not go looking for packages that don't really exist.
2112 // The standard magic import is "C", for cgo.
2114 // The only other known magic imports are appengine and appengine/*.
2115 // These are so old that they predate "go get" and did not use URL-like paths.
2116 // Most code today now uses google.golang.org/appengine instead,
2117 // but not all code has been so updated. When we mostly ignore build tags
2118 // during "go vendor", we look into "// +build appengine" files and
2119 // may see these legacy imports. We drop them so that the module
2120 // search does not look for modules to try to satisfy them.
2121 func scanDir(modroot string, dir string, tags map[string]bool) (imports_, testImports []string, err error) {
2122 if ip, mierr := modindex.GetPackage(modroot, dir); mierr == nil {
2123 imports_, testImports, err = ip.ScanDir(tags)
2125 } else if !errors.Is(mierr, modindex.ErrNotIndexed) {
2126 return nil, nil, mierr
2129 imports_, testImports, err = imports.ScanDir(dir, tags)
2132 filter := func(x []string) []string {
2134 for _, pkg := range x {
2135 if pkg != "C" && pkg != "appengine" && !strings.HasPrefix(pkg, "appengine/") &&
2136 pkg != "appengine_internal" && !strings.HasPrefix(pkg, "appengine_internal/") {
2144 return filter(imports_), filter(testImports), err
2147 // buildStacks computes minimal import stacks for each package,
2148 // for use in error messages. When it completes, packages that
2149 // are part of the original root set have pkg.stack == nil,
2150 // and other packages have pkg.stack pointing at the next
2151 // package up the import stack in their minimal chain.
2152 // As a side effect, buildStacks also constructs ld.pkgs,
2153 // the list of all packages loaded.
2154 func (ld *loader) buildStacks() {
2155 if len(ld.pkgs) > 0 {
2156 panic("buildStacks")
2158 for _, pkg := range ld.roots {
2159 pkg.stack = pkg // sentinel to avoid processing in next loop
2160 ld.pkgs = append(ld.pkgs, pkg)
2162 for i := 0; i < len(ld.pkgs); i++ { // not range: appending to ld.pkgs in loop
2164 for _, next := range pkg.imports {
2165 if next.stack == nil {
2167 ld.pkgs = append(ld.pkgs, next)
2170 if next := pkg.test; next != nil && next.stack == nil {
2172 ld.pkgs = append(ld.pkgs, next)
2175 for _, pkg := range ld.roots {
2180 // stackText builds the import stack text to use when
2181 // reporting an error in pkg. It has the general form
2186 // other2.test imports
2188 func (pkg *loadPkg) stackText() string {
2189 var stack []*loadPkg
2190 for p := pkg; p != nil; p = p.stack {
2191 stack = append(stack, p)
2194 var buf strings.Builder
2195 for i := len(stack) - 1; i >= 0; i-- {
2197 fmt.Fprint(&buf, p.path)
2198 if p.testOf != nil {
2199 fmt.Fprint(&buf, ".test")
2202 if stack[i-1].testOf == p {
2203 fmt.Fprint(&buf, " tested by\n\t")
2205 fmt.Fprint(&buf, " imports\n\t")
2212 // why returns the text to use in "go mod why" output about the given package.
2213 // It is less ornate than the stackText but contains the same information.
2214 func (pkg *loadPkg) why() string {
2215 var buf strings.Builder
2216 var stack []*loadPkg
2217 for p := pkg; p != nil; p = p.stack {
2218 stack = append(stack, p)
2221 for i := len(stack) - 1; i >= 0; i-- {
2223 if p.testOf != nil {
2224 fmt.Fprintf(&buf, "%s.test\n", p.testOf.path)
2226 fmt.Fprintf(&buf, "%s\n", p.path)
2232 // Why returns the "go mod why" output stanza for the given package,
2233 // without the leading # comment.
2234 // The package graph must have been loaded already, usually by LoadPackages.
2235 // If there is no reason for the package to be in the current build,
2236 // Why returns an empty string.
2237 func Why(path string) string {
2238 pkg, ok := loaded.pkgCache.Get(path)
2245 // WhyDepth returns the number of steps in the Why listing.
2246 // If there is no reason for the package to be in the current build,
2247 // WhyDepth returns 0.
2248 func WhyDepth(path string) int {
2250 pkg, _ := loaded.pkgCache.Get(path)
2251 for p := pkg; p != nil; p = p.stack {