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