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

View as plain text