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