github.com/go-asm/go@v1.21.1-0.20240213172139-40c5ead50c48/cmd/go/workcmd/init.go (about) 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 "github.com/go-asm/go/cmd/go/base" 14 "github.com/go-asm/go/cmd/go/fsys" 15 "github.com/go-asm/go/cmd/go/gover" 16 "github.com/go-asm/go/cmd/go/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 modload.InitWorkfile() 48 49 modload.ForceUseModules = true 50 51 gowork := modload.WorkFilePath() 52 if gowork == "" { 53 gowork = filepath.Join(base.Cwd(), "go.work") 54 } 55 56 if _, err := fsys.Stat(gowork); err == nil { 57 base.Fatalf("go: %s already exists", gowork) 58 } 59 60 goV := gover.Local() // Use current Go version by default 61 wf := new(modfile.WorkFile) 62 wf.Syntax = new(modfile.FileSyntax) 63 wf.AddGoStmt(goV) 64 workUse(ctx, gowork, wf, args) 65 modload.WriteWorkFile(gowork, wf) 66 }