1
2
3
4
5
6
7 package modcmd
8
9 import (
10 "cmd/go/internal/base"
11 "cmd/go/internal/modload"
12 "context"
13 )
14
15 var cmdInit = &base.Command{
16 UsageLine: "go mod init [module-path]",
17 Short: "initialize new module in current directory",
18 Long: `
19 Init initializes and writes a new go.mod file in the current directory, in
20 effect creating a new module rooted at the current directory. The go.mod file
21 must not already exist.
22
23 Init accepts one optional argument, the module path for the new module. If the
24 module path argument is omitted, init will attempt to infer the module path
25 using import comments in .go files and the current directory (if in GOPATH).
26
27 See https://golang.org/ref/mod#go-mod-init for more about 'go mod init'.
28 `,
29 Run: runInit,
30 }
31
32 func init() {
33 base.AddChdirFlag(&cmdInit.Flag)
34 base.AddModCommonFlags(&cmdInit.Flag)
35 }
36
37 func runInit(ctx context.Context, cmd *base.Command, args []string) {
38 if len(args) > 1 {
39 base.Fatalf("go: 'go mod init' accepts at most one argument")
40 }
41 var modPath string
42 if len(args) == 1 {
43 modPath = args[0]
44 }
45
46 modload.ForceUseModules = true
47 modload.CreateModFile(ctx, modPath)
48 }
49
View as plain text