1
2
3
4
5
6
7 package workcmd
8
9 import (
10 "context"
11 "path/filepath"
12
13 "cmd/go/internal/base"
14 "cmd/go/internal/fsys"
15 "cmd/go/internal/modload"
16
17 "golang.org/x/mod/modfile"
18 )
19
20 var cmdInit = &base.Command{
21 UsageLine: "go work init [moddirs]",
22 Short: "initialize workspace file",
23 Long: `Init initializes and writes a new go.work file in the
24 current directory, in effect creating a new workspace at the current
25 directory.
26
27 go work init optionally accepts paths to the workspace modules as
28 arguments. If the argument is omitted, an empty workspace with no
29 modules will be created.
30
31 Each argument path is added to a use directive in the go.work file. The
32 current go version will also be listed in the go.work file.
33
34 See the workspaces reference at https://go.dev/ref/mod#workspaces
35 for more information.
36 `,
37 Run: runInit,
38 }
39
40 func init() {
41 base.AddChdirFlag(&cmdInit.Flag)
42 base.AddModCommonFlags(&cmdInit.Flag)
43 }
44
45 func runInit(ctx context.Context, cmd *base.Command, args []string) {
46 moduleLoaderState := modload.NewState()
47 moduleLoaderState.InitWorkfile()
48
49 moduleLoaderState.ForceUseModules = true
50
51 gowork := modload.WorkFilePath(moduleLoaderState)
52 if gowork == "" {
53 gowork = filepath.Join(base.Cwd(), "go.work")
54 }
55
56 if _, err := fsys.Stat(gowork); err == nil {
57 base.Fatalf("go: %s already exists", gowork)
58 }
59
60 wf := new(modfile.WorkFile)
61 wf.Syntax = new(modfile.FileSyntax)
62 wf.AddGoStmt(modload.DefaultModInitGoVersion())
63 workUse(ctx, moduleLoaderState, gowork, wf, args)
64 modload.WriteWorkFile(gowork, wf)
65 }
66
View as plain text