| 1 |
// Copyright 2021 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 work init |
| 6 |
|
| 7 |
package workcmd |
| 8 |
|
| 9 |
import ( |
| 10 |
"context" |
| 11 |
"path/filepath" |
| 12 |
|
| 13 |
"cmd/go/internal/base" |
| 14 |
"cmd/go/internal/fsys" |
| 15 |
"cmd/go/internal/gover" |
| 16 |
"cmd/go/internal/modload" |
| 17 |
|
| 18 |
"golang.org/x/mod/modfile" |
| 19 |
) |
| 20 |
|
| 21 |
var cmdInit = &base.Command{ |
| 22 |
UsageLine: "go work init [moddirs]", |
| 23 |
Short: "initialize workspace file", |
| 24 |
Long: `Init initializes and writes a new go.work file in the |
| 25 |
current directory, in effect creating a new workspace at the current |
| 26 |
directory. |
| 27 |
|
| 28 |
go work init optionally accepts paths to the workspace modules as |
| 29 |
arguments. If the argument is omitted, an empty workspace with no |
| 30 |
modules will be created. |
| 31 |
|
| 32 |
Each argument path is added to a use directive in the go.work file. The |
| 33 |
current go version will also be listed in the go.work file. |
| 34 |
|
| 35 |
See the workspaces reference at https://go.dev/ref/mod#workspaces |
| 36 |
for more information. |
| 37 |
`, |
| 38 |
Run: runInit, |
| 39 |
} |
| 40 |
|
| 41 |
func init() { |
| 42 |
base.AddChdirFlag(&cmdInit.Flag) |
| 43 |
base.AddModCommonFlags(&cmdInit.Flag) |
| 44 |
} |
| 45 |
|
| 46 |
func runInit(ctx context.Context, cmd *base.Command, args []string) { |
| 47 |
moduleLoaderState := modload.NewState() |
| 48 |
moduleLoaderState.InitWorkfile() |
| 49 |
|
| 50 |
moduleLoaderState.ForceUseModules = true |
| 51 |
|
| 52 |
gowork := modload.WorkFilePath(moduleLoaderState) |
| 53 |
if gowork == "" { |
| 54 |
gowork = filepath.Join(base.Cwd(), "go.work") |
| 55 |
} |
| 56 |
|
| 57 |
if _, err := fsys.Stat(gowork); err == nil { |
| 58 |
base.Fatalf("go: %s already exists", gowork) |
| 59 |
} |
| 60 |
|
| 61 |
goV := gover.Local() // Use current Go version by default |
| 62 |
wf := new(modfile.WorkFile) |
| 63 |
wf.Syntax = new(modfile.FileSyntax) |
| 64 |
wf.AddGoStmt(goV) |
| 65 |
workUse(ctx, moduleLoaderState, gowork, wf, args) |
| 66 |
modload.WriteWorkFile(gowork, wf) |
| 67 |
} |