]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/go/internal/modload/init.go
[dev.cmdgo] all: merge master (c2f96e6) into dev.cmdgo
[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         "go/build"
14         "internal/lazyregexp"
15         "os"
16         "path"
17         "path/filepath"
18         "strconv"
19         "strings"
20         "sync"
21
22         "cmd/go/internal/base"
23         "cmd/go/internal/cfg"
24         "cmd/go/internal/fsys"
25         "cmd/go/internal/lockedfile"
26         "cmd/go/internal/modconv"
27         "cmd/go/internal/modfetch"
28         "cmd/go/internal/search"
29
30         "golang.org/x/mod/modfile"
31         "golang.org/x/mod/module"
32         "golang.org/x/mod/semver"
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
49 func TODOWorkspaces(s string) error {
50         return fmt.Errorf("need to support this for workspaces: %s", s)
51 }
52
53 // Variables set in Init.
54 var (
55         initialized bool
56
57         // These are primarily used to initialize the MainModules, and should be
58         // eventually superceded by them but are still used in cases where the module
59         // roots are required but MainModules hasn't been initialized yet. Set to
60         // the modRoots of the main modules.
61         // modRoots != nil implies len(modRoots) > 0
62         modRoots []string
63         gopath   string
64 )
65
66 // Variable set in InitWorkfile
67 var (
68         // Set to the path to the go.work file, or "" if workspace mode is disabled.
69         workFilePath string
70 )
71
72 type MainModuleSet struct {
73         // versions are the module.Version values of each of the main modules.
74         // For each of them, the Path fields are ordinary module paths and the Version
75         // fields are empty strings.
76         versions []module.Version
77
78         // modRoot maps each module in versions to its absolute filesystem path.
79         modRoot map[module.Version]string
80
81         // pathPrefix is the path prefix for packages in the module, without a trailing
82         // slash. For most modules, pathPrefix is just version.Path, but the
83         // standard-library module "std" has an empty prefix.
84         pathPrefix map[module.Version]string
85
86         // inGorootSrc caches whether modRoot is within GOROOT/src.
87         // The "std" module is special within GOROOT/src, but not otherwise.
88         inGorootSrc map[module.Version]bool
89
90         modFiles map[module.Version]*modfile.File
91
92         modContainingCWD module.Version
93
94         indexMu sync.Mutex
95         indices map[module.Version]*modFileIndex
96 }
97
98 func (mms *MainModuleSet) PathPrefix(m module.Version) string {
99         return mms.pathPrefix[m]
100 }
101
102 // Versions returns the module.Version values of each of the main modules.
103 // For each of them, the Path fields are ordinary module paths and the Version
104 // fields are empty strings.
105 // Callers should not modify the returned slice.
106 func (mms *MainModuleSet) Versions() []module.Version {
107         if mms == nil {
108                 return nil
109         }
110         return mms.versions
111 }
112
113 func (mms *MainModuleSet) Contains(path string) bool {
114         if mms == nil {
115                 return false
116         }
117         for _, v := range mms.versions {
118                 if v.Path == path {
119                         return true
120                 }
121         }
122         return false
123 }
124
125 func (mms *MainModuleSet) ModRoot(m module.Version) string {
126         _ = TODOWorkspaces(" Do we need the Init? The original modRoot calls it. Audit callers.")
127         Init()
128         if mms == nil {
129                 return ""
130         }
131         return mms.modRoot[m]
132 }
133
134 func (mms *MainModuleSet) InGorootSrc(m module.Version) bool {
135         if mms == nil {
136                 return false
137         }
138         return mms.inGorootSrc[m]
139 }
140
141 func (mms *MainModuleSet) mustGetSingleMainModule() module.Version {
142         if mms == nil || len(mms.versions) == 0 {
143                 panic("internal error: mustGetSingleMainModule called in context with no main modules")
144         }
145         if len(mms.versions) != 1 {
146                 _ = TODOWorkspaces("Check if we're in workspace mode before returning the below error.")
147                 panic("internal error: mustGetSingleMainModule called in workspace mode")
148         }
149         return mms.versions[0]
150 }
151
152 func (mms *MainModuleSet) GetSingleIndexOrNil() *modFileIndex {
153         if mms == nil {
154                 return nil
155         }
156         if len(mms.versions) == 0 {
157                 return nil
158         }
159         if len(mms.versions) != 1 {
160                 _ = TODOWorkspaces("Check if we're in workspace mode before returning the below error.")
161                 panic("internal error: mustGetSingleMainModule called in workspace mode")
162         }
163         return mms.indices[mms.versions[0]]
164 }
165
166 func (mms *MainModuleSet) Index(m module.Version) *modFileIndex {
167         mms.indexMu.Lock()
168         defer mms.indexMu.Unlock()
169         return mms.indices[m]
170 }
171
172 func (mms *MainModuleSet) SetIndex(m module.Version, index *modFileIndex) {
173         mms.indexMu.Lock()
174         defer mms.indexMu.Unlock()
175         mms.indices[m] = index
176 }
177
178 func (mms *MainModuleSet) ModFile(m module.Version) *modfile.File {
179         return mms.modFiles[m]
180 }
181
182 func (mms *MainModuleSet) Len() int {
183         if mms == nil {
184                 return 0
185         }
186         return len(mms.versions)
187 }
188
189 // ModContainingCWD returns the main module containing the working directory,
190 // or module.Version{} if none of the main modules contain the working
191 // directory.
192 func (mms *MainModuleSet) ModContainingCWD() module.Version {
193         return mms.modContainingCWD
194 }
195
196 var MainModules *MainModuleSet
197
198 type Root int
199
200 const (
201         // AutoRoot is the default for most commands. modload.Init will look for
202         // a go.mod file in the current directory or any parent. If none is found,
203         // modules may be disabled (GO111MODULE=auto) or commands may run in a
204         // limited module mode.
205         AutoRoot Root = iota
206
207         // NoRoot is used for commands that run in module mode and ignore any go.mod
208         // file the current directory or in parent directories.
209         NoRoot
210
211         // NeedRoot is used for commands that must run in module mode and don't
212         // make sense without a main module.
213         NeedRoot
214 )
215
216 // ModFile returns the parsed go.mod file.
217 //
218 // Note that after calling LoadPackages or LoadModGraph,
219 // the require statements in the modfile.File are no longer
220 // the source of truth and will be ignored: edits made directly
221 // will be lost at the next call to WriteGoMod.
222 // To make permanent changes to the require statements
223 // in go.mod, edit it before loading.
224 func ModFile() *modfile.File {
225         Init()
226         modFile := MainModules.ModFile(MainModules.mustGetSingleMainModule())
227         if modFile == nil {
228                 die()
229         }
230         return modFile
231 }
232
233 func BinDir() string {
234         Init()
235         return filepath.Join(gopath, "bin")
236 }
237
238 // InitWorkfile initializes the workFilePath variable for commands that
239 // operate in workspace mode. It should not be called by other commands,
240 // for example 'go mod tidy', that don't operate in workspace mode.
241 func InitWorkfile() {
242         switch cfg.WorkFile {
243         case "off":
244                 workFilePath = ""
245         case "", "auto":
246                 workFilePath = findWorkspaceFile(base.Cwd())
247         default:
248                 workFilePath = cfg.WorkFile
249         }
250 }
251
252 // WorkFilePath returns the path of the go.work file, or "" if not in
253 // workspace mode. WorkFilePath must be called after InitWorkfile.
254 func WorkFilePath() string {
255         return workFilePath
256 }
257
258 // Init determines whether module mode is enabled, locates the root of the
259 // current module (if any), sets environment variables for Git subprocesses, and
260 // configures the cfg, codehost, load, modfetch, and search packages for use
261 // with modules.
262 func Init() {
263         if initialized {
264                 return
265         }
266         initialized = true
267
268         // Keep in sync with WillBeEnabled. We perform extra validation here, and
269         // there are lots of diagnostics and side effects, so we can't use
270         // WillBeEnabled directly.
271         var mustUseModules bool
272         env := cfg.Getenv("GO111MODULE")
273         switch env {
274         default:
275                 base.Fatalf("go: unknown environment setting GO111MODULE=%s", env)
276         case "auto":
277                 mustUseModules = ForceUseModules
278         case "on", "":
279                 mustUseModules = true
280         case "off":
281                 if ForceUseModules {
282                         base.Fatalf("go: modules disabled by GO111MODULE=off; see 'go help modules'")
283                 }
284                 mustUseModules = false
285                 return
286         }
287
288         if err := fsys.Init(base.Cwd()); err != nil {
289                 base.Fatalf("go: %v", err)
290         }
291
292         // Disable any prompting for passwords by Git.
293         // Only has an effect for 2.3.0 or later, but avoiding
294         // the prompt in earlier versions is just too hard.
295         // If user has explicitly set GIT_TERMINAL_PROMPT=1, keep
296         // prompting.
297         // See golang.org/issue/9341 and golang.org/issue/12706.
298         if os.Getenv("GIT_TERMINAL_PROMPT") == "" {
299                 os.Setenv("GIT_TERMINAL_PROMPT", "0")
300         }
301
302         // Disable any ssh connection pooling by Git.
303         // If a Git subprocess forks a child into the background to cache a new connection,
304         // that child keeps stdout/stderr open. After the Git subprocess exits,
305         // os /exec expects to be able to read from the stdout/stderr pipe
306         // until EOF to get all the data that the Git subprocess wrote before exiting.
307         // The EOF doesn't come until the child exits too, because the child
308         // is holding the write end of the pipe.
309         // This is unfortunate, but it has come up at least twice
310         // (see golang.org/issue/13453 and golang.org/issue/16104)
311         // and confuses users when it does.
312         // If the user has explicitly set GIT_SSH or GIT_SSH_COMMAND,
313         // assume they know what they are doing and don't step on it.
314         // But default to turning off ControlMaster.
315         if os.Getenv("GIT_SSH") == "" && os.Getenv("GIT_SSH_COMMAND") == "" {
316                 os.Setenv("GIT_SSH_COMMAND", "ssh -o ControlMaster=no -o BatchMode=yes")
317         }
318
319         if os.Getenv("GCM_INTERACTIVE") == "" {
320                 os.Setenv("GCM_INTERACTIVE", "never")
321         }
322         if modRoots != nil {
323                 // modRoot set before Init was called ("go mod init" does this).
324                 // No need to search for go.mod.
325         } else if RootMode == NoRoot {
326                 if cfg.ModFile != "" && !base.InGOFLAGS("-modfile") {
327                         base.Fatalf("go: -modfile cannot be used with commands that ignore the current module")
328                 }
329                 modRoots = nil
330         } else if inWorkspaceMode() {
331                 // We're in workspace mode.
332         } else {
333                 if modRoot := findModuleRoot(base.Cwd()); modRoot == "" {
334                         if cfg.ModFile != "" {
335                                 base.Fatalf("go: cannot find main module, but -modfile was set.\n\t-modfile cannot be used to set the module root directory.")
336                         }
337                         if RootMode == NeedRoot {
338                                 base.Fatalf("go: %v", ErrNoModRoot)
339                         }
340                         if !mustUseModules {
341                                 // GO111MODULE is 'auto', and we can't find a module root.
342                                 // Stay in GOPATH mode.
343                                 return
344                         }
345                 } else if search.InDir(modRoot, os.TempDir()) == "." {
346                         // If you create /tmp/go.mod for experimenting,
347                         // then any tests that create work directories under /tmp
348                         // will find it and get modules when they're not expecting them.
349                         // It's a bit of a peculiar thing to disallow but quite mysterious
350                         // when it happens. See golang.org/issue/26708.
351                         fmt.Fprintf(os.Stderr, "go: warning: ignoring go.mod in system temp root %v\n", os.TempDir())
352                         if !mustUseModules {
353                                 return
354                         }
355                 } else {
356                         modRoots = []string{modRoot}
357                 }
358         }
359         if cfg.ModFile != "" && !strings.HasSuffix(cfg.ModFile, ".mod") {
360                 base.Fatalf("go: -modfile=%s: file does not have .mod extension", cfg.ModFile)
361         }
362
363         // We're in module mode. Set any global variables that need to be set.
364         cfg.ModulesEnabled = true
365         setDefaultBuildMod()
366         _ = TODOWorkspaces("ensure that buildmod is readonly")
367         list := filepath.SplitList(cfg.BuildContext.GOPATH)
368         if len(list) == 0 || list[0] == "" {
369                 base.Fatalf("missing $GOPATH")
370         }
371         gopath = list[0]
372         if _, err := fsys.Stat(filepath.Join(gopath, "go.mod")); err == nil {
373                 base.Fatalf("$GOPATH/go.mod exists but should not")
374         }
375
376         if inWorkspaceMode() {
377                 _ = TODOWorkspaces("go.work.sum, and also allow modfetch to fall back to individual go.sums")
378                 _ = TODOWorkspaces("replaces")
379                 var err error
380                 modRoots, err = loadWorkFile(workFilePath)
381                 if err != nil {
382                         base.Fatalf("reading go.work: %v", err)
383                 }
384                 modfetch.GoSumFile = workFilePath + ".sum"
385                 // TODO(matloob) should workRoot just be workFile?
386         } else if modRoots == nil {
387                 // We're in module mode, but not inside a module.
388                 //
389                 // Commands like 'go build', 'go run', 'go list' have no go.mod file to
390                 // read or write. They would need to find and download the latest versions
391                 // of a potentially large number of modules with no way to save version
392                 // information. We can succeed slowly (but not reproducibly), but that's
393                 // not usually a good experience.
394                 //
395                 // Instead, we forbid resolving import paths to modules other than std and
396                 // cmd. Users may still build packages specified with .go files on the
397                 // command line, but they'll see an error if those files import anything
398                 // outside std.
399                 //
400                 // This can be overridden by calling AllowMissingModuleImports.
401                 // For example, 'go get' does this, since it is expected to resolve paths.
402                 //
403                 // See golang.org/issue/32027.
404         } else {
405                 modfetch.GoSumFile = strings.TrimSuffix(modFilePath(modRoots[0]), ".mod") + ".sum"
406         }
407 }
408
409 // WillBeEnabled checks whether modules should be enabled but does not
410 // initialize modules by installing hooks. If Init has already been called,
411 // WillBeEnabled returns the same result as Enabled.
412 //
413 // This function is needed to break a cycle. The main package needs to know
414 // whether modules are enabled in order to install the module or GOPATH version
415 // of 'go get', but Init reads the -modfile flag in 'go get', so it shouldn't
416 // be called until the command is installed and flags are parsed. Instead of
417 // calling Init and Enabled, the main package can call this function.
418 func WillBeEnabled() bool {
419         if modRoots != nil || cfg.ModulesEnabled {
420                 // Already enabled.
421                 return true
422         }
423         if initialized {
424                 // Initialized, not enabled.
425                 return false
426         }
427
428         // Keep in sync with Init. Init does extra validation and prints warnings or
429         // exits, so it can't call this function directly.
430         env := cfg.Getenv("GO111MODULE")
431         switch env {
432         case "on", "":
433                 return true
434         case "auto":
435                 break
436         default:
437                 return false
438         }
439
440         if modRoot := findModuleRoot(base.Cwd()); modRoot == "" {
441                 // GO111MODULE is 'auto', and we can't find a module root.
442                 // Stay in GOPATH mode.
443                 return false
444         } else if search.InDir(modRoot, os.TempDir()) == "." {
445                 // If you create /tmp/go.mod for experimenting,
446                 // then any tests that create work directories under /tmp
447                 // will find it and get modules when they're not expecting them.
448                 // It's a bit of a peculiar thing to disallow but quite mysterious
449                 // when it happens. See golang.org/issue/26708.
450                 return false
451         }
452         return true
453 }
454
455 // Enabled reports whether modules are (or must be) enabled.
456 // If modules are enabled but there is no main module, Enabled returns true
457 // and then the first use of module information will call die
458 // (usually through MustModRoot).
459 func Enabled() bool {
460         Init()
461         return modRoots != nil || cfg.ModulesEnabled
462 }
463
464 func VendorDir() string {
465         return filepath.Join(MainModules.ModRoot(MainModules.mustGetSingleMainModule()), "vendor")
466 }
467
468 func inWorkspaceMode() bool {
469         if !initialized {
470                 panic("inWorkspaceMode called before modload.Init called")
471         }
472         return workFilePath != ""
473 }
474
475 // HasModRoot reports whether a main module is present.
476 // HasModRoot may return false even if Enabled returns true: for example, 'get'
477 // does not require a main module.
478 func HasModRoot() bool {
479         Init()
480         return modRoots != nil
481 }
482
483 // MustHaveModRoot checks that a main module or main modules are present,
484 // and calls base.Fatalf if there are no main modules.
485 func MustHaveModRoot() {
486         Init()
487         if !HasModRoot() {
488                 die()
489         }
490 }
491
492 // ModFilePath returns the path that would be used for the go.mod
493 // file, if in module mode. ModFilePath calls base.Fatalf if there is no main
494 // module, even if -modfile is set.
495 func ModFilePath() string {
496         MustHaveModRoot()
497         return modFilePath(findModuleRoot(base.Cwd()))
498 }
499
500 func modFilePath(modRoot string) string {
501         if cfg.ModFile != "" {
502                 return cfg.ModFile
503         }
504         return filepath.Join(modRoot, "go.mod")
505 }
506
507 func die() {
508         if cfg.Getenv("GO111MODULE") == "off" {
509                 base.Fatalf("go: modules disabled by GO111MODULE=off; see 'go help modules'")
510         }
511         if dir, name := findAltConfig(base.Cwd()); dir != "" {
512                 rel, err := filepath.Rel(base.Cwd(), dir)
513                 if err != nil {
514                         rel = dir
515                 }
516                 cdCmd := ""
517                 if rel != "." {
518                         cdCmd = fmt.Sprintf("cd %s && ", rel)
519                 }
520                 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)
521         }
522         base.Fatalf("go: %v", ErrNoModRoot)
523 }
524
525 var ErrNoModRoot = errors.New("go.mod file not found in current directory or any parent directory; see 'go help modules'")
526
527 type goModDirtyError struct{}
528
529 func (goModDirtyError) Error() string {
530         if cfg.BuildModExplicit {
531                 return fmt.Sprintf("updates to go.mod needed, disabled by -mod=%v; to update it:\n\tgo mod tidy", cfg.BuildMod)
532         }
533         if cfg.BuildModReason != "" {
534                 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)
535         }
536         return "updates to go.mod needed; to update it:\n\tgo mod tidy"
537 }
538
539 var errGoModDirty error = goModDirtyError{}
540
541 func loadWorkFile(path string) (modRoots []string, err error) {
542         workDir := filepath.Dir(path)
543         workData, err := lockedfile.Read(path)
544         if err != nil {
545                 return nil, err
546         }
547         wf, err := modfile.ParseWork(path, workData, nil)
548         if err != nil {
549                 return nil, err
550         }
551         seen := map[string]bool{}
552         for _, d := range wf.Directory {
553                 modRoot := d.Path
554                 if !filepath.IsAbs(modRoot) {
555                         modRoot = filepath.Join(workDir, modRoot)
556                 }
557                 if seen[modRoot] {
558                         return nil, fmt.Errorf("path %s appears multiple times in workspace", modRoot)
559                 }
560                 seen[modRoot] = true
561                 modRoots = append(modRoots, modRoot)
562         }
563         return modRoots, nil
564 }
565
566 // LoadModFile sets Target and, if there is a main module, parses the initial
567 // build list from its go.mod file.
568 //
569 // LoadModFile may make changes in memory, like adding a go directive and
570 // ensuring requirements are consistent, and will write those changes back to
571 // disk unless DisallowWriteGoMod is in effect.
572 //
573 // As a side-effect, LoadModFile may change cfg.BuildMod to "vendor" if
574 // -mod wasn't set explicitly and automatic vendoring should be enabled.
575 //
576 // If LoadModFile or CreateModFile has already been called, LoadModFile returns
577 // the existing in-memory requirements (rather than re-reading them from disk).
578 //
579 // LoadModFile checks the roots of the module graph for consistency with each
580 // other, but unlike LoadModGraph does not load the full module graph or check
581 // it for global consistency. Most callers outside of the modload package should
582 // use LoadModGraph instead.
583 func LoadModFile(ctx context.Context) *Requirements {
584         rs, needCommit := loadModFile(ctx)
585         if needCommit {
586                 commitRequirements(ctx, modFileGoVersion(), rs)
587         }
588         return rs
589 }
590
591 // loadModFile is like LoadModFile, but does not implicitly commit the
592 // requirements back to disk after fixing inconsistencies.
593 //
594 // If needCommit is true, after the caller makes any other needed changes to the
595 // returned requirements they should invoke commitRequirements to fix any
596 // inconsistencies that may be present in the on-disk go.mod file.
597 func loadModFile(ctx context.Context) (rs *Requirements, needCommit bool) {
598         if requirements != nil {
599                 return requirements, false
600         }
601
602         Init()
603         if len(modRoots) == 0 {
604                 _ = TODOWorkspaces("Instead of creating a fake module with an empty modroot, make MainModules.Len() == 0 mean that we're in module mode but not inside any module.")
605                 mainModule := module.Version{Path: "command-line-arguments"}
606                 MainModules = makeMainModules([]module.Version{mainModule}, []string{""}, []*modfile.File{nil}, []*modFileIndex{nil})
607                 goVersion := LatestGoVersion()
608                 rawGoVersion.Store(mainModule, goVersion)
609                 requirements = newRequirements(modDepthFromGoVersion(goVersion), nil, nil)
610                 return requirements, false
611         }
612
613         var modFiles []*modfile.File
614         var mainModules []module.Version
615         var indices []*modFileIndex
616         for _, modroot := range modRoots {
617                 gomod := modFilePath(modroot)
618                 var data []byte
619                 var err error
620                 if gomodActual, ok := fsys.OverlayPath(gomod); ok {
621                         // Don't lock go.mod if it's part of the overlay.
622                         // On Plan 9, locking requires chmod, and we don't want to modify any file
623                         // in the overlay. See #44700.
624                         data, err = os.ReadFile(gomodActual)
625                 } else {
626                         data, err = lockedfile.Read(gomodActual)
627                 }
628                 if err != nil {
629                         base.Fatalf("go: %v", err)
630                 }
631
632                 var fixed bool
633                 f, err := modfile.Parse(gomod, data, fixVersion(ctx, &fixed))
634                 if err != nil {
635                         // Errors returned by modfile.Parse begin with file:line.
636                         base.Fatalf("go: errors parsing go.mod:\n%s\n", err)
637                 }
638                 if f.Module == nil {
639                         // No module declaration. Must add module path.
640                         base.Fatalf("go: no module declaration in go.mod. To specify the module path:\n\tgo mod edit -module=example.com/mod")
641                 }
642
643                 modFiles = append(modFiles, f)
644                 mainModule := f.Module.Mod
645                 mainModules = append(mainModules, mainModule)
646                 indices = append(indices, indexModFile(data, f, mainModule, fixed))
647
648                 if err := module.CheckImportPath(f.Module.Mod.Path); err != nil {
649                         if pathErr, ok := err.(*module.InvalidPathError); ok {
650                                 pathErr.Kind = "module"
651                         }
652                         base.Fatalf("go: %v", err)
653                 }
654         }
655
656         MainModules = makeMainModules(mainModules, modRoots, modFiles, indices)
657         setDefaultBuildMod() // possibly enable automatic vendoring
658         rs = requirementsFromModFiles(ctx, modFiles)
659
660         if inWorkspaceMode() {
661                 // We don't need to do anything for vendor or update the mod file so
662                 // return early.
663
664                 _ = TODOWorkspaces("don't worry about commits for now, but eventually will want to update go.work files")
665                 return rs, false
666         }
667
668         mainModule := MainModules.mustGetSingleMainModule()
669
670         if cfg.BuildMod == "vendor" {
671                 readVendorList(mainModule)
672                 index := MainModules.Index(mainModule)
673                 modFile := MainModules.ModFile(mainModule)
674                 checkVendorConsistency(index, modFile)
675                 rs.initVendor(vendorList)
676         }
677
678         if rs.hasRedundantRoot() {
679                 // If any module path appears more than once in the roots, we know that the
680                 // go.mod file needs to be updated even though we have not yet loaded any
681                 // transitive dependencies.
682                 var err error
683                 rs, err = updateRoots(ctx, rs.direct, rs, nil, nil, false)
684                 if err != nil {
685                         base.Fatalf("go: %v", err)
686                 }
687         }
688
689         if MainModules.Index(mainModule).goVersionV == "" {
690                 // TODO(#45551): Do something more principled instead of checking
691                 // cfg.CmdName directly here.
692                 if cfg.BuildMod == "mod" && cfg.CmdName != "mod graph" && cfg.CmdName != "mod why" {
693                         addGoStmt(MainModules.ModFile(mainModule), mainModule, LatestGoVersion())
694                         if go117EnableLazyLoading {
695                                 // We need to add a 'go' version to the go.mod file, but we must assume
696                                 // that its existing contents match something between Go 1.11 and 1.16.
697                                 // Go 1.11 through 1.16 have eager requirements, but the latest Go
698                                 // version uses lazy requirements instead — so we need to cnvert the
699                                 // requirements to be lazy.
700                                 var err error
701                                 rs, err = convertDepth(ctx, rs, lazy)
702                                 if err != nil {
703                                         base.Fatalf("go: %v", err)
704                                 }
705                         }
706                 } else {
707                         rawGoVersion.Store(mainModule, modFileGoVersion())
708                 }
709         }
710
711         requirements = rs
712         return requirements, true
713 }
714
715 // CreateModFile initializes a new module by creating a go.mod file.
716 //
717 // If modPath is empty, CreateModFile will attempt to infer the path from the
718 // directory location within GOPATH.
719 //
720 // If a vendoring configuration file is present, CreateModFile will attempt to
721 // translate it to go.mod directives. The resulting build list may not be
722 // exactly the same as in the legacy configuration (for example, we can't get
723 // packages at multiple versions from the same module).
724 func CreateModFile(ctx context.Context, modPath string) {
725         modRoot := base.Cwd()
726         modRoots = []string{modRoot}
727         Init()
728         modFilePath := modFilePath(modRoot)
729         if _, err := fsys.Stat(modFilePath); err == nil {
730                 base.Fatalf("go: %s already exists", modFilePath)
731         }
732
733         if modPath == "" {
734                 var err error
735                 modPath, err = findModulePath(modRoot)
736                 if err != nil {
737                         base.Fatalf("go: %v", err)
738                 }
739         } else if err := module.CheckImportPath(modPath); err != nil {
740                 if pathErr, ok := err.(*module.InvalidPathError); ok {
741                         pathErr.Kind = "module"
742                         // Same as build.IsLocalPath()
743                         if pathErr.Path == "." || pathErr.Path == ".." ||
744                                 strings.HasPrefix(pathErr.Path, "./") || strings.HasPrefix(pathErr.Path, "../") {
745                                 pathErr.Err = errors.New("is a local import path")
746                         }
747                 }
748                 base.Fatalf("go: %v", err)
749         } else if _, _, ok := module.SplitPathVersion(modPath); !ok {
750                 if strings.HasPrefix(modPath, "gopkg.in/") {
751                         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))
752                         base.Fatalf(`go: invalid module path "%v": %v`, modPath, invalidMajorVersionMsg)
753                 }
754                 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))
755                 base.Fatalf(`go: invalid module path "%v": %v`, modPath, invalidMajorVersionMsg)
756         }
757
758         fmt.Fprintf(os.Stderr, "go: creating new go.mod: module %s\n", modPath)
759         modFile := new(modfile.File)
760         modFile.AddModuleStmt(modPath)
761         MainModules = makeMainModules([]module.Version{modFile.Module.Mod}, []string{modRoot}, []*modfile.File{modFile}, []*modFileIndex{nil})
762         addGoStmt(modFile, modFile.Module.Mod, LatestGoVersion()) // Add the go directive before converted module requirements.
763
764         convertedFrom, err := convertLegacyConfig(modFile, modPath)
765         if convertedFrom != "" {
766                 fmt.Fprintf(os.Stderr, "go: copying requirements from %s\n", base.ShortPath(convertedFrom))
767         }
768         if err != nil {
769                 base.Fatalf("go: %v", err)
770         }
771
772         rs := requirementsFromModFiles(ctx, []*modfile.File{modFile})
773         rs, err = updateRoots(ctx, rs.direct, rs, nil, nil, false)
774         if err != nil {
775                 base.Fatalf("go: %v", err)
776         }
777         commitRequirements(ctx, modFileGoVersion(), rs)
778
779         // Suggest running 'go mod tidy' unless the project is empty. Even if we
780         // imported all the correct requirements above, we're probably missing
781         // some sums, so the next build command in -mod=readonly will likely fail.
782         //
783         // We look for non-hidden .go files or subdirectories to determine whether
784         // this is an existing project. Walking the tree for packages would be more
785         // accurate, but could take much longer.
786         empty := true
787         files, _ := os.ReadDir(modRoot)
788         for _, f := range files {
789                 name := f.Name()
790                 if strings.HasPrefix(name, ".") || strings.HasPrefix(name, "_") {
791                         continue
792                 }
793                 if strings.HasSuffix(name, ".go") || f.IsDir() {
794                         empty = false
795                         break
796                 }
797         }
798         if !empty {
799                 fmt.Fprintf(os.Stderr, "go: to add module requirements and sums:\n\tgo mod tidy\n")
800         }
801 }
802
803 // CreateWorkFile initializes a new workspace by creating a go.work file.
804 func CreateWorkFile(ctx context.Context, workFile string, modDirs []string) {
805         _ = TODOWorkspaces("Report an error if the file already exists.")
806
807         goV := LatestGoVersion() // Use current Go version by default
808         workF := new(modfile.WorkFile)
809         workF.Syntax = new(modfile.FileSyntax)
810         workF.AddGoStmt(goV)
811
812         for _, dir := range modDirs {
813                 _ = TODOWorkspaces("Add the module path of the module.")
814                 workF.AddDirectory(dir, "")
815         }
816
817         data := modfile.Format(workF.Syntax)
818         lockedfile.Write(workFile, bytes.NewReader(data), 0644)
819 }
820
821 // fixVersion returns a modfile.VersionFixer implemented using the Query function.
822 //
823 // It resolves commit hashes and branch names to versions,
824 // canonicalizes versions that appeared in early vgo drafts,
825 // and does nothing for versions that already appear to be canonical.
826 //
827 // The VersionFixer sets 'fixed' if it ever returns a non-canonical version.
828 func fixVersion(ctx context.Context, fixed *bool) modfile.VersionFixer {
829         return func(path, vers string) (resolved string, err error) {
830                 defer func() {
831                         if err == nil && resolved != vers {
832                                 *fixed = true
833                         }
834                 }()
835
836                 // Special case: remove the old -gopkgin- hack.
837                 if strings.HasPrefix(path, "gopkg.in/") && strings.Contains(vers, "-gopkgin-") {
838                         vers = vers[strings.Index(vers, "-gopkgin-")+len("-gopkgin-"):]
839                 }
840
841                 // fixVersion is called speculatively on every
842                 // module, version pair from every go.mod file.
843                 // Avoid the query if it looks OK.
844                 _, pathMajor, ok := module.SplitPathVersion(path)
845                 if !ok {
846                         return "", &module.ModuleError{
847                                 Path: path,
848                                 Err: &module.InvalidVersionError{
849                                         Version: vers,
850                                         Err:     fmt.Errorf("malformed module path %q", path),
851                                 },
852                         }
853                 }
854                 if vers != "" && module.CanonicalVersion(vers) == vers {
855                         if err := module.CheckPathMajor(vers, pathMajor); err != nil {
856                                 return "", module.VersionError(module.Version{Path: path, Version: vers}, err)
857                         }
858                         return vers, nil
859                 }
860
861                 info, err := Query(ctx, path, vers, "", nil)
862                 if err != nil {
863                         return "", err
864                 }
865                 return info.Version, nil
866         }
867 }
868
869 // AllowMissingModuleImports allows import paths to be resolved to modules
870 // when there is no module root. Normally, this is forbidden because it's slow
871 // and there's no way to make the result reproducible, but some commands
872 // like 'go get' are expected to do this.
873 //
874 // This function affects the default cfg.BuildMod when outside of a module,
875 // so it can only be called prior to Init.
876 func AllowMissingModuleImports() {
877         if initialized {
878                 panic("AllowMissingModuleImports after Init")
879         }
880         allowMissingModuleImports = true
881 }
882
883 // makeMainModules creates a MainModuleSet and associated variables according to
884 // the given main modules.
885 func makeMainModules(ms []module.Version, rootDirs []string, modFiles []*modfile.File, indices []*modFileIndex) *MainModuleSet {
886         for _, m := range ms {
887                 if m.Version != "" {
888                         panic("mainModulesCalled with module.Version with non empty Version field: " + fmt.Sprintf("%#v", m))
889                 }
890         }
891         modRootContainingCWD := findModuleRoot(base.Cwd())
892         mainModules := &MainModuleSet{
893                 versions:    ms[:len(ms):len(ms)],
894                 inGorootSrc: map[module.Version]bool{},
895                 pathPrefix:  map[module.Version]string{},
896                 modRoot:     map[module.Version]string{},
897                 modFiles:    map[module.Version]*modfile.File{},
898                 indices:     map[module.Version]*modFileIndex{},
899         }
900         for i, m := range ms {
901                 mainModules.pathPrefix[m] = m.Path
902                 mainModules.modRoot[m] = rootDirs[i]
903                 mainModules.modFiles[m] = modFiles[i]
904                 mainModules.indices[m] = indices[i]
905
906                 if mainModules.modRoot[m] == modRootContainingCWD {
907                         mainModules.modContainingCWD = m
908                 }
909
910                 if rel := search.InDir(rootDirs[i], cfg.GOROOTsrc); rel != "" {
911                         mainModules.inGorootSrc[m] = true
912                         if m.Path == "std" {
913                                 // The "std" module in GOROOT/src is the Go standard library. Unlike other
914                                 // modules, the packages in the "std" module have no import-path prefix.
915                                 //
916                                 // Modules named "std" outside of GOROOT/src do not receive this special
917                                 // treatment, so it is possible to run 'go test .' in other GOROOTs to
918                                 // test individual packages using a combination of the modified package
919                                 // and the ordinary standard library.
920                                 // (See https://golang.org/issue/30756.)
921                                 mainModules.pathPrefix[m] = ""
922                         }
923                 }
924         }
925         return mainModules
926 }
927
928 // requirementsFromModFiles returns the set of non-excluded requirements from
929 // the global modFile.
930 func requirementsFromModFiles(ctx context.Context, modFiles []*modfile.File) *Requirements {
931         rootCap := 0
932         for i := range modFiles {
933                 rootCap += len(modFiles[i].Require)
934         }
935         roots := make([]module.Version, 0, rootCap)
936         mPathCount := make(map[string]int)
937         for _, m := range MainModules.Versions() {
938                 mPathCount[m.Path] = 1
939         }
940         direct := map[string]bool{}
941         for _, modFile := range modFiles {
942         requirement:
943                 for _, r := range modFile.Require {
944                         // TODO(#45713): Maybe join
945                         for _, mainModule := range MainModules.Versions() {
946                                 if index := MainModules.Index(mainModule); index != nil && index.exclude[r.Mod] {
947                                         if cfg.BuildMod == "mod" {
948                                                 fmt.Fprintf(os.Stderr, "go: dropping requirement on excluded version %s %s\n", r.Mod.Path, r.Mod.Version)
949                                         } else {
950                                                 fmt.Fprintf(os.Stderr, "go: ignoring requirement on excluded version %s %s\n", r.Mod.Path, r.Mod.Version)
951                                         }
952                                         continue requirement
953                                 }
954                         }
955
956                         roots = append(roots, r.Mod)
957                         if !r.Indirect {
958                                 direct[r.Mod.Path] = true
959                         }
960                 }
961         }
962         module.Sort(roots)
963         rs := newRequirements(modDepthFromGoVersion(modFileGoVersion()), roots, direct)
964         return rs
965 }
966
967 // setDefaultBuildMod sets a default value for cfg.BuildMod if the -mod flag
968 // wasn't provided. setDefaultBuildMod may be called multiple times.
969 func setDefaultBuildMod() {
970         if cfg.BuildModExplicit {
971                 if inWorkspaceMode() && cfg.BuildMod != "readonly" {
972                         base.Fatalf("go: -mod may only be set to readonly when in workspace mode." +
973                                 "\n\tRemove the -mod flag to use the default readonly value," +
974                                 "\n\tor set -workfile=off to disable workspace mode.")
975                 }
976                 // Don't override an explicit '-mod=' argument.
977                 return
978         }
979
980         // TODO(#40775): commands should pass in the module mode as an option
981         // to modload functions instead of relying on an implicit setting
982         // based on command name.
983         switch cfg.CmdName {
984         case "get", "mod download", "mod init", "mod tidy":
985                 // These commands are intended to update go.mod and go.sum.
986                 cfg.BuildMod = "mod"
987                 return
988         case "mod graph", "mod verify", "mod why":
989                 // These commands should not update go.mod or go.sum, but they should be
990                 // able to fetch modules not in go.sum and should not report errors if
991                 // go.mod is inconsistent. They're useful for debugging, and they need
992                 // to work in buggy situations.
993                 cfg.BuildMod = "mod"
994                 allowWriteGoMod = false
995                 return
996         case "mod vendor":
997                 cfg.BuildMod = "readonly"
998                 return
999         }
1000         if modRoots == nil {
1001                 if allowMissingModuleImports {
1002                         cfg.BuildMod = "mod"
1003                 } else {
1004                         cfg.BuildMod = "readonly"
1005                 }
1006                 return
1007         }
1008
1009         if len(modRoots) == 1 {
1010                 index := MainModules.GetSingleIndexOrNil()
1011                 if fi, err := fsys.Stat(filepath.Join(modRoots[0], "vendor")); err == nil && fi.IsDir() {
1012                         modGo := "unspecified"
1013                         if index != nil && index.goVersionV != "" {
1014                                 if semver.Compare(index.goVersionV, "v1.14") >= 0 {
1015                                         // The Go version is at least 1.14, and a vendor directory exists.
1016                                         // Set -mod=vendor by default.
1017                                         cfg.BuildMod = "vendor"
1018                                         cfg.BuildModReason = "Go version in go.mod is at least 1.14 and vendor directory exists."
1019                                         return
1020                                 } else {
1021                                         modGo = index.goVersionV[1:]
1022                                 }
1023                         }
1024
1025                         // Since a vendor directory exists, we should record why we didn't use it.
1026                         // This message won't normally be shown, but it may appear with import errors.
1027                         cfg.BuildModReason = fmt.Sprintf("Go version in go.mod is %s, so vendor directory was not used.", modGo)
1028                 }
1029         }
1030
1031         cfg.BuildMod = "readonly"
1032 }
1033
1034 func mustHaveCompleteRequirements() bool {
1035         return cfg.BuildMod != "mod" && !inWorkspaceMode()
1036 }
1037
1038 // convertLegacyConfig imports module requirements from a legacy vendoring
1039 // configuration file, if one is present.
1040 func convertLegacyConfig(modFile *modfile.File, modPath string) (from string, err error) {
1041         noneSelected := func(path string) (version string) { return "none" }
1042         queryPackage := func(path, rev string) (module.Version, error) {
1043                 pkgMods, modOnly, err := QueryPattern(context.Background(), path, rev, noneSelected, nil)
1044                 if err != nil {
1045                         return module.Version{}, err
1046                 }
1047                 if len(pkgMods) > 0 {
1048                         return pkgMods[0].Mod, nil
1049                 }
1050                 return modOnly.Mod, nil
1051         }
1052         for _, name := range altConfigs {
1053                 if len(modRoots) != 1 {
1054                         panic(TODOWorkspaces("what do do here?"))
1055                 }
1056                 cfg := filepath.Join(modRoots[0], name)
1057                 data, err := os.ReadFile(cfg)
1058                 if err == nil {
1059                         convert := modconv.Converters[name]
1060                         if convert == nil {
1061                                 return "", nil
1062                         }
1063                         cfg = filepath.ToSlash(cfg)
1064                         err := modconv.ConvertLegacyConfig(modFile, cfg, data, queryPackage)
1065                         return name, err
1066                 }
1067         }
1068         return "", nil
1069 }
1070
1071 // addGoStmt adds a go directive to the go.mod file if it does not already
1072 // include one. The 'go' version added, if any, is the latest version supported
1073 // by this toolchain.
1074 func addGoStmt(modFile *modfile.File, mod module.Version, v string) {
1075         if modFile.Go != nil && modFile.Go.Version != "" {
1076                 return
1077         }
1078         if err := modFile.AddGoStmt(v); err != nil {
1079                 base.Fatalf("go: internal error: %v", err)
1080         }
1081         rawGoVersion.Store(mod, v)
1082 }
1083
1084 // LatestGoVersion returns the latest version of the Go language supported by
1085 // this toolchain, like "1.17".
1086 func LatestGoVersion() string {
1087         tags := build.Default.ReleaseTags
1088         version := tags[len(tags)-1]
1089         if !strings.HasPrefix(version, "go") || !modfile.GoVersionRE.MatchString(version[2:]) {
1090                 base.Fatalf("go: internal error: unrecognized default version %q", version)
1091         }
1092         return version[2:]
1093 }
1094
1095 // priorGoVersion returns the Go major release immediately preceding v,
1096 // or v itself if v is the first Go major release (1.0) or not a supported
1097 // Go version.
1098 func priorGoVersion(v string) string {
1099         vTag := "go" + v
1100         tags := build.Default.ReleaseTags
1101         for i, tag := range tags {
1102                 if tag == vTag {
1103                         if i == 0 {
1104                                 return v
1105                         }
1106
1107                         version := tags[i-1]
1108                         if !strings.HasPrefix(version, "go") || !modfile.GoVersionRE.MatchString(version[2:]) {
1109                                 base.Fatalf("go: internal error: unrecognized version %q", version)
1110                         }
1111                         return version[2:]
1112                 }
1113         }
1114         return v
1115 }
1116
1117 var altConfigs = []string{
1118         "Gopkg.lock",
1119
1120         "GLOCKFILE",
1121         "Godeps/Godeps.json",
1122         "dependencies.tsv",
1123         "glide.lock",
1124         "vendor.conf",
1125         "vendor.yml",
1126         "vendor/manifest",
1127         "vendor/vendor.json",
1128
1129         ".git/config",
1130 }
1131
1132 func findModuleRoot(dir string) (roots string) {
1133         if dir == "" {
1134                 panic("dir not set")
1135         }
1136         dir = filepath.Clean(dir)
1137
1138         // Look for enclosing go.mod.
1139         for {
1140                 if fi, err := fsys.Stat(filepath.Join(dir, "go.mod")); err == nil && !fi.IsDir() {
1141                         return dir
1142                 }
1143                 d := filepath.Dir(dir)
1144                 if d == dir {
1145                         break
1146                 }
1147                 dir = d
1148         }
1149         return ""
1150 }
1151
1152 func findWorkspaceFile(dir string) (root string) {
1153         if dir == "" {
1154                 panic("dir not set")
1155         }
1156         dir = filepath.Clean(dir)
1157
1158         // Look for enclosing go.mod.
1159         for {
1160                 f := filepath.Join(dir, "go.work")
1161                 if fi, err := fsys.Stat(f); err == nil && !fi.IsDir() {
1162                         return f
1163                 }
1164                 d := filepath.Dir(dir)
1165                 if d == dir {
1166                         break
1167                 }
1168                 if d == cfg.GOROOT {
1169                         _ = TODOWorkspaces("Address how go.work files interact with GOROOT")
1170                         return "" // As a special case, don't cross GOROOT to find a go.work file.
1171                 }
1172                 dir = d
1173         }
1174         return ""
1175 }
1176
1177 func findAltConfig(dir string) (root, name string) {
1178         if dir == "" {
1179                 panic("dir not set")
1180         }
1181         dir = filepath.Clean(dir)
1182         if rel := search.InDir(dir, cfg.BuildContext.GOROOT); rel != "" {
1183                 // Don't suggest creating a module from $GOROOT/.git/config
1184                 // or a config file found in any parent of $GOROOT (see #34191).
1185                 return "", ""
1186         }
1187         for {
1188                 for _, name := range altConfigs {
1189                         if fi, err := fsys.Stat(filepath.Join(dir, name)); err == nil && !fi.IsDir() {
1190                                 return dir, name
1191                         }
1192                 }
1193                 d := filepath.Dir(dir)
1194                 if d == dir {
1195                         break
1196                 }
1197                 dir = d
1198         }
1199         return "", ""
1200 }
1201
1202 func findModulePath(dir string) (string, error) {
1203         // TODO(bcmills): once we have located a plausible module path, we should
1204         // query version control (if available) to verify that it matches the major
1205         // version of the most recent tag.
1206         // See https://golang.org/issue/29433, https://golang.org/issue/27009, and
1207         // https://golang.org/issue/31549.
1208
1209         // Cast about for import comments,
1210         // first in top-level directory, then in subdirectories.
1211         list, _ := os.ReadDir(dir)
1212         for _, info := range list {
1213                 if info.Type().IsRegular() && strings.HasSuffix(info.Name(), ".go") {
1214                         if com := findImportComment(filepath.Join(dir, info.Name())); com != "" {
1215                                 return com, nil
1216                         }
1217                 }
1218         }
1219         for _, info1 := range list {
1220                 if info1.IsDir() {
1221                         files, _ := os.ReadDir(filepath.Join(dir, info1.Name()))
1222                         for _, info2 := range files {
1223                                 if info2.Type().IsRegular() && strings.HasSuffix(info2.Name(), ".go") {
1224                                         if com := findImportComment(filepath.Join(dir, info1.Name(), info2.Name())); com != "" {
1225                                                 return path.Dir(com), nil
1226                                         }
1227                                 }
1228                         }
1229                 }
1230         }
1231
1232         // Look for Godeps.json declaring import path.
1233         data, _ := os.ReadFile(filepath.Join(dir, "Godeps/Godeps.json"))
1234         var cfg1 struct{ ImportPath string }
1235         json.Unmarshal(data, &cfg1)
1236         if cfg1.ImportPath != "" {
1237                 return cfg1.ImportPath, nil
1238         }
1239
1240         // Look for vendor.json declaring import path.
1241         data, _ = os.ReadFile(filepath.Join(dir, "vendor/vendor.json"))
1242         var cfg2 struct{ RootPath string }
1243         json.Unmarshal(data, &cfg2)
1244         if cfg2.RootPath != "" {
1245                 return cfg2.RootPath, nil
1246         }
1247
1248         // Look for path in GOPATH.
1249         var badPathErr error
1250         for _, gpdir := range filepath.SplitList(cfg.BuildContext.GOPATH) {
1251                 if gpdir == "" {
1252                         continue
1253                 }
1254                 if rel := search.InDir(dir, filepath.Join(gpdir, "src")); rel != "" && rel != "." {
1255                         path := filepath.ToSlash(rel)
1256                         // gorelease will alert users publishing their modules to fix their paths.
1257                         if err := module.CheckImportPath(path); err != nil {
1258                                 badPathErr = err
1259                                 break
1260                         }
1261                         return path, nil
1262                 }
1263         }
1264
1265         reason := "outside GOPATH, module path must be specified"
1266         if badPathErr != nil {
1267                 // return a different error message if the module was in GOPATH, but
1268                 // the module path determined above would be an invalid path.
1269                 reason = fmt.Sprintf("bad module path inferred from directory in GOPATH: %v", badPathErr)
1270         }
1271         msg := `cannot determine module path for source directory %s (%s)
1272
1273 Example usage:
1274         'go mod init example.com/m' to initialize a v0 or v1 module
1275         'go mod init example.com/m/v2' to initialize a v2 module
1276
1277 Run 'go help mod init' for more information.
1278 `
1279         return "", fmt.Errorf(msg, dir, reason)
1280 }
1281
1282 var (
1283         importCommentRE = lazyregexp.New(`(?m)^package[ \t]+[^ \t\r\n/]+[ \t]+//[ \t]+import[ \t]+(\"[^"]+\")[ \t]*\r?\n`)
1284 )
1285
1286 func findImportComment(file string) string {
1287         data, err := os.ReadFile(file)
1288         if err != nil {
1289                 return ""
1290         }
1291         m := importCommentRE.FindSubmatch(data)
1292         if m == nil {
1293                 return ""
1294         }
1295         path, err := strconv.Unquote(string(m[1]))
1296         if err != nil {
1297                 return ""
1298         }
1299         return path
1300 }
1301
1302 var allowWriteGoMod = true
1303
1304 // DisallowWriteGoMod causes future calls to WriteGoMod to do nothing at all.
1305 func DisallowWriteGoMod() {
1306         allowWriteGoMod = false
1307 }
1308
1309 // AllowWriteGoMod undoes the effect of DisallowWriteGoMod:
1310 // future calls to WriteGoMod will update go.mod if needed.
1311 // Note that any past calls have been discarded, so typically
1312 // a call to AlowWriteGoMod should be followed by a call to WriteGoMod.
1313 func AllowWriteGoMod() {
1314         allowWriteGoMod = true
1315 }
1316
1317 // WriteGoMod writes the current build list back to go.mod.
1318 func WriteGoMod(ctx context.Context) {
1319         if !allowWriteGoMod {
1320                 panic("WriteGoMod called while disallowed")
1321         }
1322         commitRequirements(ctx, modFileGoVersion(), LoadModFile(ctx))
1323 }
1324
1325 // commitRequirements writes sets the global requirements variable to rs and
1326 // writes its contents back to the go.mod file on disk.
1327 func commitRequirements(ctx context.Context, goVersion string, rs *Requirements) {
1328         requirements = rs
1329
1330         if !allowWriteGoMod {
1331                 // Some package outside of modload promised to update the go.mod file later.
1332                 return
1333         }
1334
1335         if inWorkspaceMode() {
1336                 // go.mod files aren't updated in workspace mode, but we still want to
1337                 // update the go.work.sum file.
1338                 if err := modfetch.WriteGoSum(keepSums(ctx, loaded, rs, addBuildListZipSums), mustHaveCompleteRequirements()); err != nil {
1339                         base.Fatalf("go: %v", err)
1340                 }
1341                 return
1342         }
1343
1344         if MainModules.Len() != 1 || MainModules.ModRoot(MainModules.Versions()[0]) == "" {
1345                 // We aren't in a module, so we don't have anywhere to write a go.mod file.
1346                 return
1347         }
1348         mainModule := MainModules.Versions()[0]
1349         modFilePath := modFilePath(MainModules.ModRoot(mainModule))
1350         modFile := MainModules.ModFile(mainModule)
1351
1352         var list []*modfile.Require
1353         for _, m := range rs.rootModules {
1354                 list = append(list, &modfile.Require{
1355                         Mod:      m,
1356                         Indirect: !rs.direct[m.Path],
1357                 })
1358         }
1359         if goVersion != "" {
1360                 modFile.AddGoStmt(goVersion)
1361         }
1362         if semver.Compare("v"+modFileGoVersion(), separateIndirectVersionV) < 0 {
1363                 modFile.SetRequire(list)
1364         } else {
1365                 modFile.SetRequireSeparateIndirect(list)
1366         }
1367         modFile.Cleanup()
1368
1369         index := MainModules.GetSingleIndexOrNil()
1370         dirty := index.modFileIsDirty(modFile)
1371         if dirty && cfg.BuildMod != "mod" {
1372                 // If we're about to fail due to -mod=readonly,
1373                 // prefer to report a dirty go.mod over a dirty go.sum
1374                 base.Fatalf("go: %v", errGoModDirty)
1375         }
1376
1377         if !dirty && cfg.CmdName != "mod tidy" {
1378                 // The go.mod file has the same semantic content that it had before
1379                 // (but not necessarily the same exact bytes).
1380                 // Don't write go.mod, but write go.sum in case we added or trimmed sums.
1381                 // 'go mod init' shouldn't write go.sum, since it will be incomplete.
1382                 if cfg.CmdName != "mod init" {
1383                         if err := modfetch.WriteGoSum(keepSums(ctx, loaded, rs, addBuildListZipSums), mustHaveCompleteRequirements()); err != nil {
1384                                 base.Fatalf("go: %v", err)
1385                         }
1386                 }
1387                 return
1388         }
1389         if _, ok := fsys.OverlayPath(modFilePath); ok {
1390                 if dirty {
1391                         base.Fatalf("go: updates to go.mod needed, but go.mod is part of the overlay specified with -overlay")
1392                 }
1393                 return
1394         }
1395
1396         new, err := modFile.Format()
1397         if err != nil {
1398                 base.Fatalf("go: %v", err)
1399         }
1400         defer func() {
1401                 if MainModules.Len() != 1 {
1402                         panic(TODOWorkspaces("There should be exactly one main module when committing reqs"))
1403                 }
1404
1405                 mainModule := MainModules.Versions()[0]
1406
1407                 // At this point we have determined to make the go.mod file on disk equal to new.
1408                 MainModules.SetIndex(mainModule, indexModFile(new, modFile, mainModule, false))
1409
1410                 // Update go.sum after releasing the side lock and refreshing the index.
1411                 // 'go mod init' shouldn't write go.sum, since it will be incomplete.
1412                 if cfg.CmdName != "mod init" {
1413                         if err := modfetch.WriteGoSum(keepSums(ctx, loaded, rs, addBuildListZipSums), mustHaveCompleteRequirements()); err != nil {
1414                                 base.Fatalf("go: %v", err)
1415                         }
1416                 }
1417         }()
1418
1419         // Make a best-effort attempt to acquire the side lock, only to exclude
1420         // previous versions of the 'go' command from making simultaneous edits.
1421         if unlock, err := modfetch.SideLock(); err == nil {
1422                 defer unlock()
1423         }
1424
1425         errNoChange := errors.New("no update needed")
1426
1427         err = lockedfile.Transform(modFilePath, func(old []byte) ([]byte, error) {
1428                 if bytes.Equal(old, new) {
1429                         // The go.mod file is already equal to new, possibly as the result of some
1430                         // other process.
1431                         return nil, errNoChange
1432                 }
1433
1434                 if index != nil && !bytes.Equal(old, index.data) {
1435                         // The contents of the go.mod file have changed. In theory we could add all
1436                         // of the new modules to the build list, recompute, and check whether any
1437                         // module in *our* build list got bumped to a different version, but that's
1438                         // a lot of work for marginal benefit. Instead, fail the command: if users
1439                         // want to run concurrent commands, they need to start with a complete,
1440                         // consistent module definition.
1441                         return nil, fmt.Errorf("existing contents have changed since last read")
1442                 }
1443
1444                 return new, nil
1445         })
1446
1447         if err != nil && err != errNoChange {
1448                 base.Fatalf("go: updating go.mod: %v", err)
1449         }
1450 }
1451
1452 // keepSums returns the set of modules (and go.mod file entries) for which
1453 // checksums would be needed in order to reload the same set of packages
1454 // loaded by the most recent call to LoadPackages or ImportFromFiles,
1455 // including any go.mod files needed to reconstruct the MVS result,
1456 // in addition to the checksums for every module in keepMods.
1457 func keepSums(ctx context.Context, ld *loader, rs *Requirements, which whichSums) map[module.Version]bool {
1458         // Every module in the full module graph contributes its requirements,
1459         // so in order to ensure that the build list itself is reproducible,
1460         // we need sums for every go.mod in the graph (regardless of whether
1461         // that version is selected).
1462         keep := make(map[module.Version]bool)
1463
1464         // Add entries for modules in the build list with paths that are prefixes of
1465         // paths of loaded packages. We need to retain sums for all of these modules —
1466         // not just the modules containing the actual packages — in order to rule out
1467         // ambiguous import errors the next time we load the package.
1468         if ld != nil {
1469                 for _, pkg := range ld.pkgs {
1470                         // We check pkg.mod.Path here instead of pkg.inStd because the
1471                         // pseudo-package "C" is not in std, but not provided by any module (and
1472                         // shouldn't force loading the whole module graph).
1473                         if pkg.testOf != nil || (pkg.mod.Path == "" && pkg.err == nil) || module.CheckImportPath(pkg.path) != nil {
1474                                 continue
1475                         }
1476
1477                         if rs.depth == lazy && pkg.mod.Path != "" {
1478                                 if v, ok := rs.rootSelected(pkg.mod.Path); ok && v == pkg.mod.Version {
1479                                         // pkg was loaded from a root module, and because the main module is
1480                                         // lazy we do not check non-root modules for conflicts for packages
1481                                         // that can be found in roots. So we only need the checksums for the
1482                                         // root modules that may contain pkg, not all possible modules.
1483                                         for prefix := pkg.path; prefix != "."; prefix = path.Dir(prefix) {
1484                                                 if v, ok := rs.rootSelected(prefix); ok && v != "none" {
1485                                                         m := module.Version{Path: prefix, Version: v}
1486                                                         r, _ := resolveReplacement(m)
1487                                                         keep[r] = true
1488                                                 }
1489                                         }
1490                                         continue
1491                                 }
1492                         }
1493
1494                         mg, _ := rs.Graph(ctx)
1495                         for prefix := pkg.path; prefix != "."; prefix = path.Dir(prefix) {
1496                                 if v := mg.Selected(prefix); v != "none" {
1497                                         m := module.Version{Path: prefix, Version: v}
1498                                         r, _ := resolveReplacement(m)
1499                                         keep[r] = true
1500                                 }
1501                         }
1502                 }
1503         }
1504
1505         if rs.graph.Load() == nil {
1506                 // The module graph was not loaded, possibly because the main module is lazy
1507                 // or possibly because we haven't needed to load the graph yet.
1508                 // Save sums for the root modules (or their replacements), but don't
1509                 // incur the cost of loading the graph just to find and retain the sums.
1510                 for _, m := range rs.rootModules {
1511                         r, _ := resolveReplacement(m)
1512                         keep[modkey(r)] = true
1513                         if which == addBuildListZipSums {
1514                                 keep[r] = true
1515                         }
1516                 }
1517         } else {
1518                 mg, _ := rs.Graph(ctx)
1519                 mg.WalkBreadthFirst(func(m module.Version) {
1520                         if _, ok := mg.RequiredBy(m); ok {
1521                                 // The requirements from m's go.mod file are present in the module graph,
1522                                 // so they are relevant to the MVS result regardless of whether m was
1523                                 // actually selected.
1524                                 r, _ := resolveReplacement(m)
1525                                 keep[modkey(r)] = true
1526                         }
1527                 })
1528
1529                 if which == addBuildListZipSums {
1530                         for _, m := range mg.BuildList() {
1531                                 r, _ := resolveReplacement(m)
1532                                 keep[r] = true
1533                         }
1534                 }
1535         }
1536
1537         return keep
1538 }
1539
1540 type whichSums int8
1541
1542 const (
1543         loadedZipSumsOnly = whichSums(iota)
1544         addBuildListZipSums
1545 )
1546
1547 // modKey returns the module.Version under which the checksum for m's go.mod
1548 // file is stored in the go.sum file.
1549 func modkey(m module.Version) module.Version {
1550         return module.Version{Path: m.Path, Version: m.Version + "/go.mod"}
1551 }
1552
1553 func suggestModulePath(path string) string {
1554         var m string
1555
1556         i := len(path)
1557         for i > 0 && ('0' <= path[i-1] && path[i-1] <= '9' || path[i-1] == '.') {
1558                 i--
1559         }
1560         url := path[:i]
1561         url = strings.TrimSuffix(url, "/v")
1562         url = strings.TrimSuffix(url, "/")
1563
1564         f := func(c rune) bool {
1565                 return c > '9' || c < '0'
1566         }
1567         s := strings.FieldsFunc(path[i:], f)
1568         if len(s) > 0 {
1569                 m = s[0]
1570         }
1571         m = strings.TrimLeft(m, "0")
1572         if m == "" || m == "1" {
1573                 return url + "/v2"
1574         }
1575
1576         return url + "/v" + m
1577 }
1578
1579 func suggestGopkgIn(path string) string {
1580         var m string
1581         i := len(path)
1582         for i > 0 && (('0' <= path[i-1] && path[i-1] <= '9') || (path[i-1] == '.')) {
1583                 i--
1584         }
1585         url := path[:i]
1586         url = strings.TrimSuffix(url, ".v")
1587         url = strings.TrimSuffix(url, "/v")
1588         url = strings.TrimSuffix(url, "/")
1589
1590         f := func(c rune) bool {
1591                 return c > '9' || c < '0'
1592         }
1593         s := strings.FieldsFunc(path, f)
1594         if len(s) > 0 {
1595                 m = s[0]
1596         }
1597
1598         m = strings.TrimLeft(m, "0")
1599
1600         if m == "" {
1601                 return url + ".v1"
1602         }
1603         return url + ".v" + m
1604 }