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

View as plain text