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

View as plain text