Source file src/cmd/go/internal/modcmd/init.go

     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, vendoring tool configuration files (like
    26  Gopkg.lock), and the current directory (if in GOPATH).
    27  
    28  See https://golang.org/ref/mod#go-mod-init for more about 'go mod init'.
    29  `,
    30  	Run: runInit,
    31  }
    32  
    33  func init() {
    34  	base.AddChdirFlag(&cmdInit.Flag)
    35  	base.AddModCommonFlags(&cmdInit.Flag)
    36  }
    37  
    38  func runInit(ctx context.Context, cmd *base.Command, args []string) {
    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  	modload.ForceUseModules = true
    48  	modload.CreateModFile(ctx, modPath) // does all the hard work
    49  }
    50  

View as plain text