aboutsummaryrefslogtreecommitdiff
path: root/src/cmd/go/internal/modcmd/editwork.go
blob: f05d9245e7da3eb875d7e52659a9ceda8a2ce7e7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// go mod editwork

package modcmd

import (
	"bytes"
	"cmd/go/internal/base"
	"cmd/go/internal/lockedfile"
	"cmd/go/internal/modload"
	"context"
	"encoding/json"
	"errors"
	"os"
	"strings"

	"golang.org/x/mod/modfile"
)

var cmdEditwork = &base.Command{
	UsageLine: "go mod editwork [editing flags] [go.work]",
	Short:     "edit go.work from tools or scripts",
	Long: `Editwork provides a command-line interface for editing go.work,
for use primarily by tools or scripts. It only reads go.work;
it does not look up information about the modules involved.
If no file is specified, editwork looks for a go.work file in the current
directory and its parent directories

The editing flags specify a sequence of editing operations.

The -fmt flag reformats the go.work file without making other changes.
This reformatting is also implied by any other modifications that use or
rewrite the go.mod file. The only time this flag is needed is if no other
flags are specified, as in 'go mod editwork -fmt'.

The -directory=path and -dropdirectory=path flags
add and drop a directory from the go.work files set of module directories.

The -replace=old[@v]=new[@v] flag adds a replacement of the given
module path and version pair. If the @v in old@v is omitted, a
replacement without a version on the left side is added, which applies
to all versions of the old module path. If the @v in new@v is omitted,
the new path should be a local module root directory, not a module
path. Note that -replace overrides any redundant replacements for old[@v],
so omitting @v will drop existing replacements for specific versions.

The -dropreplace=old[@v] flag drops a replacement of the given
module path and version pair. If the @v is omitted, a replacement without
a version on the left side is dropped.

The -directory, -dropdirectory, -replace, and -dropreplace,
editing flags may be repeated, and the changes are applied in the order given.

The -go=version flag sets the expected Go language version.

The -print flag prints the final go.work in its text format instead of
writing it back to go.mod.

The -json flag prints the final go.work file in JSON format instead of
writing it back to go.mod. The JSON output corresponds to these Go types:

	type Module struct {
		Path    string
		Version string
	}

	type GoWork struct {
		Go        string
		Directory []Directory
		Replace   []Replace
	}

	type Directory struct {
		Path       string
		ModulePath string
	}

	type Replace struct {
		Old Module
		New Module
	}

See the workspaces design proposal at
https://go.googlesource.com/proposal/+/master/design/45713-workspace.md for
more information.
`,
}

var (
	editworkFmt   = cmdEditwork.Flag.Bool("fmt", false, "")
	editworkGo    = cmdEditwork.Flag.String("go", "", "")
	editworkJSON  = cmdEditwork.Flag.Bool("json", false, "")
	editworkPrint = cmdEditwork.Flag.Bool("print", false, "")
	workedits     []func(file *modfile.WorkFile) // edits specified in flags
)

func init() {
	cmdEditwork.Run = runEditwork // break init cycle

	cmdEditwork.Flag.Var(flagFunc(flagEditworkDirectory), "directory", "")
	cmdEditwork.Flag.Var(flagFunc(flagEditworkDropDirectory), "dropdirectory", "")
	cmdEditwork.Flag.Var(flagFunc(flagEditworkReplace), "replace", "")
	cmdEditwork.Flag.Var(flagFunc(flagEditworkDropReplace), "dropreplace", "")

	base.AddWorkfileFlag(&cmdEditwork.Flag)
}

func runEditwork(ctx context.Context, cmd *base.Command, args []string) {
	anyFlags :=
		*editworkGo != "" ||
			*editworkJSON ||
			*editworkPrint ||
			*editworkFmt ||
			len(workedits) > 0

	if !anyFlags {
		base.Fatalf("go mod edit: no flags specified (see 'go help mod edit').")
	}

	if *editworkJSON && *editworkPrint {
		base.Fatalf("go mod edit: cannot use both -json and -print")
	}

	if len(args) > 1 {
		base.Fatalf("go mod edit: too many arguments")
	}
	var gowork string
	if len(args) == 1 {
		gowork = args[0]
	} else {
		modload.InitWorkfile()
		gowork = modload.WorkFilePath()
	}

	if *editworkGo != "" {
		if !modfile.GoVersionRE.MatchString(*editworkGo) {
			base.Fatalf(`go mod: invalid -go option; expecting something like "-go %s"`, modload.LatestGoVersion())
		}
	}

	data, err := lockedfile.Read(gowork)
	if err != nil {
		base.Fatalf("go: %v", err)
	}

	workFile, err := modfile.ParseWork(gowork, data, nil)
	if err != nil {
		base.Fatalf("go: errors parsing %s:\n%s", base.ShortPath(gowork), err)
	}

	if *editworkGo != "" {
		if err := workFile.AddGoStmt(*editworkGo); err != nil {
			base.Fatalf("go: internal error: %v", err)
		}
	}

	if len(workedits) > 0 {
		for _, edit := range workedits {
			edit(workFile)
		}
	}
	workFile.SortBlocks()
	workFile.Cleanup() // clean file after edits

	if *editworkJSON {
		editworkPrintJSON(workFile)
		return
	}

	out := modfile.Format(workFile.Syntax)

	if *editworkPrint {
		os.Stdout.Write(out)
		return
	}

	err = lockedfile.Transform(gowork, func(lockedData []byte) ([]byte, error) {
		if !bytes.Equal(lockedData, data) {
			return nil, errors.New("go.work changed during editing; not overwriting")
		}
		return out, nil
	})
	if err != nil {
		base.Fatalf("go: %v", err)
	}
}

// flagEditworkDirectory implements the -directory flag.
func flagEditworkDirectory(arg string) {
	workedits = append(workedits, func(f *modfile.WorkFile) {
		if err := f.AddDirectory(arg, ""); err != nil {
			base.Fatalf("go mod: -directory=%s: %v", arg, err)
		}
	})
}

// flagEditworkDropDirectory implements the -dropdirectory flag.
func flagEditworkDropDirectory(arg string) {
	workedits = append(workedits, func(f *modfile.WorkFile) {
		if err := f.DropDirectory(arg); err != nil {
			base.Fatalf("go mod: -dropdirectory=%s: %v", arg, err)
		}
	})
}

// flagReplace implements the -replace flag.
func flagEditworkReplace(arg string) {
	var i int
	if i = strings.Index(arg, "="); i < 0 {
		base.Fatalf("go mod: -replace=%s: need old[@v]=new[@w] (missing =)", arg)
	}
	old, new := strings.TrimSpace(arg[:i]), strings.TrimSpace(arg[i+1:])
	if strings.HasPrefix(new, ">") {
		base.Fatalf("go mod: -replace=%s: separator between old and new is =, not =>", arg)
	}
	oldPath, oldVersion, err := parsePathVersionOptional("old", old, false)
	if err != nil {
		base.Fatalf("go mod: -replace=%s: %v", arg, err)
	}
	newPath, newVersion, err := parsePathVersionOptional("new", new, true)
	if err != nil {
		base.Fatalf("go mod: -replace=%s: %v", arg, err)
	}
	if newPath == new && !modfile.IsDirectoryPath(new) {
		base.Fatalf("go mod: -replace=%s: unversioned new path must be local directory", arg)
	}

	workedits = append(workedits, func(f *modfile.WorkFile) {
		if err := f.AddReplace(oldPath, oldVersion, newPath, newVersion); err != nil {
			base.Fatalf("go mod: -replace=%s: %v", arg, err)
		}
	})
}

// flagDropReplace implements the -dropreplace flag.
func flagEditworkDropReplace(arg string) {
	path, version, err := parsePathVersionOptional("old", arg, true)
	if err != nil {
		base.Fatalf("go mod: -dropreplace=%s: %v", arg, err)
	}
	workedits = append(workedits, func(f *modfile.WorkFile) {
		if err := f.DropReplace(path, version); err != nil {
			base.Fatalf("go mod: -dropreplace=%s: %v", arg, err)
		}
	})
}

// editPrintJSON prints the -json output.
func editworkPrintJSON(workFile *modfile.WorkFile) {
	var f workfileJSON
	if workFile.Go != nil {
		f.Go = workFile.Go.Version
	}
	for _, d := range workFile.Directory {
		f.Directory = append(f.Directory, directoryJSON{DiskPath: d.Path, ModPath: d.ModulePath})
	}

	for _, r := range workFile.Replace {
		f.Replace = append(f.Replace, replaceJSON{r.Old, r.New})
	}
	data, err := json.MarshalIndent(&f, "", "\t")
	if err != nil {
		base.Fatalf("go: internal error: %v", err)
	}
	data = append(data, '\n')
	os.Stdout.Write(data)
}

// workfileJSON is the -json output data structure.
type workfileJSON struct {
	Go        string `json:",omitempty"`
	Directory []directoryJSON
	Replace   []replaceJSON
}

type directoryJSON struct {
	DiskPath string
	ModPath  string `json:",omitempty"`
}