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 we implement lazy loading, we will record the modules providing packages
44 // in "all" even when we are only loading individual packages, so we set the
45 // pkgInAll flag regardless of the whether the "all" pattern is a root.
46 // (This is necessary to maintain the “import invariant” described in
47 // https://golang.org/design/36460-lazy-module-loading.)
49 // Because "go mod vendor" prunes out the tests of vendored packages, the
50 // behavior of the "all" pattern with -mod=vendor in Go 1.11–1.15 is the same
51 // as the "all" pattern (regardless of the -mod flag) in 1.16+.
52 // The loader uses the GoVersion parameter to determine whether the "all"
53 // pattern should close over tests (as in Go 1.11–1.15) or stop at only those
54 // packages transitively imported by the packages and tests in the main module
55 // ("all" in Go 1.16+ and "go mod vendor" in Go 1.11+).
57 // Note that it is possible for a loaded package NOT to be in "all" even when we
58 // are loading the "all" pattern. For example, packages that are transitive
59 // dependencies of other roots named on the command line must be loaded, but are
60 // not in "all". (The mod_notall test illustrates this behavior.)
61 // Similarly, if the LoadTests flag is set but the "all" pattern does not close
62 // over test dependencies, then when we load the test of a package that is in
63 // "all" but outside the main module, the dependencies of that test will not
64 // necessarily themselves be in "all". (That configuration does not arise in Go
65 // 1.11–1.15, but it will be possible in Go 1.16+.)
67 // Loading proceeds from the roots, using a parallel work-queue with a limit on
68 // the amount of active work (to avoid saturating disks, CPU cores, and/or
69 // network connections). Each package is added to the queue the first time it is
70 // imported by another package. When we have finished identifying the imports of
71 // a package, we add the test for that package if it is needed. A test may be
73 // - the package matches a root pattern and tests of the roots were requested, or
74 // - the package is in the main module and the "all" pattern is requested
75 // (because the "all" pattern includes the dependencies of tests in the main
77 // - the package is in "all" and the definition of "all" we are using includes
78 // dependencies of tests (as is the case in Go ≤1.15).
80 // After all available packages have been loaded, we examine the results to
81 // identify any requested or imported packages that are still missing, and if
82 // so, which modules we could add to the module graph in order to make the
83 // missing packages available. We add those to the module graph and iterate,
84 // until either all packages resolve successfully or we cannot identify any
85 // module that would resolve any remaining missing package.
87 // If the main module is “tidy” (that is, if "go mod tidy" is a no-op for it)
88 // and all requested packages are in "all", then loading completes in a single
90 // TODO(bcmills): We should also be able to load in a single iteration if the
91 // requested packages all come from modules that are themselves tidy, regardless
92 // of whether those packages are in "all". Today, that requires two iterations
93 // 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/imports"
117 "cmd/go/internal/modfetch"
118 "cmd/go/internal/mvs"
119 "cmd/go/internal/par"
120 "cmd/go/internal/search"
121 "cmd/go/internal/str"
123 "golang.org/x/mod/module"
124 "golang.org/x/mod/semver"
127 // loaded is the most recently-used package loader.
128 // It holds details about individual packages.
130 // This variable should only be accessed directly in top-level exported
131 // functions. All other functions that require or produce a *loader should pass
132 // or return it as an explicit parameter.
135 // PackageOpts control the behavior of the LoadPackages function.
136 type PackageOpts struct {
137 // GoVersion is the Go version to which the go.mod file should be updated
138 // after packages have been loaded.
140 // An empty GoVersion means to use the Go version already specified in the
141 // main module's go.mod file, or the latest Go version if there is no main
145 // Tags are the build tags in effect (as interpreted by the
146 // cmd/go/internal/imports package).
147 // If nil, treated as equivalent to imports.Tags().
150 // Tidy, if true, requests that the build list and go.sum file be reduced to
151 // the minimial dependencies needed to reproducibly reload the requested
155 // VendorModulesInGOROOTSrc indicates that if we are within a module in
156 // GOROOT/src, packages in the module's vendor directory should be resolved as
157 // actual module dependencies (instead of standard-library packages).
158 VendorModulesInGOROOTSrc bool
160 // ResolveMissingImports indicates that we should attempt to add module
161 // dependencies as needed to resolve imports of packages that are not found.
163 // For commands that support the -mod flag, resolving imports may still fail
164 // if the flag is set to "readonly" (the default) or "vendor".
165 ResolveMissingImports bool
167 // AllowPackage, if non-nil, is called after identifying the module providing
168 // each package. If AllowPackage returns a non-nil error, that error is set
169 // for the package, and the imports and test of that package will not be
172 // AllowPackage may be invoked concurrently by multiple goroutines,
173 // and may be invoked multiple times for a given package path.
174 AllowPackage func(ctx context.Context, path string, mod module.Version) error
176 // LoadTests loads the test dependencies of each package matching a requested
177 // pattern. If ResolveMissingImports is also true, test dependencies will be
178 // resolved if missing.
181 // UseVendorAll causes the "all" package pattern to be interpreted as if
182 // running "go mod vendor" (or building with "-mod=vendor").
184 // This is a no-op for modules that declare 'go 1.16' or higher, for which this
185 // is the default (and only) interpretation of the "all" pattern in module mode.
188 // AllowErrors indicates that LoadPackages should not terminate the process if
192 // SilencePackageErrors indicates that LoadPackages should not print errors
193 // that occur while matching or loading packages, and should not terminate the
194 // process if such an error occurs.
196 // Errors encountered in the module graph will still be reported.
198 // The caller may retrieve the silenced package errors using the Lookup
199 // function, and matching errors are still populated in the Errs field of the
200 // associated search.Match.)
201 SilencePackageErrors bool
203 // SilenceMissingStdImports indicates that LoadPackages should not print
204 // errors or terminate the process if an imported package is missing, and the
205 // import path looks like it might be in the standard library (perhaps in a
207 SilenceMissingStdImports bool
209 // SilenceNoGoErrors indicates that LoadPackages should not print
210 // imports.ErrNoGo errors.
211 // This allows the caller to invoke LoadPackages (and report other errors)
212 // without knowing whether the requested packages exist for the given tags.
214 // Note that if a requested package does not exist *at all*, it will fail
215 // during module resolution and the error will not be suppressed.
216 SilenceNoGoErrors bool
218 // SilenceUnmatchedWarnings suppresses the warnings normally emitted for
219 // patterns that did not match any packages.
220 SilenceUnmatchedWarnings bool
223 // LoadPackages identifies the set of packages matching the given patterns and
224 // loads the packages in the import graph rooted at that set.
225 func LoadPackages(ctx context.Context, opts PackageOpts, patterns ...string) (matches []*search.Match, loadedPackages []string) {
226 if opts.Tags == nil {
227 opts.Tags = imports.Tags()
230 patterns = search.CleanPatterns(patterns)
231 matches = make([]*search.Match, 0, len(patterns))
232 allPatternIsRoot := false
233 for _, pattern := range patterns {
234 matches = append(matches, search.NewMatch(pattern))
235 if pattern == "all" {
236 allPatternIsRoot = true
240 updateMatches := func(rs *Requirements, ld *loader) {
241 for _, m := range matches {
244 // Evaluate list of file system directories on first iteration.
246 matchLocalDirs(ctx, m, rs)
249 // Make a copy of the directory list and translate to import paths.
250 // Note that whether a directory corresponds to an import path
251 // changes as the build list is updated, and a directory can change
252 // from not being in the build list to being in it and back as
253 // the exact version of a particular module increases during
254 // the loader iterations.
256 for _, dir := range m.Dirs {
257 pkg, err := resolveLocalPackage(ctx, dir, rs)
259 if !m.IsLiteral() && (err == errPkgIsBuiltin || err == errPkgIsGorootSrc) {
260 continue // Don't include "builtin" or GOROOT/src in wildcard patterns.
263 // If we're outside of a module, ensure that the failure mode
272 m.Pkgs = append(m.Pkgs, pkg)
276 m.Pkgs = []string{m.Pattern()}
278 case strings.Contains(m.Pattern(), "..."):
280 mg, err := rs.Graph(ctx)
282 // The module graph is (or may be) incomplete — perhaps we failed to
283 // load the requirements of some module. This is an error in matching
284 // the patterns to packages, because we may be missing some packages
285 // or we may erroneously match packages in the wrong versions of
286 // modules. However, for cases like 'go list -e', the error should not
287 // necessarily prevent us from loading the packages we could find.
288 m.Errs = append(m.Errs, err)
290 matchPackages(ctx, m, opts.Tags, includeStd, mg.BuildList())
292 case m.Pattern() == "all":
294 // The initial roots are the packages in the main module.
295 // loadFromRoots will expand that to "all".
297 matchPackages(ctx, m, opts.Tags, omitStd, []module.Version{Target})
299 // Starting with the packages in the main module,
300 // enumerate the full list of "all".
301 m.Pkgs = ld.computePatternAll()
304 case m.Pattern() == "std" || m.Pattern() == "cmd":
306 m.MatchPackages() // Locate the packages within GOROOT/src.
310 panic(fmt.Sprintf("internal error: modload missing case for pattern %s", m.Pattern()))
315 initialRS, _ := loadModFile(ctx) // Ignore needCommit — we're going to commit at the end regardless.
317 if opts.GoVersion == "" {
318 opts.GoVersion = modFileGoVersion()
321 ld := loadFromRoots(ctx, loaderParams{
323 requirements: initialRS,
325 allPatternIsRoot: allPatternIsRoot,
327 listRoots: func(rs *Requirements) (roots []string) {
328 updateMatches(rs, nil)
329 for _, m := range matches {
330 roots = append(roots, m.Pkgs...)
336 // One last pass to finalize wildcards.
337 updateMatches(ld.requirements, ld)
339 // List errors in matching patterns (such as directory permission
340 // errors for wildcard patterns).
341 if !ld.SilencePackageErrors {
342 for _, match := range matches {
343 for _, err := range match.Errs {
344 ld.errorf("%v\n", err)
350 if !opts.SilenceUnmatchedWarnings {
351 search.WarnUnmatched(matches)
356 mg, _ := ld.requirements.Graph(ctx)
358 for _, m := range initialRS.rootModules {
360 if ld.requirements.depth == eager {
361 // m is unused if it was dropped from the module graph entirely. If it
362 // was only demoted from direct to indirect, it may still be in use via
363 // a transitive import.
364 unused = mg.Selected(m.Path) == "none"
366 // m is unused if it was dropped from the roots. If it is still present
367 // as a transitive dependency, that transitive dependency is not needed
368 // by any package or test in the main module.
369 _, ok := ld.requirements.rootSelected(m.Path)
373 fmt.Fprintf(os.Stderr, "unused %s\n", m.Path)
378 modfetch.TrimGoSum(keepSums(ctx, ld, ld.requirements, loadedZipSumsOnly))
381 // Success! Update go.mod and go.sum (if needed) and return the results.
383 commitRequirements(ctx, opts.GoVersion, loaded.requirements)
385 for _, pkg := range ld.pkgs {
387 loadedPackages = append(loadedPackages, pkg.path)
390 sort.Strings(loadedPackages)
391 return matches, loadedPackages
394 // matchLocalDirs is like m.MatchDirs, but tries to avoid scanning directories
395 // outside of the standard library and active modules.
396 func matchLocalDirs(ctx context.Context, m *search.Match, rs *Requirements) {
398 panic(fmt.Sprintf("internal error: resolveLocalDirs on non-local pattern %s", m.Pattern()))
401 if i := strings.Index(m.Pattern(), "..."); i >= 0 {
402 // The pattern is local, but it is a wildcard. Its packages will
403 // only resolve to paths if they are inside of the standard
404 // library, the main module, or some dependency of the main
405 // module. Verify that before we walk the filesystem: a filesystem
406 // walk in a directory like /var or /etc can be very expensive!
407 dir := filepath.Dir(filepath.Clean(m.Pattern()[:i+3]))
409 if !filepath.IsAbs(dir) {
410 absDir = filepath.Join(base.Cwd, dir)
412 if search.InDir(absDir, cfg.GOROOTsrc) == "" && search.InDir(absDir, ModRoot()) == "" && pathInModuleCache(ctx, absDir, rs) == "" {
414 m.AddError(fmt.Errorf("directory prefix %s outside available modules", base.ShortPath(absDir)))
422 // resolveLocalPackage resolves a filesystem path to a package path.
423 func resolveLocalPackage(ctx context.Context, dir string, rs *Requirements) (string, error) {
425 if filepath.IsAbs(dir) {
426 absDir = filepath.Clean(dir)
428 absDir = filepath.Join(base.Cwd, dir)
431 bp, err := cfg.BuildContext.ImportDir(absDir, 0)
432 if err != nil && (bp == nil || len(bp.IgnoredGoFiles) == 0) {
433 // golang.org/issue/32917: We should resolve a relative path to a
434 // package path only if the relative path actually contains the code
437 // If the named directory does not exist or contains no Go files,
438 // the package does not exist.
439 // Other errors may affect package loading, but not resolution.
440 if _, err := fsys.Stat(absDir); err != nil {
441 if os.IsNotExist(err) {
442 // Canonicalize OS-specific errors to errDirectoryNotFound so that error
443 // messages will be easier for users to search for.
444 return "", &fs.PathError{Op: "stat", Path: absDir, Err: errDirectoryNotFound}
448 if _, noGo := err.(*build.NoGoError); noGo {
449 // A directory that does not contain any Go source files — even ignored
450 // ones! — is not a Go package, and we can't resolve it to a package
451 // path because that path could plausibly be provided by some other
454 // Any other error indicates that the package “exists” (at least in the
455 // sense that it cannot exist in any other module), but has some other
456 // problem (such as a syntax error).
461 if modRoot != "" && absDir == modRoot {
462 if absDir == cfg.GOROOTsrc {
463 return "", errPkgIsGorootSrc
465 return targetPrefix, nil
468 // Note: The checks for @ here are just to avoid misinterpreting
469 // the module cache directories (formerly GOPATH/src/mod/foo@v1.5.2/bar).
470 // It's not strictly necessary but helpful to keep the checks.
471 if modRoot != "" && strings.HasPrefix(absDir, modRoot+string(filepath.Separator)) && !strings.Contains(absDir[len(modRoot):], "@") {
472 suffix := filepath.ToSlash(absDir[len(modRoot):])
473 if strings.HasPrefix(suffix, "/vendor/") {
474 if cfg.BuildMod != "vendor" {
475 return "", fmt.Errorf("without -mod=vendor, directory %s has no package path", absDir)
479 pkg := strings.TrimPrefix(suffix, "/vendor/")
480 if _, ok := vendorPkgModule[pkg]; !ok {
481 return "", fmt.Errorf("directory %s is not a package listed in vendor/modules.txt", absDir)
486 if targetPrefix == "" {
487 pkg := strings.TrimPrefix(suffix, "/")
488 if pkg == "builtin" {
489 // "builtin" is a pseudo-package with a real source file.
490 // It's not included in "std", so it shouldn't resolve from "."
491 // within module "std" either.
492 return "", errPkgIsBuiltin
497 pkg := targetPrefix + suffix
498 if _, ok, err := dirInModule(pkg, targetPrefix, modRoot, true); err != nil {
501 return "", &PackageNotInModuleError{Mod: Target, Pattern: pkg}
506 if sub := search.InDir(absDir, cfg.GOROOTsrc); sub != "" && sub != "." && !strings.Contains(sub, "@") {
507 pkg := filepath.ToSlash(sub)
508 if pkg == "builtin" {
509 return "", errPkgIsBuiltin
514 pkg := pathInModuleCache(ctx, absDir, rs)
516 return "", fmt.Errorf("directory %s outside available modules", base.ShortPath(absDir))
522 errDirectoryNotFound = errors.New("directory not found")
523 errPkgIsGorootSrc = errors.New("GOROOT/src is not an importable package")
524 errPkgIsBuiltin = errors.New(`"builtin" is a pseudo-package, not an importable package`)
527 // pathInModuleCache returns the import path of the directory dir,
528 // if dir is in the module cache copy of a module in our build list.
529 func pathInModuleCache(ctx context.Context, dir string, rs *Requirements) string {
530 tryMod := func(m module.Version) (string, bool) {
533 if repl := Replacement(m); repl.Path != "" && repl.Version == "" {
535 if !filepath.IsAbs(root) {
536 root = filepath.Join(ModRoot(), root)
538 } else if repl.Path != "" {
539 root, err = modfetch.DownloadDir(repl)
541 root, err = modfetch.DownloadDir(m)
547 sub := search.InDir(dir, root)
551 sub = filepath.ToSlash(sub)
552 if strings.Contains(sub, "/vendor/") || strings.HasPrefix(sub, "vendor/") || strings.Contains(sub, "@") {
556 return path.Join(m.Path, filepath.ToSlash(sub)), true
559 if rs.depth == lazy {
560 for _, m := range rs.rootModules {
561 if v, _ := rs.rootSelected(m.Path); v != m.Version {
562 continue // m is a root, but we have a higher root for the same path.
564 if importPath, ok := tryMod(m); ok {
565 // checkMultiplePaths ensures that a module can be used for at most one
566 // requirement, so this must be it.
572 // None of the roots contained dir, or we're in eager mode and want to load
573 // the full module graph more aggressively. Either way, check the full graph
574 // to see if the directory is a non-root dependency.
576 // If the roots are not consistent with the full module graph, the selected
577 // versions of root modules may differ from what we already checked above.
578 // Re-check those paths too.
580 mg, _ := rs.Graph(ctx)
581 var importPath string
582 for _, m := range mg.BuildList() {
584 importPath, found = tryMod(m)
592 // ImportFromFiles adds modules to the build list as needed
593 // to satisfy the imports in the named Go source files.
595 // Errors in missing dependencies are silenced.
597 // TODO(bcmills): Silencing errors seems off. Take a closer look at this and
598 // figure out what the error-reporting actually ought to be.
599 func ImportFromFiles(ctx context.Context, gofiles []string) {
600 rs := LoadModFile(ctx)
602 tags := imports.Tags()
603 imports, testImports, err := imports.ScanFiles(gofiles, tags)
605 base.Fatalf("go: %v", err)
608 goVersion := modFileGoVersion()
609 loaded = loadFromRoots(ctx, loaderParams{
610 PackageOpts: PackageOpts{
611 GoVersion: goVersion,
613 ResolveMissingImports: true,
614 SilencePackageErrors: true,
617 listRoots: func(*Requirements) (roots []string) {
618 roots = append(roots, imports...)
619 roots = append(roots, testImports...)
623 commitRequirements(ctx, goVersion, loaded.requirements)
626 // DirImportPath returns the effective import path for dir,
627 // provided it is within the main module, or else returns ".".
628 func DirImportPath(ctx context.Context, dir string) string {
632 LoadModFile(ctx) // Sets targetPrefix.
634 if !filepath.IsAbs(dir) {
635 dir = filepath.Join(base.Cwd, dir)
637 dir = filepath.Clean(dir)
643 if strings.HasPrefix(dir, modRoot+string(filepath.Separator)) {
644 suffix := filepath.ToSlash(dir[len(modRoot):])
645 if strings.HasPrefix(suffix, "/vendor/") {
646 return strings.TrimPrefix(suffix, "/vendor/")
648 return targetPrefix + suffix
653 // TargetPackages returns the list of packages in the target (top-level) module
654 // matching pattern, which may be relative to the working directory, under all
655 // build tag settings.
656 func TargetPackages(ctx context.Context, pattern string) *search.Match {
657 // TargetPackages is relative to the main module, so ensure that the main
658 // module is a thing that can contain packages.
659 LoadModFile(ctx) // Sets Target.
660 ModRoot() // Emits an error if Target cannot contain packages.
662 m := search.NewMatch(pattern)
663 matchPackages(ctx, m, imports.AnyTags(), omitStd, []module.Version{Target})
667 // ImportMap returns the actual package import path
668 // for an import path found in source code.
669 // If the given import path does not appear in the source code
670 // for the packages that have been loaded, ImportMap returns the empty string.
671 func ImportMap(path string) string {
672 pkg, ok := loaded.pkgCache.Get(path).(*loadPkg)
679 // PackageDir returns the directory containing the source code
680 // for the package named by the import path.
681 func PackageDir(path string) string {
682 pkg, ok := loaded.pkgCache.Get(path).(*loadPkg)
689 // PackageModule returns the module providing the package named by the import path.
690 func PackageModule(path string) module.Version {
691 pkg, ok := loaded.pkgCache.Get(path).(*loadPkg)
693 return module.Version{}
698 // PackageImports returns the imports for the package named by the import path.
699 // Test imports will be returned as well if tests were loaded for the package
700 // (i.e., if "all" was loaded or if LoadTests was set and the path was matched
701 // by a command line argument). PackageImports will return nil for
702 // unknown package paths.
703 func PackageImports(path string) (imports, testImports []string) {
704 pkg, ok := loaded.pkgCache.Get(path).(*loadPkg)
708 imports = make([]string, len(pkg.imports))
709 for i, p := range pkg.imports {
713 testImports = make([]string, len(pkg.test.imports))
714 for i, p := range pkg.test.imports {
715 testImports[i] = p.path
718 return imports, testImports
721 // Lookup returns the source directory, import path, and any loading error for
722 // the package at path as imported from the package in parentDir.
723 // Lookup requires that one of the Load functions in this package has already
725 func Lookup(parentPath string, parentIsStd bool, path string) (dir, realPath string, err error) {
727 panic("Lookup called with empty package path")
731 path = loaded.stdVendor(parentPath, path)
733 pkg, ok := loaded.pkgCache.Get(path).(*loadPkg)
735 // The loader should have found all the relevant paths.
736 // There are a few exceptions, though:
737 // - during go list without -test, the p.Resolve calls to process p.TestImports and p.XTestImports
738 // end up here to canonicalize the import paths.
739 // - during any load, non-loaded packages like "unsafe" end up here.
740 // - during any load, build-injected dependencies like "runtime/cgo" end up here.
741 // - because we ignore appengine/* in the module loader,
742 // the dependencies of any actual appengine/* library end up here.
743 dir := findStandardImportPath(path)
745 return dir, path, nil
747 return "", "", errMissing
749 return pkg.dir, pkg.path, pkg.err
752 // A loader manages the process of loading information about
753 // the required packages for a particular build,
754 // checking that the packages are available in the module set,
755 // and updating the module set if needed.
759 // allClosesOverTests indicates whether the "all" pattern includes
760 // dependencies of tests outside the main module (as in Go 1.11–1.15).
761 // (Otherwise — as in Go 1.16+ — the "all" pattern includes only the packages
762 // transitively *imported by* the packages and tests in the main module.)
763 allClosesOverTests bool
767 // reset on each iteration
769 pkgCache *par.Cache // package path (string) → *loadPkg
770 pkgs []*loadPkg // transitive closure of loaded packages and tests; populated in buildStacks
773 // loaderParams configure the packages loaded by, and the properties reported
774 // by, a loader instance.
775 type loaderParams struct {
777 requirements *Requirements
779 allPatternIsRoot bool // Is the "all" pattern an additional root?
781 listRoots func(rs *Requirements) []string
784 func (ld *loader) reset() {
786 case <-ld.work.Idle():
788 panic("loader.reset when not idle")
792 ld.pkgCache = new(par.Cache)
796 // errorf reports an error via either os.Stderr or base.Errorf,
797 // according to whether ld.AllowErrors is set.
798 func (ld *loader) errorf(format string, args ...interface{}) {
800 fmt.Fprintf(os.Stderr, format, args...)
802 base.Errorf(format, args...)
806 // A loadPkg records information about a single loaded package.
807 type loadPkg struct {
808 // Populated at construction time:
809 path string // import path
812 // Populated at construction time and updated by (*loader).applyPkgFlags:
813 flags atomicLoadPkgFlags
815 // Populated by (*loader).load:
816 mod module.Version // module providing package
817 dir string // directory containing source code
818 err error // error loading package
819 imports []*loadPkg // packages imported by this one
820 testImports []string // test-only imports, saved for use by pkg.test.
823 // Populated by (*loader).pkgTest:
827 // Populated by postprocessing in (*loader).buildStacks:
828 stack *loadPkg // package importing this one in minimal import stack for this pkg
831 // loadPkgFlags is a set of flags tracking metadata about a package.
832 type loadPkgFlags int8
835 // pkgInAll indicates that the package is in the "all" package pattern,
836 // regardless of whether we are loading the "all" package pattern.
838 // When the pkgInAll flag and pkgImportsLoaded flags are both set, the caller
839 // who set the last of those flags must propagate the pkgInAll marking to all
840 // of the imports of the marked package.
842 // A test is marked with pkgInAll if that test would promote the packages it
843 // imports to be in "all" (such as when the test is itself within the main
844 // module, or when ld.allClosesOverTests is true).
845 pkgInAll loadPkgFlags = 1 << iota
847 // pkgIsRoot indicates that the package matches one of the root package
848 // patterns requested by the caller.
850 // If LoadTests is set, then when pkgIsRoot and pkgImportsLoaded are both set,
851 // the caller who set the last of those flags must populate a test for the
852 // package (in the pkg.test field).
854 // If the "all" pattern is included as a root, then non-test packages in "all"
855 // are also roots (and must be marked pkgIsRoot).
858 // pkgImportsLoaded indicates that the imports and testImports fields of a
859 // loadPkg have been populated.
863 // has reports whether all of the flags in cond are set in f.
864 func (f loadPkgFlags) has(cond loadPkgFlags) bool {
865 return f&cond == cond
868 // An atomicLoadPkgFlags stores a loadPkgFlags for which individual flags can be
870 type atomicLoadPkgFlags struct {
874 // update sets the given flags in af (in addition to any flags already set).
876 // update returns the previous flag state so that the caller may determine which
877 // flags were newly-set.
878 func (af *atomicLoadPkgFlags) update(flags loadPkgFlags) (old loadPkgFlags) {
880 old := atomic.LoadInt32(&af.bits)
881 new := old | int32(flags)
882 if new == old || atomic.CompareAndSwapInt32(&af.bits, old, new) {
883 return loadPkgFlags(old)
888 // has reports whether all of the flags in cond are set in af.
889 func (af *atomicLoadPkgFlags) has(cond loadPkgFlags) bool {
890 return loadPkgFlags(atomic.LoadInt32(&af.bits))&cond == cond
893 // isTest reports whether pkg is a test of another package.
894 func (pkg *loadPkg) isTest() bool {
895 return pkg.testOf != nil
898 // fromExternalModule reports whether pkg was loaded from a module other than
900 func (pkg *loadPkg) fromExternalModule() bool {
901 if pkg.mod.Path == "" {
902 return false // loaded from the standard library, not a module
904 if pkg.mod.Path == Target.Path {
905 return false // loaded from the main module.
910 var errMissing = errors.New("cannot find package")
912 // loadFromRoots attempts to load the build graph needed to process a set of
913 // root packages and their dependencies.
915 // The set of root packages is returned by the params.listRoots function, and
916 // expanded to the full set of packages by tracing imports (and possibly tests)
918 func loadFromRoots(ctx context.Context, params loaderParams) *loader {
920 loaderParams: params,
921 work: par.NewQueue(runtime.GOMAXPROCS(0)),
924 if params.GoVersion != "" {
925 if semver.Compare("v"+params.GoVersion, narrowAllVersionV) < 0 && !ld.UseVendorAll {
926 // The module's go version explicitly predates the change in "all" for lazy
927 // loading, so continue to use the older interpretation.
928 // (If params.GoVersion is empty, we are probably not in any module at all
929 // and should use the latest semantics.)
930 ld.allClosesOverTests = true
934 ld.requirements, err = convertDepth(ctx, ld.requirements, modDepthFromGoVersion(params.GoVersion))
936 ld.errorf("go: %v\n", err)
940 if ld.requirements.depth == eager {
942 ld.requirements, _, err = expandGraph(ctx, ld.requirements)
944 ld.errorf("go: %v\n", err)
951 // Load the root packages and their imports.
952 // Note: the returned roots can change on each iteration,
953 // since the expansion of package patterns depends on the
954 // build list we're using.
955 rootPkgs := ld.listRoots(ld.requirements)
957 if ld.requirements.depth == lazy && cfg.BuildMod == "mod" {
958 // Before we start loading transitive imports of packages, locate all of
959 // the root packages and promote their containing modules to root modules
960 // dependencies. If their go.mod files are tidy (the common case) and the
961 // set of root packages does not change then we can select the correct
962 // versions of all transitive imports on the first try and complete
963 // loading in a single iteration.
964 changedBuildList := ld.preloadRootModules(ctx, rootPkgs)
965 if changedBuildList {
966 // The build list has changed, so the set of root packages may have also
967 // changed. Start over to pick up the changes. (Preloading roots is much
968 // cheaper than loading the full import graph, so we would rather pay
969 // for an extra iteration of preloading than potentially end up
970 // discarding the result of a full iteration of loading.)
975 inRoots := map[*loadPkg]bool{}
976 for _, path := range rootPkgs {
977 root := ld.pkg(ctx, path, pkgIsRoot)
979 ld.roots = append(ld.roots, root)
984 // ld.pkg adds imported packages to the work queue and calls applyPkgFlags,
985 // which adds tests (and test dependencies) as needed.
987 // When all of the work in the queue has completed, we'll know that the
988 // transitive closure of dependencies has been loaded.
993 changed, err := ld.updateRequirements(ctx)
995 ld.errorf("go: %v\n", err)
999 // Don't resolve missing imports until the module graph have stabilized.
1000 // If the roots are still changing, they may turn out to specify a
1001 // requirement on the missing package(s), and we would rather use a
1002 // version specified by a new root than add a new dependency on an
1003 // unrelated version.
1007 if !ld.ResolveMissingImports || (!HasModRoot() && !allowMissingModuleImports) {
1008 // We've loaded as much as we can without resolving missing imports.
1012 modAddedBy := ld.resolveMissingImports(ctx)
1013 if len(modAddedBy) == 0 {
1014 // The roots are stable, and we've resolved all of the missing packages
1019 toAdd := make([]module.Version, 0, len(modAddedBy))
1020 for m, _ := range modAddedBy {
1021 toAdd = append(toAdd, m)
1023 module.Sort(toAdd) // to make errors deterministic
1025 // We ran updateRequirements before resolving missing imports and it didn't
1026 // make any changes, so we know that the requirement graph is already
1027 // consistent with ld.pkgs: we don't need to pass ld.pkgs to updateRoots
1028 // again. (That would waste time looking for changes that we have already
1030 var noPkgs []*loadPkg
1031 // We also know that we're going to call updateRequirements again next
1032 // iteration so we don't need to also update it here. (That would waste time
1033 // computing a "direct" map that we'll have to recompute later anyway.)
1034 direct := ld.requirements.direct
1035 rs, err := updateRoots(ctx, direct, ld.requirements, noPkgs, toAdd)
1037 // If an error was found in a newly added module, report the package
1038 // import stack instead of the module requirement stack. Packages
1039 // are more descriptive.
1040 if err, ok := err.(*mvs.BuildListError); ok {
1041 if pkg := modAddedBy[err.Module()]; pkg != nil {
1042 ld.errorf("go: %s: %v\n", pkg.stackText(), err.Err)
1046 ld.errorf("go: %v\n", err)
1049 if reflect.DeepEqual(rs.rootModules, ld.requirements.rootModules) {
1050 // Something is deeply wrong. resolveMissingImports gave us a non-empty
1051 // set of modules to add to the graph, but adding those modules had no
1052 // effect — either they were already in the graph, or updateRoots did not
1053 // add them as requested.
1054 panic(fmt.Sprintf("internal error: adding %v to module graph had no effect on root requirements (%v)", toAdd, rs.rootModules))
1056 ld.requirements = rs
1058 base.ExitIfErrors() // TODO(bcmills): Is this actually needed?
1060 // Tidy the build list, if applicable, before we report errors.
1061 // (The process of tidying may remove errors from irrelevant dependencies.)
1063 rs, err := tidyRoots(ctx, ld.requirements, ld.pkgs)
1065 ld.errorf("go: %v\n", err)
1068 if ld.requirements.depth == lazy {
1069 // We continuously add tidy roots to ld.requirements during loading, so at
1070 // this point the tidy roots should be a subset of the roots of
1071 // ld.requirements, ensuring that no new dependencies are brought inside
1072 // the lazy-loading horizon.
1073 // If that is not the case, there is a bug in the loading loop above.
1074 for _, m := range rs.rootModules {
1075 if v, ok := ld.requirements.rootSelected(m.Path); !ok || v != m.Version {
1076 ld.errorf("go: internal error: a requirement on %v is needed but was not added during package loading\n", m)
1081 ld.requirements = rs
1084 // Report errors, if any.
1085 for _, pkg := range ld.pkgs {
1090 // Add importer information to checksum errors.
1091 if sumErr := (*ImportMissingSumError)(nil); errors.As(pkg.err, &sumErr) {
1092 if importer := pkg.stack; importer != nil {
1093 sumErr.importer = importer.path
1094 sumErr.importerVersion = importer.mod.Version
1095 sumErr.importerIsTest = importer.testOf != nil
1099 if ld.SilencePackageErrors {
1102 if stdErr := (*ImportMissingError)(nil); errors.As(pkg.err, &stdErr) &&
1103 stdErr.isStd && ld.SilenceMissingStdImports {
1106 if ld.SilenceNoGoErrors && errors.Is(pkg.err, imports.ErrNoGo) {
1110 ld.errorf("%s: %v\n", pkg.stackText(), pkg.err)
1113 ld.checkMultiplePaths()
1117 // updateRequirements ensures that ld.requirements is consistent with the
1118 // information gained from ld.pkgs and includes the modules in add as roots at
1119 // at least the given versions.
1123 // - Modules that provide packages directly imported from the main module are
1124 // marked as direct, and are promoted to explicit roots. If a needed root
1125 // cannot be promoted due to -mod=readonly or -mod=vendor, the importing
1126 // package is marked with an error.
1128 // - If ld scanned the "all" pattern independent of build constraints, it is
1129 // guaranteed to have seen every direct import. Module dependencies that did
1130 // not provide any directly-imported package are then marked as indirect.
1132 // - Root dependencies are updated to their selected versions.
1134 // The "changed" return value reports whether the update changed the selected
1135 // version of any module that either provided a loaded package or may now
1136 // provide a package that was previously unresolved.
1137 func (ld *loader) updateRequirements(ctx context.Context) (changed bool, err error) {
1138 rs := ld.requirements
1140 // direct contains the set of modules believed to provide packages directly
1141 // imported by the main module.
1142 var direct map[string]bool
1144 // If we didn't scan all of the imports from the main module, or didn't use
1145 // imports.AnyTags, then we didn't necessarily load every package that
1146 // contributes “direct” imports — so we can't safely mark existing direct
1147 // dependencies in ld.requirements as indirect-only. Propagate them as direct.
1148 loadedDirect := ld.allPatternIsRoot && reflect.DeepEqual(ld.Tags, imports.AnyTags())
1150 direct = make(map[string]bool)
1152 // TODO(bcmills): It seems like a shame to allocate and copy a map here when
1153 // it will only rarely actually vary from rs.direct. Measure this cost and
1154 // maybe avoid the copy.
1155 direct = make(map[string]bool, len(rs.direct))
1156 for mPath := range rs.direct {
1157 direct[mPath] = true
1161 for _, pkg := range ld.pkgs {
1162 if pkg.mod != Target {
1165 for _, dep := range pkg.imports {
1166 if !dep.fromExternalModule() {
1170 if pkg.err == nil && cfg.BuildMod != "mod" {
1171 if v, ok := rs.rootSelected(dep.mod.Path); !ok || v != dep.mod.Version {
1172 // dep.mod is not an explicit dependency, but needs to be.
1173 // Because we are not in "mod" mode, we will not be able to update it.
1174 // Instead, mark the importing package with an error.
1176 // TODO(#41688): The resulting error message fails to include the file
1177 // position of the import statement (because that information is not
1178 // tracked by the module loader). Figure out how to plumb the import
1179 // position through.
1180 pkg.err = &DirectImportFromImplicitDependencyError{
1181 ImporterPath: pkg.path,
1182 ImportedPath: dep.path,
1185 // cfg.BuildMod does not allow us to change dep.mod to be a direct
1186 // dependency, so don't mark it as such.
1191 // dep is a package directly imported by a package or test in the main
1192 // module and loaded from some other module (not the standard library).
1193 // Mark its module as a direct dependency.
1194 direct[dep.mod.Path] = true
1198 var addRoots []module.Version
1200 // When we are tidying a lazy module, we may need to add roots to preserve
1201 // the versions of indirect, test-only dependencies that are upgraded
1202 // above or otherwise missing from the go.mod files of direct
1203 // dependencies. (For example, the direct dependency might be a very
1204 // stable codebase that predates modules and thus lacks a go.mod file, or
1205 // the author of the direct dependency may have forgotten to commit a
1206 // change to the go.mod file, or may have made an erroneous hand-edit that
1207 // causes it to be untidy.)
1209 // Promoting an indirect dependency to a root adds the next layer of its
1210 // dependencies to the module graph, which may increase the selected
1211 // versions of other modules from which we have already loaded packages.
1212 // So after we promote an indirect dependency to a root, we need to reload
1213 // packages, which means another iteration of loading.
1215 // As an extra wrinkle, the upgrades due to promoting a root can cause
1216 // previously-resolved packages to become unresolved. For example, the
1217 // module providing an unstable package might be upgraded to a version
1218 // that no longer contains that package. If we then resolve the missing
1219 // package, we might add yet another root that upgrades away some other
1220 // dependency. (The tests in mod_tidy_convergence*.txt illustrate some
1221 // particularly worrisome cases.)
1223 // To ensure that this process of promoting, adding, and upgrading roots
1224 // eventually terminates, during iteration we only ever add modules to the
1225 // root set — we only remove irrelevant roots at the very end of
1226 // iteration, after we have already added every root that we plan to need
1227 // in the (eventual) tidy root set.
1229 // Since we do not remove any roots during iteration, even if they no
1230 // longer provide any imported packages, the selected versions of the
1231 // roots can only increase and the set of roots can only expand. The set
1232 // of extant root paths is finite and the set of versions of each path is
1233 // finite, so the iteration *must* reach a stable fixed-point.
1234 tidy, err := tidyRoots(ctx, rs, ld.pkgs)
1238 addRoots = tidy.rootModules
1241 rs, err = updateRoots(ctx, direct, rs, ld.pkgs, addRoots)
1243 // We don't actually know what even the root requirements are supposed to be,
1244 // so we can't proceed with loading. Return the error to the caller
1248 if rs != ld.requirements && !reflect.DeepEqual(rs.rootModules, ld.requirements.rootModules) {
1249 // The roots of the module graph have changed in some way (not just the
1250 // "direct" markings). Check whether the changes affected any of the loaded
1252 mg, err := rs.Graph(ctx)
1256 for _, pkg := range ld.pkgs {
1257 if pkg.fromExternalModule() && mg.Selected(pkg.mod.Path) != pkg.mod.Version {
1262 // Promoting a module to a root may resolve an import that was
1263 // previously missing (by pulling in a previously-prune dependency that
1264 // provides it) or ambiguous (by promoting exactly one of the
1265 // alternatives to a root and ignoring the second-level alternatives) or
1266 // otherwise errored out (by upgrading from a version that cannot be
1267 // fetched to one that can be).
1269 // Instead of enumerating all of the possible errors, we'll just check
1270 // whether importFromModules returns nil for the package.
1271 // False-positives are ok: if we have a false-positive here, we'll do an
1272 // extra iteration of package loading this time, but we'll still
1273 // converge when the root set stops changing.
1275 // In some sense, we can think of this as ‘upgraded the module providing
1276 // pkg.path from "none" to a version higher than "none"’.
1277 if _, _, err = importFromModules(ctx, pkg.path, rs, nil); err == nil {
1285 ld.requirements = rs
1289 // resolveMissingImports returns a set of modules that could be added as
1290 // dependencies in order to resolve missing packages from pkgs.
1292 // The newly-resolved packages are added to the addedModuleFor map, and
1293 // resolveMissingImports returns a map from each new module version to
1294 // the first missing package that module would resolve.
1295 func (ld *loader) resolveMissingImports(ctx context.Context) (modAddedBy map[module.Version]*loadPkg) {
1296 type pkgMod struct {
1300 var pkgMods []pkgMod
1301 for _, pkg := range ld.pkgs {
1306 // If we are missing a test, we are also missing its non-test version, and
1307 // we should only add the missing import once.
1310 if !errors.As(pkg.err, new(*ImportMissingError)) {
1311 // Leave other errors for Import or load.Packages to report.
1316 var mod module.Version
1317 ld.work.Add(func() {
1319 mod, err = queryImport(ctx, pkg.path, ld.requirements)
1321 // pkg.err was already non-nil, so we can reasonably attribute the error
1322 // for pkg to either the original error or the one returned by
1323 // queryImport. The existing error indicates only that we couldn't find
1324 // the package, whereas the query error also explains why we didn't fix
1325 // the problem — so we prefer the latter.
1329 // err is nil, but we intentionally leave pkg.err non-nil and pkg.mod
1330 // unset: we still haven't satisfied other invariants of a
1331 // successfully-loaded package, such as scanning and loading the imports
1332 // of that package. If we succeed in resolving the new dependency graph,
1333 // the caller can reload pkg and update the error at that point.
1335 // Even then, the package might not be loaded from the version we've
1336 // identified here. The module may be upgraded by some other dependency,
1337 // or by a transitive dependency of mod itself, or — less likely — the
1338 // package may be rejected by an AllowPackage hook or rendered ambiguous
1339 // by some other newly-added or newly-upgraded dependency.
1342 pkgMods = append(pkgMods, pkgMod{pkg: pkg, mod: &mod})
1346 modAddedBy = map[module.Version]*loadPkg{}
1347 for _, pm := range pkgMods {
1348 pkg, mod := pm.pkg, *pm.mod
1353 fmt.Fprintf(os.Stderr, "go: found %s in %s %s\n", pkg.path, mod.Path, mod.Version)
1354 if modAddedBy[mod] == nil {
1355 modAddedBy[mod] = pkg
1362 // pkg locates the *loadPkg for path, creating and queuing it for loading if
1363 // needed, and updates its state to reflect the given flags.
1365 // The imports of the returned *loadPkg will be loaded asynchronously in the
1366 // ld.work queue, and its test (if requested) will also be populated once
1367 // imports have been resolved. When ld.work goes idle, all transitive imports of
1368 // the requested package (and its test, if requested) will have been loaded.
1369 func (ld *loader) pkg(ctx context.Context, path string, flags loadPkgFlags) *loadPkg {
1370 if flags.has(pkgImportsLoaded) {
1371 panic("internal error: (*loader).pkg called with pkgImportsLoaded flag set")
1374 pkg := ld.pkgCache.Do(path, func() interface{} {
1378 ld.applyPkgFlags(ctx, pkg, flags)
1380 ld.work.Add(func() { ld.load(ctx, pkg) })
1384 ld.applyPkgFlags(ctx, pkg, flags)
1388 // applyPkgFlags updates pkg.flags to set the given flags and propagate the
1389 // (transitive) effects of those flags, possibly loading or enqueueing further
1390 // packages as a result.
1391 func (ld *loader) applyPkgFlags(ctx context.Context, pkg *loadPkg, flags loadPkgFlags) {
1396 if flags.has(pkgInAll) && ld.allPatternIsRoot && !pkg.isTest() {
1397 // This package matches a root pattern by virtue of being in "all".
1401 old := pkg.flags.update(flags)
1403 if new == old || !new.has(pkgImportsLoaded) {
1404 // We either didn't change the state of pkg, or we don't know anything about
1405 // its dependencies yet. Either way, we can't usefully load its test or
1406 // update its dependencies.
1411 // Check whether we should add (or update the flags for) a test for pkg.
1412 // ld.pkgTest is idempotent and extra invocations are inexpensive,
1413 // so it's ok if we call it more than is strictly necessary.
1416 case ld.allPatternIsRoot && pkg.mod == Target:
1417 // We are loading the "all" pattern, which includes packages imported by
1418 // tests in the main module. This package is in the main module, so we
1419 // need to identify the imports of its test even if LoadTests is not set.
1421 // (We will filter out the extra tests explicitly in computePatternAll.)
1424 case ld.allPatternIsRoot && ld.allClosesOverTests && new.has(pkgInAll):
1425 // This variant of the "all" pattern includes imports of tests of every
1426 // package that is itself in "all", and pkg is in "all", so its test is
1427 // also in "all" (as above).
1430 case ld.LoadTests && new.has(pkgIsRoot):
1431 // LoadTest explicitly requests tests of “the root packages”.
1436 var testFlags loadPkgFlags
1437 if pkg.mod == Target || (ld.allClosesOverTests && new.has(pkgInAll)) {
1438 // Tests of packages in the main module are in "all", in the sense that
1439 // they cause the packages they import to also be in "all". So are tests
1440 // of packages in "all" if "all" closes over test dependencies.
1441 testFlags |= pkgInAll
1443 ld.pkgTest(ctx, pkg, testFlags)
1447 if new.has(pkgInAll) && !old.has(pkgInAll|pkgImportsLoaded) {
1448 // We have just marked pkg with pkgInAll, or we have just loaded its
1449 // imports, or both. Now is the time to propagate pkgInAll to the imports.
1450 for _, dep := range pkg.imports {
1451 ld.applyPkgFlags(ctx, dep, pkgInAll)
1456 // preloadRootModules loads the module requirements needed to identify the
1457 // selected version of each module providing a package in rootPkgs,
1458 // adding new root modules to the module graph if needed.
1459 func (ld *loader) preloadRootModules(ctx context.Context, rootPkgs []string) (changedBuildList bool) {
1460 needc := make(chan map[module.Version]bool, 1)
1461 needc <- map[module.Version]bool{}
1462 for _, path := range rootPkgs {
1464 ld.work.Add(func() {
1465 // First, try to identify the module containing the package using only roots.
1467 // If the main module is tidy and the package is in "all" — or if we're
1468 // lucky — we can identify all of its imports without actually loading the
1469 // full module graph.
1470 m, _, err := importFromModules(ctx, path, ld.requirements, nil)
1472 var missing *ImportMissingError
1473 if errors.As(err, &missing) && ld.ResolveMissingImports {
1474 // This package isn't provided by any selected module.
1475 // If we can find it, it will be a new root dependency.
1476 m, err = queryImport(ctx, path, ld.requirements)
1479 // We couldn't identify the root module containing this package.
1480 // Leave it unresolved; we will report it during loading.
1485 // The package is in std or cmd. We don't need to change the root set.
1489 v, ok := ld.requirements.rootSelected(m.Path)
1490 if !ok || v != m.Version {
1491 // We found the requested package in m, but m is not a root, so
1492 // loadModGraph will not load its requirements. We need to promote the
1493 // module to a root to ensure that any other packages this package
1494 // imports are resolved from correct dependency versions.
1496 // (This is the “argument invariant” from the lazy loading design.)
1507 return false // No roots to add.
1510 toAdd := make([]module.Version, 0, len(need))
1511 for m := range need {
1512 toAdd = append(toAdd, m)
1516 rs, err := updateRoots(ctx, ld.requirements.direct, ld.requirements, nil, toAdd)
1518 // We are missing some root dependency, and for some reason we can't load
1519 // enough of the module dependency graph to add the missing root. Package
1520 // loading is doomed to fail, so fail quickly.
1521 ld.errorf("go: %v\n", err)
1525 if reflect.DeepEqual(rs.rootModules, ld.requirements.rootModules) {
1526 // Something is deeply wrong. resolveMissingImports gave us a non-empty
1527 // set of modules to add to the graph, but adding those modules had no
1528 // effect — either they were already in the graph, or updateRoots did not
1529 // add them as requested.
1530 panic(fmt.Sprintf("internal error: adding %v to module graph had no effect on root requirements (%v)", toAdd, rs.rootModules))
1533 ld.requirements = rs
1537 // load loads an individual package.
1538 func (ld *loader) load(ctx context.Context, pkg *loadPkg) {
1539 if strings.Contains(pkg.path, "@") {
1540 // Leave for error during load.
1543 if build.IsLocalImport(pkg.path) || filepath.IsAbs(pkg.path) {
1544 // Leave for error during load.
1545 // (Module mode does not allow local imports.)
1549 if search.IsMetaPackage(pkg.path) {
1550 pkg.err = &invalidImportError{
1551 importPath: pkg.path,
1552 err: fmt.Errorf("%q is not an importable package; see 'go help packages'", pkg.path),
1558 if ld.requirements.depth == eager {
1560 mg, err = ld.requirements.Graph(ctx)
1562 // We already checked the error from Graph in loadFromRoots and/or
1563 // updateRequirements, so we ignored the error on purpose and we should
1564 // keep trying to push past it.
1566 // However, because mg may be incomplete (and thus may select inaccurate
1567 // versions), we shouldn't use it to load packages. Instead, we pass a nil
1568 // *ModuleGraph, which will cause mg to first try loading from only the
1569 // main module and root dependencies.
1574 pkg.mod, pkg.dir, pkg.err = importFromModules(ctx, pkg.path, ld.requirements, mg)
1578 if pkg.mod == Target {
1579 // Go ahead and mark pkg as in "all". This provides the invariant that a
1580 // package that is *only* imported by other packages in "all" is always
1581 // marked as such before loading its imports.
1583 // We don't actually rely on that invariant at the moment, but it may
1584 // improve efficiency somewhat and makes the behavior a bit easier to reason
1585 // about (by reducing churn on the flag bits of dependencies), and costs
1586 // essentially nothing (these atomic flag ops are essentially free compared
1587 // to scanning source code for imports).
1588 ld.applyPkgFlags(ctx, pkg, pkgInAll)
1590 if ld.AllowPackage != nil {
1591 if err := ld.AllowPackage(ctx, pkg.path, pkg.mod); err != nil {
1596 pkg.inStd = (search.IsStandardImportPath(pkg.path) && search.InDir(pkg.dir, cfg.GOROOTsrc) != "")
1598 var imports, testImports []string
1600 if cfg.BuildContext.Compiler == "gccgo" && pkg.inStd {
1601 // We can't scan standard packages for gccgo.
1604 imports, testImports, err = scanDir(pkg.dir, ld.Tags)
1611 pkg.imports = make([]*loadPkg, 0, len(imports))
1612 var importFlags loadPkgFlags
1613 if pkg.flags.has(pkgInAll) {
1614 importFlags = pkgInAll
1616 for _, path := range imports {
1618 // Imports from packages in "std" and "cmd" should resolve using
1619 // GOROOT/src/vendor even when "std" is not the main module.
1620 path = ld.stdVendor(pkg.path, path)
1622 pkg.imports = append(pkg.imports, ld.pkg(ctx, path, importFlags))
1624 pkg.testImports = testImports
1626 ld.applyPkgFlags(ctx, pkg, pkgImportsLoaded)
1629 // pkgTest locates the test of pkg, creating it if needed, and updates its state
1630 // to reflect the given flags.
1632 // pkgTest requires that the imports of pkg have already been loaded (flagged
1633 // with pkgImportsLoaded).
1634 func (ld *loader) pkgTest(ctx context.Context, pkg *loadPkg, testFlags loadPkgFlags) *loadPkg {
1636 panic("pkgTest called on a test package")
1639 createdTest := false
1640 pkg.testOnce.Do(func() {
1641 pkg.test = &loadPkg{
1649 ld.applyPkgFlags(ctx, pkg.test, testFlags)
1655 test.imports = make([]*loadPkg, 0, len(pkg.testImports))
1656 var importFlags loadPkgFlags
1657 if test.flags.has(pkgInAll) {
1658 importFlags = pkgInAll
1660 for _, path := range pkg.testImports {
1662 path = ld.stdVendor(test.path, path)
1664 test.imports = append(test.imports, ld.pkg(ctx, path, importFlags))
1666 pkg.testImports = nil
1667 ld.applyPkgFlags(ctx, test, pkgImportsLoaded)
1669 ld.applyPkgFlags(ctx, test, testFlags)
1675 // stdVendor returns the canonical import path for the package with the given
1676 // path when imported from the standard-library package at parentPath.
1677 func (ld *loader) stdVendor(parentPath, path string) string {
1678 if search.IsStandardImportPath(path) {
1682 if str.HasPathPrefix(parentPath, "cmd") {
1683 if !ld.VendorModulesInGOROOTSrc || Target.Path != "cmd" {
1684 vendorPath := pathpkg.Join("cmd", "vendor", path)
1685 if _, err := os.Stat(filepath.Join(cfg.GOROOTsrc, filepath.FromSlash(vendorPath))); err == nil {
1689 } else if !ld.VendorModulesInGOROOTSrc || Target.Path != "std" || str.HasPathPrefix(parentPath, "vendor") {
1690 // If we are outside of the 'std' module, resolve imports from within 'std'
1691 // to the vendor directory.
1693 // Do the same for importers beginning with the prefix 'vendor/' even if we
1694 // are *inside* of the 'std' module: the 'vendor/' packages that resolve
1695 // globally from GOROOT/src/vendor (and are listed as part of 'go list std')
1696 // are distinct from the real module dependencies, and cannot import
1697 // internal packages from the real module.
1699 // (Note that although the 'vendor/' packages match the 'std' *package*
1700 // pattern, they are not part of the std *module*, and do not affect
1701 // 'go mod tidy' and similar module commands when working within std.)
1702 vendorPath := pathpkg.Join("vendor", path)
1703 if _, err := os.Stat(filepath.Join(cfg.GOROOTsrc, filepath.FromSlash(vendorPath))); err == nil {
1708 // Not vendored: resolve from modules.
1712 // computePatternAll returns the list of packages matching pattern "all",
1713 // starting with a list of the import paths for the packages in the main module.
1714 func (ld *loader) computePatternAll() (all []string) {
1715 for _, pkg := range ld.pkgs {
1716 if pkg.flags.has(pkgInAll) && !pkg.isTest() {
1717 all = append(all, pkg.path)
1724 // checkMultiplePaths verifies that a given module path is used as itself
1725 // or as a replacement for another module, but not both at the same time.
1727 // (See https://golang.org/issue/26607 and https://golang.org/issue/34650.)
1728 func (ld *loader) checkMultiplePaths() {
1729 mods := ld.requirements.rootModules
1730 if cached := ld.requirements.graph.Load(); cached != nil {
1731 if mg := cached.(cachedGraph).mg; mg != nil {
1732 mods = mg.BuildList()
1736 firstPath := map[module.Version]string{}
1737 for _, mod := range mods {
1738 src := resolveReplacement(mod)
1739 if prev, ok := firstPath[src]; !ok {
1740 firstPath[src] = mod.Path
1741 } else if prev != mod.Path {
1742 ld.errorf("go: %s@%s used for two different module paths (%s and %s)\n", src.Path, src.Version, prev, mod.Path)
1747 // scanDir is like imports.ScanDir but elides known magic imports from the list,
1748 // so that we do not go looking for packages that don't really exist.
1750 // The standard magic import is "C", for cgo.
1752 // The only other known magic imports are appengine and appengine/*.
1753 // These are so old that they predate "go get" and did not use URL-like paths.
1754 // Most code today now uses google.golang.org/appengine instead,
1755 // but not all code has been so updated. When we mostly ignore build tags
1756 // during "go vendor", we look into "// +build appengine" files and
1757 // may see these legacy imports. We drop them so that the module
1758 // search does not look for modules to try to satisfy them.
1759 func scanDir(dir string, tags map[string]bool) (imports_, testImports []string, err error) {
1760 imports_, testImports, err = imports.ScanDir(dir, tags)
1762 filter := func(x []string) []string {
1764 for _, pkg := range x {
1765 if pkg != "C" && pkg != "appengine" && !strings.HasPrefix(pkg, "appengine/") &&
1766 pkg != "appengine_internal" && !strings.HasPrefix(pkg, "appengine_internal/") {
1774 return filter(imports_), filter(testImports), err
1777 // buildStacks computes minimal import stacks for each package,
1778 // for use in error messages. When it completes, packages that
1779 // are part of the original root set have pkg.stack == nil,
1780 // and other packages have pkg.stack pointing at the next
1781 // package up the import stack in their minimal chain.
1782 // As a side effect, buildStacks also constructs ld.pkgs,
1783 // the list of all packages loaded.
1784 func (ld *loader) buildStacks() {
1785 if len(ld.pkgs) > 0 {
1786 panic("buildStacks")
1788 for _, pkg := range ld.roots {
1789 pkg.stack = pkg // sentinel to avoid processing in next loop
1790 ld.pkgs = append(ld.pkgs, pkg)
1792 for i := 0; i < len(ld.pkgs); i++ { // not range: appending to ld.pkgs in loop
1794 for _, next := range pkg.imports {
1795 if next.stack == nil {
1797 ld.pkgs = append(ld.pkgs, next)
1800 if next := pkg.test; next != nil && next.stack == nil {
1802 ld.pkgs = append(ld.pkgs, next)
1805 for _, pkg := range ld.roots {
1810 // stackText builds the import stack text to use when
1811 // reporting an error in pkg. It has the general form
1816 // other2.test imports
1819 func (pkg *loadPkg) stackText() string {
1820 var stack []*loadPkg
1821 for p := pkg; p != nil; p = p.stack {
1822 stack = append(stack, p)
1825 var buf bytes.Buffer
1826 for i := len(stack) - 1; i >= 0; i-- {
1828 fmt.Fprint(&buf, p.path)
1829 if p.testOf != nil {
1830 fmt.Fprint(&buf, ".test")
1833 if stack[i-1].testOf == p {
1834 fmt.Fprint(&buf, " tested by\n\t")
1836 fmt.Fprint(&buf, " imports\n\t")
1843 // why returns the text to use in "go mod why" output about the given package.
1844 // It is less ornate than the stackText but contains the same information.
1845 func (pkg *loadPkg) why() string {
1846 var buf strings.Builder
1847 var stack []*loadPkg
1848 for p := pkg; p != nil; p = p.stack {
1849 stack = append(stack, p)
1852 for i := len(stack) - 1; i >= 0; i-- {
1854 if p.testOf != nil {
1855 fmt.Fprintf(&buf, "%s.test\n", p.testOf.path)
1857 fmt.Fprintf(&buf, "%s\n", p.path)
1863 // Why returns the "go mod why" output stanza for the given package,
1864 // without the leading # comment.
1865 // The package graph must have been loaded already, usually by LoadPackages.
1866 // If there is no reason for the package to be in the current build,
1867 // Why returns an empty string.
1868 func Why(path string) string {
1869 pkg, ok := loaded.pkgCache.Get(path).(*loadPkg)
1876 // WhyDepth returns the number of steps in the Why listing.
1877 // If there is no reason for the package to be in the current build,
1878 // WhyDepth returns 0.
1879 func WhyDepth(path string) int {
1881 pkg, _ := loaded.pkgCache.Get(path).(*loadPkg)
1882 for p := pkg; p != nil; p = p.stack {