Debian Codegraph @

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

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