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

View as plain text