Source file src/cmd/go/internal/modload/init.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 provides module and package loading functionality.
     6  package modload
     7  
     8  import (
     9  	"bytes"
    10  	"context"
    11  	"errors"
    12  	"fmt"
    13  	"internal/godebugs"
    14  	"internal/lazyregexp"
    15  	"io"
    16  	"maps"
    17  	"os"
    18  	"path"
    19  	"path/filepath"
    20  	"slices"
    21  	"strconv"
    22  	"strings"
    23  	"sync"
    24  
    25  	"cmd/go/internal/base"
    26  	"cmd/go/internal/cfg"
    27  	"cmd/go/internal/fips140"
    28  	"cmd/go/internal/fsys"
    29  	"cmd/go/internal/gover"
    30  	"cmd/go/internal/lockedfile"
    31  	"cmd/go/internal/modfetch"
    32  	"cmd/go/internal/search"
    33  
    34  	"golang.org/x/mod/modfile"
    35  	"golang.org/x/mod/module"
    36  )
    37  
    38  // Variables set by other packages.
    39  //
    40  // TODO(#40775): See if these can be plumbed as explicit parameters.
    41  var (
    42  	// ExplicitWriteGoMod prevents LoadPackages, ListModules, and other functions
    43  	// from updating go.mod and go.sum or reporting errors when updates are
    44  	// needed. A package should set this if it would cause go.mod to be written
    45  	// multiple times (for example, 'go get' calls LoadPackages multiple times) or
    46  	// if it needs some other operation to be successful before go.mod and go.sum
    47  	// can be written (for example, 'go mod download' must download modules before
    48  	// adding sums to go.sum). Packages that set this are responsible for calling
    49  	// WriteGoMod explicitly.
    50  	ExplicitWriteGoMod bool
    51  )
    52  
    53  // Variables set in Init.
    54  var (
    55  	gopath string
    56  )
    57  
    58  // EnterModule resets MainModules and requirements to refer to just this one module.
    59  func EnterModule(ld *Loader, ctx context.Context, enterModroot string) {
    60  	ld.MainModules = nil // reset MainModules
    61  	ld.requirements = nil
    62  	ld.workFilePath = "" // Force module mode
    63  	ld.Fetcher().Reset()
    64  
    65  	ld.modRoots = []string{enterModroot}
    66  	LoadModFile(ld, ctx)
    67  }
    68  
    69  // EnterWorkspace enters workspace mode from module mode, applying the updated requirements to the main
    70  // module to that module in the workspace. There should be no calls to any of the exported
    71  // functions of the modload package running concurrently with a call to EnterWorkspace as
    72  // EnterWorkspace will modify the global state they depend on in a non-thread-safe way.
    73  func EnterWorkspace(ld *Loader, ctx context.Context) (exit func(), err error) {
    74  	// Find the identity of the main module that will be updated before we reset modload state.
    75  	mm := ld.MainModules.mustGetSingleMainModule(ld)
    76  	// Get the updated modfile we will use for that module.
    77  	_, _, updatedmodfile, err := UpdateGoModFromReqs(ld, ctx, WriteOpts{})
    78  	if err != nil {
    79  		return nil, err
    80  	}
    81  
    82  	// Reset the state to a clean state.
    83  	oldstate := ld.setState(NewLoader())
    84  	ld.ForceUseModules = true
    85  
    86  	// Load in workspace mode.
    87  	ld.InitWorkfile()
    88  	LoadModFile(ld, ctx)
    89  
    90  	// Update the content of the previous main module, and recompute the requirements.
    91  	*ld.MainModules.ModFile(mm) = *updatedmodfile
    92  	ld.requirements = requirementsFromModFiles(ld, ctx, ld.MainModules.workFile, slices.Collect(maps.Values(ld.MainModules.modFiles)), nil)
    93  
    94  	return func() {
    95  		ld.setState(oldstate)
    96  	}, nil
    97  }
    98  
    99  type MainModuleSet struct {
   100  	// versions are the module.Version values of each of the main modules.
   101  	// For each of them, the Path fields are ordinary module paths and the Version
   102  	// fields are empty strings.
   103  	// versions is clipped (len=cap).
   104  	versions []module.Version
   105  
   106  	// modRoot maps each module in versions to its absolute filesystem path.
   107  	modRoot map[module.Version]string
   108  
   109  	// pathPrefix is the path prefix for packages in the module, without a trailing
   110  	// slash. For most modules, pathPrefix is just version.Path, but the
   111  	// standard-library module "std" has an empty prefix.
   112  	pathPrefix map[module.Version]string
   113  
   114  	// inGorootSrc caches whether modRoot is within GOROOT/src.
   115  	// The "std" module is special within GOROOT/src, but not otherwise.
   116  	inGorootSrc map[module.Version]bool
   117  
   118  	modFiles map[module.Version]*modfile.File
   119  
   120  	tools map[string]bool
   121  
   122  	modContainingCWD module.Version
   123  
   124  	workFile *modfile.WorkFile
   125  
   126  	workFileReplaceMap map[module.Version]module.Version
   127  	// highest replaced version of each module path; empty string for wildcard-only replacements
   128  	highestReplaced map[string]string
   129  
   130  	indexMu sync.RWMutex
   131  	indices map[module.Version]*modFileIndex
   132  }
   133  
   134  func (mms *MainModuleSet) PathPrefix(m module.Version) string {
   135  	return mms.pathPrefix[m]
   136  }
   137  
   138  // Versions returns the module.Version values of each of the main modules.
   139  // For each of them, the Path fields are ordinary module paths and the Version
   140  // fields are empty strings.
   141  // Callers should not modify the returned slice.
   142  func (mms *MainModuleSet) Versions() []module.Version {
   143  	if mms == nil {
   144  		return nil
   145  	}
   146  	return mms.versions
   147  }
   148  
   149  // Tools returns the tools defined by all the main modules.
   150  // The key is the absolute package path of the tool.
   151  func (mms *MainModuleSet) Tools() map[string]bool {
   152  	if mms == nil {
   153  		return nil
   154  	}
   155  	return mms.tools
   156  }
   157  
   158  func (mms *MainModuleSet) Contains(path string) bool {
   159  	if mms == nil {
   160  		return false
   161  	}
   162  	for _, v := range mms.versions {
   163  		if v.Path == path {
   164  			return true
   165  		}
   166  	}
   167  	return false
   168  }
   169  
   170  func (mms *MainModuleSet) ModRoot(m module.Version) string {
   171  	if mms == nil {
   172  		return ""
   173  	}
   174  	return mms.modRoot[m]
   175  }
   176  
   177  func (mms *MainModuleSet) InGorootSrc(m module.Version) bool {
   178  	if mms == nil {
   179  		return false
   180  	}
   181  	return mms.inGorootSrc[m]
   182  }
   183  
   184  func (mms *MainModuleSet) mustGetSingleMainModule(ld *Loader) module.Version {
   185  	mm, err := mms.getSingleMainModule(ld)
   186  	if err != nil {
   187  		panic(err)
   188  	}
   189  	return mm
   190  }
   191  
   192  func (mms *MainModuleSet) getSingleMainModule(ld *Loader) (module.Version, error) {
   193  	if mms == nil || len(mms.versions) == 0 {
   194  		return module.Version{}, errors.New("internal error: mustGetSingleMainModule called in context with no main modules")
   195  	}
   196  	if len(mms.versions) != 1 {
   197  		if ld.inWorkspaceMode() {
   198  			return module.Version{}, errors.New("internal error: mustGetSingleMainModule called in workspace mode")
   199  		} else {
   200  			return module.Version{}, errors.New("internal error: multiple main modules present outside of workspace mode")
   201  		}
   202  	}
   203  	return mms.versions[0], nil
   204  }
   205  
   206  func (mms *MainModuleSet) GetSingleIndexOrNil(ld *Loader) *modFileIndex {
   207  	if mms == nil {
   208  		return nil
   209  	}
   210  	if len(mms.versions) == 0 {
   211  		return nil
   212  	}
   213  	return mms.indices[mms.mustGetSingleMainModule(ld)]
   214  }
   215  
   216  func (mms *MainModuleSet) Index(m module.Version) *modFileIndex {
   217  	mms.indexMu.RLock()
   218  	defer mms.indexMu.RUnlock()
   219  	return mms.indices[m]
   220  }
   221  
   222  func (mms *MainModuleSet) SetIndex(m module.Version, index *modFileIndex) {
   223  	mms.indexMu.Lock()
   224  	defer mms.indexMu.Unlock()
   225  	mms.indices[m] = index
   226  }
   227  
   228  func (mms *MainModuleSet) ModFile(m module.Version) *modfile.File {
   229  	return mms.modFiles[m]
   230  }
   231  
   232  func (mms *MainModuleSet) WorkFile() *modfile.WorkFile {
   233  	return mms.workFile
   234  }
   235  
   236  func (mms *MainModuleSet) Len() int {
   237  	if mms == nil {
   238  		return 0
   239  	}
   240  	return len(mms.versions)
   241  }
   242  
   243  // ModContainingCWD returns the main module containing the working directory,
   244  // or module.Version{} if none of the main modules contain the working
   245  // directory.
   246  func (mms *MainModuleSet) ModContainingCWD() module.Version {
   247  	return mms.modContainingCWD
   248  }
   249  
   250  func (mms *MainModuleSet) HighestReplaced() map[string]string {
   251  	return mms.highestReplaced
   252  }
   253  
   254  // GoVersion returns the go version set on the single module, in module mode,
   255  // or the go.work file in workspace mode.
   256  func (mms *MainModuleSet) GoVersion(ld *Loader) string {
   257  	if ld.inWorkspaceMode() {
   258  		return gover.FromGoWork(mms.workFile)
   259  	}
   260  	if mms != nil && len(mms.versions) == 1 {
   261  		f := mms.ModFile(mms.mustGetSingleMainModule(ld))
   262  		if f == nil {
   263  			// Special case: we are outside a module, like 'go run x.go'.
   264  			// Assume the local Go version.
   265  			// TODO(#49228): Clean this up; see loadModFile.
   266  			return gover.Local()
   267  		}
   268  		return gover.FromGoMod(f)
   269  	}
   270  	return gover.DefaultGoModVersion
   271  }
   272  
   273  // Godebugs returns the godebug lines set on the single module, in module mode,
   274  // or on the go.work file in workspace mode.
   275  // The caller must not modify the result.
   276  func (mms *MainModuleSet) Godebugs(ld *Loader) []*modfile.Godebug {
   277  	if ld.inWorkspaceMode() {
   278  		if mms.workFile != nil {
   279  			return mms.workFile.Godebug
   280  		}
   281  		return nil
   282  	}
   283  	if mms != nil && len(mms.versions) == 1 {
   284  		f := mms.ModFile(mms.mustGetSingleMainModule(ld))
   285  		if f == nil {
   286  			// Special case: we are outside a module, like 'go run x.go'.
   287  			return nil
   288  		}
   289  		return f.Godebug
   290  	}
   291  	return nil
   292  }
   293  
   294  func (mms *MainModuleSet) WorkFileReplaceMap() map[module.Version]module.Version {
   295  	return mms.workFileReplaceMap
   296  }
   297  
   298  type Root int
   299  
   300  const (
   301  	// AutoRoot is the default for most commands. modload.Init will look for
   302  	// a go.mod file in the current directory or any parent. If none is found,
   303  	// modules may be disabled (GO111MODULE=auto) or commands may run in a
   304  	// limited module mode.
   305  	AutoRoot Root = iota
   306  
   307  	// NoRoot is used for commands that run in module mode and ignore any go.mod
   308  	// file the current directory or in parent directories.
   309  	NoRoot
   310  
   311  	// NeedRoot is used for commands that must run in module mode and don't
   312  	// make sense without a main module.
   313  	NeedRoot
   314  )
   315  
   316  // ModFile returns the parsed go.mod file.
   317  //
   318  // Note that after calling LoadPackages or LoadModGraph,
   319  // the require statements in the modfile.File are no longer
   320  // the source of truth and will be ignored: edits made directly
   321  // will be lost at the next call to WriteGoMod.
   322  // To make permanent changes to the require statements
   323  // in go.mod, edit it before loading.
   324  func ModFile(ld *Loader) *modfile.File {
   325  	Init(ld)
   326  	modFile := ld.MainModules.ModFile(ld.MainModules.mustGetSingleMainModule(ld))
   327  	if modFile == nil {
   328  		die(ld)
   329  	}
   330  	return modFile
   331  }
   332  
   333  func BinDir(ld *Loader) string {
   334  	Init(ld)
   335  	if cfg.GOBIN != "" {
   336  		return cfg.GOBIN
   337  	}
   338  	if gopath == "" {
   339  		return ""
   340  	}
   341  	return filepath.Join(gopath, "bin")
   342  }
   343  
   344  // InitWorkfile initializes the workFilePath variable for commands that
   345  // operate in workspace mode. It should not be called by other commands,
   346  // for example 'go mod tidy', that don't operate in workspace mode.
   347  func (ld *Loader) InitWorkfile() {
   348  	// Initialize fsys early because we need overlay to read go.work file.
   349  	fips140.Init()
   350  	if err := fsys.Init(); err != nil {
   351  		base.Fatal(err)
   352  	}
   353  	ld.workFilePath = ld.FindGoWork(base.Cwd())
   354  }
   355  
   356  // FindGoWork returns the name of the go.work file for this command,
   357  // or the empty string if there isn't one.
   358  // Most code should use Init and Enabled rather than use this directly.
   359  // It is exported mainly for Go toolchain switching, which must process
   360  // the go.work very early at startup.
   361  func (ld *Loader) FindGoWork(wd string) string {
   362  	if ld.RootMode == NoRoot {
   363  		return ""
   364  	}
   365  
   366  	switch gowork := cfg.Getenv("GOWORK"); gowork {
   367  	case "off":
   368  		return ""
   369  	case "", "auto":
   370  		return findWorkspaceFile(wd)
   371  	default:
   372  		if !filepath.IsAbs(gowork) {
   373  			base.Fatalf("go: invalid GOWORK: not an absolute path")
   374  		}
   375  		return gowork
   376  	}
   377  }
   378  
   379  // WorkFilePath returns the absolute path of the go.work file, or "" if not in
   380  // workspace mode. WorkFilePath must be called after InitWorkfile.
   381  func WorkFilePath(ld *Loader) string {
   382  	return ld.workFilePath
   383  }
   384  
   385  // Reset clears all the initialized, cached state about the use of modules,
   386  // so that we can start over.
   387  func (ld *Loader) Reset() {
   388  	ld.setState(NewLoader())
   389  }
   390  
   391  func (ld *Loader) setState(new *Loader) (old *Loader) {
   392  	old = &Loader{
   393  		initialized:     ld.initialized,
   394  		ForceUseModules: ld.ForceUseModules,
   395  		RootMode:        ld.RootMode,
   396  		modRoots:        ld.modRoots,
   397  		modulesEnabled:  cfg.ModulesEnabled,
   398  		MainModules:     ld.MainModules,
   399  		requirements:    ld.requirements,
   400  		workFilePath:    ld.workFilePath,
   401  		fetcher:         ld.fetcher,
   402  	}
   403  	ld.initialized = new.initialized
   404  	ld.ForceUseModules = new.ForceUseModules
   405  	ld.RootMode = new.RootMode
   406  	ld.modRoots = new.modRoots
   407  	cfg.ModulesEnabled = new.modulesEnabled
   408  	ld.MainModules = new.MainModules
   409  	ld.requirements = new.requirements
   410  	ld.workFilePath = new.workFilePath
   411  	// The modfetch package's global state is used to compute
   412  	// the go.sum file, so save and restore it along with the
   413  	// modload state.
   414  	old.fetcher = ld.fetcher.SetState(new.fetcher)
   415  
   416  	return old
   417  }
   418  
   419  type Loader struct {
   420  	initialized               bool
   421  	allowMissingModuleImports bool
   422  
   423  	// ForceUseModules may be set to force modules to be enabled when
   424  	// GO111MODULE=auto or to report an error when GO111MODULE=off.
   425  	ForceUseModules bool
   426  
   427  	// RootMode determines whether a module root is needed.
   428  	RootMode Root
   429  
   430  	// These are primarily used to initialize the MainModules, and should
   431  	// be eventually superseded by them but are still used in cases where
   432  	// the module roots are required but MainModules has not been
   433  	// initialized yet. Set to the modRoots of the main modules.
   434  	// modRoots != nil implies len(modRoots) > 0
   435  	modRoots       []string
   436  	modulesEnabled bool
   437  	MainModules    *MainModuleSet
   438  
   439  	// pkgLoader is the most recently-used package loader.
   440  	// It holds details about individual packages.
   441  	//
   442  	// This variable should only be accessed directly in top-level exported
   443  	// functions. All other functions that require or produce a *packageLoader should pass
   444  	// or return it as an explicit parameter.
   445  	pkgLoader *packageLoader
   446  
   447  	// requirements is the requirement graph for the main module.
   448  	//
   449  	// It is always non-nil if the main module's go.mod file has been
   450  	// loaded.
   451  	//
   452  	// This variable should only be read from the loadModFile
   453  	// function, and should only be written in the loadModFile and
   454  	// commitRequirements functions.  All other functions that need or
   455  	// produce a *Requirements should accept and/or return an explicit
   456  	// parameter.
   457  	requirements *Requirements
   458  
   459  	// Set to the path to the go.work file, or "" if workspace mode is
   460  	// disabled
   461  	workFilePath string
   462  	fetcher      *modfetch.Fetcher
   463  }
   464  
   465  func NewLoader() *Loader {
   466  	s := new(Loader)
   467  	s.fetcher = modfetch.NewFetcher()
   468  	return s
   469  }
   470  
   471  func NewDisabledState() *Loader {
   472  	fips140.Init()
   473  	return &Loader{initialized: true, modulesEnabled: false}
   474  }
   475  
   476  func (ld *Loader) Fetcher() *modfetch.Fetcher {
   477  	return ld.fetcher
   478  }
   479  
   480  // Init determines whether module mode is enabled, locates the root of the
   481  // current module (if any), sets environment variables for Git subprocesses, and
   482  // configures the cfg, codehost, load, modfetch, and search packages for use
   483  // with modules.
   484  func Init(ld *Loader) {
   485  	if ld.initialized {
   486  		return
   487  	}
   488  	ld.initialized = true
   489  
   490  	fips140.Init()
   491  
   492  	// Keep in sync with WillBeEnabled. We perform extra validation here, and
   493  	// there are lots of diagnostics and side effects, so we can't use
   494  	// WillBeEnabled directly.
   495  	var mustUseModules bool
   496  	env := cfg.Getenv("GO111MODULE")
   497  	switch env {
   498  	default:
   499  		base.Fatalf("go: unknown environment setting GO111MODULE=%s", env)
   500  	case "auto":
   501  		mustUseModules = ld.ForceUseModules
   502  	case "on", "":
   503  		mustUseModules = true
   504  	case "off":
   505  		if ld.ForceUseModules {
   506  			base.Fatalf("go: modules disabled by GO111MODULE=off; see 'go help modules'")
   507  		}
   508  		mustUseModules = false
   509  		return
   510  	}
   511  
   512  	if err := fsys.Init(); err != nil {
   513  		base.Fatal(err)
   514  	}
   515  
   516  	// Disable any prompting for passwords by Git.
   517  	// Only has an effect for 2.3.0 or later, but avoiding
   518  	// the prompt in earlier versions is just too hard.
   519  	// If user has explicitly set GIT_TERMINAL_PROMPT=1, keep
   520  	// prompting.
   521  	// See golang.org/issue/9341 and golang.org/issue/12706.
   522  	if os.Getenv("GIT_TERMINAL_PROMPT") == "" {
   523  		os.Setenv("GIT_TERMINAL_PROMPT", "0")
   524  	}
   525  
   526  	if os.Getenv("GCM_INTERACTIVE") == "" {
   527  		os.Setenv("GCM_INTERACTIVE", "never")
   528  	}
   529  	if ld.modRoots != nil {
   530  		// modRoot set before Init was called ("go mod init" does this).
   531  		// No need to search for go.mod.
   532  	} else if ld.RootMode == NoRoot {
   533  		if cfg.ModFile != "" && !base.InGOFLAGS("-modfile") {
   534  			base.Fatalf("go: -modfile cannot be used with commands that ignore the current module")
   535  		}
   536  		ld.modRoots = nil
   537  	} else if ld.workFilePath != "" {
   538  		// We're in workspace mode, which implies module mode.
   539  		if cfg.ModFile != "" {
   540  			base.Fatalf("go: -modfile cannot be used in workspace mode")
   541  		}
   542  	} else {
   543  		if modRoot := findModuleRoot(base.Cwd()); modRoot == "" {
   544  			if cfg.ModFile != "" {
   545  				base.Fatalf("go: cannot find main module, but -modfile was set.\n\t-modfile cannot be used to set the module root directory.")
   546  			}
   547  			if ld.RootMode == NeedRoot {
   548  				base.Fatal(NewNoMainModulesError(ld))
   549  			}
   550  			if !mustUseModules {
   551  				// GO111MODULE is 'auto', and we can't find a module root.
   552  				// Stay in GOPATH mode.
   553  				return
   554  			}
   555  		} else if search.InDir(modRoot, os.TempDir()) == "." {
   556  			// If you create /tmp/go.mod for experimenting,
   557  			// then any tests that create work directories under /tmp
   558  			// will find it and get modules when they're not expecting them.
   559  			// It's a bit of a peculiar thing to disallow but quite mysterious
   560  			// when it happens. See golang.org/issue/26708.
   561  			fmt.Fprintf(os.Stderr, "go: warning: ignoring go.mod in system temp root %v\n", os.TempDir())
   562  			if ld.RootMode == NeedRoot {
   563  				base.Fatal(NewNoMainModulesError(ld))
   564  			}
   565  			if !mustUseModules {
   566  				return
   567  			}
   568  		} else {
   569  			ld.modRoots = []string{modRoot}
   570  		}
   571  	}
   572  	if cfg.ModFile != "" && !strings.HasSuffix(cfg.ModFile, ".mod") {
   573  		base.Fatalf("go: -modfile=%s: file does not have .mod extension", cfg.ModFile)
   574  	}
   575  
   576  	// We're in module mode. Set any global variables that need to be set.
   577  	cfg.ModulesEnabled = true
   578  	setDefaultBuildMod(ld)
   579  	list := filepath.SplitList(cfg.BuildContext.GOPATH)
   580  	if len(list) > 0 && list[0] != "" {
   581  		gopath = list[0]
   582  		if _, err := fsys.Stat(filepath.Join(gopath, "go.mod")); err == nil {
   583  			fmt.Fprintf(os.Stderr, "go: warning: ignoring go.mod in $GOPATH %v\n", gopath)
   584  			if ld.RootMode == NeedRoot {
   585  				base.Fatal(NewNoMainModulesError(ld))
   586  			}
   587  			if !mustUseModules {
   588  				return
   589  			}
   590  		}
   591  	}
   592  }
   593  
   594  // WillBeEnabled checks whether modules should be enabled but does not
   595  // initialize modules by installing hooks. If Init has already been called,
   596  // WillBeEnabled returns the same result as Enabled.
   597  //
   598  // This function is needed to break a cycle. The main package needs to know
   599  // whether modules are enabled in order to install the module or GOPATH version
   600  // of 'go get', but Init reads the -modfile flag in 'go get', so it shouldn't
   601  // be called until the command is installed and flags are parsed. Instead of
   602  // calling Init and Enabled, the main package can call this function.
   603  func (ld *Loader) WillBeEnabled() bool {
   604  	if ld.modRoots != nil || cfg.ModulesEnabled {
   605  		// Already enabled.
   606  		return true
   607  	}
   608  	if ld.initialized {
   609  		// Initialized, not enabled.
   610  		return false
   611  	}
   612  
   613  	// Keep in sync with Init. Init does extra validation and prints warnings or
   614  	// exits, so it can't call this function directly.
   615  	env := cfg.Getenv("GO111MODULE")
   616  	switch env {
   617  	case "on", "":
   618  		return true
   619  	case "auto":
   620  		break
   621  	default:
   622  		return false
   623  	}
   624  
   625  	return FindGoMod(base.Cwd()) != "" || ld.FindGoWork(base.Cwd()) != ""
   626  }
   627  
   628  // FindGoMod returns the name of the go.mod file for this command,
   629  // or the empty string if there isn't one.
   630  // Most code should use Init and Enabled rather than use this directly.
   631  // It is exported mainly for Go toolchain switching, which must process
   632  // the go.mod very early at startup.
   633  func FindGoMod(wd string) string {
   634  	modRoot := findModuleRoot(wd)
   635  	if modRoot == "" {
   636  		// GO111MODULE is 'auto', and we can't find a module root.
   637  		// Stay in GOPATH mode.
   638  		return ""
   639  	}
   640  	if search.InDir(modRoot, os.TempDir()) == "." {
   641  		// If you create /tmp/go.mod for experimenting,
   642  		// then any tests that create work directories under /tmp
   643  		// will find it and get modules when they're not expecting them.
   644  		// It's a bit of a peculiar thing to disallow but quite mysterious
   645  		// when it happens. See golang.org/issue/26708.
   646  		return ""
   647  	}
   648  	return filepath.Join(modRoot, "go.mod")
   649  }
   650  
   651  // Enabled reports whether modules are (or must be) enabled.
   652  // If modules are enabled but there is no main module, Enabled returns true
   653  // and then the first use of module information will call die
   654  // (usually through MustModRoot).
   655  func (ld *Loader) Enabled() bool {
   656  	Init(ld)
   657  	return ld.modRoots != nil || cfg.ModulesEnabled
   658  }
   659  
   660  func (ld *Loader) vendorDir() (string, error) {
   661  	if ld.inWorkspaceMode() {
   662  		return filepath.Join(filepath.Dir(WorkFilePath(ld)), "vendor"), nil
   663  	}
   664  	mainModule, err := ld.MainModules.getSingleMainModule(ld)
   665  	if err != nil {
   666  		return "", err
   667  	}
   668  	// Even if -mod=vendor, we could be operating with no mod root (and thus no
   669  	// vendor directory). As long as there are no dependencies that is expected
   670  	// to work. See script/vendor_outside_module.txt.
   671  	modRoot := ld.MainModules.ModRoot(mainModule)
   672  	if modRoot == "" {
   673  		return "", errors.New("vendor directory does not exist when in single module mode outside of a module")
   674  	}
   675  	return filepath.Join(modRoot, "vendor"), nil
   676  }
   677  
   678  func (ld *Loader) VendorDirOrEmpty() string {
   679  	dir, err := ld.vendorDir()
   680  	if err != nil {
   681  		return ""
   682  	}
   683  	return dir
   684  }
   685  
   686  func VendorDir(ld *Loader) string {
   687  	dir, err := ld.vendorDir()
   688  	if err != nil {
   689  		panic(err)
   690  	}
   691  	return dir
   692  }
   693  
   694  func (ld *Loader) inWorkspaceMode() bool {
   695  	if !ld.initialized {
   696  		panic("inWorkspaceMode called before modload.Init called")
   697  	}
   698  	if !ld.Enabled() {
   699  		return false
   700  	}
   701  	return ld.workFilePath != ""
   702  }
   703  
   704  // HasModRoot reports whether a main module or main modules are present.
   705  // HasModRoot may return false even if Enabled returns true: for example, 'get'
   706  // does not require a main module.
   707  func (ld *Loader) HasModRoot() bool {
   708  	Init(ld)
   709  	return ld.modRoots != nil
   710  }
   711  
   712  // MustHaveModRoot checks that a main module or main modules are present,
   713  // and calls base.Fatalf if there are no main modules.
   714  func (ld *Loader) MustHaveModRoot() {
   715  	Init(ld)
   716  	if !ld.HasModRoot() {
   717  		die(ld)
   718  	}
   719  }
   720  
   721  // ModFilePath returns the path that would be used for the go.mod
   722  // file, if in module mode. ModFilePath calls base.Fatalf if there is no main
   723  // module, even if -modfile is set.
   724  func (ld *Loader) ModFilePath() string {
   725  	ld.MustHaveModRoot()
   726  	return modFilePath(findModuleRoot(base.Cwd()))
   727  }
   728  
   729  func modFilePath(modRoot string) string {
   730  	// TODO(matloob): This seems incompatible with workspaces
   731  	// (unless the user's intention is to replace all workspace modules' modfiles?).
   732  	// Should we produce an error in workspace mode if cfg.ModFile is set?
   733  	if cfg.ModFile != "" {
   734  		return cfg.ModFile
   735  	}
   736  	return filepath.Join(modRoot, "go.mod")
   737  }
   738  
   739  func die(ld *Loader) {
   740  	if cfg.Getenv("GO111MODULE") == "off" {
   741  		base.Fatalf("go: modules disabled by GO111MODULE=off; see 'go help modules'")
   742  	}
   743  	if !ld.inWorkspaceMode() {
   744  		if dir, name := findAltConfig(base.Cwd()); dir != "" {
   745  			rel, err := filepath.Rel(base.Cwd(), dir)
   746  			if err != nil {
   747  				rel = dir
   748  			}
   749  			cdCmd := ""
   750  			if rel != "." {
   751  				cdCmd = fmt.Sprintf("cd %s && ", rel)
   752  			}
   753  			base.Fatalf("go: cannot find main module, but found %s in %s\n\tto create a module there, run:\n\t%sgo mod init", name, dir, cdCmd)
   754  		}
   755  	}
   756  	base.Fatal(NewNoMainModulesError(ld))
   757  }
   758  
   759  var ErrNoModRoot = errors.New("no module root")
   760  
   761  // noMainModulesError returns the appropriate error if there is no main module or
   762  // main modules depending on whether the go command is in workspace mode.
   763  type noMainModulesError struct {
   764  	inWorkspaceMode bool
   765  }
   766  
   767  func (e noMainModulesError) Error() string {
   768  	if e.inWorkspaceMode {
   769  		return "no modules were found in the current workspace; see 'go help work'"
   770  	}
   771  	return "go.mod file not found in current directory or any parent directory; see 'go help modules'"
   772  }
   773  
   774  func (e noMainModulesError) Unwrap() error {
   775  	return ErrNoModRoot
   776  }
   777  
   778  func NewNoMainModulesError(ld *Loader) noMainModulesError {
   779  	return noMainModulesError{
   780  		inWorkspaceMode: ld.inWorkspaceMode(),
   781  	}
   782  }
   783  
   784  type goModDirtyError struct{}
   785  
   786  func (goModDirtyError) Error() string {
   787  	if cfg.BuildModExplicit {
   788  		return fmt.Sprintf("updates to go.mod needed, disabled by -mod=%v; to update it:\n\tgo mod tidy", cfg.BuildMod)
   789  	}
   790  	if cfg.BuildModReason != "" {
   791  		return fmt.Sprintf("updates to go.mod needed, disabled by -mod=%s\n\t(%s)\n\tto update it:\n\tgo mod tidy", cfg.BuildMod, cfg.BuildModReason)
   792  	}
   793  	return "updates to go.mod needed; to update it:\n\tgo mod tidy"
   794  }
   795  
   796  var errGoModDirty error = goModDirtyError{}
   797  
   798  // LoadWorkFile parses and checks the go.work file at the given path,
   799  // and returns the absolute paths of the workspace modules' modroots.
   800  // It does not modify the global state of the modload package.
   801  func LoadWorkFile(path string) (workFile *modfile.WorkFile, modRoots []string, err error) {
   802  	workDir := filepath.Dir(path)
   803  	wf, err := ReadWorkFile(path)
   804  	if err != nil {
   805  		return nil, nil, err
   806  	}
   807  	seen := map[string]bool{}
   808  	for _, d := range wf.Use {
   809  		modRoot := d.Path
   810  		if !filepath.IsAbs(modRoot) {
   811  			modRoot = filepath.Join(workDir, modRoot)
   812  		}
   813  
   814  		if seen[modRoot] {
   815  			return nil, nil, fmt.Errorf("error loading go.work:\n%s:%d: path %s appears multiple times in workspace", base.ShortPath(path), d.Syntax.Start.Line, modRoot)
   816  		}
   817  		seen[modRoot] = true
   818  		modRoots = append(modRoots, modRoot)
   819  	}
   820  
   821  	for _, g := range wf.Godebug {
   822  		if err := CheckGodebug("godebug", g.Key, g.Value); err != nil {
   823  			return nil, nil, fmt.Errorf("error loading go.work:\n%s:%d: %w", base.ShortPath(path), g.Syntax.Start.Line, err)
   824  		}
   825  	}
   826  
   827  	return wf, modRoots, nil
   828  }
   829  
   830  // ReadWorkFile reads and parses the go.work file at the given path.
   831  func ReadWorkFile(path string) (*modfile.WorkFile, error) {
   832  	path = base.ShortPath(path) // use short path in any errors
   833  	workData, err := fsys.ReadFile(path)
   834  	if err != nil {
   835  		return nil, fmt.Errorf("reading go.work: %w", err)
   836  	}
   837  
   838  	f, err := modfile.ParseWork(path, workData, nil)
   839  	if err != nil {
   840  		return nil, fmt.Errorf("errors parsing go.work:\n%w", err)
   841  	}
   842  	if f.Go != nil && gover.Compare(f.Go.Version, gover.Local()) > 0 && cfg.CmdName != "work edit" {
   843  		base.Fatal(&gover.TooNewError{What: base.ShortPath(path), GoVersion: f.Go.Version})
   844  	}
   845  	return f, nil
   846  }
   847  
   848  // WriteWorkFile cleans and writes out the go.work file to the given path.
   849  func WriteWorkFile(path string, wf *modfile.WorkFile) error {
   850  	wf.SortBlocks()
   851  	wf.Cleanup()
   852  	out := modfile.Format(wf.Syntax)
   853  
   854  	return os.WriteFile(path, out, 0o666)
   855  }
   856  
   857  // UpdateWorkGoVersion updates the go line in wf to be at least goVers,
   858  // reporting whether it changed the file.
   859  func UpdateWorkGoVersion(wf *modfile.WorkFile, goVers string) (changed bool) {
   860  	old := gover.FromGoWork(wf)
   861  	if gover.Compare(old, goVers) >= 0 {
   862  		return false
   863  	}
   864  
   865  	wf.AddGoStmt(goVers)
   866  
   867  	if wf.Toolchain == nil {
   868  		return true
   869  	}
   870  
   871  	// Drop the toolchain line if it is implied by the go line,
   872  	// if its version is older than the version in the go line,
   873  	// or if it is asking for a toolchain older than Go 1.21,
   874  	// which will not understand the toolchain line.
   875  	// Previously, a toolchain line set to the local toolchain
   876  	// version was added so that future operations on the go file
   877  	// would use the same toolchain logic for reproducibility.
   878  	// This behavior seemed to cause user confusion without much
   879  	// benefit so it was removed. See #65847.
   880  	toolchain := wf.Toolchain.Name
   881  	toolVers := gover.FromToolchain(toolchain)
   882  	if toolchain == "go"+goVers || gover.Compare(toolVers, goVers) < 0 || gover.Compare(toolVers, gover.GoStrictVersion) < 0 {
   883  		wf.DropToolchainStmt()
   884  	}
   885  
   886  	return true
   887  }
   888  
   889  // UpdateWorkFile updates comments on directory directives in the go.work
   890  // file to include the associated module path.
   891  func UpdateWorkFile(wf *modfile.WorkFile) {
   892  	missingModulePaths := map[string]string{} // module directory listed in file -> abspath modroot
   893  
   894  	for _, d := range wf.Use {
   895  		if d.Path == "" {
   896  			continue // d is marked for deletion.
   897  		}
   898  		modRoot := d.Path
   899  		if d.ModulePath == "" {
   900  			missingModulePaths[d.Path] = modRoot
   901  		}
   902  	}
   903  
   904  	// Clean up and annotate directories.
   905  	// TODO(matloob): update x/mod to actually add module paths.
   906  	for moddir, absmodroot := range missingModulePaths {
   907  		_, f, err := ReadModFile(filepath.Join(absmodroot, "go.mod"), nil)
   908  		if err != nil {
   909  			continue // Error will be reported if modules are loaded.
   910  		}
   911  		wf.AddUse(moddir, f.Module.Mod.Path)
   912  	}
   913  }
   914  
   915  // LoadModFile sets Target and, if there is a main module, parses the initial
   916  // build list from its go.mod file.
   917  //
   918  // LoadModFile may make changes in memory, like adding a go directive and
   919  // ensuring requirements are consistent. The caller is responsible for ensuring
   920  // those changes are written to disk by calling LoadPackages or ListModules
   921  // (unless ExplicitWriteGoMod is set) or by calling WriteGoMod directly.
   922  //
   923  // As a side-effect, LoadModFile may change cfg.BuildMod to "vendor" if
   924  // -mod wasn't set explicitly and automatic vendoring should be enabled.
   925  //
   926  // If LoadModFile or CreateModFile has already been called, LoadModFile returns
   927  // the existing in-memory requirements (rather than re-reading them from disk).
   928  //
   929  // LoadModFile checks the roots of the module graph for consistency with each
   930  // other, but unlike LoadModGraph does not load the full module graph or check
   931  // it for global consistency. Most callers outside of the modload package should
   932  // use LoadModGraph instead.
   933  func LoadModFile(ld *Loader, ctx context.Context) *Requirements {
   934  	rs, err := loadModFile(ld, ctx, nil)
   935  	if err != nil {
   936  		base.Fatal(err)
   937  	}
   938  	return rs
   939  }
   940  
   941  func loadModFile(ld *Loader, ctx context.Context, opts *PackageOpts) (*Requirements, error) {
   942  	if ld.requirements != nil {
   943  		return ld.requirements, nil
   944  	}
   945  
   946  	Init(ld)
   947  	var workFile *modfile.WorkFile
   948  	if ld.inWorkspaceMode() {
   949  		var err error
   950  		workFile, ld.modRoots, err = LoadWorkFile(ld.workFilePath)
   951  		if err != nil {
   952  			return nil, err
   953  		}
   954  		for _, modRoot := range ld.modRoots {
   955  			sumFile := strings.TrimSuffix(modFilePath(modRoot), ".mod") + ".sum"
   956  			ld.Fetcher().AddWorkspaceGoSumFile(sumFile)
   957  		}
   958  		ld.Fetcher().SetGoSumFile(ld.workFilePath + ".sum")
   959  	} else if len(ld.modRoots) == 0 {
   960  		// We're in module mode, but not inside a module.
   961  		//
   962  		// Commands like 'go build', 'go run', 'go list' have no go.mod file to
   963  		// read or write. They would need to find and download the latest versions
   964  		// of a potentially large number of modules with no way to save version
   965  		// information. We can succeed slowly (but not reproducibly), but that's
   966  		// not usually a good experience.
   967  		//
   968  		// Instead, we forbid resolving import paths to modules other than std and
   969  		// cmd. Users may still build packages specified with .go files on the
   970  		// command line, but they'll see an error if those files import anything
   971  		// outside std.
   972  		//
   973  		// This can be overridden by calling AllowMissingModuleImports.
   974  		// For example, 'go get' does this, since it is expected to resolve paths.
   975  		//
   976  		// See golang.org/issue/32027.
   977  	} else {
   978  		ld.Fetcher().SetGoSumFile(strings.TrimSuffix(modFilePath(ld.modRoots[0]), ".mod") + ".sum")
   979  	}
   980  	if len(ld.modRoots) == 0 {
   981  		// TODO(#49228): Instead of creating a fake module with an empty modroot,
   982  		// make MainModules.Len() == 0 mean that we're in module mode but not inside
   983  		// any module.
   984  		mainModule := module.Version{Path: "command-line-arguments"}
   985  		ld.MainModules = makeMainModules(ld, []module.Version{mainModule}, []string{""}, []*modfile.File{nil}, []*modFileIndex{nil}, nil)
   986  		var (
   987  			goVersion string
   988  			pruning   modPruning
   989  			roots     []module.Version
   990  			direct    = map[string]bool{"go": true}
   991  		)
   992  		if ld.inWorkspaceMode() {
   993  			// Since we are in a workspace, the Go version for the synthetic
   994  			// "command-line-arguments" module must not exceed the Go version
   995  			// for the workspace.
   996  			goVersion = ld.MainModules.GoVersion(ld)
   997  			pruning = workspace
   998  			roots = []module.Version{
   999  				mainModule,
  1000  				{Path: "go", Version: goVersion},
  1001  				{Path: "toolchain", Version: gover.LocalToolchain()},
  1002  			}
  1003  		} else {
  1004  			goVersion = gover.Local()
  1005  			pruning = pruningForGoVersion(goVersion)
  1006  			roots = []module.Version{
  1007  				{Path: "go", Version: goVersion},
  1008  				{Path: "toolchain", Version: gover.LocalToolchain()},
  1009  			}
  1010  		}
  1011  		rawGoVersion.Store(mainModule, goVersion)
  1012  		ld.requirements = newRequirements(ld, pruning, roots, direct)
  1013  		if cfg.BuildMod == "vendor" {
  1014  			// For issue 56536: Some users may have GOFLAGS=-mod=vendor set.
  1015  			// Make sure it behaves as though the fake module is vendored
  1016  			// with no dependencies.
  1017  			ld.requirements.initVendor(ld, nil)
  1018  		}
  1019  		return ld.requirements, nil
  1020  	}
  1021  
  1022  	var modFiles []*modfile.File
  1023  	var mainModules []module.Version
  1024  	var indices []*modFileIndex
  1025  	var errs []error
  1026  	for _, modroot := range ld.modRoots {
  1027  		gomod := modFilePath(modroot)
  1028  		var fixed bool
  1029  		data, f, err := ReadModFile(gomod, fixVersion(ld, ctx, &fixed))
  1030  		if err != nil {
  1031  			if ld.inWorkspaceMode() {
  1032  				if tooNew, ok := err.(*gover.TooNewError); ok && !strings.HasPrefix(cfg.CmdName, "work ") {
  1033  					// Switching to a newer toolchain won't help - the go.work has the wrong version.
  1034  					// Report this more specific error, unless we are a command like 'go work use'
  1035  					// or 'go work sync', which will fix the problem after the caller sees the TooNewError
  1036  					// and switches to a newer toolchain.
  1037  					err = errWorkTooOld(gomod, workFile, tooNew.GoVersion)
  1038  				} else {
  1039  					err = fmt.Errorf("cannot load module %s listed in go.work file: %w",
  1040  						base.ShortPath(filepath.Dir(gomod)), base.ShortPathError(err))
  1041  				}
  1042  			}
  1043  			errs = append(errs, err)
  1044  			continue
  1045  		}
  1046  		if ld.inWorkspaceMode() && !strings.HasPrefix(cfg.CmdName, "work ") {
  1047  			// Refuse to use workspace if its go version is too old.
  1048  			// Disable this check if we are a workspace command like work use or work sync,
  1049  			// which will fix the problem.
  1050  			mv := gover.FromGoMod(f)
  1051  			wv := gover.FromGoWork(workFile)
  1052  			if gover.Compare(mv, wv) > 0 && gover.Compare(mv, gover.GoStrictVersion) >= 0 {
  1053  				errs = append(errs, errWorkTooOld(gomod, workFile, mv))
  1054  				continue
  1055  			}
  1056  		}
  1057  
  1058  		if !ld.inWorkspaceMode() {
  1059  			ok := true
  1060  			for _, g := range f.Godebug {
  1061  				if err := CheckGodebug("godebug", g.Key, g.Value); err != nil {
  1062  					errs = append(errs, fmt.Errorf("error loading go.mod:\n%s:%d: %v", base.ShortPath(gomod), g.Syntax.Start.Line, err))
  1063  					ok = false
  1064  				}
  1065  			}
  1066  			if !ok {
  1067  				continue
  1068  			}
  1069  		}
  1070  
  1071  		modFiles = append(modFiles, f)
  1072  		mainModule := f.Module.Mod
  1073  		mainModules = append(mainModules, mainModule)
  1074  		indices = append(indices, indexModFile(data, f, mainModule, fixed))
  1075  
  1076  		if err := module.CheckImportPath(f.Module.Mod.Path); err != nil {
  1077  			if pathErr, ok := err.(*module.InvalidPathError); ok {
  1078  				pathErr.Kind = "module"
  1079  			}
  1080  			errs = append(errs, err)
  1081  		}
  1082  	}
  1083  	if len(errs) > 0 {
  1084  		return nil, errors.Join(errs...)
  1085  	}
  1086  
  1087  	ld.MainModules = makeMainModules(ld, mainModules, ld.modRoots, modFiles, indices, workFile)
  1088  	setDefaultBuildMod(ld) // possibly enable automatic vendoring
  1089  	rs := requirementsFromModFiles(ld, ctx, workFile, modFiles, opts)
  1090  
  1091  	if cfg.BuildMod == "vendor" {
  1092  		readVendorList(VendorDir(ld))
  1093  		versions := ld.MainModules.Versions()
  1094  		indexes := make([]*modFileIndex, 0, len(versions))
  1095  		modFiles := make([]*modfile.File, 0, len(versions))
  1096  		modRoots := make([]string, 0, len(versions))
  1097  		for _, m := range versions {
  1098  			indexes = append(indexes, ld.MainModules.Index(m))
  1099  			modFiles = append(modFiles, ld.MainModules.ModFile(m))
  1100  			modRoots = append(modRoots, ld.MainModules.ModRoot(m))
  1101  		}
  1102  		checkVendorConsistency(ld, indexes, modFiles, modRoots)
  1103  		rs.initVendor(ld, vendorList)
  1104  	}
  1105  
  1106  	if ld.inWorkspaceMode() {
  1107  		// We don't need to update the mod file so return early.
  1108  		ld.requirements = rs
  1109  		return rs, nil
  1110  	}
  1111  
  1112  	mainModule := ld.MainModules.mustGetSingleMainModule(ld)
  1113  
  1114  	if rs.hasRedundantRoot(ld) {
  1115  		// If any module path appears more than once in the roots, we know that the
  1116  		// go.mod file needs to be updated even though we have not yet loaded any
  1117  		// transitive dependencies.
  1118  		var err error
  1119  		rs, err = updateRoots(ld, ctx, rs.direct, rs, nil, nil, false)
  1120  		if err != nil {
  1121  			return nil, err
  1122  		}
  1123  	}
  1124  
  1125  	if ld.MainModules.Index(mainModule).goVersion == "" && rs.pruning != workspace {
  1126  		// TODO(#45551): Do something more principled instead of checking
  1127  		// cfg.CmdName directly here.
  1128  		if cfg.BuildMod == "mod" && cfg.CmdName != "mod graph" && cfg.CmdName != "mod why" {
  1129  			// go line is missing from go.mod; add one there and add to derived requirements.
  1130  			v := gover.Local()
  1131  			if opts != nil && opts.TidyGoVersion != "" {
  1132  				v = opts.TidyGoVersion
  1133  			}
  1134  			addGoStmt(ld.MainModules.ModFile(mainModule), mainModule, v)
  1135  			rs = overrideRoots(ld, ctx, rs, []module.Version{{Path: "go", Version: v}})
  1136  
  1137  			// We need to add a 'go' version to the go.mod file, but we must assume
  1138  			// that its existing contents match something between Go 1.11 and 1.16.
  1139  			// Go 1.11 through 1.16 do not support graph pruning, but the latest Go
  1140  			// version uses a pruned module graph — so we need to convert the
  1141  			// requirements to support pruning.
  1142  			if gover.Compare(v, gover.ExplicitIndirectVersion) >= 0 {
  1143  				var err error
  1144  				rs, err = convertPruning(ld, ctx, rs, pruned)
  1145  				if err != nil {
  1146  					return nil, err
  1147  				}
  1148  			}
  1149  		} else {
  1150  			rawGoVersion.Store(mainModule, gover.DefaultGoModVersion)
  1151  		}
  1152  	}
  1153  
  1154  	ld.requirements = rs
  1155  	return ld.requirements, nil
  1156  }
  1157  
  1158  func errWorkTooOld(gomod string, wf *modfile.WorkFile, goVers string) error {
  1159  	verb := "lists"
  1160  	if wf == nil || wf.Go == nil {
  1161  		// A go.work file implicitly requires go1.18
  1162  		// even when it doesn't list any version.
  1163  		verb = "implicitly requires"
  1164  	}
  1165  	return fmt.Errorf("module %s listed in go.work file requires go >= %s, but go.work %s go %s; to download and use go %s:\n\tgo work use",
  1166  		base.ShortPath(filepath.Dir(gomod)), goVers, verb, gover.FromGoWork(wf), goVers)
  1167  }
  1168  
  1169  // CheckReservedModulePath checks whether the module path is a reserved module path
  1170  // that can't be used for a user's module.
  1171  func CheckReservedModulePath(path string) error {
  1172  	if gover.IsToolchain(path) {
  1173  		return errors.New("module path is reserved")
  1174  	}
  1175  
  1176  	return nil
  1177  }
  1178  
  1179  // CreateModFile initializes a new module by creating a go.mod file.
  1180  //
  1181  // If modPath is empty, CreateModFile will attempt to infer the path from the
  1182  // directory location within GOPATH.
  1183  //
  1184  // If a vendoring configuration file is present, CreateModFile will attempt to
  1185  // translate it to go.mod directives. The resulting build list may not be
  1186  // exactly the same as in the legacy configuration (for example, we can't get
  1187  // packages at multiple versions from the same module).
  1188  func CreateModFile(ld *Loader, ctx context.Context, modPath string) {
  1189  	modRoot := base.Cwd()
  1190  	ld.modRoots = []string{modRoot}
  1191  	Init(ld)
  1192  	modFilePath := modFilePath(modRoot)
  1193  	if _, err := fsys.Stat(modFilePath); err == nil {
  1194  		base.Fatalf("go: %s already exists", modFilePath)
  1195  	}
  1196  
  1197  	if modPath == "" {
  1198  		var err error
  1199  		modPath, err = findModulePath(modRoot)
  1200  		if err != nil {
  1201  			base.Fatal(err)
  1202  		}
  1203  	}
  1204  	checkModulePath(modPath)
  1205  
  1206  	fmt.Fprintf(os.Stderr, "go: creating new go.mod: module %s\n", modPath)
  1207  	modFile := new(modfile.File)
  1208  	modFile.AddModuleStmt(modPath)
  1209  	ld.MainModules = makeMainModules(ld, []module.Version{modFile.Module.Mod}, []string{modRoot}, []*modfile.File{modFile}, []*modFileIndex{nil}, nil)
  1210  	addGoStmt(modFile, modFile.Module.Mod, gover.Local()) // Add the go directive before converted module requirements.
  1211  
  1212  	rs := requirementsFromModFiles(ld, ctx, nil, []*modfile.File{modFile}, nil)
  1213  	rs, err := updateRoots(ld, ctx, rs.direct, rs, nil, nil, false)
  1214  	if err != nil {
  1215  		base.Fatal(err)
  1216  	}
  1217  	ld.requirements = rs
  1218  	if err := commitRequirements(ld, ctx, WriteOpts{}); err != nil {
  1219  		base.Fatal(err)
  1220  	}
  1221  
  1222  	// Suggest running 'go mod tidy' unless the project is empty. Even if we
  1223  	// imported all the correct requirements above, we're probably missing
  1224  	// some sums, so the next build command in -mod=readonly will likely fail.
  1225  	//
  1226  	// We look for non-hidden .go files or subdirectories to determine whether
  1227  	// this is an existing project. Walking the tree for packages would be more
  1228  	// accurate, but could take much longer.
  1229  	empty := true
  1230  	files, _ := os.ReadDir(modRoot)
  1231  	for _, f := range files {
  1232  		name := f.Name()
  1233  		if strings.HasPrefix(name, ".") || strings.HasPrefix(name, "_") {
  1234  			continue
  1235  		}
  1236  		if strings.HasSuffix(name, ".go") || f.IsDir() {
  1237  			empty = false
  1238  			break
  1239  		}
  1240  	}
  1241  	if !empty {
  1242  		fmt.Fprintf(os.Stderr, "go: to add module requirements and sums:\n\tgo mod tidy\n")
  1243  	}
  1244  }
  1245  
  1246  func checkModulePath(modPath string) {
  1247  	if err := module.CheckImportPath(modPath); err != nil {
  1248  		if pathErr, ok := err.(*module.InvalidPathError); ok {
  1249  			pathErr.Kind = "module"
  1250  			// Same as build.IsLocalPath()
  1251  			if pathErr.Path == "." || pathErr.Path == ".." ||
  1252  				strings.HasPrefix(pathErr.Path, "./") || strings.HasPrefix(pathErr.Path, "../") {
  1253  				pathErr.Err = errors.New("is a local import path")
  1254  			}
  1255  		}
  1256  		base.Fatal(err)
  1257  	}
  1258  	if err := CheckReservedModulePath(modPath); err != nil {
  1259  		base.Fatalf(`go: invalid module path %q: `, modPath)
  1260  	}
  1261  	if _, _, ok := module.SplitPathVersion(modPath); !ok {
  1262  		if strings.HasPrefix(modPath, "gopkg.in/") {
  1263  			invalidMajorVersionMsg := fmt.Errorf("module paths beginning with gopkg.in/ must always have a major version suffix in the form of .vN:\n\tgo mod init %s", suggestGopkgIn(modPath))
  1264  			base.Fatalf(`go: invalid module path "%v": %v`, modPath, invalidMajorVersionMsg)
  1265  		}
  1266  		invalidMajorVersionMsg := fmt.Errorf("major version suffixes must be in the form of /vN and are only allowed for v2 or later:\n\tgo mod init %s", suggestModulePath(modPath))
  1267  		base.Fatalf(`go: invalid module path "%v": %v`, modPath, invalidMajorVersionMsg)
  1268  	}
  1269  }
  1270  
  1271  // fixVersion returns a modfile.VersionFixer implemented using the Query function.
  1272  //
  1273  // It resolves commit hashes and branch names to versions,
  1274  // canonicalizes versions that appeared in early vgo drafts,
  1275  // and does nothing for versions that already appear to be canonical.
  1276  //
  1277  // The VersionFixer sets 'fixed' if it ever returns a non-canonical version.
  1278  func fixVersion(ld *Loader, ctx context.Context, fixed *bool) modfile.VersionFixer {
  1279  	return func(path, vers string) (resolved string, err error) {
  1280  		defer func() {
  1281  			if err == nil && resolved != vers {
  1282  				*fixed = true
  1283  			}
  1284  		}()
  1285  
  1286  		// Special case: remove the old -gopkgin- hack.
  1287  		if strings.HasPrefix(path, "gopkg.in/") && strings.Contains(vers, "-gopkgin-") {
  1288  			vers = vers[strings.Index(vers, "-gopkgin-")+len("-gopkgin-"):]
  1289  		}
  1290  
  1291  		// fixVersion is called speculatively on every
  1292  		// module, version pair from every go.mod file.
  1293  		// Avoid the query if it looks OK.
  1294  		_, pathMajor, ok := module.SplitPathVersion(path)
  1295  		if !ok {
  1296  			return "", &module.ModuleError{
  1297  				Path: path,
  1298  				Err: &module.InvalidVersionError{
  1299  					Version: vers,
  1300  					Err:     fmt.Errorf("malformed module path %q", path),
  1301  				},
  1302  			}
  1303  		}
  1304  		if vers != "" && module.CanonicalVersion(vers) == vers {
  1305  			if err := module.CheckPathMajor(vers, pathMajor); err != nil {
  1306  				return "", module.VersionError(module.Version{Path: path, Version: vers}, err)
  1307  			}
  1308  			return vers, nil
  1309  		}
  1310  
  1311  		info, err := Query(ld, ctx, path, vers, "", nil)
  1312  		if err != nil {
  1313  			return "", err
  1314  		}
  1315  		return info.Version, nil
  1316  	}
  1317  }
  1318  
  1319  // AllowMissingModuleImports allows import paths to be resolved to modules
  1320  // when there is no module root. Normally, this is forbidden because it's slow
  1321  // and there's no way to make the result reproducible, but some commands
  1322  // like 'go get' are expected to do this.
  1323  //
  1324  // This function affects the default cfg.BuildMod when outside of a module,
  1325  // so it can only be called prior to Init.
  1326  func (ld *Loader) AllowMissingModuleImports() {
  1327  	if ld.initialized {
  1328  		panic("AllowMissingModuleImports after Init")
  1329  	}
  1330  	ld.allowMissingModuleImports = true
  1331  }
  1332  
  1333  // makeMainModules creates a MainModuleSet and associated variables according to
  1334  // the given main modules.
  1335  func makeMainModules(ld *Loader, ms []module.Version, rootDirs []string, modFiles []*modfile.File, indices []*modFileIndex, workFile *modfile.WorkFile) *MainModuleSet {
  1336  	for _, m := range ms {
  1337  		if m.Version != "" {
  1338  			panic("mainModulesCalled with module.Version with non empty Version field: " + fmt.Sprintf("%#v", m))
  1339  		}
  1340  	}
  1341  	modRootContainingCWD := findModuleRoot(base.Cwd())
  1342  	mainModules := &MainModuleSet{
  1343  		versions:        slices.Clip(ms),
  1344  		inGorootSrc:     map[module.Version]bool{},
  1345  		pathPrefix:      map[module.Version]string{},
  1346  		modRoot:         map[module.Version]string{},
  1347  		modFiles:        map[module.Version]*modfile.File{},
  1348  		indices:         map[module.Version]*modFileIndex{},
  1349  		highestReplaced: map[string]string{},
  1350  		tools:           map[string]bool{},
  1351  		workFile:        workFile,
  1352  	}
  1353  	var workFileReplaces []*modfile.Replace
  1354  	if workFile != nil {
  1355  		workFileReplaces = workFile.Replace
  1356  		mainModules.workFileReplaceMap = toReplaceMap(workFile.Replace)
  1357  	}
  1358  	mainModulePaths := make(map[string]bool)
  1359  	for _, m := range ms {
  1360  		if mainModulePaths[m.Path] {
  1361  			base.Errorf("go: module %s appears multiple times in workspace", m.Path)
  1362  		}
  1363  		mainModulePaths[m.Path] = true
  1364  	}
  1365  	replacedByWorkFile := make(map[string]bool)
  1366  	replacements := make(map[module.Version]module.Version)
  1367  	for _, r := range workFileReplaces {
  1368  		if mainModulePaths[r.Old.Path] && r.Old.Version == "" {
  1369  			base.Errorf("go: workspace module %v is replaced at all versions in the go.work file. To fix, remove the replacement from the go.work file or specify the version at which to replace the module.", r.Old.Path)
  1370  		}
  1371  		replacedByWorkFile[r.Old.Path] = true
  1372  		v, ok := mainModules.highestReplaced[r.Old.Path]
  1373  		if !ok || gover.ModCompare(r.Old.Path, r.Old.Version, v) > 0 {
  1374  			mainModules.highestReplaced[r.Old.Path] = r.Old.Version
  1375  		}
  1376  		replacements[r.Old] = r.New
  1377  	}
  1378  	for i, m := range ms {
  1379  		mainModules.pathPrefix[m] = m.Path
  1380  		mainModules.modRoot[m] = rootDirs[i]
  1381  		mainModules.modFiles[m] = modFiles[i]
  1382  		mainModules.indices[m] = indices[i]
  1383  
  1384  		if mainModules.modRoot[m] == modRootContainingCWD {
  1385  			mainModules.modContainingCWD = m
  1386  		}
  1387  
  1388  		if rel := search.InDir(rootDirs[i], cfg.GOROOTsrc); rel != "" {
  1389  			mainModules.inGorootSrc[m] = true
  1390  			if m.Path == "std" {
  1391  				// The "std" module in GOROOT/src is the Go standard library. Unlike other
  1392  				// modules, the packages in the "std" module have no import-path prefix.
  1393  				//
  1394  				// Modules named "std" outside of GOROOT/src do not receive this special
  1395  				// treatment, so it is possible to run 'go test .' in other GOROOTs to
  1396  				// test individual packages using a combination of the modified package
  1397  				// and the ordinary standard library.
  1398  				// (See https://golang.org/issue/30756.)
  1399  				mainModules.pathPrefix[m] = ""
  1400  			}
  1401  		}
  1402  
  1403  		if modFiles[i] != nil {
  1404  			curModuleReplaces := make(map[module.Version]bool)
  1405  			for _, r := range modFiles[i].Replace {
  1406  				if replacedByWorkFile[r.Old.Path] {
  1407  					continue
  1408  				}
  1409  				var newV module.Version = r.New
  1410  				if WorkFilePath(ld) != "" && newV.Version == "" && !filepath.IsAbs(newV.Path) {
  1411  					// Since we are in a workspace, we may be loading replacements from
  1412  					// multiple go.mod files. Relative paths in those replacement are
  1413  					// relative to the go.mod file, not the workspace, so the same string
  1414  					// may refer to two different paths and different strings may refer to
  1415  					// the same path. Convert them all to be absolute instead.
  1416  					//
  1417  					// (We could do this outside of a workspace too, but it would mean that
  1418  					// replacement paths in error strings needlessly differ from what's in
  1419  					// the go.mod file.)
  1420  					newV.Path = filepath.Join(rootDirs[i], newV.Path)
  1421  				}
  1422  				if prev, ok := replacements[r.Old]; ok && !curModuleReplaces[r.Old] && prev != newV {
  1423  					base.Fatalf("go: conflicting replacements for %v:\n\t%v\n\t%v\nuse \"go work edit -replace %v=[override]\" to resolve", r.Old, prev, newV, r.Old)
  1424  				}
  1425  				curModuleReplaces[r.Old] = true
  1426  				replacements[r.Old] = newV
  1427  
  1428  				v, ok := mainModules.highestReplaced[r.Old.Path]
  1429  				if !ok || gover.ModCompare(r.Old.Path, r.Old.Version, v) > 0 {
  1430  					mainModules.highestReplaced[r.Old.Path] = r.Old.Version
  1431  				}
  1432  			}
  1433  
  1434  			for _, t := range modFiles[i].Tool {
  1435  				if err := module.CheckImportPath(t.Path); err != nil {
  1436  					if e, ok := err.(*module.InvalidPathError); ok {
  1437  						e.Kind = "tool"
  1438  					}
  1439  					base.Fatal(err)
  1440  				}
  1441  
  1442  				mainModules.tools[t.Path] = true
  1443  			}
  1444  		}
  1445  	}
  1446  
  1447  	return mainModules
  1448  }
  1449  
  1450  // requirementsFromModFiles returns the set of non-excluded requirements from
  1451  // the global modFile.
  1452  func requirementsFromModFiles(ld *Loader, ctx context.Context, workFile *modfile.WorkFile, modFiles []*modfile.File, opts *PackageOpts) *Requirements {
  1453  	var roots []module.Version
  1454  	direct := map[string]bool{}
  1455  	var pruning modPruning
  1456  	if ld.inWorkspaceMode() {
  1457  		pruning = workspace
  1458  		roots = make([]module.Version, len(ld.MainModules.Versions()), 2+len(ld.MainModules.Versions()))
  1459  		copy(roots, ld.MainModules.Versions())
  1460  		goVersion := gover.FromGoWork(workFile)
  1461  		var toolchain string
  1462  		if workFile.Toolchain != nil {
  1463  			toolchain = workFile.Toolchain.Name
  1464  		}
  1465  		roots = appendGoAndToolchainRoots(roots, goVersion, toolchain, direct)
  1466  		direct = directRequirements(modFiles)
  1467  	} else {
  1468  		pruning = pruningForGoVersion(ld.MainModules.GoVersion(ld))
  1469  		if len(modFiles) != 1 {
  1470  			panic(fmt.Errorf("requirementsFromModFiles called with %v modfiles outside workspace mode", len(modFiles)))
  1471  		}
  1472  		modFile := modFiles[0]
  1473  		roots, direct = rootsFromModFile(ld, ld.MainModules.mustGetSingleMainModule(ld), modFile, withToolchainRoot)
  1474  	}
  1475  
  1476  	gover.ModSort(roots)
  1477  	rs := newRequirements(ld, pruning, roots, direct)
  1478  	return rs
  1479  }
  1480  
  1481  type addToolchainRoot bool
  1482  
  1483  const (
  1484  	omitToolchainRoot addToolchainRoot = false
  1485  	withToolchainRoot                  = true
  1486  )
  1487  
  1488  func directRequirements(modFiles []*modfile.File) map[string]bool {
  1489  	direct := make(map[string]bool)
  1490  	for _, modFile := range modFiles {
  1491  		for _, r := range modFile.Require {
  1492  			if !r.Indirect {
  1493  				direct[r.Mod.Path] = true
  1494  			}
  1495  		}
  1496  	}
  1497  	return direct
  1498  }
  1499  
  1500  func rootsFromModFile(ld *Loader, m module.Version, modFile *modfile.File, addToolchainRoot addToolchainRoot) (roots []module.Version, direct map[string]bool) {
  1501  	direct = make(map[string]bool)
  1502  	padding := 2 // Add padding for the toolchain and go version, added upon return.
  1503  	if !addToolchainRoot {
  1504  		padding = 1
  1505  	}
  1506  	roots = make([]module.Version, 0, padding+len(modFile.Require))
  1507  	for _, r := range modFile.Require {
  1508  		if index := ld.MainModules.Index(m); index != nil && index.exclude[r.Mod] {
  1509  			if cfg.BuildMod == "mod" {
  1510  				fmt.Fprintf(os.Stderr, "go: dropping requirement on excluded version %s %s\n", r.Mod.Path, r.Mod.Version)
  1511  			} else {
  1512  				fmt.Fprintf(os.Stderr, "go: ignoring requirement on excluded version %s %s\n", r.Mod.Path, r.Mod.Version)
  1513  			}
  1514  			continue
  1515  		}
  1516  
  1517  		roots = append(roots, r.Mod)
  1518  		if !r.Indirect {
  1519  			direct[r.Mod.Path] = true
  1520  		}
  1521  	}
  1522  	goVersion := gover.FromGoMod(modFile)
  1523  	var toolchain string
  1524  	if addToolchainRoot && modFile.Toolchain != nil {
  1525  		toolchain = modFile.Toolchain.Name
  1526  	}
  1527  	roots = appendGoAndToolchainRoots(roots, goVersion, toolchain, direct)
  1528  	return roots, direct
  1529  }
  1530  
  1531  func appendGoAndToolchainRoots(roots []module.Version, goVersion, toolchain string, direct map[string]bool) []module.Version {
  1532  	// Add explicit go and toolchain versions, inferring as needed.
  1533  	roots = append(roots, module.Version{Path: "go", Version: goVersion})
  1534  	direct["go"] = true // Every module directly uses the language and runtime.
  1535  
  1536  	if toolchain != "" {
  1537  		roots = append(roots, module.Version{Path: "toolchain", Version: toolchain})
  1538  		// Leave the toolchain as indirect: nothing in the user's module directly
  1539  		// imports a package from the toolchain, and (like an indirect dependency in
  1540  		// a module without graph pruning) we may remove the toolchain line
  1541  		// automatically if the 'go' version is changed so that it implies the exact
  1542  		// same toolchain.
  1543  	}
  1544  	return roots
  1545  }
  1546  
  1547  // setDefaultBuildMod sets a default value for cfg.BuildMod if the -mod flag
  1548  // wasn't provided. setDefaultBuildMod may be called multiple times.
  1549  func setDefaultBuildMod(ld *Loader) {
  1550  	if cfg.BuildModExplicit {
  1551  		if ld.inWorkspaceMode() && cfg.BuildMod != "readonly" && cfg.BuildMod != "vendor" {
  1552  			switch cfg.CmdName {
  1553  			case "work sync", "mod graph", "mod verify", "mod why":
  1554  				// These commands run with BuildMod set to mod, but they don't take the
  1555  				// -mod flag, so we should never get here.
  1556  				panic("in workspace mode and -mod was set explicitly, but command doesn't support setting -mod")
  1557  			default:
  1558  				base.Fatalf("go: -mod may only be set to readonly or vendor when in workspace mode, but it is set to %q"+
  1559  					"\n\tRemove the -mod flag to use the default readonly value, "+
  1560  					"\n\tor set GOWORK=off to disable workspace mode.", cfg.BuildMod)
  1561  			}
  1562  		}
  1563  		// Don't override an explicit '-mod=' argument.
  1564  		return
  1565  	}
  1566  
  1567  	// TODO(#40775): commands should pass in the module mode as an option
  1568  	// to modload functions instead of relying on an implicit setting
  1569  	// based on command name.
  1570  	switch cfg.CmdName {
  1571  	case "get", "mod download", "mod init", "mod tidy", "work sync":
  1572  		// These commands are intended to update go.mod and go.sum.
  1573  		cfg.BuildMod = "mod"
  1574  		return
  1575  	case "mod graph", "mod verify", "mod why":
  1576  		// These commands should not update go.mod or go.sum, but they should be
  1577  		// able to fetch modules not in go.sum and should not report errors if
  1578  		// go.mod is inconsistent. They're useful for debugging, and they need
  1579  		// to work in buggy situations.
  1580  		cfg.BuildMod = "mod"
  1581  		return
  1582  	case "mod vendor", "work vendor":
  1583  		cfg.BuildMod = "readonly"
  1584  		return
  1585  	}
  1586  	if ld.modRoots == nil {
  1587  		if ld.allowMissingModuleImports {
  1588  			cfg.BuildMod = "mod"
  1589  		} else {
  1590  			cfg.BuildMod = "readonly"
  1591  		}
  1592  		return
  1593  	}
  1594  
  1595  	if len(ld.modRoots) >= 1 {
  1596  		var goVersion string
  1597  		var versionSource string
  1598  		if ld.inWorkspaceMode() {
  1599  			versionSource = "go.work"
  1600  			if wfg := ld.MainModules.WorkFile().Go; wfg != nil {
  1601  				goVersion = wfg.Version
  1602  			}
  1603  		} else {
  1604  			versionSource = "go.mod"
  1605  			index := ld.MainModules.GetSingleIndexOrNil(ld)
  1606  			if index != nil {
  1607  				goVersion = index.goVersion
  1608  			}
  1609  		}
  1610  		vendorDir := ""
  1611  		if ld.workFilePath != "" {
  1612  			vendorDir = filepath.Join(filepath.Dir(ld.workFilePath), "vendor")
  1613  		} else {
  1614  			if len(ld.modRoots) != 1 {
  1615  				panic(fmt.Errorf("outside workspace mode, but have %v modRoots", ld.modRoots))
  1616  			}
  1617  			vendorDir = filepath.Join(ld.modRoots[0], "vendor")
  1618  		}
  1619  		if fi, err := fsys.Stat(vendorDir); err == nil && fi.IsDir() {
  1620  			if goVersion != "" {
  1621  				if gover.Compare(goVersion, "1.14") < 0 {
  1622  					// The go version is less than 1.14. Don't set -mod=vendor by default.
  1623  					// Since a vendor directory exists, we should record why we didn't use it.
  1624  					// This message won't normally be shown, but it may appear with import errors.
  1625  					cfg.BuildModReason = fmt.Sprintf("Go version in "+versionSource+" is %s, so vendor directory was not used.", goVersion)
  1626  				} else {
  1627  					vendoredWorkspace, err := modulesTextIsForWorkspace(vendorDir)
  1628  					if err != nil {
  1629  						base.Fatalf("go: reading modules.txt for vendor directory: %v", err)
  1630  					}
  1631  					if vendoredWorkspace != (versionSource == "go.work") {
  1632  						if vendoredWorkspace {
  1633  							cfg.BuildModReason = "Outside workspace mode, but vendor directory is for a workspace."
  1634  						} else {
  1635  							cfg.BuildModReason = "In workspace mode, but vendor directory is not for a workspace"
  1636  						}
  1637  					} else {
  1638  						// The Go version is at least 1.14, a vendor directory exists, and
  1639  						// the modules.txt was generated in the same mode the command is running in.
  1640  						// Set -mod=vendor by default.
  1641  						cfg.BuildMod = "vendor"
  1642  						cfg.BuildModReason = "Go version in " + versionSource + " is at least 1.14 and vendor directory exists."
  1643  						return
  1644  					}
  1645  				}
  1646  			} else {
  1647  				cfg.BuildModReason = fmt.Sprintf("Go version in %s is unspecified, so vendor directory was not used.", versionSource)
  1648  			}
  1649  		}
  1650  	}
  1651  
  1652  	cfg.BuildMod = "readonly"
  1653  }
  1654  
  1655  func modulesTextIsForWorkspace(vendorDir string) (bool, error) {
  1656  	f, err := fsys.Open(filepath.Join(vendorDir, "modules.txt"))
  1657  	if errors.Is(err, os.ErrNotExist) {
  1658  		// Some vendor directories exist that don't contain modules.txt.
  1659  		// This mostly happens when converting to modules.
  1660  		// We want to preserve the behavior that mod=vendor is set (even though
  1661  		// readVendorList does nothing in that case).
  1662  		return false, nil
  1663  	}
  1664  	if err != nil {
  1665  		return false, err
  1666  	}
  1667  	defer f.Close()
  1668  	var buf [512]byte
  1669  	n, err := f.Read(buf[:])
  1670  	if err != nil && err != io.EOF {
  1671  		return false, err
  1672  	}
  1673  	line, _, _ := strings.Cut(string(buf[:n]), "\n")
  1674  	if annotations, ok := strings.CutPrefix(line, "## "); ok {
  1675  		for entry := range strings.SplitSeq(annotations, ";") {
  1676  			entry = strings.TrimSpace(entry)
  1677  			if entry == "workspace" {
  1678  				return true, nil
  1679  			}
  1680  		}
  1681  	}
  1682  	return false, nil
  1683  }
  1684  
  1685  func mustHaveCompleteRequirements(ld *Loader) bool {
  1686  	return cfg.BuildMod != "mod" && !ld.inWorkspaceMode()
  1687  }
  1688  
  1689  // addGoStmt adds a go directive to the go.mod file if it does not already
  1690  // include one. The 'go' version added, if any, is the latest version supported
  1691  // by this toolchain.
  1692  func addGoStmt(modFile *modfile.File, mod module.Version, v string) {
  1693  	if modFile.Go != nil && modFile.Go.Version != "" {
  1694  		return
  1695  	}
  1696  	forceGoStmt(modFile, mod, v)
  1697  }
  1698  
  1699  func forceGoStmt(modFile *modfile.File, mod module.Version, v string) {
  1700  	if err := modFile.AddGoStmt(v); err != nil {
  1701  		base.Fatalf("go: internal error: %v", err)
  1702  	}
  1703  	rawGoVersion.Store(mod, v)
  1704  }
  1705  
  1706  var altConfigs = []string{
  1707  	".git/config",
  1708  }
  1709  
  1710  func findModuleRoot(dir string) (roots string) {
  1711  	if dir == "" {
  1712  		panic("dir not set")
  1713  	}
  1714  	dir = filepath.Clean(dir)
  1715  
  1716  	// Look for enclosing go.mod.
  1717  	for {
  1718  		if fi, err := fsys.Stat(filepath.Join(dir, "go.mod")); err == nil && !fi.IsDir() {
  1719  			return dir
  1720  		}
  1721  		d := filepath.Dir(dir)
  1722  		if d == dir {
  1723  			break
  1724  		}
  1725  		dir = d
  1726  	}
  1727  	return ""
  1728  }
  1729  
  1730  func findWorkspaceFile(dir string) (root string) {
  1731  	if dir == "" {
  1732  		panic("dir not set")
  1733  	}
  1734  	dir = filepath.Clean(dir)
  1735  
  1736  	// Look for enclosing go.mod.
  1737  	for {
  1738  		f := filepath.Join(dir, "go.work")
  1739  		if fi, err := fsys.Stat(f); err == nil && !fi.IsDir() {
  1740  			return f
  1741  		}
  1742  		d := filepath.Dir(dir)
  1743  		if d == dir {
  1744  			break
  1745  		}
  1746  		if d == cfg.GOROOT {
  1747  			// As a special case, don't cross GOROOT to find a go.work file.
  1748  			// The standard library and commands built in go always use the vendored
  1749  			// dependencies, so avoid using a most likely irrelevant go.work file.
  1750  			return ""
  1751  		}
  1752  		dir = d
  1753  	}
  1754  	return ""
  1755  }
  1756  
  1757  func findAltConfig(dir string) (root, name string) {
  1758  	if dir == "" {
  1759  		panic("dir not set")
  1760  	}
  1761  	dir = filepath.Clean(dir)
  1762  	if rel := search.InDir(dir, cfg.BuildContext.GOROOT); rel != "" {
  1763  		// Don't suggest creating a module from $GOROOT/.git/config
  1764  		// or a config file found in any parent of $GOROOT (see #34191).
  1765  		return "", ""
  1766  	}
  1767  	for {
  1768  		for _, name := range altConfigs {
  1769  			if fi, err := fsys.Stat(filepath.Join(dir, name)); err == nil && !fi.IsDir() {
  1770  				return dir, name
  1771  			}
  1772  		}
  1773  		d := filepath.Dir(dir)
  1774  		if d == dir {
  1775  			break
  1776  		}
  1777  		dir = d
  1778  	}
  1779  	return "", ""
  1780  }
  1781  
  1782  func findModulePath(dir string) (string, error) {
  1783  	// TODO(bcmills): once we have located a plausible module path, we should
  1784  	// query version control (if available) to verify that it matches the major
  1785  	// version of the most recent tag.
  1786  	// See https://golang.org/issue/29433, https://golang.org/issue/27009, and
  1787  	// https://golang.org/issue/31549.
  1788  
  1789  	// Cast about for import comments,
  1790  	// first in top-level directory, then in subdirectories.
  1791  	list, _ := os.ReadDir(dir)
  1792  	for _, info := range list {
  1793  		if info.Type().IsRegular() && strings.HasSuffix(info.Name(), ".go") {
  1794  			if com := findImportComment(filepath.Join(dir, info.Name())); com != "" {
  1795  				return com, nil
  1796  			}
  1797  		}
  1798  	}
  1799  	for _, info1 := range list {
  1800  		if info1.IsDir() {
  1801  			files, _ := os.ReadDir(filepath.Join(dir, info1.Name()))
  1802  			for _, info2 := range files {
  1803  				if info2.Type().IsRegular() && strings.HasSuffix(info2.Name(), ".go") {
  1804  					if com := findImportComment(filepath.Join(dir, info1.Name(), info2.Name())); com != "" {
  1805  						return path.Dir(com), nil
  1806  					}
  1807  				}
  1808  			}
  1809  		}
  1810  	}
  1811  
  1812  	// Look for path in GOPATH.
  1813  	var badPathErr error
  1814  	for _, gpdir := range filepath.SplitList(cfg.BuildContext.GOPATH) {
  1815  		if gpdir == "" {
  1816  			continue
  1817  		}
  1818  		if rel := search.InDir(dir, filepath.Join(gpdir, "src")); rel != "" && rel != "." {
  1819  			path := filepath.ToSlash(rel)
  1820  			// gorelease will alert users publishing their modules to fix their paths.
  1821  			if err := module.CheckImportPath(path); err != nil {
  1822  				badPathErr = err
  1823  				break
  1824  			}
  1825  			return path, nil
  1826  		}
  1827  	}
  1828  
  1829  	reason := "outside GOPATH, module path must be specified"
  1830  	if badPathErr != nil {
  1831  		// return a different error message if the module was in GOPATH, but
  1832  		// the module path determined above would be an invalid path.
  1833  		reason = fmt.Sprintf("bad module path inferred from directory in GOPATH: %v", badPathErr)
  1834  	}
  1835  	msg := `cannot determine module path for source directory %s (%s)
  1836  
  1837  Example usage:
  1838  	'go mod init example.com/m' to initialize a v0 or v1 module
  1839  	'go mod init example.com/m/v2' to initialize a v2 module
  1840  
  1841  Run 'go help mod init' for more information.
  1842  `
  1843  	return "", fmt.Errorf(msg, dir, reason)
  1844  }
  1845  
  1846  var importCommentRE = lazyregexp.New(`(?m)^package[ \t]+[^ \t\r\n/]+[ \t]+//[ \t]+import[ \t]+(\"[^"]+\")[ \t]*\r?\n`)
  1847  
  1848  func findImportComment(file string) string {
  1849  	data, err := os.ReadFile(file)
  1850  	if err != nil {
  1851  		return ""
  1852  	}
  1853  	m := importCommentRE.FindSubmatch(data)
  1854  	if m == nil {
  1855  		return ""
  1856  	}
  1857  	path, err := strconv.Unquote(string(m[1]))
  1858  	if err != nil {
  1859  		return ""
  1860  	}
  1861  	return path
  1862  }
  1863  
  1864  // WriteOpts control the behavior of WriteGoMod.
  1865  type WriteOpts struct {
  1866  	DropToolchain     bool // go get toolchain@none
  1867  	ExplicitToolchain bool // go get has set explicit toolchain version
  1868  
  1869  	AddTools  []string // go get -tool example.com/m1
  1870  	DropTools []string // go get -tool example.com/m1@none
  1871  
  1872  	// TODO(bcmills): Make 'go mod tidy' update the go version in the Requirements
  1873  	// instead of writing directly to the modfile.File
  1874  	TidyWroteGo bool // Go.Version field already updated by 'go mod tidy'
  1875  }
  1876  
  1877  // WriteGoMod writes the current build list back to go.mod.
  1878  func WriteGoMod(ld *Loader, ctx context.Context, opts WriteOpts) error {
  1879  	ld.requirements = LoadModFile(ld, ctx)
  1880  	return commitRequirements(ld, ctx, opts)
  1881  }
  1882  
  1883  var errNoChange = errors.New("no update needed")
  1884  
  1885  // UpdateGoModFromReqs returns a modified go.mod file using the current
  1886  // requirements. It does not commit these changes to disk.
  1887  func UpdateGoModFromReqs(ld *Loader, ctx context.Context, opts WriteOpts) (before, after []byte, modFile *modfile.File, err error) {
  1888  	if ld.MainModules.Len() != 1 || ld.MainModules.ModRoot(ld.MainModules.Versions()[0]) == "" {
  1889  		// We aren't in a module, so we don't have anywhere to write a go.mod file.
  1890  		return nil, nil, nil, errNoChange
  1891  	}
  1892  	mainModule := ld.MainModules.mustGetSingleMainModule(ld)
  1893  	modFile = ld.MainModules.ModFile(mainModule)
  1894  	if modFile == nil {
  1895  		// command-line-arguments has no .mod file to write.
  1896  		return nil, nil, nil, errNoChange
  1897  	}
  1898  	before, err = modFile.Format()
  1899  	if err != nil {
  1900  		return nil, nil, nil, err
  1901  	}
  1902  
  1903  	var list []*modfile.Require
  1904  	toolchain := ""
  1905  	goVersion := ""
  1906  	for _, m := range ld.requirements.rootModules {
  1907  		if m.Path == "go" {
  1908  			goVersion = m.Version
  1909  			continue
  1910  		}
  1911  		if m.Path == "toolchain" {
  1912  			toolchain = m.Version
  1913  			continue
  1914  		}
  1915  		list = append(list, &modfile.Require{
  1916  			Mod:      m,
  1917  			Indirect: !ld.requirements.direct[m.Path],
  1918  		})
  1919  	}
  1920  
  1921  	// Update go line.
  1922  	// Every MVS graph we consider should have go as a root,
  1923  	// and toolchain is either implied by the go line or explicitly a root.
  1924  	if goVersion == "" {
  1925  		base.Fatalf("go: internal error: missing go root module in WriteGoMod")
  1926  	}
  1927  	if gover.Compare(goVersion, gover.Local()) > 0 {
  1928  		// We cannot assume that we know how to update a go.mod to a newer version.
  1929  		return nil, nil, nil, &gover.TooNewError{What: "updating go.mod", GoVersion: goVersion}
  1930  	}
  1931  	wroteGo := opts.TidyWroteGo
  1932  	if !wroteGo && modFile.Go == nil || modFile.Go.Version != goVersion {
  1933  		alwaysUpdate := cfg.BuildMod == "mod" || cfg.CmdName == "mod tidy" || cfg.CmdName == "get"
  1934  		if modFile.Go == nil && goVersion == gover.DefaultGoModVersion && !alwaysUpdate {
  1935  			// The go.mod has no go line, the implied default Go version matches
  1936  			// what we've computed for the graph, and we're not in one of the
  1937  			// traditional go.mod-updating programs, so leave it alone.
  1938  		} else {
  1939  			wroteGo = true
  1940  			forceGoStmt(modFile, mainModule, goVersion)
  1941  		}
  1942  	}
  1943  	if toolchain == "" {
  1944  		toolchain = "go" + goVersion
  1945  	}
  1946  
  1947  	toolVers := gover.FromToolchain(toolchain)
  1948  	if opts.DropToolchain || toolchain == "go"+goVersion || (gover.Compare(toolVers, gover.GoStrictVersion) < 0 && !opts.ExplicitToolchain) {
  1949  		// go get toolchain@none or toolchain matches go line or isn't valid; drop it.
  1950  		// TODO(#57001): 'go get' should reject explicit toolchains below GoStrictVersion.
  1951  		modFile.DropToolchainStmt()
  1952  	} else {
  1953  		modFile.AddToolchainStmt(toolchain)
  1954  	}
  1955  
  1956  	for _, path := range opts.AddTools {
  1957  		modFile.AddTool(path)
  1958  	}
  1959  
  1960  	for _, path := range opts.DropTools {
  1961  		modFile.DropTool(path)
  1962  	}
  1963  
  1964  	// Update require blocks.
  1965  	if gover.Compare(goVersion, gover.SeparateIndirectVersion) < 0 {
  1966  		modFile.SetRequire(list)
  1967  	} else {
  1968  		modFile.SetRequireSeparateIndirect(list)
  1969  	}
  1970  	modFile.Cleanup()
  1971  	after, err = modFile.Format()
  1972  	if err != nil {
  1973  		return nil, nil, nil, err
  1974  	}
  1975  	return before, after, modFile, nil
  1976  }
  1977  
  1978  // commitRequirements ensures go.mod and go.sum are up to date with the current
  1979  // requirements.
  1980  //
  1981  // In "mod" mode, commitRequirements writes changes to go.mod and go.sum.
  1982  //
  1983  // In "readonly" and "vendor" modes, commitRequirements returns an error if
  1984  // go.mod or go.sum are out of date in a semantically significant way.
  1985  //
  1986  // In workspace mode, commitRequirements only writes changes to go.work.sum.
  1987  func commitRequirements(ld *Loader, ctx context.Context, opts WriteOpts) (err error) {
  1988  	if ld.inWorkspaceMode() {
  1989  		// go.mod files aren't updated in workspace mode, but we still want to
  1990  		// update the go.work.sum file.
  1991  		return ld.Fetcher().WriteGoSum(ctx, keepSums(ld, ctx, ld.pkgLoader, ld.requirements, addBuildListZipSums), mustHaveCompleteRequirements(ld))
  1992  	}
  1993  	_, updatedGoMod, modFile, err := UpdateGoModFromReqs(ld, ctx, opts)
  1994  	if err != nil {
  1995  		if errors.Is(err, errNoChange) {
  1996  			return nil
  1997  		}
  1998  		return err
  1999  	}
  2000  
  2001  	index := ld.MainModules.GetSingleIndexOrNil(ld)
  2002  	dirty := index.modFileIsDirty(modFile) || len(opts.DropTools) > 0 || len(opts.AddTools) > 0
  2003  	if dirty && cfg.BuildMod != "mod" {
  2004  		// If we're about to fail due to -mod=readonly,
  2005  		// prefer to report a dirty go.mod over a dirty go.sum
  2006  		return errGoModDirty
  2007  	}
  2008  
  2009  	if !dirty && cfg.CmdName != "mod tidy" {
  2010  		// The go.mod file has the same semantic content that it had before
  2011  		// (but not necessarily the same exact bytes).
  2012  		// Don't write go.mod, but write go.sum in case we added or trimmed sums.
  2013  		// 'go mod init' shouldn't write go.sum, since it will be incomplete.
  2014  		if cfg.CmdName != "mod init" {
  2015  			if err := ld.Fetcher().WriteGoSum(ctx, keepSums(ld, ctx, ld.pkgLoader, ld.requirements, addBuildListZipSums), mustHaveCompleteRequirements(ld)); err != nil {
  2016  				return err
  2017  			}
  2018  		}
  2019  		return nil
  2020  	}
  2021  
  2022  	mainModule := ld.MainModules.mustGetSingleMainModule(ld)
  2023  	modFilePath := modFilePath(ld.MainModules.ModRoot(mainModule))
  2024  	if fsys.Replaced(modFilePath) {
  2025  		if dirty {
  2026  			return errors.New("updates to go.mod needed, but go.mod is part of the overlay specified with -overlay")
  2027  		}
  2028  		return nil
  2029  	}
  2030  	defer func() {
  2031  		// At this point we have determined to make the go.mod file on disk equal to new.
  2032  		ld.MainModules.SetIndex(mainModule, indexModFile(updatedGoMod, modFile, mainModule, false))
  2033  
  2034  		// Update go.sum after releasing the side lock and refreshing the index.
  2035  		// 'go mod init' shouldn't write go.sum, since it will be incomplete.
  2036  		if cfg.CmdName != "mod init" {
  2037  			if err == nil {
  2038  				err = ld.Fetcher().WriteGoSum(ctx, keepSums(ld, ctx, ld.pkgLoader, ld.requirements, addBuildListZipSums), mustHaveCompleteRequirements(ld))
  2039  			}
  2040  		}
  2041  	}()
  2042  
  2043  	// Make a best-effort attempt to acquire the side lock, only to exclude
  2044  	// previous versions of the 'go' command from making simultaneous edits.
  2045  	if unlock, err := modfetch.SideLock(ctx); err == nil {
  2046  		defer unlock()
  2047  	}
  2048  
  2049  	err = lockedfile.Transform(modFilePath, func(old []byte) ([]byte, error) {
  2050  		if bytes.Equal(old, updatedGoMod) {
  2051  			// The go.mod file is already equal to new, possibly as the result of some
  2052  			// other process.
  2053  			return nil, errNoChange
  2054  		}
  2055  
  2056  		if index != nil && !bytes.Equal(old, index.data) {
  2057  			// The contents of the go.mod file have changed. In theory we could add all
  2058  			// of the new modules to the build list, recompute, and check whether any
  2059  			// module in *our* build list got bumped to a different version, but that's
  2060  			// a lot of work for marginal benefit. Instead, fail the command: if users
  2061  			// want to run concurrent commands, they need to start with a complete,
  2062  			// consistent module definition.
  2063  			return nil, fmt.Errorf("existing contents have changed since last read")
  2064  		}
  2065  
  2066  		return updatedGoMod, nil
  2067  	})
  2068  
  2069  	if err != nil && err != errNoChange {
  2070  		return fmt.Errorf("updating go.mod: %w", err)
  2071  	}
  2072  	return nil
  2073  }
  2074  
  2075  // keepSums returns the set of modules (and go.mod file entries) for which
  2076  // checksums would be needed in order to reload the same set of packages
  2077  // loaded by the most recent call to LoadPackages or ImportFromFiles,
  2078  // including any go.mod files needed to reconstruct the MVS result
  2079  // or identify go versions,
  2080  // in addition to the checksums for every module in keepMods.
  2081  func keepSums(ld *Loader, ctx context.Context, pld *packageLoader, rs *Requirements, which whichSums) map[module.Version]bool {
  2082  	// Every module in the full module graph contributes its requirements,
  2083  	// so in order to ensure that the build list itself is reproducible,
  2084  	// we need sums for every go.mod in the graph (regardless of whether
  2085  	// that version is selected).
  2086  	keep := make(map[module.Version]bool)
  2087  
  2088  	// Add entries for modules in the build list with paths that are prefixes of
  2089  	// paths of loaded packages. We need to retain sums for all of these modules —
  2090  	// not just the modules containing the actual packages — in order to rule out
  2091  	// ambiguous import errors the next time we load the package.
  2092  	keepModSumsForZipSums := true
  2093  	if pld == nil {
  2094  		if gover.Compare(ld.MainModules.GoVersion(ld), gover.TidyGoModSumVersion) < 0 && cfg.BuildMod != "mod" {
  2095  			keepModSumsForZipSums = false
  2096  		}
  2097  	} else {
  2098  		keepPkgGoModSums := true
  2099  		if gover.Compare(pld.requirements.GoVersion(ld), gover.TidyGoModSumVersion) < 0 && (pld.Tidy || cfg.BuildMod != "mod") {
  2100  			keepPkgGoModSums = false
  2101  			keepModSumsForZipSums = false
  2102  		}
  2103  		for _, pkg := range pld.pkgs {
  2104  			// We check pkg.mod.Path here instead of pkg.inStd because the
  2105  			// pseudo-package "C" is not in std, but not provided by any module (and
  2106  			// shouldn't force loading the whole module graph).
  2107  			if pkg.testOf != nil || (pkg.mod.Path == "" && pkg.err == nil) || module.CheckImportPath(pkg.path) != nil {
  2108  				continue
  2109  			}
  2110  
  2111  			// We need the checksum for the go.mod file for pkg.mod
  2112  			// so that we know what Go version to use to compile pkg.
  2113  			// However, we didn't do so before Go 1.21, and the bug is relatively
  2114  			// minor, so we maintain the previous (buggy) behavior in 'go mod tidy' to
  2115  			// avoid introducing unnecessary churn.
  2116  			if keepPkgGoModSums {
  2117  				r := resolveReplacement(ld, pkg.mod)
  2118  				keep[modkey(r)] = true
  2119  			}
  2120  
  2121  			if rs.pruning == pruned && pkg.mod.Path != "" {
  2122  				if v, ok := rs.rootSelected(ld, pkg.mod.Path); ok && v == pkg.mod.Version {
  2123  					// pkg was loaded from a root module, and because the main module has
  2124  					// a pruned module graph we do not check non-root modules for
  2125  					// conflicts for packages that can be found in roots. So we only need
  2126  					// the checksums for the root modules that may contain pkg, not all
  2127  					// possible modules.
  2128  					for prefix := pkg.path; prefix != "."; prefix = path.Dir(prefix) {
  2129  						if v, ok := rs.rootSelected(ld, prefix); ok && v != "none" {
  2130  							m := module.Version{Path: prefix, Version: v}
  2131  							r := resolveReplacement(ld, m)
  2132  							keep[r] = true
  2133  						}
  2134  					}
  2135  					continue
  2136  				}
  2137  			}
  2138  
  2139  			mg, _ := rs.Graph(ld, ctx)
  2140  			for prefix := pkg.path; prefix != "."; prefix = path.Dir(prefix) {
  2141  				if v := mg.Selected(prefix); v != "none" {
  2142  					m := module.Version{Path: prefix, Version: v}
  2143  					r := resolveReplacement(ld, m)
  2144  					keep[r] = true
  2145  				}
  2146  			}
  2147  		}
  2148  	}
  2149  
  2150  	if rs.graph.Load() == nil {
  2151  		// We haven't needed to load the module graph so far.
  2152  		// Save sums for the root modules (or their replacements), but don't
  2153  		// incur the cost of loading the graph just to find and retain the sums.
  2154  		for _, m := range rs.rootModules {
  2155  			r := resolveReplacement(ld, m)
  2156  			keep[modkey(r)] = true
  2157  			if which == addBuildListZipSums {
  2158  				keep[r] = true
  2159  			}
  2160  		}
  2161  	} else {
  2162  		mg, _ := rs.Graph(ld, ctx)
  2163  		mg.WalkBreadthFirst(func(m module.Version) {
  2164  			if _, ok := mg.RequiredBy(m); ok {
  2165  				// The requirements from m's go.mod file are present in the module graph,
  2166  				// so they are relevant to the MVS result regardless of whether m was
  2167  				// actually selected.
  2168  				r := resolveReplacement(ld, m)
  2169  				keep[modkey(r)] = true
  2170  			}
  2171  		})
  2172  
  2173  		if which == addBuildListZipSums {
  2174  			for _, m := range mg.BuildList() {
  2175  				r := resolveReplacement(ld, m)
  2176  				if keepModSumsForZipSums {
  2177  					keep[modkey(r)] = true // we need the go version from the go.mod file to do anything useful with the zipfile
  2178  				}
  2179  				keep[r] = true
  2180  			}
  2181  		}
  2182  	}
  2183  
  2184  	return keep
  2185  }
  2186  
  2187  type whichSums int8
  2188  
  2189  const (
  2190  	loadedZipSumsOnly = whichSums(iota)
  2191  	addBuildListZipSums
  2192  )
  2193  
  2194  // modkey returns the module.Version under which the checksum for m's go.mod
  2195  // file is stored in the go.sum file.
  2196  func modkey(m module.Version) module.Version {
  2197  	return module.Version{Path: m.Path, Version: m.Version + "/go.mod"}
  2198  }
  2199  
  2200  func suggestModulePath(path string) string {
  2201  	var m string
  2202  
  2203  	i := len(path)
  2204  	for i > 0 && ('0' <= path[i-1] && path[i-1] <= '9' || path[i-1] == '.') {
  2205  		i--
  2206  	}
  2207  	url := path[:i]
  2208  	url = strings.TrimSuffix(url, "/v")
  2209  	url = strings.TrimSuffix(url, "/")
  2210  
  2211  	f := func(c rune) bool {
  2212  		return c > '9' || c < '0'
  2213  	}
  2214  	s := strings.FieldsFunc(path[i:], f)
  2215  	if len(s) > 0 {
  2216  		m = s[0]
  2217  	}
  2218  	m = strings.TrimLeft(m, "0")
  2219  	if m == "" || m == "1" {
  2220  		return url + "/v2"
  2221  	}
  2222  
  2223  	return url + "/v" + m
  2224  }
  2225  
  2226  func suggestGopkgIn(path string) string {
  2227  	var m string
  2228  	i := len(path)
  2229  	for i > 0 && (('0' <= path[i-1] && path[i-1] <= '9') || (path[i-1] == '.')) {
  2230  		i--
  2231  	}
  2232  	url := path[:i]
  2233  	url = strings.TrimSuffix(url, ".v")
  2234  	url = strings.TrimSuffix(url, "/v")
  2235  	url = strings.TrimSuffix(url, "/")
  2236  
  2237  	f := func(c rune) bool {
  2238  		return c > '9' || c < '0'
  2239  	}
  2240  	s := strings.FieldsFunc(path, f)
  2241  	if len(s) > 0 {
  2242  		m = s[0]
  2243  	}
  2244  
  2245  	m = strings.TrimLeft(m, "0")
  2246  
  2247  	if m == "" {
  2248  		return url + ".v1"
  2249  	}
  2250  	return url + ".v" + m
  2251  }
  2252  
  2253  func CheckGodebug(verb, k, v string) error {
  2254  	if strings.ContainsAny(k, " \t") {
  2255  		return fmt.Errorf("key contains space")
  2256  	}
  2257  	if strings.ContainsAny(v, " \t") {
  2258  		return fmt.Errorf("value contains space")
  2259  	}
  2260  	if strings.ContainsAny(k, ",") {
  2261  		return fmt.Errorf("key contains comma")
  2262  	}
  2263  	if strings.ContainsAny(v, ",") {
  2264  		return fmt.Errorf("value contains comma")
  2265  	}
  2266  	if k == "default" {
  2267  		if !strings.HasPrefix(v, "go") || !gover.IsValid(v[len("go"):]) {
  2268  			return fmt.Errorf("value for default= must be goVERSION")
  2269  		}
  2270  		if gover.Compare(v[len("go"):], gover.Local()) > 0 {
  2271  			return fmt.Errorf("default=%s too new (toolchain is go%s)", v, gover.Local())
  2272  		}
  2273  		return nil
  2274  	}
  2275  	if godebugs.Lookup(k) != nil {
  2276  		return nil
  2277  	}
  2278  	for _, info := range godebugs.Removed {
  2279  		if info.Name == k {
  2280  			return fmt.Errorf("use of removed %s %q, see https://go.dev/doc/godebug#go-1%v", verb, k, info.Removed)
  2281  		}
  2282  	}
  2283  	return fmt.Errorf("unknown %s %q", verb, k)
  2284  }
  2285  

View as plain text