]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/go/internal/modload/buildlist.go
[dev.cmdgo] all: merge master (c2f96e6) into dev.cmdgo
[gostls13.git] / src / cmd / go / internal / modload / buildlist.go
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.
4
5 package modload
6
7 import (
8         "cmd/go/internal/base"
9         "cmd/go/internal/cfg"
10         "cmd/go/internal/mvs"
11         "cmd/go/internal/par"
12         "context"
13         "fmt"
14         "os"
15         "reflect"
16         "runtime"
17         "runtime/debug"
18         "strings"
19         "sync"
20         "sync/atomic"
21
22         "golang.org/x/mod/module"
23         "golang.org/x/mod/semver"
24 )
25
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)]
29 }
30
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.
34         //
35         // If eager, the graph includes all transitive requirements regardless of depth.
36         //
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.
40         depth modDepth
41
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
47
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.
50         //
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.
55         //
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'.
61         //
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
68
69         graphOnce sync.Once    // guards writes to (but not reads from) graph
70         graph     atomic.Value // cachedGraph
71 }
72
73 // A cachedGraph is a non-nil *ModuleGraph, together with any error discovered
74 // while loading that graph.
75 type cachedGraph struct {
76         mg  *ModuleGraph
77         err error // If err is non-nil, mg may be incomplete (but must still be non-nil).
78 }
79
80 // requirements is the requirement graph for the main module.
81 //
82 // It is always non-nil if the main module's go.mod file has been loaded.
83 //
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
89
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
92 // Graph method.
93 //
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.
97 //
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))
104                 }
105                 if m.Path == "" || m.Version == "" {
106                         panic(fmt.Sprintf("bad requirement: rootModules[%v] = %v", i, m))
107                 }
108                 if i > 0 {
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))
112                         }
113                 }
114         }
115
116         rs := &Requirements{
117                 depth:          depth,
118                 rootModules:    capVersionSlice(rootModules),
119                 maxRootVersion: make(map[string]string, len(rootModules)),
120                 direct:         direct,
121         }
122
123         for _, m := range rootModules {
124                 if v, ok := rs.maxRootVersion[m.Path]; ok && cmpVersion(v, m.Version) >= 0 {
125                         continue
126                 }
127                 rs.maxRootVersion[m.Path] = m.Version
128         }
129         return rs
130 }
131
132 // initVendor initializes rs.graph from the given list of vendored module
133 // dependencies, overriding the graph that would normally be loaded from module
134 // requirements.
135 func (rs *Requirements) initVendor(vendorList []module.Version) {
136         rs.graphOnce.Do(func() {
137                 mg := &ModuleGraph{
138                         g: mvs.NewGraph(cmpVersion, MainModules.Versions()),
139                 }
140
141                 if MainModules.Len() != 1 {
142                         panic("There should be exactly one main moudle in Vendor mode.")
143                 }
144                 mainModule := MainModules.Versions()[0]
145
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”.
150                         //
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)
156                                         inconsistent = true
157                                 }
158                         }
159                         if inconsistent {
160                                 base.Fatalf("go: %v", errGoModDirty)
161                         }
162
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)
167                 } else {
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.
171                         //
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
176                         // dependencies.
177                         vendorMod := module.Version{Path: "vendor/modules.txt", Version: ""}
178                         mg.g.Require(mainModule, append(rs.rootModules, vendorMod))
179                         mg.g.Require(vendorMod, vendorList)
180                 }
181
182                 rs.graph.Store(cachedGraph{mg, nil})
183         })
184 }
185
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
188 // dependency.
189 func (rs *Requirements) rootSelected(path string) (version string, ok bool) {
190         if MainModules.Contains(path) {
191                 return "", true
192         }
193         if v, ok := rs.maxRootVersion[path]; ok {
194                 return v, true
195         }
196         return "", false
197 }
198
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
202 // selection.
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) {
206                         return true
207                 }
208         }
209         return false
210 }
211
212 // Graph returns the graph of module requirements loaded from the current
213 // root modules (as reported by RootModules).
214 //
215 // Graph always makes a best effort to load the requirement graph despite any
216 // errors, and always returns a non-nil *ModuleGraph.
217 //
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})
224         })
225         cached := rs.graph.Load().(cachedGraph)
226         return cached.mg, cached.err
227 }
228
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]
233 }
234
235 // A ModuleGraph represents the complete graph of module dependencies
236 // of a main module.
237 //
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 {
241         g         *mvs.Graph
242         loadCache par.Cache // module.Version → summaryError
243
244         buildListOnce sync.Once
245         buildList     []module.Version
246 }
247
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
252         err     error
253 }
254
255 var readModGraphDebugOnce sync.Once
256
257 // readModGraph reads and returns the module dependency graph starting at the
258 // given roots.
259 //
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) {
263         if depth == lazy {
264                 readModGraphDebugOnce.Do(func() {
265                         for _, f := range strings.Split(os.Getenv("GODEBUG"), ",") {
266                                 switch f {
267                                 case "lazymod=log":
268                                         debug.PrintStack()
269                                         fmt.Fprintf(os.Stderr, "go: read full module graph.\n")
270                                 case "lazymod=strict":
271                                         debug.PrintStack()
272                                         base.Fatalf("go: read full module graph (forbidden by GODEBUG=lazymod=strict).")
273                                 }
274                         }
275                 })
276         }
277
278         var (
279                 mu       sync.Mutex // guards mg.g and hasError during loading
280                 hasError bool
281                 mg       = &ModuleGraph{
282                         g: mvs.NewGraph(cmpVersion, MainModules.Versions()),
283                 }
284         )
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)
290         }
291
292         var (
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
295         )
296
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)
303
304                         mu.Lock()
305                         if err == nil {
306                                 mg.g.Require(m, summary.require)
307                         } else {
308                                 hasError = true
309                         }
310                         mu.Unlock()
311
312                         return summaryError{summary, err}
313                 }).(summaryError)
314
315                 return cached.summary, cached.err
316         }
317
318         var enqueue func(m module.Version, depth modDepth)
319         enqueue = func(m module.Version, depth modDepth) {
320                 if m.Version == "none" {
321                         return
322                 }
323
324                 if depth == eager {
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.
329                                 return
330                         }
331                 }
332
333                 loadQueue.Add(func() {
334                         summary, err := loadOne(m)
335                         if err != nil {
336                                 return // findError will report the error later.
337                         }
338
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
343                         // dependencies.
344                         if depth == eager || summary.depth == eager {
345                                 for _, r := range summary.require {
346                                         enqueue(r, eager)
347                                 }
348                         }
349                 })
350         }
351
352         for _, m := range roots {
353                 enqueue(m, depth)
354         }
355         <-loadQueue.Idle()
356
357         if hasError {
358                 return mg, mg.findError()
359         }
360         return mg, nil
361 }
362
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).
366 //
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)
371 }
372
373 // Selected returns the selected version of the module with the given path.
374 //
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)
378 }
379
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)
385 }
386
387 // BuildList returns the selected versions of all modules present in the graph,
388 // beginning with Target.
389 //
390 // The order of the remaining elements in the list is deterministic
391 // but arbitrary.
392 //
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())
398         })
399         return mg.buildList
400 }
401
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
406         })
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)
411         }
412
413         return nil
414 }
415
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 {
421                                 return false
422                         }
423                 }
424         }
425         return true
426 }
427
428 // LoadModGraph loads and returns the graph of module dependencies of the main module,
429 // without loading any packages.
430 //
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).
434 //
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)
440
441         if goVersion != "" {
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)
448                 }
449
450                 mg, err := rs.Graph(ctx)
451                 if err != nil {
452                         base.Fatalf("go: %v", err)
453                 }
454                 return mg
455         }
456
457         rs, mg, err := expandGraph(ctx, rs)
458         if err != nil {
459                 base.Fatalf("go: %v", err)
460         }
461
462         commitRequirements(ctx, modFileGoVersion(), rs)
463         return mg
464 }
465
466 // expandGraph loads the complete module graph from rs.
467 //
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
472 // out.)
473 //
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)
480         if mgErr != nil {
481                 // Without the graph, we can't update the roots: we don't know which
482                 // versions of transitive dependencies would be selected.
483                 return rs, mg, mgErr
484         }
485
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.
492
493                 newRS, rsErr := updateRoots(ctx, rs.direct, rs, nil, nil, false)
494                 if rsErr != nil {
495                         // Failed to update roots, perhaps because of an error in a transitive
496                         // dependency needed for the update. Return the original Requirements
497                         // instead.
498                         return rs, mg, rsErr
499                 }
500                 rs = newRS
501                 mg, mgErr = rs.Graph(ctx)
502         }
503
504         return rs, mg, mgErr
505 }
506
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
510 // given version.
511 //
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.)
515 //
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.
519 //
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
522 // result.
523 func EditBuildList(ctx context.Context, add, mustSelect []module.Version) (changed bool, err error) {
524         rs, changed, err := editRequirements(ctx, LoadModFile(ctx), add, mustSelect)
525         if err != nil {
526                 return false, err
527         }
528         commitRequirements(ctx, modFileGoVersion(), rs)
529         return changed, err
530 }
531
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
536         // mustSelect.
537         Conflicts []Conflict
538 }
539
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)
545         }
546         return b.String()
547 }
548
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
553         Dep        module.Version
554         Constraint module.Version
555 }
556
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)
564         }
565         return tidyLazyRoots(ctx, mainModule, rs.direct, pkgs)
566 }
567
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)
571         }
572         return updateLazyRoots(ctx, direct, rs, pkgs, add, rootsImported)
573 }
574
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:
577 //
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
582 //         root.
583 //
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.
586 //
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) {
591         var (
592                 roots        []module.Version
593                 pathIncluded = map[string]bool{mainModule.Path: true}
594         )
595         // We start by adding roots for every package in "all".
596         //
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.
605         var (
606                 queue  []*loadPkg
607                 queued = map[*loadPkg]bool{}
608         )
609         for _, pkg := range pkgs {
610                 if !pkg.flags.has(pkgInAll) {
611                         continue
612                 }
613                 if pkg.fromExternalModule() && !pathIncluded[pkg.mod.Path] {
614                         roots = append(roots, pkg.mod)
615                         pathIncluded[pkg.mod.Path] = true
616                 }
617                 queue = append(queue, pkg)
618                 queued[pkg] = true
619         }
620         module.Sort(roots)
621         tidy := newRequirements(lazy, roots, direct)
622
623         for len(queue) > 0 {
624                 roots = tidy.rootModules
625                 mg, err := tidy.Graph(ctx)
626                 if err != nil {
627                         return nil, err
628                 }
629
630                 prevQueue := queue
631                 queue = nil
632                 for _, pkg := range prevQueue {
633                         m := pkg.mod
634                         if m.Path == "" {
635                                 continue
636                         }
637                         for _, dep := range pkg.imports {
638                                 if !queued[dep] {
639                                         queue = append(queue, dep)
640                                         queued[dep] = true
641                                 }
642                         }
643                         if pkg.test != nil && !queued[pkg.test] {
644                                 queue = append(queue, pkg.test)
645                                 queued[pkg.test] = true
646                         }
647                         if !pathIncluded[m.Path] {
648                                 if s := mg.Selected(m.Path); cmpVersion(s, m.Version) < 0 {
649                                         roots = append(roots, m)
650                                 }
651                                 pathIncluded[m.Path] = true
652                         }
653                 }
654
655                 if len(roots) > len(tidy.rootModules) {
656                         module.Sort(roots)
657                         tidy = newRequirements(lazy, roots, tidy.direct)
658                 }
659         }
660
661         _, err := tidy.Graph(ctx)
662         if err != nil {
663                 return nil, err
664         }
665         return tidy, nil
666 }
667
668 // updateLazyRoots returns a set of root requirements that maintains the “lazy
669 // loading” invariants of the go.mod file:
670 //
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
678 //         root (otherwise).
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.
682 //
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.
685 //
686 // The above invariants together imply the “lazy loading” invariants for the
687 // go.mod file:
688 //
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).
695 //
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
699 //         pkgIsRoot.
700 //
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.
709 //
710 // (See https://golang.org/design/36460-lazy-module-loading#invariants for more
711 // detail.)
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
715
716         spotCheckRoot := map[module.Version]bool{}
717
718         // “The selected version of the module providing each package marked with
719         // either pkgInAll or pkgIsRoot is included as a root.”
720         needSort := false
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.
725                         continue
726                 }
727
728                 switch {
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.
736                         //
737                         // (This is the “import invariant” that makes lazy loading possible.)
738
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').
742
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
749                         // horizon.
750                         //
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.
757                         //
758                         // (This is the “argument invariant” of lazy loading, and is important for
759                         // reproducibility.)
760
761                 default:
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.
767                         continue
768                 }
769
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.
778                         //
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.
786                         //
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
796                 } else {
797                         roots = append(roots, pkg.mod)
798                         rootsUpgraded = true
799                         // The roots slice was initially sorted because rs.rootModules was sorted,
800                         // but the root we just added could be out of order.
801                         needSort = true
802                 }
803         }
804
805         for _, m := range add {
806                 if v, ok := rs.rootSelected(m.Path); !ok || cmpVersion(v, m.Version) < 0 {
807                         roots = append(roots, m)
808                         rootsUpgraded = true
809                         needSort = true
810                 }
811         }
812         if needSort {
813                 module.Sort(roots)
814         }
815
816         // "Each root appears only once, at the selected version of its path ….”
817         for {
818                 var mg *ModuleGraph
819                 if rootsUpgraded {
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
822                         // requirements.
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
830                         }
831
832                         rs = newRequirements(lazy, roots, direct)
833                         var err error
834                         mg, err = rs.Graph(ctx)
835                         if err != nil {
836                                 return rs, err
837                         }
838                 } else {
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.
860                                 var err error
861                                 mg, err = rs.Graph(ctx)
862                                 if err != nil {
863                                         return rs, err
864                                 }
865                         }
866                 }
867
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
873                 }
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.
879                                 //
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
885                                 // over.
886                                 //
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.)
892                                 continue
893                         }
894
895                         var v string
896                         if mg == nil {
897                                 v, _ = rs.rootSelected(m.Path)
898                         } else {
899                                 v = mg.Selected(m.Path)
900                         }
901                         roots = append(roots, module.Version{Path: m.Path, Version: v})
902                         inRootPaths[m.Path] = true
903                         if v != m.Version {
904                                 rootsUpgraded = true
905                         }
906                 }
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.
911
912                 if !rootsUpgraded {
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.
917                                 return rs, nil
918                         }
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.
922                         break
923                 }
924         }
925
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).
929                 return rs, nil
930         }
931         return newRequirements(lazy, roots, direct), nil
932 }
933
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)
938         defer cancel()
939
940         work := par.NewQueue(runtime.GOMAXPROCS(0))
941         for m := range mods {
942                 m := m
943                 work.Add(func() {
944                         if ctx.Err() != nil {
945                                 return
946                         }
947
948                         summary, err := goModSummary(m)
949                         if err != nil {
950                                 cancel()
951                                 return
952                         }
953
954                         for _, r := range summary.require {
955                                 if v, ok := rs.rootSelected(r.Path); ok && cmpVersion(v, r.Version) < 0 {
956                                         cancel()
957                                         return
958                                 }
959                         }
960                 })
961         }
962         <-work.Idle()
963
964         if ctx.Err() != nil {
965                 // Either we failed a spot-check, or the caller no longer cares about our
966                 // answer anyway.
967                 return false
968         }
969
970         return true
971 }
972
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) {
977         var (
978                 keep     []module.Version
979                 keptPath = map[string]bool{}
980         )
981         var (
982                 rootPaths   []string // module paths that should be included as roots
983                 inRootPaths = map[string]bool{}
984         )
985         for _, pkg := range pkgs {
986                 if !pkg.fromExternalModule() {
987                         continue
988                 }
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
995                         }
996                 }
997         }
998
999         min, err := mvs.Req(mainModule, rootPaths, &mvsReqs{roots: keep})
1000         if err != nil {
1001                 return nil, err
1002         }
1003         return newRequirements(eager, min, direct), nil
1004 }
1005
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.
1009 //
1010 // The roots are updated such that:
1011 //
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)
1022         if err != nil {
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.
1026                 return rs, err
1027         }
1028
1029         if mustHaveCompleteRequirements() {
1030                 // Instead of actually updating the requirements, just check that no updates
1031                 // are needed.
1032                 if rs == nil {
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
1036                 }
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
1041                         }
1042                 }
1043                 for _, m := range add {
1044                         if m.Version != mg.Selected(m.Path) {
1045                                 return rs, errGoModDirty
1046                         }
1047                 }
1048                 for mPath := range direct {
1049                         if _, ok := rs.rootSelected(mPath); !ok {
1050                                 // Module m is supposed to be listed explicitly, but isn't.
1051                                 //
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
1056                         }
1057                 }
1058
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.
1063                 return rs, nil
1064         }
1065
1066         var (
1067                 rootPaths   []string // module paths that should be included as roots
1068                 inRootPaths = map[string]bool{}
1069         )
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.)
1074                 //
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
1080                 }
1081         }
1082
1083         // “The selected version of every module path in direct is included as a root.”
1084         //
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
1093                 }
1094         }
1095
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})
1100                 if err != nil {
1101                         return rs, err
1102                 }
1103                 roots = append(roots, min...)
1104         }
1105         if MainModules.Len() > 1 {
1106                 module.Sort(roots)
1107         }
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).
1111                 return rs, nil
1112         }
1113
1114         return newRequirements(eager, roots, direct), nil
1115 }
1116
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 {
1121                 return rs, nil
1122         }
1123
1124         if depth == eager {
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
1129                 // does.
1130                 return updateEagerRoots(ctx, rs.direct, rs, nil)
1131         }
1132
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
1135         // build list.
1136         //
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)
1141         if err != nil {
1142                 return rs, err
1143         }
1144         return newRequirements(lazy, mg.BuildList()[MainModules.Len():], rs.direct), nil
1145 }