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/gover"
16 "cmd/go/internal/modload"
17
18 "golang.org/x/mod/modfile"
19 )
20
21 var cmdInit = &base.Command{
22 UsageLine: "go work init [moddirs]",
23 Short: "initialize workspace file",
24 Long: `Init initializes and writes a new go.work file in the
25 current directory, in effect creating a new workspace at the current
26 directory.
27
28 go work init optionally accepts paths to the workspace modules as
29 arguments. If the argument is omitted, an empty workspace with no
30 modules will be created.
31
32 Each argument path is added to a use directive in the go.work file. The
33 current go version will also be listed in the go.work file.
34
35 See the workspaces reference at https://go.dev/ref/mod#workspaces
36 for more information.
37 `,
38 Run: runInit,
39 }
40
41 func init() {
42 base.AddChdirFlag(&cmdInit.Flag)
43 base.AddModCommonFlags(&cmdInit.Flag)
44 }
45
46 func runInit(ctx context.Context, cmd *base.Command, args []string) {
47 modload.InitWorkfile()
48
49 modload.ForceUseModules = true
50
51 gowork := modload.WorkFilePath()
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 goV := gover.Local()
61 wf := new(modfile.WorkFile)
62 wf.Syntax = new(modfile.FileSyntax)
63 wf.AddGoStmt(goV)
64 workUse(ctx, gowork, wf, args)
65 modload.WriteWorkFile(gowork, wf)
66 }
67
View as plain text