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