| 1 |
// Copyright 2018 The Go Authors. All rights reserved. |
| 2 |
// Use of this source code is governed by a BSD-style |
| 3 |
// license that can be found in the LICENSE file. |
| 4 |
|
| 5 |
// go mod init |
| 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 |
moduleLoaderState := modload.NewState() |
| 39 |
if len(args) > 1 { |
| 40 |
base.Fatalf("go: 'go mod init' accepts at most one argument") |
| 41 |
} |
| 42 |
var modPath string |
| 43 |
if len(args) == 1 { |
| 44 |
modPath = args[0] |
| 45 |
} |
| 46 |
|
| 47 |
moduleLoaderState.ForceUseModules = true |
| 48 |
modload.CreateModFile(moduleLoaderState, ctx, modPath) // does all the hard work |
| 49 |
} |