github.com/bir3/gocompiler@v0.3.205/src/cmd/gocmd/internal/modload/buildlist.go (about)

     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  	"github.com/bir3/gocompiler/src/cmd/gocmd/internal/base"
     9  	"github.com/bir3/gocompiler/src/cmd/gocmd/internal/cfg"
    10  	"github.com/bir3/gocompiler/src/cmd/gocmd/internal/mvs"
    11  	"github.com/bir3/gocompiler/src/cmd/gocmd/internal/par"
    12  	"context"
    13  	"fmt"
    14  	"os"
    15  	"reflect"
    16  	"runtime"
    17  	"runtime/debug"
    18  	"strings"
    19  	"sync"
    20  	"sync/atomic"
    21  
    22  	"github.com/bir3/gocompiler/src/xvendor/golang.org/x/mod/module"
    23  	"github.com/bir3/gocompiler/src/xvendor/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  	// pruning is the pruning at which the requirement graph is computed.
    34  	//
    35  	// If unpruned, the graph includes all transitive requirements regardless
    36  	// of whether the requiring module supports pruning.
    37  	//
    38  	// If pruned, the graph includes only the root modules, the explicit
    39  	// requirements of those root modules, and the transitive requirements of only
    40  	// the root modules that do not support pruning.
    41  	//
    42  	// If workspace, the graph includes only the workspace modules, the explicit
    43  	// requirements of the workspace modules, and the transitive requirements of
    44  	// the workspace modules that do not support pruning.
    45  	pruning modPruning
    46  
    47  	// rootModules is the set of root modules of the graph, sorted and capped to
    48  	// length. It may contain duplicates, and may contain multiple versions for a
    49  	// given module path. The root modules of the groph are the set of main
    50  	// modules in workspace mode, and the main module's direct requirements
    51  	// outside workspace mode.
    52  	rootModules    []module.Version
    53  	maxRootVersion map[string]string
    54  
    55  	// direct is the set of module paths for which we believe the module provides
    56  	// a package directly imported by a package or test in the main module.
    57  	//
    58  	// The "direct" map controls which modules are annotated with "// indirect"
    59  	// comments in the go.mod file, and may impact which modules are listed as
    60  	// explicit roots (vs. indirect-only dependencies). However, it should not
    61  	// have a semantic effect on the build list overall.
    62  	//
    63  	// The initial direct map is populated from the existing "// indirect"
    64  	// comments (or lack thereof) in the go.mod file. It is updated by the
    65  	// package loader: dependencies may be promoted to direct if new
    66  	// direct imports are observed, and may be demoted to indirect during
    67  	// 'go mod tidy' or 'go mod vendor'.
    68  	//
    69  	// The direct map is keyed by module paths, not module versions. When a
    70  	// module's selected version changes, we assume that it remains direct if the
    71  	// previous version was a direct dependency. That assumption might not hold in
    72  	// rare cases (such as if a dependency splits out a nested module, or merges a
    73  	// nested module back into a parent module).
    74  	direct map[string]bool
    75  
    76  	graphOnce sync.Once // guards writes to (but not reads from) graph
    77  	graph     atomic.Pointer[cachedGraph]
    78  }
    79  
    80  // A cachedGraph is a non-nil *ModuleGraph, together with any error discovered
    81  // while loading that graph.
    82  type cachedGraph struct {
    83  	mg  *ModuleGraph
    84  	err error // If err is non-nil, mg may be incomplete (but must still be non-nil).
    85  }
    86  
    87  // requirements is the requirement graph for the main module.
    88  //
    89  // It is always non-nil if the main module's go.mod file has been loaded.
    90  //
    91  // This variable should only be read from the loadModFile function, and should
    92  // only be written in the loadModFile and commitRequirements functions.
    93  // All other functions that need or produce a *Requirements should
    94  // accept and/or return an explicit parameter.
    95  var requirements *Requirements
    96  
    97  // newRequirements returns a new requirement set with the given root modules.
    98  // The dependencies of the roots will be loaded lazily at the first call to the
    99  // Graph method.
   100  //
   101  // The rootModules slice must be sorted according to module.Sort.
   102  // The caller must not modify the rootModules slice or direct map after passing
   103  // them to newRequirements.
   104  //
   105  // If vendoring is in effect, the caller must invoke initVendor on the returned
   106  // *Requirements before any other method.
   107  func newRequirements(pruning modPruning, rootModules []module.Version, direct map[string]bool) *Requirements {
   108  	if pruning == workspace {
   109  		return &Requirements{
   110  			pruning:        pruning,
   111  			rootModules:    capVersionSlice(rootModules),
   112  			maxRootVersion: nil,
   113  			direct:         direct,
   114  		}
   115  	}
   116  
   117  	if workFilePath != "" && pruning != workspace {
   118  		panic("in workspace mode, but pruning is not workspace in newRequirements")
   119  	}
   120  
   121  	for i, m := range rootModules {
   122  		if m.Version == "" && MainModules.Contains(m.Path) {
   123  			panic(fmt.Sprintf("newRequirements called with untrimmed build list: rootModules[%v] is a main module", i))
   124  		}
   125  		if m.Path == "" || m.Version == "" {
   126  			panic(fmt.Sprintf("bad requirement: rootModules[%v] = %v", i, m))
   127  		}
   128  		if i > 0 {
   129  			prev := rootModules[i-1]
   130  			if prev.Path > m.Path || (prev.Path == m.Path && semver.Compare(prev.Version, m.Version) > 0) {
   131  				panic(fmt.Sprintf("newRequirements called with unsorted roots: %v", rootModules))
   132  			}
   133  		}
   134  	}
   135  
   136  	rs := &Requirements{
   137  		pruning:        pruning,
   138  		rootModules:    capVersionSlice(rootModules),
   139  		maxRootVersion: make(map[string]string, len(rootModules)),
   140  		direct:         direct,
   141  	}
   142  
   143  	for _, m := range rootModules {
   144  		if v, ok := rs.maxRootVersion[m.Path]; ok && cmpVersion(v, m.Version) >= 0 {
   145  			continue
   146  		}
   147  		rs.maxRootVersion[m.Path] = m.Version
   148  	}
   149  	return rs
   150  }
   151  
   152  // initVendor initializes rs.graph from the given list of vendored module
   153  // dependencies, overriding the graph that would normally be loaded from module
   154  // requirements.
   155  func (rs *Requirements) initVendor(vendorList []module.Version) {
   156  	rs.graphOnce.Do(func() {
   157  		mg := &ModuleGraph{
   158  			g: mvs.NewGraph(cmpVersion, MainModules.Versions()),
   159  		}
   160  
   161  		if MainModules.Len() != 1 {
   162  			panic("There should be exactly one main module in Vendor mode.")
   163  		}
   164  		mainModule := MainModules.Versions()[0]
   165  
   166  		if rs.pruning == pruned {
   167  			// The roots of a pruned module should already include every module in the
   168  			// vendor list, because the vendored modules are the same as those needed
   169  			// for graph pruning.
   170  			//
   171  			// Just to be sure, we'll double-check that here.
   172  			inconsistent := false
   173  			for _, m := range vendorList {
   174  				if v, ok := rs.rootSelected(m.Path); !ok || v != m.Version {
   175  					base.Errorf("go: vendored module %v should be required explicitly in go.mod", m)
   176  					inconsistent = true
   177  				}
   178  			}
   179  			if inconsistent {
   180  				base.Fatalf("go: %v", errGoModDirty)
   181  			}
   182  
   183  			// Now we can treat the rest of the module graph as effectively “pruned
   184  			// out”, as though we are viewing the main module from outside: in vendor
   185  			// mode, the root requirements *are* the complete module graph.
   186  			mg.g.Require(mainModule, rs.rootModules)
   187  		} else {
   188  			// The transitive requirements of the main module are not in general available
   189  			// from the vendor directory, and we don't actually know how we got from
   190  			// the roots to the final build list.
   191  			//
   192  			// Instead, we'll inject a fake "vendor/modules.txt" module that provides
   193  			// those transitive dependencies, and mark it as a dependency of the main
   194  			// module. That allows us to elide the actual structure of the module
   195  			// graph, but still distinguishes between direct and indirect
   196  			// dependencies.
   197  			vendorMod := module.Version{Path: "vendor/modules.txt", Version: ""}
   198  			mg.g.Require(mainModule, append(rs.rootModules, vendorMod))
   199  			mg.g.Require(vendorMod, vendorList)
   200  		}
   201  
   202  		rs.graph.Store(&cachedGraph{mg, nil})
   203  	})
   204  }
   205  
   206  // rootSelected returns the version of the root dependency with the given module
   207  // path, or the zero module.Version and ok=false if the module is not a root
   208  // dependency.
   209  func (rs *Requirements) rootSelected(path string) (version string, ok bool) {
   210  	if MainModules.Contains(path) {
   211  		return "", true
   212  	}
   213  	if v, ok := rs.maxRootVersion[path]; ok {
   214  		return v, true
   215  	}
   216  	return "", false
   217  }
   218  
   219  // hasRedundantRoot returns true if the root list contains multiple requirements
   220  // of the same module or a requirement on any version of the main module.
   221  // Redundant requirements should be pruned, but they may influence version
   222  // selection.
   223  func (rs *Requirements) hasRedundantRoot() bool {
   224  	for i, m := range rs.rootModules {
   225  		if MainModules.Contains(m.Path) || (i > 0 && m.Path == rs.rootModules[i-1].Path) {
   226  			return true
   227  		}
   228  	}
   229  	return false
   230  }
   231  
   232  // Graph returns the graph of module requirements loaded from the current
   233  // root modules (as reported by RootModules).
   234  //
   235  // Graph always makes a best effort to load the requirement graph despite any
   236  // errors, and always returns a non-nil *ModuleGraph.
   237  //
   238  // If the requirements of any relevant module fail to load, Graph also
   239  // returns a non-nil error of type *mvs.BuildListError.
   240  func (rs *Requirements) Graph(ctx context.Context) (*ModuleGraph, error) {
   241  	rs.graphOnce.Do(func() {
   242  		mg, mgErr := readModGraph(ctx, rs.pruning, rs.rootModules)
   243  		rs.graph.Store(&cachedGraph{mg, mgErr})
   244  	})
   245  	cached := rs.graph.Load()
   246  	return cached.mg, cached.err
   247  }
   248  
   249  // IsDirect returns whether the given module provides a package directly
   250  // imported by a package or test in the main module.
   251  func (rs *Requirements) IsDirect(path string) bool {
   252  	return rs.direct[path]
   253  }
   254  
   255  // A ModuleGraph represents the complete graph of module dependencies
   256  // of a main module.
   257  //
   258  // If the main module supports module graph pruning, the graph does not include
   259  // transitive dependencies of non-root (implicit) dependencies.
   260  type ModuleGraph struct {
   261  	g         *mvs.Graph
   262  	loadCache par.Cache // module.Version → summaryError
   263  
   264  	buildListOnce sync.Once
   265  	buildList     []module.Version
   266  }
   267  
   268  // A summaryError is either a non-nil modFileSummary or a non-nil error
   269  // encountered while reading or parsing that summary.
   270  type summaryError struct {
   271  	summary *modFileSummary
   272  	err     error
   273  }
   274  
   275  var readModGraphDebugOnce sync.Once
   276  
   277  // readModGraph reads and returns the module dependency graph starting at the
   278  // given roots.
   279  //
   280  // Unlike LoadModGraph, readModGraph does not attempt to diagnose or update
   281  // inconsistent roots.
   282  func readModGraph(ctx context.Context, pruning modPruning, roots []module.Version) (*ModuleGraph, error) {
   283  	if pruning == pruned {
   284  		// Enable diagnostics for lazy module loading
   285  		// (https://golang.org/ref/mod#lazy-loading) only if the module graph is
   286  		// pruned.
   287  		//
   288  		// In unpruned modules,we load the module graph much more aggressively (in
   289  		// order to detect inconsistencies that wouldn't be feasible to spot-check),
   290  		// so it wouldn't be useful to log when that occurs (because it happens in
   291  		// normal operation all the time).
   292  		readModGraphDebugOnce.Do(func() {
   293  			for _, f := range strings.Split(os.Getenv("GODEBUG"), ",") {
   294  				switch f {
   295  				case "lazymod=log":
   296  					debug.PrintStack()
   297  					fmt.Fprintf(os.Stderr, "go: read full module graph.\n")
   298  				case "lazymod=strict":
   299  					debug.PrintStack()
   300  					base.Fatalf("go: read full module graph (forbidden by GODEBUG=lazymod=strict).")
   301  				}
   302  			}
   303  		})
   304  	}
   305  
   306  	var (
   307  		mu       sync.Mutex // guards mg.g and hasError during loading
   308  		hasError bool
   309  		mg       = &ModuleGraph{
   310  			g: mvs.NewGraph(cmpVersion, MainModules.Versions()),
   311  		}
   312  	)
   313  	if pruning != workspace {
   314  		if inWorkspaceMode() {
   315  			panic("pruning is not workspace in workspace mode")
   316  		}
   317  		mg.g.Require(MainModules.mustGetSingleMainModule(), roots)
   318  	}
   319  
   320  	var (
   321  		loadQueue       = par.NewQueue(runtime.GOMAXPROCS(0))
   322  		loadingUnpruned sync.Map // module.Version → nil; the set of modules that have been or are being loaded via roots that do not support pruning
   323  	)
   324  
   325  	// loadOne synchronously loads the explicit requirements for module m.
   326  	// It does not load the transitive requirements of m even if the go version in
   327  	// m's go.mod file indicates that it supports graph pruning.
   328  	loadOne := func(m module.Version) (*modFileSummary, error) {
   329  		cached := mg.loadCache.Do(m, func() any {
   330  			summary, err := goModSummary(m)
   331  
   332  			mu.Lock()
   333  			if err == nil {
   334  				mg.g.Require(m, summary.require)
   335  			} else {
   336  				hasError = true
   337  			}
   338  			mu.Unlock()
   339  
   340  			return summaryError{summary, err}
   341  		}).(summaryError)
   342  
   343  		return cached.summary, cached.err
   344  	}
   345  
   346  	var enqueue func(m module.Version, pruning modPruning)
   347  	enqueue = func(m module.Version, pruning modPruning) {
   348  		if m.Version == "none" {
   349  			return
   350  		}
   351  
   352  		if pruning == unpruned {
   353  			if _, dup := loadingUnpruned.LoadOrStore(m, nil); dup {
   354  				// m has already been enqueued for loading. Since unpruned loading may
   355  				// follow cycles in the requirement graph, we need to return early
   356  				// to avoid making the load queue infinitely long.
   357  				return
   358  			}
   359  		}
   360  
   361  		loadQueue.Add(func() {
   362  			summary, err := loadOne(m)
   363  			if err != nil {
   364  				return // findError will report the error later.
   365  			}
   366  
   367  			// If the version in m's go.mod file does not support pruning, then we
   368  			// cannot assume that the explicit requirements of m (added by loadOne)
   369  			// are sufficient to build the packages it contains. We must load its full
   370  			// transitive dependency graph to be sure that we see all relevant
   371  			// dependencies.
   372  			if pruning != pruned || summary.pruning == unpruned {
   373  				nextPruning := summary.pruning
   374  				if pruning == unpruned {
   375  					nextPruning = unpruned
   376  				}
   377  				for _, r := range summary.require {
   378  					enqueue(r, nextPruning)
   379  				}
   380  			}
   381  		})
   382  	}
   383  
   384  	for _, m := range roots {
   385  		enqueue(m, pruning)
   386  	}
   387  	<-loadQueue.Idle()
   388  
   389  	// Reload any dependencies of the main modules which are not
   390  	// at their selected versions at workspace mode, because the
   391  	// requirements don't accurately reflect the transitive imports.
   392  	if pruning == workspace {
   393  		// hasDepsInAll contains the set of modules that need to be loaded
   394  		// at workspace pruning because any of their dependencies may
   395  		// provide packages in all.
   396  		hasDepsInAll := make(map[string]bool)
   397  		seen := map[module.Version]bool{}
   398  		for _, m := range roots {
   399  			hasDepsInAll[m.Path] = true
   400  		}
   401  		// This loop will terminate because it will call enqueue on each version of
   402  		// each dependency of the modules in hasDepsInAll at most once (and only
   403  		// calls enqueue on successively increasing versions of each dependency).
   404  		for {
   405  			needsEnqueueing := map[module.Version]bool{}
   406  			for p := range hasDepsInAll {
   407  				m := module.Version{Path: p, Version: mg.g.Selected(p)}
   408  				if !seen[m] {
   409  					needsEnqueueing[m] = true
   410  					continue
   411  				}
   412  				reqs, _ := mg.g.RequiredBy(m)
   413  				for _, r := range reqs {
   414  					s := module.Version{Path: r.Path, Version: mg.g.Selected(r.Path)}
   415  					if cmpVersion(s.Version, r.Version) > 0 && !seen[s] {
   416  						needsEnqueueing[s] = true
   417  					}
   418  				}
   419  			}
   420  			// add all needs enqueueing to paths we care about
   421  			if len(needsEnqueueing) == 0 {
   422  				break
   423  			}
   424  
   425  			for p := range needsEnqueueing {
   426  				enqueue(p, workspace)
   427  				seen[p] = true
   428  				hasDepsInAll[p.Path] = true
   429  			}
   430  			<-loadQueue.Idle()
   431  		}
   432  	}
   433  
   434  	if hasError {
   435  		return mg, mg.findError()
   436  	}
   437  	return mg, nil
   438  }
   439  
   440  // RequiredBy returns the dependencies required by module m in the graph,
   441  // or ok=false if module m's dependencies are pruned out.
   442  //
   443  // The caller must not modify the returned slice, but may safely append to it
   444  // and may rely on it not to be modified.
   445  func (mg *ModuleGraph) RequiredBy(m module.Version) (reqs []module.Version, ok bool) {
   446  	return mg.g.RequiredBy(m)
   447  }
   448  
   449  // Selected returns the selected version of the module with the given path.
   450  //
   451  // If no version is selected, Selected returns version "none".
   452  func (mg *ModuleGraph) Selected(path string) (version string) {
   453  	return mg.g.Selected(path)
   454  }
   455  
   456  // WalkBreadthFirst invokes f once, in breadth-first order, for each module
   457  // version other than "none" that appears in the graph, regardless of whether
   458  // that version is selected.
   459  func (mg *ModuleGraph) WalkBreadthFirst(f func(m module.Version)) {
   460  	mg.g.WalkBreadthFirst(f)
   461  }
   462  
   463  // BuildList returns the selected versions of all modules present in the graph,
   464  // beginning with Target.
   465  //
   466  // The order of the remaining elements in the list is deterministic
   467  // but arbitrary.
   468  //
   469  // The caller must not modify the returned list, but may safely append to it
   470  // and may rely on it not to be modified.
   471  func (mg *ModuleGraph) BuildList() []module.Version {
   472  	mg.buildListOnce.Do(func() {
   473  		mg.buildList = capVersionSlice(mg.g.BuildList())
   474  	})
   475  	return mg.buildList
   476  }
   477  
   478  func (mg *ModuleGraph) findError() error {
   479  	errStack := mg.g.FindPath(func(m module.Version) bool {
   480  		cached := mg.loadCache.Get(m)
   481  		return cached != nil && cached.(summaryError).err != nil
   482  	})
   483  	if len(errStack) > 0 {
   484  		err := mg.loadCache.Get(errStack[len(errStack)-1]).(summaryError).err
   485  		var noUpgrade func(from, to module.Version) bool
   486  		return mvs.NewBuildListError(err, errStack, noUpgrade)
   487  	}
   488  
   489  	return nil
   490  }
   491  
   492  func (mg *ModuleGraph) allRootsSelected() bool {
   493  	var roots []module.Version
   494  	if inWorkspaceMode() {
   495  		roots = MainModules.Versions()
   496  	} else {
   497  		roots, _ = mg.g.RequiredBy(MainModules.mustGetSingleMainModule())
   498  	}
   499  	for _, m := range roots {
   500  		if mg.Selected(m.Path) != m.Version {
   501  			return false
   502  		}
   503  	}
   504  	return true
   505  }
   506  
   507  // LoadModGraph loads and returns the graph of module dependencies of the main module,
   508  // without loading any packages.
   509  //
   510  // If the goVersion string is non-empty, the returned graph is the graph
   511  // as interpreted by the given Go version (instead of the version indicated
   512  // in the go.mod file).
   513  //
   514  // Modules are loaded automatically (and lazily) in LoadPackages:
   515  // LoadModGraph need only be called if LoadPackages is not,
   516  // typically in commands that care about modules but no particular package.
   517  func LoadModGraph(ctx context.Context, goVersion string) *ModuleGraph {
   518  	rs := LoadModFile(ctx)
   519  
   520  	if goVersion != "" {
   521  		pruning := pruningForGoVersion(goVersion)
   522  		if pruning == unpruned && rs.pruning != unpruned {
   523  			// Use newRequirements instead of convertDepth because convertDepth
   524  			// also updates roots; here, we want to report the unmodified roots
   525  			// even though they may seem inconsistent.
   526  			rs = newRequirements(unpruned, rs.rootModules, rs.direct)
   527  		}
   528  
   529  		mg, err := rs.Graph(ctx)
   530  		if err != nil {
   531  			base.Fatalf("go: %v", err)
   532  		}
   533  		return mg
   534  	}
   535  
   536  	rs, mg, err := expandGraph(ctx, rs)
   537  	if err != nil {
   538  		base.Fatalf("go: %v", err)
   539  	}
   540  
   541  	requirements = rs
   542  
   543  	return mg
   544  }
   545  
   546  // expandGraph loads the complete module graph from rs.
   547  //
   548  // If the complete graph reveals that some root of rs is not actually the
   549  // selected version of its path, expandGraph computes a new set of roots that
   550  // are consistent. (With a pruned module graph, this may result in upgrades to
   551  // other modules due to requirements that were previously pruned out.)
   552  //
   553  // expandGraph returns the updated roots, along with the module graph loaded
   554  // from those roots and any error encountered while loading that graph.
   555  // expandGraph returns non-nil requirements and a non-nil graph regardless of
   556  // errors. On error, the roots might not be updated to be consistent.
   557  func expandGraph(ctx context.Context, rs *Requirements) (*Requirements, *ModuleGraph, error) {
   558  	mg, mgErr := rs.Graph(ctx)
   559  	if mgErr != nil {
   560  		// Without the graph, we can't update the roots: we don't know which
   561  		// versions of transitive dependencies would be selected.
   562  		return rs, mg, mgErr
   563  	}
   564  
   565  	if !mg.allRootsSelected() {
   566  		// The roots of rs are not consistent with the rest of the graph. Update
   567  		// them. In an unpruned module this is a no-op for the build list as a whole —
   568  		// it just promotes what were previously transitive requirements to be
   569  		// roots — but in a pruned module it may pull in previously-irrelevant
   570  		// transitive dependencies.
   571  
   572  		newRS, rsErr := updateRoots(ctx, rs.direct, rs, nil, nil, false)
   573  		if rsErr != nil {
   574  			// Failed to update roots, perhaps because of an error in a transitive
   575  			// dependency needed for the update. Return the original Requirements
   576  			// instead.
   577  			return rs, mg, rsErr
   578  		}
   579  		rs = newRS
   580  		mg, mgErr = rs.Graph(ctx)
   581  	}
   582  
   583  	return rs, mg, mgErr
   584  }
   585  
   586  // EditBuildList edits the global build list by first adding every module in add
   587  // to the existing build list, then adjusting versions (and adding or removing
   588  // requirements as needed) until every module in mustSelect is selected at the
   589  // given version.
   590  //
   591  // (Note that the newly-added modules might not be selected in the resulting
   592  // build list: they could be lower than existing requirements or conflict with
   593  // versions in mustSelect.)
   594  //
   595  // If the versions listed in mustSelect are mutually incompatible (due to one of
   596  // the listed modules requiring a higher version of another), EditBuildList
   597  // returns a *ConstraintError and leaves the build list in its previous state.
   598  //
   599  // On success, EditBuildList reports whether the selected version of any module
   600  // in the build list may have been changed (possibly to or from "none") as a
   601  // result.
   602  func EditBuildList(ctx context.Context, add, mustSelect []module.Version) (changed bool, err error) {
   603  	rs, changed, err := editRequirements(ctx, LoadModFile(ctx), add, mustSelect)
   604  	if err != nil {
   605  		return false, err
   606  	}
   607  	requirements = rs
   608  	return changed, err
   609  }
   610  
   611  // A ConstraintError describes inconsistent constraints in EditBuildList
   612  type ConstraintError struct {
   613  	// Conflict lists the source of the conflict for each version in mustSelect
   614  	// that could not be selected due to the requirements of some other version in
   615  	// mustSelect.
   616  	Conflicts []Conflict
   617  }
   618  
   619  func (e *ConstraintError) Error() string {
   620  	b := new(strings.Builder)
   621  	b.WriteString("version constraints conflict:")
   622  	for _, c := range e.Conflicts {
   623  		fmt.Fprintf(b, "\n\t%v requires %v, but %v is requested", c.Source, c.Dep, c.Constraint)
   624  	}
   625  	return b.String()
   626  }
   627  
   628  // A Conflict documents that Source requires Dep, which conflicts with Constraint.
   629  // (That is, Dep has the same module path as Constraint but a higher version.)
   630  type Conflict struct {
   631  	Source     module.Version
   632  	Dep        module.Version
   633  	Constraint module.Version
   634  }
   635  
   636  // tidyRoots trims the root dependencies to the minimal requirements needed to
   637  // both retain the same versions of all packages in pkgs and satisfy the
   638  // graph-pruning invariants (if applicable).
   639  func tidyRoots(ctx context.Context, rs *Requirements, pkgs []*loadPkg) (*Requirements, error) {
   640  	mainModule := MainModules.mustGetSingleMainModule()
   641  	if rs.pruning == unpruned {
   642  		return tidyUnprunedRoots(ctx, mainModule, rs.direct, pkgs)
   643  	}
   644  	return tidyPrunedRoots(ctx, mainModule, rs.direct, pkgs)
   645  }
   646  
   647  func updateRoots(ctx context.Context, direct map[string]bool, rs *Requirements, pkgs []*loadPkg, add []module.Version, rootsImported bool) (*Requirements, error) {
   648  	switch rs.pruning {
   649  	case unpruned:
   650  		return updateUnprunedRoots(ctx, direct, rs, add)
   651  	case pruned:
   652  		return updatePrunedRoots(ctx, direct, rs, pkgs, add, rootsImported)
   653  	case workspace:
   654  		return updateWorkspaceRoots(ctx, rs, add)
   655  	default:
   656  		panic(fmt.Sprintf("unsupported pruning mode: %v", rs.pruning))
   657  	}
   658  }
   659  
   660  func updateWorkspaceRoots(ctx context.Context, rs *Requirements, add []module.Version) (*Requirements, error) {
   661  	if len(add) != 0 {
   662  		// add should be empty in workspace mode because workspace mode implies
   663  		// -mod=readonly, which in turn implies no new requirements. The code path
   664  		// that would result in add being non-empty returns an error before it
   665  		// reaches this point: The set of modules to add comes from
   666  		// resolveMissingImports, which in turn resolves each package by calling
   667  		// queryImport. But queryImport explicitly checks for -mod=readonly, and
   668  		// return an error.
   669  		panic("add is not empty")
   670  	}
   671  	return rs, nil
   672  }
   673  
   674  // tidyPrunedRoots returns a minimal set of root requirements that maintains the
   675  // invariants of the go.mod file needed to support graph pruning for the given
   676  // packages:
   677  //
   678  //  1. For each package marked with pkgInAll, the module path that provided that
   679  //     package is included as a root.
   680  //  2. For all packages, the module that provided that package either remains
   681  //     selected at the same version or is upgraded by the dependencies of a
   682  //     root.
   683  //
   684  // If any module that provided a package has been upgraded above its previous
   685  // version, the caller may need to reload and recompute the package graph.
   686  //
   687  // To ensure that the loading process eventually converges, the caller should
   688  // add any needed roots from the tidy root set (without removing existing untidy
   689  // roots) until the set of roots has converged.
   690  func tidyPrunedRoots(ctx context.Context, mainModule module.Version, direct map[string]bool, pkgs []*loadPkg) (*Requirements, error) {
   691  	var (
   692  		roots        []module.Version
   693  		pathIncluded = map[string]bool{mainModule.Path: true}
   694  	)
   695  	// We start by adding roots for every package in "all".
   696  	//
   697  	// Once that is done, we may still need to add more roots to cover upgraded or
   698  	// otherwise-missing test dependencies for packages in "all". For those test
   699  	// dependencies, we prefer to add roots for packages with shorter import
   700  	// stacks first, on the theory that the module requirements for those will
   701  	// tend to fill in the requirements for their transitive imports (which have
   702  	// deeper import stacks). So we add the missing dependencies for one depth at
   703  	// a time, starting with the packages actually in "all" and expanding outwards
   704  	// until we have scanned every package that was loaded.
   705  	var (
   706  		queue  []*loadPkg
   707  		queued = map[*loadPkg]bool{}
   708  	)
   709  	for _, pkg := range pkgs {
   710  		if !pkg.flags.has(pkgInAll) {
   711  			continue
   712  		}
   713  		if pkg.fromExternalModule() && !pathIncluded[pkg.mod.Path] {
   714  			roots = append(roots, pkg.mod)
   715  			pathIncluded[pkg.mod.Path] = true
   716  		}
   717  		queue = append(queue, pkg)
   718  		queued[pkg] = true
   719  	}
   720  	module.Sort(roots)
   721  	tidy := newRequirements(pruned, roots, direct)
   722  
   723  	for len(queue) > 0 {
   724  		roots = tidy.rootModules
   725  		mg, err := tidy.Graph(ctx)
   726  		if err != nil {
   727  			return nil, err
   728  		}
   729  
   730  		prevQueue := queue
   731  		queue = nil
   732  		for _, pkg := range prevQueue {
   733  			m := pkg.mod
   734  			if m.Path == "" {
   735  				continue
   736  			}
   737  			for _, dep := range pkg.imports {
   738  				if !queued[dep] {
   739  					queue = append(queue, dep)
   740  					queued[dep] = true
   741  				}
   742  			}
   743  			if pkg.test != nil && !queued[pkg.test] {
   744  				queue = append(queue, pkg.test)
   745  				queued[pkg.test] = true
   746  			}
   747  			if !pathIncluded[m.Path] {
   748  				if s := mg.Selected(m.Path); cmpVersion(s, m.Version) < 0 {
   749  					roots = append(roots, m)
   750  				}
   751  				pathIncluded[m.Path] = true
   752  			}
   753  		}
   754  
   755  		if len(roots) > len(tidy.rootModules) {
   756  			module.Sort(roots)
   757  			tidy = newRequirements(pruned, roots, tidy.direct)
   758  		}
   759  	}
   760  
   761  	_, err := tidy.Graph(ctx)
   762  	if err != nil {
   763  		return nil, err
   764  	}
   765  	return tidy, nil
   766  }
   767  
   768  // updatePrunedRoots returns a set of root requirements that maintains the
   769  // invariants of the go.mod file needed to support graph pruning:
   770  //
   771  //  1. The selected version of the module providing each package marked with
   772  //     either pkgInAll or pkgIsRoot is included as a root.
   773  //     Note that certain root patterns (such as '...') may explode the root set
   774  //     to contain every module that provides any package imported (or merely
   775  //     required) by any other module.
   776  //  2. Each root appears only once, at the selected version of its path
   777  //     (if rs.graph is non-nil) or at the highest version otherwise present as a
   778  //     root (otherwise).
   779  //  3. Every module path that appears as a root in rs remains a root.
   780  //  4. Every version in add is selected at its given version unless upgraded by
   781  //     (the dependencies of) an existing root or another module in add.
   782  //
   783  // The packages in pkgs are assumed to have been loaded from either the roots of
   784  // rs or the modules selected in the graph of rs.
   785  //
   786  // The above invariants together imply the graph-pruning invariants for the
   787  // go.mod file:
   788  //
   789  //  1. (The import invariant.) Every module that provides a package transitively
   790  //     imported by any package or test in the main module is included as a root.
   791  //     This follows by induction from (1) and (3) above. Transitively-imported
   792  //     packages loaded during this invocation are marked with pkgInAll (1),
   793  //     and by hypothesis any transitively-imported packages loaded in previous
   794  //     invocations were already roots in rs (3).
   795  //
   796  //  2. (The argument invariant.) Every module that provides a package matching
   797  //     an explicit package pattern is included as a root. This follows directly
   798  //     from (1): packages matching explicit package patterns are marked with
   799  //     pkgIsRoot.
   800  //
   801  //  3. (The completeness invariant.) Every module that contributed any package
   802  //     to the build is required by either the main module or one of the modules
   803  //     it requires explicitly. This invariant is left up to the caller, who must
   804  //     not load packages from outside the module graph but may add roots to the
   805  //     graph, but is facilited by (3). If the caller adds roots to the graph in
   806  //     order to resolve missing packages, then updatePrunedRoots will retain them,
   807  //     the selected versions of those roots cannot regress, and they will
   808  //     eventually be written back to the main module's go.mod file.
   809  //
   810  // (See https://golang.org/design/36460-lazy-module-loading#invariants for more
   811  // detail.)
   812  func updatePrunedRoots(ctx context.Context, direct map[string]bool, rs *Requirements, pkgs []*loadPkg, add []module.Version, rootsImported bool) (*Requirements, error) {
   813  	roots := rs.rootModules
   814  	rootsUpgraded := false
   815  
   816  	spotCheckRoot := map[module.Version]bool{}
   817  
   818  	// “The selected version of the module providing each package marked with
   819  	// either pkgInAll or pkgIsRoot is included as a root.”
   820  	needSort := false
   821  	for _, pkg := range pkgs {
   822  		if !pkg.fromExternalModule() {
   823  			// pkg was not loaded from a module dependency, so we don't need
   824  			// to do anything special to maintain that dependency.
   825  			continue
   826  		}
   827  
   828  		switch {
   829  		case pkg.flags.has(pkgInAll):
   830  			// pkg is transitively imported by a package or test in the main module.
   831  			// We need to promote the module that maintains it to a root: if some
   832  			// other module depends on the main module, and that other module also
   833  			// uses a pruned module graph, it will expect to find all of our
   834  			// transitive dependencies by reading just our go.mod file, not the go.mod
   835  			// files of everything we depend on.
   836  			//
   837  			// (This is the “import invariant” that makes graph pruning possible.)
   838  
   839  		case rootsImported && pkg.flags.has(pkgFromRoot):
   840  			// pkg is a transitive dependency of some root, and we are treating the
   841  			// roots as if they are imported by the main module (as in 'go get').
   842  
   843  		case pkg.flags.has(pkgIsRoot):
   844  			// pkg is a root of the package-import graph. (Generally this means that
   845  			// it matches a command-line argument.) We want future invocations of the
   846  			// 'go' command — such as 'go test' on the same package — to continue to
   847  			// use the same versions of its dependencies that we are using right now.
   848  			// So we need to bring this package's dependencies inside the pruned
   849  			// module graph.
   850  			//
   851  			// Making the module containing this package a root of the module graph
   852  			// does exactly that: if the module containing the package supports graph
   853  			// pruning then it should satisfy the import invariant itself, so all of
   854  			// its dependencies should be in its go.mod file, and if the module
   855  			// containing the package does not support pruning then if we make it a
   856  			// root we will load all of its (unpruned) transitive dependencies into
   857  			// the module graph.
   858  			//
   859  			// (This is the “argument invariant”, and is important for
   860  			// reproducibility.)
   861  
   862  		default:
   863  			// pkg is a dependency of some other package outside of the main module.
   864  			// As far as we know it's not relevant to the main module (and thus not
   865  			// relevant to consumers of the main module either), and its dependencies
   866  			// should already be in the module graph — included in the dependencies of
   867  			// the package that imported it.
   868  			continue
   869  		}
   870  
   871  		if _, ok := rs.rootSelected(pkg.mod.Path); ok {
   872  			// It is possible that the main module's go.mod file is incomplete or
   873  			// otherwise erroneous — for example, perhaps the author forgot to 'git
   874  			// add' their updated go.mod file after adding a new package import, or
   875  			// perhaps they made an edit to the go.mod file using a third-party tool
   876  			// ('git merge'?) that doesn't maintain consistency for module
   877  			// dependencies. If that happens, ideally we want to detect the missing
   878  			// requirements and fix them up here.
   879  			//
   880  			// However, we also need to be careful not to be too aggressive. For
   881  			// transitive dependencies of external tests, the go.mod file for the
   882  			// module containing the test itself is expected to provide all of the
   883  			// relevant dependencies, and we explicitly don't want to pull in
   884  			// requirements on *irrelevant* requirements that happen to occur in the
   885  			// go.mod files for these transitive-test-only dependencies. (See the test
   886  			// in mod_lazy_test_horizon.txt for a concrete example.
   887  			//
   888  			// The “goldilocks zone” seems to be to spot-check exactly the same
   889  			// modules that we promote to explicit roots: namely, those that provide
   890  			// packages transitively imported by the main module, and those that
   891  			// provide roots of the package-import graph. That will catch erroneous
   892  			// edits to the main module's go.mod file and inconsistent requirements in
   893  			// dependencies that provide imported packages, but will ignore erroneous
   894  			// or misleading requirements in dependencies that aren't obviously
   895  			// relevant to the packages in the main module.
   896  			spotCheckRoot[pkg.mod] = true
   897  		} else {
   898  			roots = append(roots, pkg.mod)
   899  			rootsUpgraded = true
   900  			// The roots slice was initially sorted because rs.rootModules was sorted,
   901  			// but the root we just added could be out of order.
   902  			needSort = true
   903  		}
   904  	}
   905  
   906  	for _, m := range add {
   907  		if v, ok := rs.rootSelected(m.Path); !ok || cmpVersion(v, m.Version) < 0 {
   908  			roots = append(roots, m)
   909  			rootsUpgraded = true
   910  			needSort = true
   911  		}
   912  	}
   913  	if needSort {
   914  		module.Sort(roots)
   915  	}
   916  
   917  	// "Each root appears only once, at the selected version of its path ….”
   918  	for {
   919  		var mg *ModuleGraph
   920  		if rootsUpgraded {
   921  			// We've added or upgraded one or more roots, so load the full module
   922  			// graph so that we can update those roots to be consistent with other
   923  			// requirements.
   924  			if mustHaveCompleteRequirements() {
   925  				// Our changes to the roots may have moved dependencies into or out of
   926  				// the graph-pruning horizon, which could in turn change the selected
   927  				// versions of other modules. (For pruned modules adding or removing an
   928  				// explicit root is a semantic change, not just a cosmetic one.)
   929  				return rs, errGoModDirty
   930  			}
   931  
   932  			rs = newRequirements(pruned, roots, direct)
   933  			var err error
   934  			mg, err = rs.Graph(ctx)
   935  			if err != nil {
   936  				return rs, err
   937  			}
   938  		} else {
   939  			// Since none of the roots have been upgraded, we have no reason to
   940  			// suspect that they are inconsistent with the requirements of any other
   941  			// roots. Only look at the full module graph if we've already loaded it;
   942  			// otherwise, just spot-check the explicit requirements of the roots from
   943  			// which we loaded packages.
   944  			if rs.graph.Load() != nil {
   945  				// We've already loaded the full module graph, which includes the
   946  				// requirements of all of the root modules — even the transitive
   947  				// requirements, if they are unpruned!
   948  				mg, _ = rs.Graph(ctx)
   949  			} else if cfg.BuildMod == "vendor" {
   950  				// We can't spot-check the requirements of other modules because we
   951  				// don't in general have their go.mod files available in the vendor
   952  				// directory. (Fortunately this case is impossible, because mg.graph is
   953  				// always non-nil in vendor mode!)
   954  				panic("internal error: rs.graph is unexpectedly nil with -mod=vendor")
   955  			} else if !spotCheckRoots(ctx, rs, spotCheckRoot) {
   956  				// We spot-checked the explicit requirements of the roots that are
   957  				// relevant to the packages we've loaded. Unfortunately, they're
   958  				// inconsistent in some way; we need to load the full module graph
   959  				// so that we can fix the roots properly.
   960  				var err error
   961  				mg, err = rs.Graph(ctx)
   962  				if err != nil {
   963  					return rs, err
   964  				}
   965  			}
   966  		}
   967  
   968  		roots = make([]module.Version, 0, len(rs.rootModules))
   969  		rootsUpgraded = false
   970  		inRootPaths := make(map[string]bool, len(rs.rootModules)+1)
   971  		for _, mm := range MainModules.Versions() {
   972  			inRootPaths[mm.Path] = true
   973  		}
   974  		for _, m := range rs.rootModules {
   975  			if inRootPaths[m.Path] {
   976  				// This root specifies a redundant path. We already retained the
   977  				// selected version of this path when we saw it before, so omit the
   978  				// redundant copy regardless of its version.
   979  				//
   980  				// When we read the full module graph, we include the dependencies of
   981  				// every root even if that root is redundant. That better preserves
   982  				// reproducibility if, say, some automated tool adds a redundant
   983  				// 'require' line and then runs 'go mod tidy' to try to make everything
   984  				// consistent, since the requirements of the older version are carried
   985  				// over.
   986  				//
   987  				// So omitting a root that was previously present may *reduce* the
   988  				// selected versions of non-roots, but merely removing a requirement
   989  				// cannot *increase* the selected versions of other roots as a result —
   990  				// we don't need to mark this change as an upgrade. (This particular
   991  				// change cannot invalidate any other roots.)
   992  				continue
   993  			}
   994  
   995  			var v string
   996  			if mg == nil {
   997  				v, _ = rs.rootSelected(m.Path)
   998  			} else {
   999  				v = mg.Selected(m.Path)
  1000  			}
  1001  			roots = append(roots, module.Version{Path: m.Path, Version: v})
  1002  			inRootPaths[m.Path] = true
  1003  			if v != m.Version {
  1004  				rootsUpgraded = true
  1005  			}
  1006  		}
  1007  		// Note that rs.rootModules was already sorted by module path and version,
  1008  		// and we appended to the roots slice in the same order and guaranteed that
  1009  		// each path has only one version, so roots is also sorted by module path
  1010  		// and (trivially) version.
  1011  
  1012  		if !rootsUpgraded {
  1013  			if cfg.BuildMod != "mod" {
  1014  				// The only changes to the root set (if any) were to remove duplicates.
  1015  				// The requirements are consistent (if perhaps redundant), so keep the
  1016  				// original rs to preserve its ModuleGraph.
  1017  				return rs, nil
  1018  			}
  1019  			// The root set has converged: every root going into this iteration was
  1020  			// already at its selected version, although we have have removed other
  1021  			// (redundant) roots for the same path.
  1022  			break
  1023  		}
  1024  	}
  1025  
  1026  	if rs.pruning == pruned && reflect.DeepEqual(roots, rs.rootModules) && reflect.DeepEqual(direct, rs.direct) {
  1027  		// The root set is unchanged and rs was already pruned, so keep rs to
  1028  		// preserve its cached ModuleGraph (if any).
  1029  		return rs, nil
  1030  	}
  1031  	return newRequirements(pruned, roots, direct), nil
  1032  }
  1033  
  1034  // spotCheckRoots reports whether the versions of the roots in rs satisfy the
  1035  // explicit requirements of the modules in mods.
  1036  func spotCheckRoots(ctx context.Context, rs *Requirements, mods map[module.Version]bool) bool {
  1037  	ctx, cancel := context.WithCancel(ctx)
  1038  	defer cancel()
  1039  
  1040  	work := par.NewQueue(runtime.GOMAXPROCS(0))
  1041  	for m := range mods {
  1042  		m := m
  1043  		work.Add(func() {
  1044  			if ctx.Err() != nil {
  1045  				return
  1046  			}
  1047  
  1048  			summary, err := goModSummary(m)
  1049  			if err != nil {
  1050  				cancel()
  1051  				return
  1052  			}
  1053  
  1054  			for _, r := range summary.require {
  1055  				if v, ok := rs.rootSelected(r.Path); ok && cmpVersion(v, r.Version) < 0 {
  1056  					cancel()
  1057  					return
  1058  				}
  1059  			}
  1060  		})
  1061  	}
  1062  	<-work.Idle()
  1063  
  1064  	if ctx.Err() != nil {
  1065  		// Either we failed a spot-check, or the caller no longer cares about our
  1066  		// answer anyway.
  1067  		return false
  1068  	}
  1069  
  1070  	return true
  1071  }
  1072  
  1073  // tidyUnprunedRoots returns a minimal set of root requirements that maintains
  1074  // the selected version of every module that provided or lexically could have
  1075  // provided a package in pkgs, and includes the selected version of every such
  1076  // module in direct as a root.
  1077  func tidyUnprunedRoots(ctx context.Context, mainModule module.Version, direct map[string]bool, pkgs []*loadPkg) (*Requirements, error) {
  1078  	var (
  1079  		// keep is a set of of modules that provide packages or are needed to
  1080  		// disambiguate imports.
  1081  		keep     []module.Version
  1082  		keptPath = map[string]bool{}
  1083  
  1084  		// rootPaths is a list of module paths that provide packages directly
  1085  		// imported from the main module. They should be included as roots.
  1086  		rootPaths   []string
  1087  		inRootPaths = map[string]bool{}
  1088  
  1089  		// altMods is a set of paths of modules that lexically could have provided
  1090  		// imported packages. It may be okay to remove these from the list of
  1091  		// explicit requirements if that removes them from the module graph. If they
  1092  		// are present in the module graph reachable from rootPaths, they must not
  1093  		// be at a lower version. That could cause a missing sum error or a new
  1094  		// import ambiguity.
  1095  		//
  1096  		// For example, suppose a developer rewrites imports from example.com/m to
  1097  		// example.com/m/v2, then runs 'go mod tidy'. Tidy may delete the
  1098  		// requirement on example.com/m if there is no other transitive requirement
  1099  		// on it. However, if example.com/m were downgraded to a version not in
  1100  		// go.sum, when package example.com/m/v2/p is loaded, we'd get an error
  1101  		// trying to disambiguate the import, since we can't check example.com/m
  1102  		// without its sum. See #47738.
  1103  		altMods = map[string]string{}
  1104  	)
  1105  	for _, pkg := range pkgs {
  1106  		if !pkg.fromExternalModule() {
  1107  			continue
  1108  		}
  1109  		if m := pkg.mod; !keptPath[m.Path] {
  1110  			keep = append(keep, m)
  1111  			keptPath[m.Path] = true
  1112  			if direct[m.Path] && !inRootPaths[m.Path] {
  1113  				rootPaths = append(rootPaths, m.Path)
  1114  				inRootPaths[m.Path] = true
  1115  			}
  1116  		}
  1117  		for _, m := range pkg.altMods {
  1118  			altMods[m.Path] = m.Version
  1119  		}
  1120  	}
  1121  
  1122  	// Construct a build list with a minimal set of roots.
  1123  	// This may remove or downgrade modules in altMods.
  1124  	reqs := &mvsReqs{roots: keep}
  1125  	min, err := mvs.Req(mainModule, rootPaths, reqs)
  1126  	if err != nil {
  1127  		return nil, err
  1128  	}
  1129  	buildList, err := mvs.BuildList([]module.Version{mainModule}, reqs)
  1130  	if err != nil {
  1131  		return nil, err
  1132  	}
  1133  
  1134  	// Check if modules in altMods were downgraded but not removed.
  1135  	// If so, add them to roots, which will retain an "// indirect" requirement
  1136  	// in go.mod. See comment on altMods above.
  1137  	keptAltMod := false
  1138  	for _, m := range buildList {
  1139  		if v, ok := altMods[m.Path]; ok && semver.Compare(m.Version, v) < 0 {
  1140  			keep = append(keep, module.Version{Path: m.Path, Version: v})
  1141  			keptAltMod = true
  1142  		}
  1143  	}
  1144  	if keptAltMod {
  1145  		// We must run mvs.Req again instead of simply adding altMods to min.
  1146  		// It's possible that a requirement in altMods makes some other
  1147  		// explicit indirect requirement unnecessary.
  1148  		reqs.roots = keep
  1149  		min, err = mvs.Req(mainModule, rootPaths, reqs)
  1150  		if err != nil {
  1151  			return nil, err
  1152  		}
  1153  	}
  1154  
  1155  	return newRequirements(unpruned, min, direct), nil
  1156  }
  1157  
  1158  // updateUnprunedRoots returns a set of root requirements that includes the selected
  1159  // version of every module path in direct as a root, and maintains the selected
  1160  // version of every module selected in the graph of rs.
  1161  //
  1162  // The roots are updated such that:
  1163  //
  1164  //  1. The selected version of every module path in direct is included as a root
  1165  //     (if it is not "none").
  1166  //  2. Each root is the selected version of its path. (We say that such a root
  1167  //     set is “consistent”.)
  1168  //  3. Every version selected in the graph of rs remains selected unless upgraded
  1169  //     by a dependency in add.
  1170  //  4. Every version in add is selected at its given version unless upgraded by
  1171  //     (the dependencies of) an existing root or another module in add.
  1172  func updateUnprunedRoots(ctx context.Context, direct map[string]bool, rs *Requirements, add []module.Version) (*Requirements, error) {
  1173  	mg, err := rs.Graph(ctx)
  1174  	if err != nil {
  1175  		// We can't ignore errors in the module graph even if the user passed the -e
  1176  		// flag to try to push past them. If we can't load the complete module
  1177  		// dependencies, then we can't reliably compute a minimal subset of them.
  1178  		return rs, err
  1179  	}
  1180  
  1181  	if mustHaveCompleteRequirements() {
  1182  		// Instead of actually updating the requirements, just check that no updates
  1183  		// are needed.
  1184  		if rs == nil {
  1185  			// We're being asked to reconstruct the requirements from scratch,
  1186  			// but we aren't even allowed to modify them.
  1187  			return rs, errGoModDirty
  1188  		}
  1189  		for _, m := range rs.rootModules {
  1190  			if m.Version != mg.Selected(m.Path) {
  1191  				// The root version v is misleading: the actual selected version is higher.
  1192  				return rs, errGoModDirty
  1193  			}
  1194  		}
  1195  		for _, m := range add {
  1196  			if m.Version != mg.Selected(m.Path) {
  1197  				return rs, errGoModDirty
  1198  			}
  1199  		}
  1200  		for mPath := range direct {
  1201  			if _, ok := rs.rootSelected(mPath); !ok {
  1202  				// Module m is supposed to be listed explicitly, but isn't.
  1203  				//
  1204  				// Note that this condition is also detected (and logged with more
  1205  				// detail) earlier during package loading, so it shouldn't actually be
  1206  				// possible at this point — this is just a defense in depth.
  1207  				return rs, errGoModDirty
  1208  			}
  1209  		}
  1210  
  1211  		// No explicit roots are missing and all roots are already at the versions
  1212  		// we want to keep. Any other changes we would make are purely cosmetic,
  1213  		// such as pruning redundant indirect dependencies. Per issue #34822, we
  1214  		// ignore cosmetic changes when we cannot update the go.mod file.
  1215  		return rs, nil
  1216  	}
  1217  
  1218  	var (
  1219  		rootPaths   []string // module paths that should be included as roots
  1220  		inRootPaths = map[string]bool{}
  1221  	)
  1222  	for _, root := range rs.rootModules {
  1223  		// If the selected version of the root is the same as what was already
  1224  		// listed in the go.mod file, retain it as a root (even if redundant) to
  1225  		// avoid unnecessary churn. (See https://golang.org/issue/34822.)
  1226  		//
  1227  		// We do this even for indirect requirements, since we don't know why they
  1228  		// were added and they could become direct at any time.
  1229  		if !inRootPaths[root.Path] && mg.Selected(root.Path) == root.Version {
  1230  			rootPaths = append(rootPaths, root.Path)
  1231  			inRootPaths[root.Path] = true
  1232  		}
  1233  	}
  1234  
  1235  	// “The selected version of every module path in direct is included as a root.”
  1236  	//
  1237  	// This is only for convenience and clarity for end users: in an unpruned module,
  1238  	// the choice of explicit vs. implicit dependency has no impact on MVS
  1239  	// selection (for itself or any other module).
  1240  	keep := append(mg.BuildList()[MainModules.Len():], add...)
  1241  	for _, m := range keep {
  1242  		if direct[m.Path] && !inRootPaths[m.Path] {
  1243  			rootPaths = append(rootPaths, m.Path)
  1244  			inRootPaths[m.Path] = true
  1245  		}
  1246  	}
  1247  
  1248  	var roots []module.Version
  1249  	for _, mainModule := range MainModules.Versions() {
  1250  		min, err := mvs.Req(mainModule, rootPaths, &mvsReqs{roots: keep})
  1251  		if err != nil {
  1252  			return rs, err
  1253  		}
  1254  		roots = append(roots, min...)
  1255  	}
  1256  	if MainModules.Len() > 1 {
  1257  		module.Sort(roots)
  1258  	}
  1259  	if rs.pruning == unpruned && reflect.DeepEqual(roots, rs.rootModules) && reflect.DeepEqual(direct, rs.direct) {
  1260  		// The root set is unchanged and rs was already unpruned, so keep rs to
  1261  		// preserve its cached ModuleGraph (if any).
  1262  		return rs, nil
  1263  	}
  1264  
  1265  	return newRequirements(unpruned, roots, direct), nil
  1266  }
  1267  
  1268  // convertPruning returns a version of rs with the given pruning behavior.
  1269  // If rs already has the given pruning, convertPruning returns rs unmodified.
  1270  func convertPruning(ctx context.Context, rs *Requirements, pruning modPruning) (*Requirements, error) {
  1271  	if rs.pruning == pruning {
  1272  		return rs, nil
  1273  	} else if rs.pruning == workspace || pruning == workspace {
  1274  		panic("attempthing to convert to/from workspace pruning and another pruning type")
  1275  	}
  1276  
  1277  	if pruning == unpruned {
  1278  		// We are converting a pruned module to an unpruned one. The roots of a
  1279  		// ppruned module graph are a superset of the roots of an unpruned one, so
  1280  		// we don't need to add any new roots — we just need to drop the ones that
  1281  		// are redundant, which is exactly what updateUnprunedRoots does.
  1282  		return updateUnprunedRoots(ctx, rs.direct, rs, nil)
  1283  	}
  1284  
  1285  	// We are converting an unpruned module to a pruned one.
  1286  	//
  1287  	// An unpruned module graph includes the transitive dependencies of every
  1288  	// module in the build list. As it turns out, we can express that as a pruned
  1289  	// root set! “Include the transitive dependencies of every module in the build
  1290  	// list” is exactly what happens in a pruned module if we promote every module
  1291  	// in the build list to a root.
  1292  	mg, err := rs.Graph(ctx)
  1293  	if err != nil {
  1294  		return rs, err
  1295  	}
  1296  	return newRequirements(pruned, mg.BuildList()[MainModules.Len():], rs.direct), nil
  1297  }