-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathmain.go
327 lines (313 loc) · 8.12 KB
/
main.go
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
package main
import (
"encoding/json"
"flag"
"fmt"
"go/token"
"os"
"os/exec"
"regexp"
"runtime/debug"
"golang.org/x/mod/modfile"
"golang.org/x/mod/module"
"golang.org/x/mod/semver"
"github.com/icholy/gomajor/internal/importpaths"
"github.com/icholy/gomajor/internal/modproxy"
"github.com/icholy/gomajor/internal/packages"
)
var help = `
GoMajor is a tool for major version upgrades
Usage:
gomajor <command> [arguments]
The commands are:
get upgrade to a major version
list list available updates
path modify the module path
version print the gomajor version
help show this help text
`
func main() {
flag.Usage = func() {
fmt.Println(help)
}
flag.Parse()
switch flag.Arg(0) {
case "get":
if err := getcmd(flag.Args()[1:]); err != nil {
fmt.Fprintln(os.Stderr, err.Error())
}
case "list":
if err := listcmd(flag.Args()[1:]); err != nil {
fmt.Fprintln(os.Stderr, err.Error())
}
case "path":
if err := pathcmd(flag.Args()[1:]); err != nil {
fmt.Fprintln(os.Stderr, err.Error())
}
case "version":
if err := versioncmd(); err != nil {
fmt.Fprintln(os.Stderr, err.Error())
}
case "help", "":
flag.Usage()
default:
fmt.Fprintf(os.Stderr, "unrecognized subcommand: %s\n", flag.Arg(0))
flag.Usage()
}
}
func listcmd(args []string) error {
var dir string
var pre, cached, major, jsonfmt bool
fset := flag.NewFlagSet("list", flag.ExitOnError)
fset.BoolVar(&pre, "pre", false, "allow non-v0 prerelease versions")
fset.StringVar(&dir, "dir", ".", "working directory")
fset.BoolVar(&cached, "cached", true, "only fetch cached content from the module proxy")
fset.BoolVar(&major, "major", false, "only show newer major versions")
fset.BoolVar(&jsonfmt, "json", false, "output json format")
fset.Usage = func() {
fmt.Fprintln(os.Stderr, "Usage: gomajor list [modules]")
fset.PrintDefaults()
}
fset.Parse(args)
modules, err := packages.Direct(dir)
if err != nil {
return err
}
if fset.NArg() > 0 {
prefixes := map[string]bool{}
for _, a := range fset.Args() {
prefixes[packages.ModPrefix(a)] = true
}
var filtered []module.Version
for _, m := range modules {
if prefixes[packages.ModPrefix(m.Path)] {
filtered = append(filtered, m)
}
}
modules = filtered
}
modproxy.Updates(modproxy.UpdateOptions{
Pre: pre,
Major: major,
Cached: cached,
Modules: modules,
OnUpdate: func(u modproxy.Update) {
if jsonfmt {
data, _ := json.Marshal(u)
fmt.Println(string(data))
return
}
if u.Err != nil {
fmt.Fprintf(os.Stderr, "%s: failed: %v\n", u.Module.Path, u.Err)
} else {
fmt.Printf("%s: %s [latest %v]\n", u.Module.Path, u.Module.Version, u.Latest.Version)
}
},
})
return nil
}
func getcmd(args []string) error {
var rewrite regexp.Regexp
var dir string
var pre, cached, major bool
fset := flag.NewFlagSet("get", flag.ExitOnError)
fset.BoolVar(&pre, "pre", false, "allow non-v0 prerelease versions")
fset.BoolVar(&major, "major", false, "only get newer major versions")
fset.StringVar(&dir, "dir", ".", "working directory")
fset.BoolVar(&cached, "cached", true, "only fetch cached content from the module proxy")
fset.TextVar(&rewrite, "rewrite", regexp.MustCompile(".*"), "only rewrite imports matching this regex")
fset.Usage = func() {
fmt.Fprintln(os.Stderr, "Usage: gomajor get <pathspec>")
fset.PrintDefaults()
}
fset.Parse(args)
if fset.NArg() != 1 {
return fmt.Errorf("missing package spec")
}
// check for "all" special case
if fset.Arg(0) == "all" {
modules, err := packages.Direct(dir)
if err != nil {
return err
}
modproxy.Updates(modproxy.UpdateOptions{
Pre: pre,
Major: major,
Cached: cached,
Modules: modules,
OnUpdate: func(u modproxy.Update) {
if u.Err != nil {
fmt.Fprintf(os.Stderr, "%s: failed: %v\n", u.Module.Path, u.Err)
return
}
// go get
spec := u.Latest.Path + "@" + u.Latest.Version
fmt.Println("go get", spec)
cmd := exec.Command("go", "get", spec)
cmd.Dir = dir
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return
}
// rewrite import paths
err := importpaths.RewriteModule(dir, importpaths.RewriteModuleOptions{
Prefix: packages.ModPrefix(u.Module.Path),
NewVersion: u.Latest.Version,
OnRewrite: func(pos token.Position, _, newpath string) error {
fmt.Printf("%s %s\n", pos, newpath)
return nil
},
})
if err != nil {
fmt.Fprintf(os.Stderr, "rewrite: %v", err)
}
},
})
return nil
}
// split the package spec into its components
pkgpath, query := packages.SplitSpec(fset.Arg(0))
mod, err := modproxy.QueryPackage(pkgpath, cached)
if err != nil {
return err
}
modprefix := packages.ModPrefix(mod.Path)
_, pkgdir, _ := packages.SplitPath(modprefix, pkgpath)
// figure out what version to get
var version string
switch query {
case "":
version = mod.MaxVersion("", pre)
case "latest":
latest, err := modproxy.Latest(mod.Path, cached, pre)
if err != nil {
return err
}
version = latest.MaxVersion("", pre)
query = version
default:
if !semver.IsValid(query) {
return fmt.Errorf("invalid version: %s", query)
}
// best effort to detect +incompatible versions
if v := mod.MaxVersion(query, pre); v != "" {
version = v
} else {
version = query
}
}
// go get
spec := packages.JoinPath(modprefix, version, pkgdir)
if query != "" {
spec += "@" + query
}
fmt.Println("go get", spec)
cmd := exec.Command("go", "get", spec)
cmd.Dir = dir
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return err
}
// rewrite imports
err = importpaths.RewriteModule(dir, importpaths.RewriteModuleOptions{
PkgDir: pkgdir,
Prefix: modprefix,
NewVersion: version,
OnRewrite: func(pos token.Position, oldpath, newpath string) error {
if !rewrite.MatchString(oldpath) {
return importpaths.ErrSkip
}
fmt.Printf("%s %s\n", pos, newpath)
return nil
},
})
if err != nil {
return fmt.Errorf("rewrite: %w", err)
}
return nil
}
func pathcmd(args []string) error {
var dir, version string
var next bool
fset := flag.NewFlagSet("path", flag.ExitOnError)
fset.BoolVar(&next, "next", false, "increment the module path version")
fset.StringVar(&version, "version", "", "set the module path version")
fset.StringVar(&dir, "dir", ".", "working directory")
fset.Usage = func() {
fmt.Fprintln(os.Stderr, "Usage: gomajor path [modpath]")
fset.PrintDefaults()
}
fset.Parse(args)
// find and parse go.mod
name, err := packages.FindModFile(dir)
if err != nil {
return err
}
data, err := os.ReadFile(name)
if err != nil {
return err
}
file, err := modfile.ParseLax(name, data, nil)
if err != nil {
return err
}
// figure out the new module path
modpath := fset.Arg(0)
if modpath == "" {
modpath = file.Module.Mod.Path
}
// find the current version if one wasn't provided
if version == "" {
var ok bool
version, ok = packages.ModMajor(modpath)
if !ok || version == "" {
version = "v1"
}
}
// increment the path version
if next {
version, err = modproxy.NextMajor(version)
if err != nil {
return err
}
}
if !semver.IsValid(version) {
return fmt.Errorf("invalid version: %q", version)
}
// create the new modpath
modprefix := packages.ModPrefix(modpath)
oldmodprefix := packages.ModPrefix(file.Module.Mod.Path)
modpath = packages.JoinPath(modprefix, version, "")
fmt.Printf("module %s\n", modpath)
// update go.mod
cmd := exec.Command("go", "mod", "edit", "-module", modpath)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return err
}
// rewrite import paths
err = importpaths.RewriteModule(dir, importpaths.RewriteModuleOptions{
Prefix: oldmodprefix,
NewVersion: version,
NewPrefix: modprefix,
OnRewrite: func(pos token.Position, _, newpath string) error {
fmt.Printf("%s %s\n", pos, newpath)
return nil
},
})
if err != nil {
return fmt.Errorf("rewrite: %w", err)
}
return nil
}
func versioncmd() error {
version := "(devel)"
if info, ok := debug.ReadBuildInfo(); ok {
version = info.Main.Version
}
fmt.Printf("version: %s\n", version)
return nil
}