Black Lives Matter. Support the Equal Justice Initiative.

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

Documentation: cmd/go/internal/modcmd

     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]",
    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 mod init: too many arguments")
    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) // does all the hard work
    51  }
    52  

View as plain text