cmd/go: move CreateWorkFile from modload to workcmd

In workcmd it can deal with automatic version switching.

For #57001.

Change-Id: I5027690cf744d6d73f87e837c76ea7083ed56aba
Reviewed-on: https://go-review.googlesource.com/c/go/+/499979
Reviewed-by: Bryan Mills <bcmills@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Run-TryBot: Russ Cox <rsc@golang.org>
Auto-Submit: Russ Cox <rsc@golang.org>
This commit is contained in:
Russ Cox 2023-06-01 12:59:36 -04:00 committed by Gopher Robot
parent 459cca5cb2
commit 9f450041c5
2 changed files with 32 additions and 27 deletions

View File

@ -983,32 +983,6 @@ func CreateModFile(ctx context.Context, modPath string) {
}
}
// CreateWorkFile initializes a new workspace by creating a go.work file.
func CreateWorkFile(ctx context.Context, workFile string, modDirs []string) {
if _, err := fsys.Stat(workFile); err == nil {
base.Fatalf("go: %s already exists", workFile)
}
goV := gover.Local() // Use current Go version by default
workF := new(modfile.WorkFile)
workF.Syntax = new(modfile.FileSyntax)
workF.AddGoStmt(goV)
for _, dir := range modDirs {
_, f, err := ReadModFile(filepath.Join(dir, "go.mod"), nil)
if err != nil {
if os.IsNotExist(err) {
base.Fatalf("go: creating workspace file: no go.mod file exists in directory %v", dir)
}
base.Fatalf("go: error parsing go.mod in directory %s: %v", dir, err)
}
workF.AddUse(ToDirectoryPath(dir), f.Module.Mod.Path)
}
UpdateWorkFile(workF)
WriteWorkFile(workFile, workF)
}
// fixVersion returns a modfile.VersionFixer implemented using the Query function.
//
// It resolves commit hashes and branch names to versions,

View File

@ -8,9 +8,14 @@ package workcmd
import (
"cmd/go/internal/base"
"cmd/go/internal/fsys"
"cmd/go/internal/gover"
"cmd/go/internal/modload"
"context"
"os"
"path/filepath"
"golang.org/x/mod/modfile"
)
var cmdInit = &base.Command{
@ -48,5 +53,31 @@ func runInit(ctx context.Context, cmd *base.Command, args []string) {
workFile = filepath.Join(base.Cwd(), "go.work")
}
modload.CreateWorkFile(ctx, workFile, args)
CreateWorkFile(ctx, workFile, args)
}
// CreateWorkFile initializes a new workspace by creating a go.work file.
func CreateWorkFile(ctx context.Context, workFile string, modDirs []string) {
if _, err := fsys.Stat(workFile); err == nil {
base.Fatalf("go: %s already exists", workFile)
}
goV := gover.Local() // Use current Go version by default
wf := new(modfile.WorkFile)
wf.Syntax = new(modfile.FileSyntax)
wf.AddGoStmt(goV)
for _, dir := range modDirs {
_, f, err := modload.ReadModFile(filepath.Join(dir, "go.mod"), nil)
if err != nil {
if os.IsNotExist(err) {
base.Fatalf("go: creating workspace file: no go.mod file exists in directory %v", dir)
}
base.Fatalf("go: error parsing go.mod in directory %s: %v", dir, err)
}
wf.AddUse(modload.ToDirectoryPath(dir), f.Module.Mod.Path)
}
modload.UpdateWorkFile(wf)
modload.WriteWorkFile(workFile, wf)
}