Source file src/cmd/go/internal/modload/init.go

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

View as plain text