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, vendoring tool configuration files (like
26 Gopkg.lock), and the current directory (if in GOPATH).
27
28 If a configuration file for a vendoring tool is present, init will attempt to
29 import module requirements from it.
30
31 See https://golang.org/ref/mod#go-mod-init for more about 'go mod init'.
32 `,
33 Run: runInit,
34 }
35
36 func init() {
37 base.AddModCommonFlags(&cmdInit.Flag)
38 }
39
40 func runInit(ctx context.Context, cmd *base.Command, args []string) {
41 if len(args) > 1 {
42 base.Fatalf("go: 'go mod init' accepts at most one argument")
43 }
44 var modPath string
45 if len(args) == 1 {
46 modPath = args[0]
47 }
48
49 modload.ForceUseModules = true
50 modload.CreateModFile(ctx, modPath)
51 }
52
View as plain text