1 // Copyright 2018 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
22 "cmd/go/internal/base"
24 "cmd/go/internal/fsys"
25 "cmd/go/internal/lockedfile"
26 "cmd/go/internal/modconv"
27 "cmd/go/internal/modfetch"
28 "cmd/go/internal/search"
30 "golang.org/x/mod/modfile"
31 "golang.org/x/mod/module"
32 "golang.org/x/mod/semver"
35 // Variables set by other packages.
37 // TODO(#40775): See if these can be plumbed as explicit parameters.
39 // RootMode determines whether a module root is needed.
42 // ForceUseModules may be set to force modules to be enabled when
43 // GO111MODULE=auto or to report an error when GO111MODULE=off.
46 allowMissingModuleImports bool
49 func TODOWorkspaces(s string) error {
50 return fmt.Errorf("need to support this for workspaces: %s", s)
53 // Variables set in Init.
57 // These are primarily used to initialize the MainModules, and should be
58 // eventually superceded by them but are still used in cases where the module
59 // roots are required but MainModules hasn't been initialized yet. Set to
60 // the modRoots of the main modules.
61 // modRoots != nil implies len(modRoots) > 0
66 // Variable set in InitWorkfile
68 // Set to the path to the go.work file, or "" if workspace mode is disabled.
72 type MainModuleSet struct {
73 // versions are the module.Version values of each of the main modules.
74 // For each of them, the Path fields are ordinary module paths and the Version
75 // fields are empty strings.
76 versions []module.Version
78 // modRoot maps each module in versions to its absolute filesystem path.
79 modRoot map[module.Version]string
81 // pathPrefix is the path prefix for packages in the module, without a trailing
82 // slash. For most modules, pathPrefix is just version.Path, but the
83 // standard-library module "std" has an empty prefix.
84 pathPrefix map[module.Version]string
86 // inGorootSrc caches whether modRoot is within GOROOT/src.
87 // The "std" module is special within GOROOT/src, but not otherwise.
88 inGorootSrc map[module.Version]bool
90 modFiles map[module.Version]*modfile.File
92 modContainingCWD module.Version
95 indices map[module.Version]*modFileIndex
98 func (mms *MainModuleSet) PathPrefix(m module.Version) string {
99 return mms.pathPrefix[m]
102 // Versions returns the module.Version values of each of the main modules.
103 // For each of them, the Path fields are ordinary module paths and the Version
104 // fields are empty strings.
105 // Callers should not modify the returned slice.
106 func (mms *MainModuleSet) Versions() []module.Version {
113 func (mms *MainModuleSet) Contains(path string) bool {
117 for _, v := range mms.versions {
125 func (mms *MainModuleSet) ModRoot(m module.Version) string {
126 _ = TODOWorkspaces(" Do we need the Init? The original modRoot calls it. Audit callers.")
131 return mms.modRoot[m]
134 func (mms *MainModuleSet) InGorootSrc(m module.Version) bool {
138 return mms.inGorootSrc[m]
141 func (mms *MainModuleSet) mustGetSingleMainModule() module.Version {
142 if mms == nil || len(mms.versions) == 0 {
143 panic("internal error: mustGetSingleMainModule called in context with no main modules")
145 if len(mms.versions) != 1 {
146 _ = TODOWorkspaces("Check if we're in workspace mode before returning the below error.")
147 panic("internal error: mustGetSingleMainModule called in workspace mode")
149 return mms.versions[0]
152 func (mms *MainModuleSet) GetSingleIndexOrNil() *modFileIndex {
156 if len(mms.versions) == 0 {
159 if len(mms.versions) != 1 {
160 _ = TODOWorkspaces("Check if we're in workspace mode before returning the below error.")
161 panic("internal error: mustGetSingleMainModule called in workspace mode")
163 return mms.indices[mms.versions[0]]
166 func (mms *MainModuleSet) Index(m module.Version) *modFileIndex {
168 defer mms.indexMu.Unlock()
169 return mms.indices[m]
172 func (mms *MainModuleSet) SetIndex(m module.Version, index *modFileIndex) {
174 defer mms.indexMu.Unlock()
175 mms.indices[m] = index
178 func (mms *MainModuleSet) ModFile(m module.Version) *modfile.File {
179 return mms.modFiles[m]
182 func (mms *MainModuleSet) Len() int {
186 return len(mms.versions)
189 // ModContainingCWD returns the main module containing the working directory,
190 // or module.Version{} if none of the main modules contain the working
192 func (mms *MainModuleSet) ModContainingCWD() module.Version {
193 return mms.modContainingCWD
196 var MainModules *MainModuleSet
201 // AutoRoot is the default for most commands. modload.Init will look for
202 // a go.mod file in the current directory or any parent. If none is found,
203 // modules may be disabled (GO111MODULE=auto) or commands may run in a
204 // limited module mode.
207 // NoRoot is used for commands that run in module mode and ignore any go.mod
208 // file the current directory or in parent directories.
211 // NeedRoot is used for commands that must run in module mode and don't
212 // make sense without a main module.
216 // ModFile returns the parsed go.mod file.
218 // Note that after calling LoadPackages or LoadModGraph,
219 // the require statements in the modfile.File are no longer
220 // the source of truth and will be ignored: edits made directly
221 // will be lost at the next call to WriteGoMod.
222 // To make permanent changes to the require statements
223 // in go.mod, edit it before loading.
224 func ModFile() *modfile.File {
226 modFile := MainModules.ModFile(MainModules.mustGetSingleMainModule())
233 func BinDir() string {
235 return filepath.Join(gopath, "bin")
238 // InitWorkfile initializes the workFilePath variable for commands that
239 // operate in workspace mode. It should not be called by other commands,
240 // for example 'go mod tidy', that don't operate in workspace mode.
241 func InitWorkfile() {
242 switch cfg.WorkFile {
246 workFilePath = findWorkspaceFile(base.Cwd())
248 workFilePath = cfg.WorkFile
252 // WorkFilePath returns the path of the go.work file, or "" if not in
253 // workspace mode. WorkFilePath must be called after InitWorkfile.
254 func WorkFilePath() string {
258 // Init determines whether module mode is enabled, locates the root of the
259 // current module (if any), sets environment variables for Git subprocesses, and
260 // configures the cfg, codehost, load, modfetch, and search packages for use
268 // Keep in sync with WillBeEnabled. We perform extra validation here, and
269 // there are lots of diagnostics and side effects, so we can't use
270 // WillBeEnabled directly.
271 var mustUseModules bool
272 env := cfg.Getenv("GO111MODULE")
275 base.Fatalf("go: unknown environment setting GO111MODULE=%s", env)
277 mustUseModules = ForceUseModules
279 mustUseModules = true
282 base.Fatalf("go: modules disabled by GO111MODULE=off; see 'go help modules'")
284 mustUseModules = false
288 if err := fsys.Init(base.Cwd()); err != nil {
289 base.Fatalf("go: %v", err)
292 // Disable any prompting for passwords by Git.
293 // Only has an effect for 2.3.0 or later, but avoiding
294 // the prompt in earlier versions is just too hard.
295 // If user has explicitly set GIT_TERMINAL_PROMPT=1, keep
297 // See golang.org/issue/9341 and golang.org/issue/12706.
298 if os.Getenv("GIT_TERMINAL_PROMPT") == "" {
299 os.Setenv("GIT_TERMINAL_PROMPT", "0")
302 // Disable any ssh connection pooling by Git.
303 // If a Git subprocess forks a child into the background to cache a new connection,
304 // that child keeps stdout/stderr open. After the Git subprocess exits,
305 // os /exec expects to be able to read from the stdout/stderr pipe
306 // until EOF to get all the data that the Git subprocess wrote before exiting.
307 // The EOF doesn't come until the child exits too, because the child
308 // is holding the write end of the pipe.
309 // This is unfortunate, but it has come up at least twice
310 // (see golang.org/issue/13453 and golang.org/issue/16104)
311 // and confuses users when it does.
312 // If the user has explicitly set GIT_SSH or GIT_SSH_COMMAND,
313 // assume they know what they are doing and don't step on it.
314 // But default to turning off ControlMaster.
315 if os.Getenv("GIT_SSH") == "" && os.Getenv("GIT_SSH_COMMAND") == "" {
316 os.Setenv("GIT_SSH_COMMAND", "ssh -o ControlMaster=no -o BatchMode=yes")
319 if os.Getenv("GCM_INTERACTIVE") == "" {
320 os.Setenv("GCM_INTERACTIVE", "never")
323 // modRoot set before Init was called ("go mod init" does this).
324 // No need to search for go.mod.
325 } else if RootMode == NoRoot {
326 if cfg.ModFile != "" && !base.InGOFLAGS("-modfile") {
327 base.Fatalf("go: -modfile cannot be used with commands that ignore the current module")
330 } else if inWorkspaceMode() {
331 // We're in workspace mode.
333 if modRoot := findModuleRoot(base.Cwd()); modRoot == "" {
334 if cfg.ModFile != "" {
335 base.Fatalf("go: cannot find main module, but -modfile was set.\n\t-modfile cannot be used to set the module root directory.")
337 if RootMode == NeedRoot {
338 base.Fatalf("go: %v", ErrNoModRoot)
341 // GO111MODULE is 'auto', and we can't find a module root.
342 // Stay in GOPATH mode.
345 } else if search.InDir(modRoot, os.TempDir()) == "." {
346 // If you create /tmp/go.mod for experimenting,
347 // then any tests that create work directories under /tmp
348 // will find it and get modules when they're not expecting them.
349 // It's a bit of a peculiar thing to disallow but quite mysterious
350 // when it happens. See golang.org/issue/26708.
351 fmt.Fprintf(os.Stderr, "go: warning: ignoring go.mod in system temp root %v\n", os.TempDir())
356 modRoots = []string{modRoot}
359 if cfg.ModFile != "" && !strings.HasSuffix(cfg.ModFile, ".mod") {
360 base.Fatalf("go: -modfile=%s: file does not have .mod extension", cfg.ModFile)
363 // We're in module mode. Set any global variables that need to be set.
364 cfg.ModulesEnabled = true
366 _ = TODOWorkspaces("ensure that buildmod is readonly")
367 list := filepath.SplitList(cfg.BuildContext.GOPATH)
368 if len(list) == 0 || list[0] == "" {
369 base.Fatalf("missing $GOPATH")
372 if _, err := fsys.Stat(filepath.Join(gopath, "go.mod")); err == nil {
373 base.Fatalf("$GOPATH/go.mod exists but should not")
376 if inWorkspaceMode() {
377 _ = TODOWorkspaces("go.work.sum, and also allow modfetch to fall back to individual go.sums")
378 _ = TODOWorkspaces("replaces")
380 modRoots, err = loadWorkFile(workFilePath)
382 base.Fatalf("reading go.work: %v", err)
384 modfetch.GoSumFile = workFilePath + ".sum"
385 // TODO(matloob) should workRoot just be workFile?
386 } else if modRoots == nil {
387 // We're in module mode, but not inside a module.
389 // Commands like 'go build', 'go run', 'go list' have no go.mod file to
390 // read or write. They would need to find and download the latest versions
391 // of a potentially large number of modules with no way to save version
392 // information. We can succeed slowly (but not reproducibly), but that's
393 // not usually a good experience.
395 // Instead, we forbid resolving import paths to modules other than std and
396 // cmd. Users may still build packages specified with .go files on the
397 // command line, but they'll see an error if those files import anything
400 // This can be overridden by calling AllowMissingModuleImports.
401 // For example, 'go get' does this, since it is expected to resolve paths.
403 // See golang.org/issue/32027.
405 modfetch.GoSumFile = strings.TrimSuffix(modFilePath(modRoots[0]), ".mod") + ".sum"
409 // WillBeEnabled checks whether modules should be enabled but does not
410 // initialize modules by installing hooks. If Init has already been called,
411 // WillBeEnabled returns the same result as Enabled.
413 // This function is needed to break a cycle. The main package needs to know
414 // whether modules are enabled in order to install the module or GOPATH version
415 // of 'go get', but Init reads the -modfile flag in 'go get', so it shouldn't
416 // be called until the command is installed and flags are parsed. Instead of
417 // calling Init and Enabled, the main package can call this function.
418 func WillBeEnabled() bool {
419 if modRoots != nil || cfg.ModulesEnabled {
424 // Initialized, not enabled.
428 // Keep in sync with Init. Init does extra validation and prints warnings or
429 // exits, so it can't call this function directly.
430 env := cfg.Getenv("GO111MODULE")
440 if modRoot := findModuleRoot(base.Cwd()); modRoot == "" {
441 // GO111MODULE is 'auto', and we can't find a module root.
442 // Stay in GOPATH mode.
444 } else if search.InDir(modRoot, os.TempDir()) == "." {
445 // If you create /tmp/go.mod for experimenting,
446 // then any tests that create work directories under /tmp
447 // will find it and get modules when they're not expecting them.
448 // It's a bit of a peculiar thing to disallow but quite mysterious
449 // when it happens. See golang.org/issue/26708.
455 // Enabled reports whether modules are (or must be) enabled.
456 // If modules are enabled but there is no main module, Enabled returns true
457 // and then the first use of module information will call die
458 // (usually through MustModRoot).
459 func Enabled() bool {
461 return modRoots != nil || cfg.ModulesEnabled
464 func VendorDir() string {
465 return filepath.Join(MainModules.ModRoot(MainModules.mustGetSingleMainModule()), "vendor")
468 func inWorkspaceMode() bool {
470 panic("inWorkspaceMode called before modload.Init called")
472 return workFilePath != ""
475 // HasModRoot reports whether a main module is present.
476 // HasModRoot may return false even if Enabled returns true: for example, 'get'
477 // does not require a main module.
478 func HasModRoot() bool {
480 return modRoots != nil
483 // MustHaveModRoot checks that a main module or main modules are present,
484 // and calls base.Fatalf if there are no main modules.
485 func MustHaveModRoot() {
492 // ModFilePath returns the path that would be used for the go.mod
493 // file, if in module mode. ModFilePath calls base.Fatalf if there is no main
494 // module, even if -modfile is set.
495 func ModFilePath() string {
497 return modFilePath(findModuleRoot(base.Cwd()))
500 func modFilePath(modRoot string) string {
501 if cfg.ModFile != "" {
504 return filepath.Join(modRoot, "go.mod")
508 if cfg.Getenv("GO111MODULE") == "off" {
509 base.Fatalf("go: modules disabled by GO111MODULE=off; see 'go help modules'")
511 if dir, name := findAltConfig(base.Cwd()); dir != "" {
512 rel, err := filepath.Rel(base.Cwd(), dir)
518 cdCmd = fmt.Sprintf("cd %s && ", rel)
520 base.Fatalf("go: cannot find main module, but found %s in %s\n\tto create a module there, run:\n\t%sgo mod init", name, dir, cdCmd)
522 base.Fatalf("go: %v", ErrNoModRoot)
525 var ErrNoModRoot = errors.New("go.mod file not found in current directory or any parent directory; see 'go help modules'")
527 type goModDirtyError struct{}
529 func (goModDirtyError) Error() string {
530 if cfg.BuildModExplicit {
531 return fmt.Sprintf("updates to go.mod needed, disabled by -mod=%v; to update it:\n\tgo mod tidy", cfg.BuildMod)
533 if cfg.BuildModReason != "" {
534 return fmt.Sprintf("updates to go.mod needed, disabled by -mod=%s\n\t(%s)\n\tto update it:\n\tgo mod tidy", cfg.BuildMod, cfg.BuildModReason)
536 return "updates to go.mod needed; to update it:\n\tgo mod tidy"
539 var errGoModDirty error = goModDirtyError{}
541 func loadWorkFile(path string) (modRoots []string, err error) {
542 workDir := filepath.Dir(path)
543 workData, err := lockedfile.Read(path)
547 wf, err := modfile.ParseWork(path, workData, nil)
551 seen := map[string]bool{}
552 for _, d := range wf.Directory {
554 if !filepath.IsAbs(modRoot) {
555 modRoot = filepath.Join(workDir, modRoot)
558 return nil, fmt.Errorf("path %s appears multiple times in workspace", modRoot)
561 modRoots = append(modRoots, modRoot)
566 // LoadModFile sets Target and, if there is a main module, parses the initial
567 // build list from its go.mod file.
569 // LoadModFile may make changes in memory, like adding a go directive and
570 // ensuring requirements are consistent, and will write those changes back to
571 // disk unless DisallowWriteGoMod is in effect.
573 // As a side-effect, LoadModFile may change cfg.BuildMod to "vendor" if
574 // -mod wasn't set explicitly and automatic vendoring should be enabled.
576 // If LoadModFile or CreateModFile has already been called, LoadModFile returns
577 // the existing in-memory requirements (rather than re-reading them from disk).
579 // LoadModFile checks the roots of the module graph for consistency with each
580 // other, but unlike LoadModGraph does not load the full module graph or check
581 // it for global consistency. Most callers outside of the modload package should
582 // use LoadModGraph instead.
583 func LoadModFile(ctx context.Context) *Requirements {
584 rs, needCommit := loadModFile(ctx)
586 commitRequirements(ctx, modFileGoVersion(), rs)
591 // loadModFile is like LoadModFile, but does not implicitly commit the
592 // requirements back to disk after fixing inconsistencies.
594 // If needCommit is true, after the caller makes any other needed changes to the
595 // returned requirements they should invoke commitRequirements to fix any
596 // inconsistencies that may be present in the on-disk go.mod file.
597 func loadModFile(ctx context.Context) (rs *Requirements, needCommit bool) {
598 if requirements != nil {
599 return requirements, false
603 if len(modRoots) == 0 {
604 _ = TODOWorkspaces("Instead of creating a fake module with an empty modroot, make MainModules.Len() == 0 mean that we're in module mode but not inside any module.")
605 mainModule := module.Version{Path: "command-line-arguments"}
606 MainModules = makeMainModules([]module.Version{mainModule}, []string{""}, []*modfile.File{nil}, []*modFileIndex{nil})
607 goVersion := LatestGoVersion()
608 rawGoVersion.Store(mainModule, goVersion)
609 requirements = newRequirements(modDepthFromGoVersion(goVersion), nil, nil)
610 return requirements, false
613 var modFiles []*modfile.File
614 var mainModules []module.Version
615 var indices []*modFileIndex
616 for _, modroot := range modRoots {
617 gomod := modFilePath(modroot)
620 if gomodActual, ok := fsys.OverlayPath(gomod); ok {
621 // Don't lock go.mod if it's part of the overlay.
622 // On Plan 9, locking requires chmod, and we don't want to modify any file
623 // in the overlay. See #44700.
624 data, err = os.ReadFile(gomodActual)
626 data, err = lockedfile.Read(gomodActual)
629 base.Fatalf("go: %v", err)
633 f, err := modfile.Parse(gomod, data, fixVersion(ctx, &fixed))
635 // Errors returned by modfile.Parse begin with file:line.
636 base.Fatalf("go: errors parsing go.mod:\n%s\n", err)
639 // No module declaration. Must add module path.
640 base.Fatalf("go: no module declaration in go.mod. To specify the module path:\n\tgo mod edit -module=example.com/mod")
643 modFiles = append(modFiles, f)
644 mainModule := f.Module.Mod
645 mainModules = append(mainModules, mainModule)
646 indices = append(indices, indexModFile(data, f, mainModule, fixed))
648 if err := module.CheckImportPath(f.Module.Mod.Path); err != nil {
649 if pathErr, ok := err.(*module.InvalidPathError); ok {
650 pathErr.Kind = "module"
652 base.Fatalf("go: %v", err)
656 MainModules = makeMainModules(mainModules, modRoots, modFiles, indices)
657 setDefaultBuildMod() // possibly enable automatic vendoring
658 rs = requirementsFromModFiles(ctx, modFiles)
660 if inWorkspaceMode() {
661 // We don't need to do anything for vendor or update the mod file so
664 _ = TODOWorkspaces("don't worry about commits for now, but eventually will want to update go.work files")
668 mainModule := MainModules.mustGetSingleMainModule()
670 if cfg.BuildMod == "vendor" {
671 readVendorList(mainModule)
672 index := MainModules.Index(mainModule)
673 modFile := MainModules.ModFile(mainModule)
674 checkVendorConsistency(index, modFile)
675 rs.initVendor(vendorList)
678 if rs.hasRedundantRoot() {
679 // If any module path appears more than once in the roots, we know that the
680 // go.mod file needs to be updated even though we have not yet loaded any
681 // transitive dependencies.
683 rs, err = updateRoots(ctx, rs.direct, rs, nil, nil, false)
685 base.Fatalf("go: %v", err)
689 if MainModules.Index(mainModule).goVersionV == "" {
690 // TODO(#45551): Do something more principled instead of checking
691 // cfg.CmdName directly here.
692 if cfg.BuildMod == "mod" && cfg.CmdName != "mod graph" && cfg.CmdName != "mod why" {
693 addGoStmt(MainModules.ModFile(mainModule), mainModule, LatestGoVersion())
694 if go117EnableLazyLoading {
695 // We need to add a 'go' version to the go.mod file, but we must assume
696 // that its existing contents match something between Go 1.11 and 1.16.
697 // Go 1.11 through 1.16 have eager requirements, but the latest Go
698 // version uses lazy requirements instead — so we need to cnvert the
699 // requirements to be lazy.
701 rs, err = convertDepth(ctx, rs, lazy)
703 base.Fatalf("go: %v", err)
707 rawGoVersion.Store(mainModule, modFileGoVersion())
712 return requirements, true
715 // CreateModFile initializes a new module by creating a go.mod file.
717 // If modPath is empty, CreateModFile will attempt to infer the path from the
718 // directory location within GOPATH.
720 // If a vendoring configuration file is present, CreateModFile will attempt to
721 // translate it to go.mod directives. The resulting build list may not be
722 // exactly the same as in the legacy configuration (for example, we can't get
723 // packages at multiple versions from the same module).
724 func CreateModFile(ctx context.Context, modPath string) {
725 modRoot := base.Cwd()
726 modRoots = []string{modRoot}
728 modFilePath := modFilePath(modRoot)
729 if _, err := fsys.Stat(modFilePath); err == nil {
730 base.Fatalf("go: %s already exists", modFilePath)
735 modPath, err = findModulePath(modRoot)
737 base.Fatalf("go: %v", err)
739 } else if err := module.CheckImportPath(modPath); err != nil {
740 if pathErr, ok := err.(*module.InvalidPathError); ok {
741 pathErr.Kind = "module"
742 // Same as build.IsLocalPath()
743 if pathErr.Path == "." || pathErr.Path == ".." ||
744 strings.HasPrefix(pathErr.Path, "./") || strings.HasPrefix(pathErr.Path, "../") {
745 pathErr.Err = errors.New("is a local import path")
748 base.Fatalf("go: %v", err)
749 } else if _, _, ok := module.SplitPathVersion(modPath); !ok {
750 if strings.HasPrefix(modPath, "gopkg.in/") {
751 invalidMajorVersionMsg := fmt.Errorf("module paths beginning with gopkg.in/ must always have a major version suffix in the form of .vN:\n\tgo mod init %s", suggestGopkgIn(modPath))
752 base.Fatalf(`go: invalid module path "%v": %v`, modPath, invalidMajorVersionMsg)
754 invalidMajorVersionMsg := fmt.Errorf("major version suffixes must be in the form of /vN and are only allowed for v2 or later:\n\tgo mod init %s", suggestModulePath(modPath))
755 base.Fatalf(`go: invalid module path "%v": %v`, modPath, invalidMajorVersionMsg)
758 fmt.Fprintf(os.Stderr, "go: creating new go.mod: module %s\n", modPath)
759 modFile := new(modfile.File)
760 modFile.AddModuleStmt(modPath)
761 MainModules = makeMainModules([]module.Version{modFile.Module.Mod}, []string{modRoot}, []*modfile.File{modFile}, []*modFileIndex{nil})
762 addGoStmt(modFile, modFile.Module.Mod, LatestGoVersion()) // Add the go directive before converted module requirements.
764 convertedFrom, err := convertLegacyConfig(modFile, modPath)
765 if convertedFrom != "" {
766 fmt.Fprintf(os.Stderr, "go: copying requirements from %s\n", base.ShortPath(convertedFrom))
769 base.Fatalf("go: %v", err)
772 rs := requirementsFromModFiles(ctx, []*modfile.File{modFile})
773 rs, err = updateRoots(ctx, rs.direct, rs, nil, nil, false)
775 base.Fatalf("go: %v", err)
777 commitRequirements(ctx, modFileGoVersion(), rs)
779 // Suggest running 'go mod tidy' unless the project is empty. Even if we
780 // imported all the correct requirements above, we're probably missing
781 // some sums, so the next build command in -mod=readonly will likely fail.
783 // We look for non-hidden .go files or subdirectories to determine whether
784 // this is an existing project. Walking the tree for packages would be more
785 // accurate, but could take much longer.
787 files, _ := os.ReadDir(modRoot)
788 for _, f := range files {
790 if strings.HasPrefix(name, ".") || strings.HasPrefix(name, "_") {
793 if strings.HasSuffix(name, ".go") || f.IsDir() {
799 fmt.Fprintf(os.Stderr, "go: to add module requirements and sums:\n\tgo mod tidy\n")
803 // CreateWorkFile initializes a new workspace by creating a go.work file.
804 func CreateWorkFile(ctx context.Context, workFile string, modDirs []string) {
805 _ = TODOWorkspaces("Report an error if the file already exists.")
807 goV := LatestGoVersion() // Use current Go version by default
808 workF := new(modfile.WorkFile)
809 workF.Syntax = new(modfile.FileSyntax)
812 for _, dir := range modDirs {
813 _ = TODOWorkspaces("Add the module path of the module.")
814 workF.AddDirectory(dir, "")
817 data := modfile.Format(workF.Syntax)
818 lockedfile.Write(workFile, bytes.NewReader(data), 0644)
821 // fixVersion returns a modfile.VersionFixer implemented using the Query function.
823 // It resolves commit hashes and branch names to versions,
824 // canonicalizes versions that appeared in early vgo drafts,
825 // and does nothing for versions that already appear to be canonical.
827 // The VersionFixer sets 'fixed' if it ever returns a non-canonical version.
828 func fixVersion(ctx context.Context, fixed *bool) modfile.VersionFixer {
829 return func(path, vers string) (resolved string, err error) {
831 if err == nil && resolved != vers {
836 // Special case: remove the old -gopkgin- hack.
837 if strings.HasPrefix(path, "gopkg.in/") && strings.Contains(vers, "-gopkgin-") {
838 vers = vers[strings.Index(vers, "-gopkgin-")+len("-gopkgin-"):]
841 // fixVersion is called speculatively on every
842 // module, version pair from every go.mod file.
843 // Avoid the query if it looks OK.
844 _, pathMajor, ok := module.SplitPathVersion(path)
846 return "", &module.ModuleError{
848 Err: &module.InvalidVersionError{
850 Err: fmt.Errorf("malformed module path %q", path),
854 if vers != "" && module.CanonicalVersion(vers) == vers {
855 if err := module.CheckPathMajor(vers, pathMajor); err != nil {
856 return "", module.VersionError(module.Version{Path: path, Version: vers}, err)
861 info, err := Query(ctx, path, vers, "", nil)
865 return info.Version, nil
869 // AllowMissingModuleImports allows import paths to be resolved to modules
870 // when there is no module root. Normally, this is forbidden because it's slow
871 // and there's no way to make the result reproducible, but some commands
872 // like 'go get' are expected to do this.
874 // This function affects the default cfg.BuildMod when outside of a module,
875 // so it can only be called prior to Init.
876 func AllowMissingModuleImports() {
878 panic("AllowMissingModuleImports after Init")
880 allowMissingModuleImports = true
883 // makeMainModules creates a MainModuleSet and associated variables according to
884 // the given main modules.
885 func makeMainModules(ms []module.Version, rootDirs []string, modFiles []*modfile.File, indices []*modFileIndex) *MainModuleSet {
886 for _, m := range ms {
888 panic("mainModulesCalled with module.Version with non empty Version field: " + fmt.Sprintf("%#v", m))
891 modRootContainingCWD := findModuleRoot(base.Cwd())
892 mainModules := &MainModuleSet{
893 versions: ms[:len(ms):len(ms)],
894 inGorootSrc: map[module.Version]bool{},
895 pathPrefix: map[module.Version]string{},
896 modRoot: map[module.Version]string{},
897 modFiles: map[module.Version]*modfile.File{},
898 indices: map[module.Version]*modFileIndex{},
900 for i, m := range ms {
901 mainModules.pathPrefix[m] = m.Path
902 mainModules.modRoot[m] = rootDirs[i]
903 mainModules.modFiles[m] = modFiles[i]
904 mainModules.indices[m] = indices[i]
906 if mainModules.modRoot[m] == modRootContainingCWD {
907 mainModules.modContainingCWD = m
910 if rel := search.InDir(rootDirs[i], cfg.GOROOTsrc); rel != "" {
911 mainModules.inGorootSrc[m] = true
913 // The "std" module in GOROOT/src is the Go standard library. Unlike other
914 // modules, the packages in the "std" module have no import-path prefix.
916 // Modules named "std" outside of GOROOT/src do not receive this special
917 // treatment, so it is possible to run 'go test .' in other GOROOTs to
918 // test individual packages using a combination of the modified package
919 // and the ordinary standard library.
920 // (See https://golang.org/issue/30756.)
921 mainModules.pathPrefix[m] = ""
928 // requirementsFromModFiles returns the set of non-excluded requirements from
929 // the global modFile.
930 func requirementsFromModFiles(ctx context.Context, modFiles []*modfile.File) *Requirements {
932 for i := range modFiles {
933 rootCap += len(modFiles[i].Require)
935 roots := make([]module.Version, 0, rootCap)
936 mPathCount := make(map[string]int)
937 for _, m := range MainModules.Versions() {
938 mPathCount[m.Path] = 1
940 direct := map[string]bool{}
941 for _, modFile := range modFiles {
943 for _, r := range modFile.Require {
944 // TODO(#45713): Maybe join
945 for _, mainModule := range MainModules.Versions() {
946 if index := MainModules.Index(mainModule); index != nil && index.exclude[r.Mod] {
947 if cfg.BuildMod == "mod" {
948 fmt.Fprintf(os.Stderr, "go: dropping requirement on excluded version %s %s\n", r.Mod.Path, r.Mod.Version)
950 fmt.Fprintf(os.Stderr, "go: ignoring requirement on excluded version %s %s\n", r.Mod.Path, r.Mod.Version)
956 roots = append(roots, r.Mod)
958 direct[r.Mod.Path] = true
963 rs := newRequirements(modDepthFromGoVersion(modFileGoVersion()), roots, direct)
967 // setDefaultBuildMod sets a default value for cfg.BuildMod if the -mod flag
968 // wasn't provided. setDefaultBuildMod may be called multiple times.
969 func setDefaultBuildMod() {
970 if cfg.BuildModExplicit {
971 if inWorkspaceMode() && cfg.BuildMod != "readonly" {
972 base.Fatalf("go: -mod may only be set to readonly when in workspace mode." +
973 "\n\tRemove the -mod flag to use the default readonly value," +
974 "\n\tor set -workfile=off to disable workspace mode.")
976 // Don't override an explicit '-mod=' argument.
980 // TODO(#40775): commands should pass in the module mode as an option
981 // to modload functions instead of relying on an implicit setting
982 // based on command name.
984 case "get", "mod download", "mod init", "mod tidy":
985 // These commands are intended to update go.mod and go.sum.
988 case "mod graph", "mod verify", "mod why":
989 // These commands should not update go.mod or go.sum, but they should be
990 // able to fetch modules not in go.sum and should not report errors if
991 // go.mod is inconsistent. They're useful for debugging, and they need
992 // to work in buggy situations.
994 allowWriteGoMod = false
997 cfg.BuildMod = "readonly"
1000 if modRoots == nil {
1001 if allowMissingModuleImports {
1002 cfg.BuildMod = "mod"
1004 cfg.BuildMod = "readonly"
1009 if len(modRoots) == 1 {
1010 index := MainModules.GetSingleIndexOrNil()
1011 if fi, err := fsys.Stat(filepath.Join(modRoots[0], "vendor")); err == nil && fi.IsDir() {
1012 modGo := "unspecified"
1013 if index != nil && index.goVersionV != "" {
1014 if semver.Compare(index.goVersionV, "v1.14") >= 0 {
1015 // The Go version is at least 1.14, and a vendor directory exists.
1016 // Set -mod=vendor by default.
1017 cfg.BuildMod = "vendor"
1018 cfg.BuildModReason = "Go version in go.mod is at least 1.14 and vendor directory exists."
1021 modGo = index.goVersionV[1:]
1025 // Since a vendor directory exists, we should record why we didn't use it.
1026 // This message won't normally be shown, but it may appear with import errors.
1027 cfg.BuildModReason = fmt.Sprintf("Go version in go.mod is %s, so vendor directory was not used.", modGo)
1031 cfg.BuildMod = "readonly"
1034 func mustHaveCompleteRequirements() bool {
1035 return cfg.BuildMod != "mod" && !inWorkspaceMode()
1038 // convertLegacyConfig imports module requirements from a legacy vendoring
1039 // configuration file, if one is present.
1040 func convertLegacyConfig(modFile *modfile.File, modPath string) (from string, err error) {
1041 noneSelected := func(path string) (version string) { return "none" }
1042 queryPackage := func(path, rev string) (module.Version, error) {
1043 pkgMods, modOnly, err := QueryPattern(context.Background(), path, rev, noneSelected, nil)
1045 return module.Version{}, err
1047 if len(pkgMods) > 0 {
1048 return pkgMods[0].Mod, nil
1050 return modOnly.Mod, nil
1052 for _, name := range altConfigs {
1053 if len(modRoots) != 1 {
1054 panic(TODOWorkspaces("what do do here?"))
1056 cfg := filepath.Join(modRoots[0], name)
1057 data, err := os.ReadFile(cfg)
1059 convert := modconv.Converters[name]
1063 cfg = filepath.ToSlash(cfg)
1064 err := modconv.ConvertLegacyConfig(modFile, cfg, data, queryPackage)
1071 // addGoStmt adds a go directive to the go.mod file if it does not already
1072 // include one. The 'go' version added, if any, is the latest version supported
1073 // by this toolchain.
1074 func addGoStmt(modFile *modfile.File, mod module.Version, v string) {
1075 if modFile.Go != nil && modFile.Go.Version != "" {
1078 if err := modFile.AddGoStmt(v); err != nil {
1079 base.Fatalf("go: internal error: %v", err)
1081 rawGoVersion.Store(mod, v)
1084 // LatestGoVersion returns the latest version of the Go language supported by
1085 // this toolchain, like "1.17".
1086 func LatestGoVersion() string {
1087 tags := build.Default.ReleaseTags
1088 version := tags[len(tags)-1]
1089 if !strings.HasPrefix(version, "go") || !modfile.GoVersionRE.MatchString(version[2:]) {
1090 base.Fatalf("go: internal error: unrecognized default version %q", version)
1095 // priorGoVersion returns the Go major release immediately preceding v,
1096 // or v itself if v is the first Go major release (1.0) or not a supported
1098 func priorGoVersion(v string) string {
1100 tags := build.Default.ReleaseTags
1101 for i, tag := range tags {
1107 version := tags[i-1]
1108 if !strings.HasPrefix(version, "go") || !modfile.GoVersionRE.MatchString(version[2:]) {
1109 base.Fatalf("go: internal error: unrecognized version %q", version)
1117 var altConfigs = []string{
1121 "Godeps/Godeps.json",
1127 "vendor/vendor.json",
1132 func findModuleRoot(dir string) (roots string) {
1134 panic("dir not set")
1136 dir = filepath.Clean(dir)
1138 // Look for enclosing go.mod.
1140 if fi, err := fsys.Stat(filepath.Join(dir, "go.mod")); err == nil && !fi.IsDir() {
1143 d := filepath.Dir(dir)
1152 func findWorkspaceFile(dir string) (root string) {
1154 panic("dir not set")
1156 dir = filepath.Clean(dir)
1158 // Look for enclosing go.mod.
1160 f := filepath.Join(dir, "go.work")
1161 if fi, err := fsys.Stat(f); err == nil && !fi.IsDir() {
1164 d := filepath.Dir(dir)
1168 if d == cfg.GOROOT {
1169 _ = TODOWorkspaces("Address how go.work files interact with GOROOT")
1170 return "" // As a special case, don't cross GOROOT to find a go.work file.
1177 func findAltConfig(dir string) (root, name string) {
1179 panic("dir not set")
1181 dir = filepath.Clean(dir)
1182 if rel := search.InDir(dir, cfg.BuildContext.GOROOT); rel != "" {
1183 // Don't suggest creating a module from $GOROOT/.git/config
1184 // or a config file found in any parent of $GOROOT (see #34191).
1188 for _, name := range altConfigs {
1189 if fi, err := fsys.Stat(filepath.Join(dir, name)); err == nil && !fi.IsDir() {
1193 d := filepath.Dir(dir)
1202 func findModulePath(dir string) (string, error) {
1203 // TODO(bcmills): once we have located a plausible module path, we should
1204 // query version control (if available) to verify that it matches the major
1205 // version of the most recent tag.
1206 // See https://golang.org/issue/29433, https://golang.org/issue/27009, and
1207 // https://golang.org/issue/31549.
1209 // Cast about for import comments,
1210 // first in top-level directory, then in subdirectories.
1211 list, _ := os.ReadDir(dir)
1212 for _, info := range list {
1213 if info.Type().IsRegular() && strings.HasSuffix(info.Name(), ".go") {
1214 if com := findImportComment(filepath.Join(dir, info.Name())); com != "" {
1219 for _, info1 := range list {
1221 files, _ := os.ReadDir(filepath.Join(dir, info1.Name()))
1222 for _, info2 := range files {
1223 if info2.Type().IsRegular() && strings.HasSuffix(info2.Name(), ".go") {
1224 if com := findImportComment(filepath.Join(dir, info1.Name(), info2.Name())); com != "" {
1225 return path.Dir(com), nil
1232 // Look for Godeps.json declaring import path.
1233 data, _ := os.ReadFile(filepath.Join(dir, "Godeps/Godeps.json"))
1234 var cfg1 struct{ ImportPath string }
1235 json.Unmarshal(data, &cfg1)
1236 if cfg1.ImportPath != "" {
1237 return cfg1.ImportPath, nil
1240 // Look for vendor.json declaring import path.
1241 data, _ = os.ReadFile(filepath.Join(dir, "vendor/vendor.json"))
1242 var cfg2 struct{ RootPath string }
1243 json.Unmarshal(data, &cfg2)
1244 if cfg2.RootPath != "" {
1245 return cfg2.RootPath, nil
1248 // Look for path in GOPATH.
1249 var badPathErr error
1250 for _, gpdir := range filepath.SplitList(cfg.BuildContext.GOPATH) {
1254 if rel := search.InDir(dir, filepath.Join(gpdir, "src")); rel != "" && rel != "." {
1255 path := filepath.ToSlash(rel)
1256 // gorelease will alert users publishing their modules to fix their paths.
1257 if err := module.CheckImportPath(path); err != nil {
1265 reason := "outside GOPATH, module path must be specified"
1266 if badPathErr != nil {
1267 // return a different error message if the module was in GOPATH, but
1268 // the module path determined above would be an invalid path.
1269 reason = fmt.Sprintf("bad module path inferred from directory in GOPATH: %v", badPathErr)
1271 msg := `cannot determine module path for source directory %s (%s)
1274 'go mod init example.com/m' to initialize a v0 or v1 module
1275 'go mod init example.com/m/v2' to initialize a v2 module
1277 Run 'go help mod init' for more information.
1279 return "", fmt.Errorf(msg, dir, reason)
1283 importCommentRE = lazyregexp.New(`(?m)^package[ \t]+[^ \t\r\n/]+[ \t]+//[ \t]+import[ \t]+(\"[^"]+\")[ \t]*\r?\n`)
1286 func findImportComment(file string) string {
1287 data, err := os.ReadFile(file)
1291 m := importCommentRE.FindSubmatch(data)
1295 path, err := strconv.Unquote(string(m[1]))
1302 var allowWriteGoMod = true
1304 // DisallowWriteGoMod causes future calls to WriteGoMod to do nothing at all.
1305 func DisallowWriteGoMod() {
1306 allowWriteGoMod = false
1309 // AllowWriteGoMod undoes the effect of DisallowWriteGoMod:
1310 // future calls to WriteGoMod will update go.mod if needed.
1311 // Note that any past calls have been discarded, so typically
1312 // a call to AlowWriteGoMod should be followed by a call to WriteGoMod.
1313 func AllowWriteGoMod() {
1314 allowWriteGoMod = true
1317 // WriteGoMod writes the current build list back to go.mod.
1318 func WriteGoMod(ctx context.Context) {
1319 if !allowWriteGoMod {
1320 panic("WriteGoMod called while disallowed")
1322 commitRequirements(ctx, modFileGoVersion(), LoadModFile(ctx))
1325 // commitRequirements writes sets the global requirements variable to rs and
1326 // writes its contents back to the go.mod file on disk.
1327 func commitRequirements(ctx context.Context, goVersion string, rs *Requirements) {
1330 if !allowWriteGoMod {
1331 // Some package outside of modload promised to update the go.mod file later.
1335 if inWorkspaceMode() {
1336 // go.mod files aren't updated in workspace mode, but we still want to
1337 // update the go.work.sum file.
1338 if err := modfetch.WriteGoSum(keepSums(ctx, loaded, rs, addBuildListZipSums), mustHaveCompleteRequirements()); err != nil {
1339 base.Fatalf("go: %v", err)
1344 if MainModules.Len() != 1 || MainModules.ModRoot(MainModules.Versions()[0]) == "" {
1345 // We aren't in a module, so we don't have anywhere to write a go.mod file.
1348 mainModule := MainModules.Versions()[0]
1349 modFilePath := modFilePath(MainModules.ModRoot(mainModule))
1350 modFile := MainModules.ModFile(mainModule)
1352 var list []*modfile.Require
1353 for _, m := range rs.rootModules {
1354 list = append(list, &modfile.Require{
1356 Indirect: !rs.direct[m.Path],
1359 if goVersion != "" {
1360 modFile.AddGoStmt(goVersion)
1362 if semver.Compare("v"+modFileGoVersion(), separateIndirectVersionV) < 0 {
1363 modFile.SetRequire(list)
1365 modFile.SetRequireSeparateIndirect(list)
1369 index := MainModules.GetSingleIndexOrNil()
1370 dirty := index.modFileIsDirty(modFile)
1371 if dirty && cfg.BuildMod != "mod" {
1372 // If we're about to fail due to -mod=readonly,
1373 // prefer to report a dirty go.mod over a dirty go.sum
1374 base.Fatalf("go: %v", errGoModDirty)
1377 if !dirty && cfg.CmdName != "mod tidy" {
1378 // The go.mod file has the same semantic content that it had before
1379 // (but not necessarily the same exact bytes).
1380 // Don't write go.mod, but write go.sum in case we added or trimmed sums.
1381 // 'go mod init' shouldn't write go.sum, since it will be incomplete.
1382 if cfg.CmdName != "mod init" {
1383 if err := modfetch.WriteGoSum(keepSums(ctx, loaded, rs, addBuildListZipSums), mustHaveCompleteRequirements()); err != nil {
1384 base.Fatalf("go: %v", err)
1389 if _, ok := fsys.OverlayPath(modFilePath); ok {
1391 base.Fatalf("go: updates to go.mod needed, but go.mod is part of the overlay specified with -overlay")
1396 new, err := modFile.Format()
1398 base.Fatalf("go: %v", err)
1401 if MainModules.Len() != 1 {
1402 panic(TODOWorkspaces("There should be exactly one main module when committing reqs"))
1405 mainModule := MainModules.Versions()[0]
1407 // At this point we have determined to make the go.mod file on disk equal to new.
1408 MainModules.SetIndex(mainModule, indexModFile(new, modFile, mainModule, false))
1410 // Update go.sum after releasing the side lock and refreshing the index.
1411 // 'go mod init' shouldn't write go.sum, since it will be incomplete.
1412 if cfg.CmdName != "mod init" {
1413 if err := modfetch.WriteGoSum(keepSums(ctx, loaded, rs, addBuildListZipSums), mustHaveCompleteRequirements()); err != nil {
1414 base.Fatalf("go: %v", err)
1419 // Make a best-effort attempt to acquire the side lock, only to exclude
1420 // previous versions of the 'go' command from making simultaneous edits.
1421 if unlock, err := modfetch.SideLock(); err == nil {
1425 errNoChange := errors.New("no update needed")
1427 err = lockedfile.Transform(modFilePath, func(old []byte) ([]byte, error) {
1428 if bytes.Equal(old, new) {
1429 // The go.mod file is already equal to new, possibly as the result of some
1431 return nil, errNoChange
1434 if index != nil && !bytes.Equal(old, index.data) {
1435 // The contents of the go.mod file have changed. In theory we could add all
1436 // of the new modules to the build list, recompute, and check whether any
1437 // module in *our* build list got bumped to a different version, but that's
1438 // a lot of work for marginal benefit. Instead, fail the command: if users
1439 // want to run concurrent commands, they need to start with a complete,
1440 // consistent module definition.
1441 return nil, fmt.Errorf("existing contents have changed since last read")
1447 if err != nil && err != errNoChange {
1448 base.Fatalf("go: updating go.mod: %v", err)
1452 // keepSums returns the set of modules (and go.mod file entries) for which
1453 // checksums would be needed in order to reload the same set of packages
1454 // loaded by the most recent call to LoadPackages or ImportFromFiles,
1455 // including any go.mod files needed to reconstruct the MVS result,
1456 // in addition to the checksums for every module in keepMods.
1457 func keepSums(ctx context.Context, ld *loader, rs *Requirements, which whichSums) map[module.Version]bool {
1458 // Every module in the full module graph contributes its requirements,
1459 // so in order to ensure that the build list itself is reproducible,
1460 // we need sums for every go.mod in the graph (regardless of whether
1461 // that version is selected).
1462 keep := make(map[module.Version]bool)
1464 // Add entries for modules in the build list with paths that are prefixes of
1465 // paths of loaded packages. We need to retain sums for all of these modules —
1466 // not just the modules containing the actual packages — in order to rule out
1467 // ambiguous import errors the next time we load the package.
1469 for _, pkg := range ld.pkgs {
1470 // We check pkg.mod.Path here instead of pkg.inStd because the
1471 // pseudo-package "C" is not in std, but not provided by any module (and
1472 // shouldn't force loading the whole module graph).
1473 if pkg.testOf != nil || (pkg.mod.Path == "" && pkg.err == nil) || module.CheckImportPath(pkg.path) != nil {
1477 if rs.depth == lazy && pkg.mod.Path != "" {
1478 if v, ok := rs.rootSelected(pkg.mod.Path); ok && v == pkg.mod.Version {
1479 // pkg was loaded from a root module, and because the main module is
1480 // lazy we do not check non-root modules for conflicts for packages
1481 // that can be found in roots. So we only need the checksums for the
1482 // root modules that may contain pkg, not all possible modules.
1483 for prefix := pkg.path; prefix != "."; prefix = path.Dir(prefix) {
1484 if v, ok := rs.rootSelected(prefix); ok && v != "none" {
1485 m := module.Version{Path: prefix, Version: v}
1486 r, _ := resolveReplacement(m)
1494 mg, _ := rs.Graph(ctx)
1495 for prefix := pkg.path; prefix != "."; prefix = path.Dir(prefix) {
1496 if v := mg.Selected(prefix); v != "none" {
1497 m := module.Version{Path: prefix, Version: v}
1498 r, _ := resolveReplacement(m)
1505 if rs.graph.Load() == nil {
1506 // The module graph was not loaded, possibly because the main module is lazy
1507 // or possibly because we haven't needed to load the graph yet.
1508 // Save sums for the root modules (or their replacements), but don't
1509 // incur the cost of loading the graph just to find and retain the sums.
1510 for _, m := range rs.rootModules {
1511 r, _ := resolveReplacement(m)
1512 keep[modkey(r)] = true
1513 if which == addBuildListZipSums {
1518 mg, _ := rs.Graph(ctx)
1519 mg.WalkBreadthFirst(func(m module.Version) {
1520 if _, ok := mg.RequiredBy(m); ok {
1521 // The requirements from m's go.mod file are present in the module graph,
1522 // so they are relevant to the MVS result regardless of whether m was
1523 // actually selected.
1524 r, _ := resolveReplacement(m)
1525 keep[modkey(r)] = true
1529 if which == addBuildListZipSums {
1530 for _, m := range mg.BuildList() {
1531 r, _ := resolveReplacement(m)
1543 loadedZipSumsOnly = whichSums(iota)
1547 // modKey returns the module.Version under which the checksum for m's go.mod
1548 // file is stored in the go.sum file.
1549 func modkey(m module.Version) module.Version {
1550 return module.Version{Path: m.Path, Version: m.Version + "/go.mod"}
1553 func suggestModulePath(path string) string {
1557 for i > 0 && ('0' <= path[i-1] && path[i-1] <= '9' || path[i-1] == '.') {
1561 url = strings.TrimSuffix(url, "/v")
1562 url = strings.TrimSuffix(url, "/")
1564 f := func(c rune) bool {
1565 return c > '9' || c < '0'
1567 s := strings.FieldsFunc(path[i:], f)
1571 m = strings.TrimLeft(m, "0")
1572 if m == "" || m == "1" {
1576 return url + "/v" + m
1579 func suggestGopkgIn(path string) string {
1582 for i > 0 && (('0' <= path[i-1] && path[i-1] <= '9') || (path[i-1] == '.')) {
1586 url = strings.TrimSuffix(url, ".v")
1587 url = strings.TrimSuffix(url, "/v")
1588 url = strings.TrimSuffix(url, "/")
1590 f := func(c rune) bool {
1591 return c > '9' || c < '0'
1593 s := strings.FieldsFunc(path, f)
1598 m = strings.TrimLeft(m, "0")
1603 return url + ".v" + m