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