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.
22 "golang.org/x/mod/module"
23 "golang.org/x/mod/semver"
26 // capVersionSlice returns s with its cap reduced to its length.
27 func capVersionSlice(s []module.Version) []module.Version {
28 return s[:len(s):len(s)]
31 // A Requirements represents a logically-immutable set of root module requirements.
32 type Requirements struct {
33 // depth is the depth at which the requirement graph is computed.
35 // If eager, the graph includes all transitive requirements regardless of depth.
37 // If lazy, the graph includes only the root modules, the explicit
38 // requirements of those root modules, and the transitive requirements of only
39 // the *non-lazy* root modules.
42 // rootModules is the set of module versions explicitly required by the main
43 // modules, sorted and capped to length. It may contain duplicates, and may
44 // contain multiple versions for a given module path.
45 rootModules []module.Version
46 maxRootVersion map[string]string
48 // direct is the set of module paths for which we believe the module provides
49 // a package directly imported by a package or test in the main module.
51 // The "direct" map controls which modules are annotated with "// indirect"
52 // comments in the go.mod file, and may impact which modules are listed as
53 // explicit roots (vs. indirect-only dependencies). However, it should not
54 // have a semantic effect on the build list overall.
56 // The initial direct map is populated from the existing "// indirect"
57 // comments (or lack thereof) in the go.mod file. It is updated by the
58 // package loader: dependencies may be promoted to direct if new
59 // direct imports are observed, and may be demoted to indirect during
60 // 'go mod tidy' or 'go mod vendor'.
62 // The direct map is keyed by module paths, not module versions. When a
63 // module's selected version changes, we assume that it remains direct if the
64 // previous version was a direct dependency. That assumption might not hold in
65 // rare cases (such as if a dependency splits out a nested module, or merges a
66 // nested module back into a parent module).
67 direct map[string]bool
69 graphOnce sync.Once // guards writes to (but not reads from) graph
70 graph atomic.Value // cachedGraph
73 // A cachedGraph is a non-nil *ModuleGraph, together with any error discovered
74 // while loading that graph.
75 type cachedGraph struct {
77 err error // If err is non-nil, mg may be incomplete (but must still be non-nil).
80 // requirements is the requirement graph for the main module.
82 // It is always non-nil if the main module's go.mod file has been loaded.
84 // This variable should only be read from the loadModFile function, and should
85 // only be written in the loadModFile and commitRequirements functions.
86 // All other functions that need or produce a *Requirements should
87 // accept and/or return an explicit parameter.
88 var requirements *Requirements
90 // newRequirements returns a new requirement set with the given root modules.
91 // The dependencies of the roots will be loaded lazily at the first call to the
94 // The rootModules slice must be sorted according to module.Sort.
95 // The caller must not modify the rootModules slice or direct map after passing
96 // them to newRequirements.
98 // If vendoring is in effect, the caller must invoke initVendor on the returned
99 // *Requirements before any other method.
100 func newRequirements(depth modDepth, rootModules []module.Version, direct map[string]bool) *Requirements {
101 for i, m := range rootModules {
102 if m.Version == "" && MainModules.Contains(m.Path) {
103 panic(fmt.Sprintf("newRequirements called with untrimmed build list: rootModules[%v] is a main module", i))
105 if m.Path == "" || m.Version == "" {
106 panic(fmt.Sprintf("bad requirement: rootModules[%v] = %v", i, m))
109 prev := rootModules[i-1]
110 if prev.Path > m.Path || (prev.Path == m.Path && semver.Compare(prev.Version, m.Version) > 0) {
111 panic(fmt.Sprintf("newRequirements called with unsorted roots: %v", rootModules))
118 rootModules: capVersionSlice(rootModules),
119 maxRootVersion: make(map[string]string, len(rootModules)),
123 for _, m := range rootModules {
124 if v, ok := rs.maxRootVersion[m.Path]; ok && cmpVersion(v, m.Version) >= 0 {
127 rs.maxRootVersion[m.Path] = m.Version
132 // initVendor initializes rs.graph from the given list of vendored module
133 // dependencies, overriding the graph that would normally be loaded from module
135 func (rs *Requirements) initVendor(vendorList []module.Version) {
136 rs.graphOnce.Do(func() {
138 g: mvs.NewGraph(cmpVersion, MainModules.Versions()),
141 if MainModules.Len() != 1 {
142 panic("There should be exactly one main moudle in Vendor mode.")
144 mainModule := MainModules.Versions()[0]
146 if rs.depth == lazy {
147 // The roots of a lazy module should already include every module in the
148 // vendor list, because the vendored modules are the same as those
149 // maintained as roots by the lazy loading “import invariant”.
151 // Just to be sure, we'll double-check that here.
152 inconsistent := false
153 for _, m := range vendorList {
154 if v, ok := rs.rootSelected(m.Path); !ok || v != m.Version {
155 base.Errorf("go: vendored module %v should be required explicitly in go.mod", m)
160 base.Fatalf("go: %v", errGoModDirty)
163 // Now we can treat the rest of the module graph as effectively “pruned
164 // out”, like a more aggressive version of lazy loading: in vendor mode,
165 // the root requirements *are* the complete module graph.
166 mg.g.Require(mainModule, rs.rootModules)
168 // The transitive requirements of the main module are not in general available
169 // from the vendor directory, and we don't actually know how we got from
170 // the roots to the final build list.
172 // Instead, we'll inject a fake "vendor/modules.txt" module that provides
173 // those transitive dependencies, and mark it as a dependency of the main
174 // module. That allows us to elide the actual structure of the module
175 // graph, but still distinguishes between direct and indirect
177 vendorMod := module.Version{Path: "vendor/modules.txt", Version: ""}
178 mg.g.Require(mainModule, append(rs.rootModules, vendorMod))
179 mg.g.Require(vendorMod, vendorList)
182 rs.graph.Store(cachedGraph{mg, nil})
186 // rootSelected returns the version of the root dependency with the given module
187 // path, or the zero module.Version and ok=false if the module is not a root
189 func (rs *Requirements) rootSelected(path string) (version string, ok bool) {
190 if MainModules.Contains(path) {
193 if v, ok := rs.maxRootVersion[path]; ok {
199 // hasRedundantRoot returns true if the root list contains multiple requirements
200 // of the same module or a requirement on any version of the main module.
201 // Redundant requirements should be pruned, but they may influence version
203 func (rs *Requirements) hasRedundantRoot() bool {
204 for i, m := range rs.rootModules {
205 if MainModules.Contains(m.Path) || (i > 0 && m.Path == rs.rootModules[i-1].Path) {
212 // Graph returns the graph of module requirements loaded from the current
213 // root modules (as reported by RootModules).
215 // Graph always makes a best effort to load the requirement graph despite any
216 // errors, and always returns a non-nil *ModuleGraph.
218 // If the requirements of any relevant module fail to load, Graph also
219 // returns a non-nil error of type *mvs.BuildListError.
220 func (rs *Requirements) Graph(ctx context.Context) (*ModuleGraph, error) {
221 rs.graphOnce.Do(func() {
222 mg, mgErr := readModGraph(ctx, rs.depth, rs.rootModules)
223 rs.graph.Store(cachedGraph{mg, mgErr})
225 cached := rs.graph.Load().(cachedGraph)
226 return cached.mg, cached.err
229 // IsDirect returns whether the given module provides a package directly
230 // imported by a package or test in the main module.
231 func (rs *Requirements) IsDirect(path string) bool {
232 return rs.direct[path]
235 // A ModuleGraph represents the complete graph of module dependencies
238 // If the main module is lazily loaded, the graph does not include
239 // transitive dependencies of non-root (implicit) dependencies.
240 type ModuleGraph struct {
242 loadCache par.Cache // module.Version → summaryError
244 buildListOnce sync.Once
245 buildList []module.Version
248 // A summaryError is either a non-nil modFileSummary or a non-nil error
249 // encountered while reading or parsing that summary.
250 type summaryError struct {
251 summary *modFileSummary
255 var readModGraphDebugOnce sync.Once
257 // readModGraph reads and returns the module dependency graph starting at the
260 // Unlike LoadModGraph, readModGraph does not attempt to diagnose or update
261 // inconsistent roots.
262 func readModGraph(ctx context.Context, depth modDepth, roots []module.Version) (*ModuleGraph, error) {
264 readModGraphDebugOnce.Do(func() {
265 for _, f := range strings.Split(os.Getenv("GODEBUG"), ",") {
269 fmt.Fprintf(os.Stderr, "go: read full module graph.\n")
270 case "lazymod=strict":
272 base.Fatalf("go: read full module graph (forbidden by GODEBUG=lazymod=strict).")
279 mu sync.Mutex // guards mg.g and hasError during loading
282 g: mvs.NewGraph(cmpVersion, MainModules.Versions()),
285 for _, m := range MainModules.Versions() {
286 // Require all roots from all main modules.
287 _ = TODOWorkspaces("This isn't the correct behavior. " +
288 "Fix this when the requirements struct is updated to reflect the struct of the module graph.")
289 mg.g.Require(m, roots)
293 loadQueue = par.NewQueue(runtime.GOMAXPROCS(0))
294 loadingEager sync.Map // module.Version → nil; the set of modules that have been or are being loaded via eager roots
297 // loadOne synchronously loads the explicit requirements for module m.
298 // It does not load the transitive requirements of m even if the go version in
299 // m's go.mod file indicates eager loading.
300 loadOne := func(m module.Version) (*modFileSummary, error) {
301 cached := mg.loadCache.Do(m, func() interface{} {
302 summary, err := goModSummary(m)
306 mg.g.Require(m, summary.require)
312 return summaryError{summary, err}
315 return cached.summary, cached.err
318 var enqueue func(m module.Version, depth modDepth)
319 enqueue = func(m module.Version, depth modDepth) {
320 if m.Version == "none" {
325 if _, dup := loadingEager.LoadOrStore(m, nil); dup {
326 // m has already been enqueued for loading. Since eager loading may
327 // follow cycles in the the requirement graph, we need to return early
328 // to avoid making the load queue infinitely long.
333 loadQueue.Add(func() {
334 summary, err := loadOne(m)
336 return // findError will report the error later.
339 // If the version in m's go.mod file implies eager loading, then we cannot
340 // assume that the explicit requirements of m (added by loadOne) are
341 // sufficient to build the packages it contains. We must load its full
342 // transitive dependency graph to be sure that we see all relevant
344 if depth == eager || summary.depth == eager {
345 for _, r := range summary.require {
352 for _, m := range roots {
358 return mg, mg.findError()
363 // RequiredBy returns the dependencies required by module m in the graph,
364 // or ok=false if module m's dependencies are not relevant (such as if they
365 // are pruned out by lazy loading).
367 // The caller must not modify the returned slice, but may safely append to it
368 // and may rely on it not to be modified.
369 func (mg *ModuleGraph) RequiredBy(m module.Version) (reqs []module.Version, ok bool) {
370 return mg.g.RequiredBy(m)
373 // Selected returns the selected version of the module with the given path.
375 // If no version is selected, Selected returns version "none".
376 func (mg *ModuleGraph) Selected(path string) (version string) {
377 return mg.g.Selected(path)
380 // WalkBreadthFirst invokes f once, in breadth-first order, for each module
381 // version other than "none" that appears in the graph, regardless of whether
382 // that version is selected.
383 func (mg *ModuleGraph) WalkBreadthFirst(f func(m module.Version)) {
384 mg.g.WalkBreadthFirst(f)
387 // BuildList returns the selected versions of all modules present in the graph,
388 // beginning with Target.
390 // The order of the remaining elements in the list is deterministic
393 // The caller must not modify the returned list, but may safely append to it
394 // and may rely on it not to be modified.
395 func (mg *ModuleGraph) BuildList() []module.Version {
396 mg.buildListOnce.Do(func() {
397 mg.buildList = capVersionSlice(mg.g.BuildList())
402 func (mg *ModuleGraph) findError() error {
403 errStack := mg.g.FindPath(func(m module.Version) bool {
404 cached := mg.loadCache.Get(m)
405 return cached != nil && cached.(summaryError).err != nil
407 if len(errStack) > 0 {
408 err := mg.loadCache.Get(errStack[len(errStack)-1]).(summaryError).err
409 var noUpgrade func(from, to module.Version) bool
410 return mvs.NewBuildListError(err, errStack, noUpgrade)
416 func (mg *ModuleGraph) allRootsSelected() bool {
417 for _, mm := range MainModules.Versions() {
418 roots, _ := mg.g.RequiredBy(mm)
419 for _, m := range roots {
420 if mg.Selected(m.Path) != m.Version {
428 // LoadModGraph loads and returns the graph of module dependencies of the main module,
429 // without loading any packages.
431 // If the goVersion string is non-empty, the returned graph is the graph
432 // as interpreted by the given Go version (instead of the version indicated
433 // in the go.mod file).
435 // Modules are loaded automatically (and lazily) in LoadPackages:
436 // LoadModGraph need only be called if LoadPackages is not,
437 // typically in commands that care about modules but no particular package.
438 func LoadModGraph(ctx context.Context, goVersion string) *ModuleGraph {
439 rs := LoadModFile(ctx)
442 depth := modDepthFromGoVersion(goVersion)
443 if depth == eager && rs.depth != eager {
444 // Use newRequirements instead of convertDepth because convertDepth
445 // also updates roots; here, we want to report the unmodified roots
446 // even though they may seem inconsistent.
447 rs = newRequirements(eager, rs.rootModules, rs.direct)
450 mg, err := rs.Graph(ctx)
452 base.Fatalf("go: %v", err)
457 rs, mg, err := expandGraph(ctx, rs)
459 base.Fatalf("go: %v", err)
462 commitRequirements(ctx, modFileGoVersion(), rs)
466 // expandGraph loads the complete module graph from rs.
468 // If the complete graph reveals that some root of rs is not actually the
469 // selected version of its path, expandGraph computes a new set of roots that
470 // are consistent. (When lazy loading is implemented, this may result in
471 // upgrades to other modules due to requirements that were previously pruned
474 // expandGraph returns the updated roots, along with the module graph loaded
475 // from those roots and any error encountered while loading that graph.
476 // expandGraph returns non-nil requirements and a non-nil graph regardless of
477 // errors. On error, the roots might not be updated to be consistent.
478 func expandGraph(ctx context.Context, rs *Requirements) (*Requirements, *ModuleGraph, error) {
479 mg, mgErr := rs.Graph(ctx)
481 // Without the graph, we can't update the roots: we don't know which
482 // versions of transitive dependencies would be selected.
486 if !mg.allRootsSelected() {
487 // The roots of rs are not consistent with the rest of the graph. Update
488 // them. In an eager module this is a no-op for the build list as a whole —
489 // it just promotes what were previously transitive requirements to be
490 // roots — but in a lazy module it may pull in previously-irrelevant
491 // transitive dependencies.
493 newRS, rsErr := updateRoots(ctx, rs.direct, rs, nil, nil, false)
495 // Failed to update roots, perhaps because of an error in a transitive
496 // dependency needed for the update. Return the original Requirements
501 mg, mgErr = rs.Graph(ctx)
507 // EditBuildList edits the global build list by first adding every module in add
508 // to the existing build list, then adjusting versions (and adding or removing
509 // requirements as needed) until every module in mustSelect is selected at the
512 // (Note that the newly-added modules might not be selected in the resulting
513 // build list: they could be lower than existing requirements or conflict with
514 // versions in mustSelect.)
516 // If the versions listed in mustSelect are mutually incompatible (due to one of
517 // the listed modules requiring a higher version of another), EditBuildList
518 // returns a *ConstraintError and leaves the build list in its previous state.
520 // On success, EditBuildList reports whether the selected version of any module
521 // in the build list may have been changed (possibly to or from "none") as a
523 func EditBuildList(ctx context.Context, add, mustSelect []module.Version) (changed bool, err error) {
524 rs, changed, err := editRequirements(ctx, LoadModFile(ctx), add, mustSelect)
528 commitRequirements(ctx, modFileGoVersion(), rs)
532 // A ConstraintError describes inconsistent constraints in EditBuildList
533 type ConstraintError struct {
534 // Conflict lists the source of the conflict for each version in mustSelect
535 // that could not be selected due to the requirements of some other version in
540 func (e *ConstraintError) Error() string {
541 b := new(strings.Builder)
542 b.WriteString("version constraints conflict:")
543 for _, c := range e.Conflicts {
544 fmt.Fprintf(b, "\n\t%v requires %v, but %v is requested", c.Source, c.Dep, c.Constraint)
549 // A Conflict documents that Source requires Dep, which conflicts with Constraint.
550 // (That is, Dep has the same module path as Constraint but a higher version.)
551 type Conflict struct {
552 Source module.Version
554 Constraint module.Version
557 // tidyRoots trims the root dependencies to the minimal requirements needed to
558 // both retain the same versions of all packages in pkgs and satisfy the
559 // lazy loading invariants (if applicable).
560 func tidyRoots(ctx context.Context, rs *Requirements, pkgs []*loadPkg) (*Requirements, error) {
561 mainModule := MainModules.mustGetSingleMainModule()
562 if rs.depth == eager {
563 return tidyEagerRoots(ctx, mainModule, rs.direct, pkgs)
565 return tidyLazyRoots(ctx, mainModule, rs.direct, pkgs)
568 func updateRoots(ctx context.Context, direct map[string]bool, rs *Requirements, pkgs []*loadPkg, add []module.Version, rootsImported bool) (*Requirements, error) {
569 if rs.depth == eager {
570 return updateEagerRoots(ctx, direct, rs, add)
572 return updateLazyRoots(ctx, direct, rs, pkgs, add, rootsImported)
575 // tidyLazyRoots returns a minimal set of root requirements that maintains the
576 // "lazy loading" invariants of the go.mod file for the given packages:
578 // 1. For each package marked with pkgInAll, the module path that provided that
579 // package is included as a root.
580 // 2. For all packages, the module that provided that package either remains
581 // selected at the same version or is upgraded by the dependencies of a
584 // If any module that provided a package has been upgraded above its previous,
585 // version, the caller may need to reload and recompute the package graph.
587 // To ensure that the loading process eventually converges, the caller should
588 // add any needed roots from the tidy root set (without removing existing untidy
589 // roots) until the set of roots has converged.
590 func tidyLazyRoots(ctx context.Context, mainModule module.Version, direct map[string]bool, pkgs []*loadPkg) (*Requirements, error) {
592 roots []module.Version
593 pathIncluded = map[string]bool{mainModule.Path: true}
595 // We start by adding roots for every package in "all".
597 // Once that is done, we may still need to add more roots to cover upgraded or
598 // otherwise-missing test dependencies for packages in "all". For those test
599 // dependencies, we prefer to add roots for packages with shorter import
600 // stacks first, on the theory that the module requirements for those will
601 // tend to fill in the requirements for their transitive imports (which have
602 // deeper import stacks). So we add the missing dependencies for one depth at
603 // a time, starting with the packages actually in "all" and expanding outwards
604 // until we have scanned every package that was loaded.
607 queued = map[*loadPkg]bool{}
609 for _, pkg := range pkgs {
610 if !pkg.flags.has(pkgInAll) {
613 if pkg.fromExternalModule() && !pathIncluded[pkg.mod.Path] {
614 roots = append(roots, pkg.mod)
615 pathIncluded[pkg.mod.Path] = true
617 queue = append(queue, pkg)
621 tidy := newRequirements(lazy, roots, direct)
624 roots = tidy.rootModules
625 mg, err := tidy.Graph(ctx)
632 for _, pkg := range prevQueue {
637 for _, dep := range pkg.imports {
639 queue = append(queue, dep)
643 if pkg.test != nil && !queued[pkg.test] {
644 queue = append(queue, pkg.test)
645 queued[pkg.test] = true
647 if !pathIncluded[m.Path] {
648 if s := mg.Selected(m.Path); cmpVersion(s, m.Version) < 0 {
649 roots = append(roots, m)
651 pathIncluded[m.Path] = true
655 if len(roots) > len(tidy.rootModules) {
657 tidy = newRequirements(lazy, roots, tidy.direct)
661 _, err := tidy.Graph(ctx)
668 // updateLazyRoots returns a set of root requirements that maintains the “lazy
669 // loading” invariants of the go.mod file:
671 // 1. The selected version of the module providing each package marked with
672 // either pkgInAll or pkgIsRoot is included as a root.
673 // Note that certain root patterns (such as '...') may explode the root set
674 // to contain every module that provides any package imported (or merely
675 // required) by any other module.
676 // 2. Each root appears only once, at the selected version of its path
677 // (if rs.graph is non-nil) or at the highest version otherwise present as a
679 // 3. Every module path that appears as a root in rs remains a root.
680 // 4. Every version in add is selected at its given version unless upgraded by
681 // (the dependencies of) an existing root or another module in add.
683 // The packages in pkgs are assumed to have been loaded from either the roots of
684 // rs or the modules selected in the graph of rs.
686 // The above invariants together imply the “lazy loading” invariants for the
689 // 1. (The import invariant.) Every module that provides a package transitively
690 // imported by any package or test in the main module is included as a root.
691 // This follows by induction from (1) and (3) above. Transitively-imported
692 // packages loaded during this invocation are marked with pkgInAll (1),
693 // and by hypothesis any transitively-imported packages loaded in previous
694 // invocations were already roots in rs (3).
696 // 2. (The argument invariant.) Every module that provides a package matching
697 // an explicit package pattern is included as a root. This follows directly
698 // from (1): packages matching explicit package patterns are marked with
701 // 3. (The completeness invariant.) Every module that contributed any package
702 // to the build is required by either the main module or one of the modules
703 // it requires explicitly. This invariant is left up to the caller, who must
704 // not load packages from outside the module graph but may add roots to the
705 // graph, but is facilited by (3). If the caller adds roots to the graph in
706 // order to resolve missing packages, then updateLazyRoots will retain them,
707 // the selected versions of those roots cannot regress, and they will
708 // eventually be written back to the main module's go.mod file.
710 // (See https://golang.org/design/36460-lazy-module-loading#invariants for more
712 func updateLazyRoots(ctx context.Context, direct map[string]bool, rs *Requirements, pkgs []*loadPkg, add []module.Version, rootsImported bool) (*Requirements, error) {
713 roots := rs.rootModules
714 rootsUpgraded := false
716 spotCheckRoot := map[module.Version]bool{}
718 // “The selected version of the module providing each package marked with
719 // either pkgInAll or pkgIsRoot is included as a root.”
721 for _, pkg := range pkgs {
722 if !pkg.fromExternalModule() {
723 // pkg was not loaded from a module dependency, so we don't need
724 // to do anything special to maintain that dependency.
729 case pkg.flags.has(pkgInAll):
730 // pkg is transitively imported by a package or test in the main module.
731 // We need to promote the module that maintains it to a root: if some
732 // other module depends on the main module, and that other module also
733 // uses lazy loading, it will expect to find all of our transitive
734 // dependencies by reading just our go.mod file, not the go.mod files of
735 // everything we depend on.
737 // (This is the “import invariant” that makes lazy loading possible.)
739 case rootsImported && pkg.flags.has(pkgFromRoot):
740 // pkg is a transitive dependency of some root, and we are treating the
741 // roots as if they are imported by the main module (as in 'go get').
743 case pkg.flags.has(pkgIsRoot):
744 // pkg is a root of the package-import graph. (Generally this means that
745 // it matches a command-line argument.) We want future invocations of the
746 // 'go' command — such as 'go test' on the same package — to continue to
747 // use the same versions of its dependencies that we are using right now.
748 // So we need to bring this package's dependencies inside the lazy-loading
751 // Making the module containing this package a root of the module graph
752 // does exactly that: if the module containing the package is lazy it
753 // should satisfy the import invariant itself, so all of its dependencies
754 // should be in its go.mod file, and if the module containing the package
755 // is eager then if we make it a root we will load all of its transitive
756 // dependencies into the module graph.
758 // (This is the “argument invariant” of lazy loading, and is important for
762 // pkg is a dependency of some other package outside of the main module.
763 // As far as we know it's not relevant to the main module (and thus not
764 // relevant to consumers of the main module either), and its dependencies
765 // should already be in the module graph — included in the dependencies of
766 // the package that imported it.
770 if _, ok := rs.rootSelected(pkg.mod.Path); ok {
771 // It is possible that the main module's go.mod file is incomplete or
772 // otherwise erroneous — for example, perhaps the author forgot to 'git
773 // add' their updated go.mod file after adding a new package import, or
774 // perhaps they made an edit to the go.mod file using a third-party tool
775 // ('git merge'?) that doesn't maintain consistency for module
776 // dependencies. If that happens, ideally we want to detect the missing
777 // requirements and fix them up here.
779 // However, we also need to be careful not to be too aggressive. For
780 // transitive dependencies of external tests, the go.mod file for the
781 // module containing the test itself is expected to provide all of the
782 // relevant dependencies, and we explicitly don't want to pull in
783 // requirements on *irrelevant* requirements that happen to occur in the
784 // go.mod files for these transitive-test-only dependencies. (See the test
785 // in mod_lazy_test_horizon.txt for a concrete example.
787 // The “goldilocks zone” seems to be to spot-check exactly the same
788 // modules that we promote to explicit roots: namely, those that provide
789 // packages transitively imported by the main module, and those that
790 // provide roots of the package-import graph. That will catch erroneous
791 // edits to the main module's go.mod file and inconsistent requirements in
792 // dependencies that provide imported packages, but will ignore erroneous
793 // or misleading requirements in dependencies that aren't obviously
794 // relevant to the packages in the main module.
795 spotCheckRoot[pkg.mod] = true
797 roots = append(roots, pkg.mod)
799 // The roots slice was initially sorted because rs.rootModules was sorted,
800 // but the root we just added could be out of order.
805 for _, m := range add {
806 if v, ok := rs.rootSelected(m.Path); !ok || cmpVersion(v, m.Version) < 0 {
807 roots = append(roots, m)
816 // "Each root appears only once, at the selected version of its path ….”
820 // We've added or upgraded one or more roots, so load the full module
821 // graph so that we can update those roots to be consistent with other
823 if mustHaveCompleteRequirements() {
824 // Our changes to the roots may have moved dependencies into or out of
825 // the lazy-loading horizon, which could in turn change the selected
826 // versions of other modules. (Unlike for eager modules, for lazy
827 // modules adding or removing an explicit root is a semantic change, not
828 // just a cosmetic one.)
829 return rs, errGoModDirty
832 rs = newRequirements(lazy, roots, direct)
834 mg, err = rs.Graph(ctx)
839 // Since none of the roots have been upgraded, we have no reason to
840 // suspect that they are inconsistent with the requirements of any other
841 // roots. Only look at the full module graph if we've already loaded it;
842 // otherwise, just spot-check the explicit requirements of the roots from
843 // which we loaded packages.
844 if rs.graph.Load() != nil {
845 // We've already loaded the full module graph, which includes the
846 // requirements of all of the root modules — even the transitive
847 // requirements, if they are eager!
848 mg, _ = rs.Graph(ctx)
849 } else if cfg.BuildMod == "vendor" {
850 // We can't spot-check the requirements of other modules because we
851 // don't in general have their go.mod files available in the vendor
852 // directory. (Fortunately this case is impossible, because mg.graph is
853 // always non-nil in vendor mode!)
854 panic("internal error: rs.graph is unexpectedly nil with -mod=vendor")
855 } else if !spotCheckRoots(ctx, rs, spotCheckRoot) {
856 // We spot-checked the explicit requirements of the roots that are
857 // relevant to the packages we've loaded. Unfortunately, they're
858 // inconsistent in some way; we need to load the full module graph
859 // so that we can fix the roots properly.
861 mg, err = rs.Graph(ctx)
868 roots = make([]module.Version, 0, len(rs.rootModules))
869 rootsUpgraded = false
870 inRootPaths := make(map[string]bool, len(rs.rootModules)+1)
871 for _, mm := range MainModules.Versions() {
872 inRootPaths[mm.Path] = true
874 for _, m := range rs.rootModules {
875 if inRootPaths[m.Path] {
876 // This root specifies a redundant path. We already retained the
877 // selected version of this path when we saw it before, so omit the
878 // redundant copy regardless of its version.
880 // When we read the full module graph, we include the dependencies of
881 // every root even if that root is redundant. That better preserves
882 // reproducibility if, say, some automated tool adds a redundant
883 // 'require' line and then runs 'go mod tidy' to try to make everything
884 // consistent, since the requirements of the older version are carried
887 // So omitting a root that was previously present may *reduce* the
888 // selected versions of non-roots, but merely removing a requirement
889 // cannot *increase* the selected versions of other roots as a result —
890 // we don't need to mark this change as an upgrade. (This particular
891 // change cannot invalidate any other roots.)
897 v, _ = rs.rootSelected(m.Path)
899 v = mg.Selected(m.Path)
901 roots = append(roots, module.Version{Path: m.Path, Version: v})
902 inRootPaths[m.Path] = true
907 // Note that rs.rootModules was already sorted by module path and version,
908 // and we appended to the roots slice in the same order and guaranteed that
909 // each path has only one version, so roots is also sorted by module path
910 // and (trivially) version.
913 if cfg.BuildMod != "mod" {
914 // The only changes to the root set (if any) were to remove duplicates.
915 // The requirements are consistent (if perhaps redundant), so keep the
916 // original rs to preserve its ModuleGraph.
919 // The root set has converged: every root going into this iteration was
920 // already at its selected version, although we have have removed other
921 // (redundant) roots for the same path.
926 if rs.depth == lazy && reflect.DeepEqual(roots, rs.rootModules) && reflect.DeepEqual(direct, rs.direct) {
927 // The root set is unchanged and rs was already lazy, so keep rs to
928 // preserve its cached ModuleGraph (if any).
931 return newRequirements(lazy, roots, direct), nil
934 // spotCheckRoots reports whether the versions of the roots in rs satisfy the
935 // explicit requirements of the modules in mods.
936 func spotCheckRoots(ctx context.Context, rs *Requirements, mods map[module.Version]bool) bool {
937 ctx, cancel := context.WithCancel(ctx)
940 work := par.NewQueue(runtime.GOMAXPROCS(0))
941 for m := range mods {
944 if ctx.Err() != nil {
948 summary, err := goModSummary(m)
954 for _, r := range summary.require {
955 if v, ok := rs.rootSelected(r.Path); ok && cmpVersion(v, r.Version) < 0 {
964 if ctx.Err() != nil {
965 // Either we failed a spot-check, or the caller no longer cares about our
973 // tidyEagerRoots returns a minimal set of root requirements that maintains the
974 // selected version of every module that provided a package in pkgs, and
975 // includes the selected version of every such module in direct as a root.
976 func tidyEagerRoots(ctx context.Context, mainModule module.Version, direct map[string]bool, pkgs []*loadPkg) (*Requirements, error) {
978 keep []module.Version
979 keptPath = map[string]bool{}
982 rootPaths []string // module paths that should be included as roots
983 inRootPaths = map[string]bool{}
985 for _, pkg := range pkgs {
986 if !pkg.fromExternalModule() {
989 if m := pkg.mod; !keptPath[m.Path] {
990 keep = append(keep, m)
991 keptPath[m.Path] = true
992 if direct[m.Path] && !inRootPaths[m.Path] {
993 rootPaths = append(rootPaths, m.Path)
994 inRootPaths[m.Path] = true
999 min, err := mvs.Req(mainModule, rootPaths, &mvsReqs{roots: keep})
1003 return newRequirements(eager, min, direct), nil
1006 // updateEagerRoots returns a set of root requirements that includes the selected
1007 // version of every module path in direct as a root, and maintains the selected
1008 // version of every module selected in the graph of rs.
1010 // The roots are updated such that:
1012 // 1. The selected version of every module path in direct is included as a root
1013 // (if it is not "none").
1014 // 2. Each root is the selected version of its path. (We say that such a root
1015 // set is “consistent”.)
1016 // 3. Every version selected in the graph of rs remains selected unless upgraded
1017 // by a dependency in add.
1018 // 4. Every version in add is selected at its given version unless upgraded by
1019 // (the dependencies of) an existing root or another module in add.
1020 func updateEagerRoots(ctx context.Context, direct map[string]bool, rs *Requirements, add []module.Version) (*Requirements, error) {
1021 mg, err := rs.Graph(ctx)
1023 // We can't ignore errors in the module graph even if the user passed the -e
1024 // flag to try to push past them. If we can't load the complete module
1025 // dependencies, then we can't reliably compute a minimal subset of them.
1029 if mustHaveCompleteRequirements() {
1030 // Instead of actually updating the requirements, just check that no updates
1033 // We're being asked to reconstruct the requirements from scratch,
1034 // but we aren't even allowed to modify them.
1035 return rs, errGoModDirty
1037 for _, m := range rs.rootModules {
1038 if m.Version != mg.Selected(m.Path) {
1039 // The root version v is misleading: the actual selected version is higher.
1040 return rs, errGoModDirty
1043 for _, m := range add {
1044 if m.Version != mg.Selected(m.Path) {
1045 return rs, errGoModDirty
1048 for mPath := range direct {
1049 if _, ok := rs.rootSelected(mPath); !ok {
1050 // Module m is supposed to be listed explicitly, but isn't.
1052 // Note that this condition is also detected (and logged with more
1053 // detail) earlier during package loading, so it shouldn't actually be
1054 // possible at this point — this is just a defense in depth.
1055 return rs, errGoModDirty
1059 // No explicit roots are missing and all roots are already at the versions
1060 // we want to keep. Any other changes we would make are purely cosmetic,
1061 // such as pruning redundant indirect dependencies. Per issue #34822, we
1062 // ignore cosmetic changes when we cannot update the go.mod file.
1067 rootPaths []string // module paths that should be included as roots
1068 inRootPaths = map[string]bool{}
1070 for _, root := range rs.rootModules {
1071 // If the selected version of the root is the same as what was already
1072 // listed in the go.mod file, retain it as a root (even if redundant) to
1073 // avoid unnecessary churn. (See https://golang.org/issue/34822.)
1075 // We do this even for indirect requirements, since we don't know why they
1076 // were added and they could become direct at any time.
1077 if !inRootPaths[root.Path] && mg.Selected(root.Path) == root.Version {
1078 rootPaths = append(rootPaths, root.Path)
1079 inRootPaths[root.Path] = true
1083 // “The selected version of every module path in direct is included as a root.”
1085 // This is only for convenience and clarity for end users: in an eager module,
1086 // the choice of explicit vs. implicit dependency has no impact on MVS
1087 // selection (for itself or any other module).
1088 keep := append(mg.BuildList()[MainModules.Len():], add...)
1089 for _, m := range keep {
1090 if direct[m.Path] && !inRootPaths[m.Path] {
1091 rootPaths = append(rootPaths, m.Path)
1092 inRootPaths[m.Path] = true
1096 // TODO(matloob): Make roots into a map.
1097 var roots []module.Version
1098 for _, mainModule := range MainModules.Versions() {
1099 min, err := mvs.Req(mainModule, rootPaths, &mvsReqs{roots: keep})
1103 roots = append(roots, min...)
1105 if MainModules.Len() > 1 {
1108 if rs.depth == eager && reflect.DeepEqual(roots, rs.rootModules) && reflect.DeepEqual(direct, rs.direct) {
1109 // The root set is unchanged and rs was already eager, so keep rs to
1110 // preserve its cached ModuleGraph (if any).
1114 return newRequirements(eager, roots, direct), nil
1117 // convertDepth returns a version of rs with the given depth.
1118 // If rs already has the given depth, convertDepth returns rs unmodified.
1119 func convertDepth(ctx context.Context, rs *Requirements, depth modDepth) (*Requirements, error) {
1120 if rs.depth == depth {
1125 // We are converting a lazy module to an eager one. The roots of an eager
1126 // module graph are a superset of the roots of a lazy graph, so we don't
1127 // need to add any new roots — we just need to prune away the ones that are
1128 // redundant given eager loading, which is exactly what updateEagerRoots
1130 return updateEagerRoots(ctx, rs.direct, rs, nil)
1133 // We are converting an eager module to a lazy one. The module graph of an
1134 // eager module includes the transitive dependencies of every module in the
1137 // Hey, we can express that as a lazy root set! “Include the transitive
1138 // dependencies of every module in the build list” is exactly what happens in
1139 // a lazy module if we promote every module in the build list to a root!
1140 mg, err := rs.Graph(ctx)
1144 return newRequirements(lazy, mg.BuildList()[MainModules.Len():], rs.direct), nil