/
main.go
501 lines (454 loc) · 14.2 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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
package main
import (
"bytes"
_ "embed"
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"os/exec"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"text/template"
"time"
)
const (
marjorWeight = 1e9
minorWeight = 1e4
patchWeight = 1
)
var (
semverRegex = regexp.MustCompile(`.*v(?P<major>\d*)\.(?P<minor>\d*)\.(?P<patch>\d*)(?P<suffix>.*)`)
//go:embed _tidyhack_tmpl.txt
tidyHackTmpl string
//go:embed _CHANGES.md.txt
changesTmpl string
//go:embed _README.md.txt
readmeTmpl string
)
type carver struct {
rootMod *modInfo
childMod *modInfo
// flags
repoMetadataPath string
name string
dryRun bool
w io.WriteCloser
}
var once sync.Once
func main() {
parent := flag.String("parent", "", "The path to the parent module. Required.")
child := flag.String("child", "", "The relative path to the child module from the parent module. Required.")
repoMetadataPath := flag.String("repo-metadata", "", "The full path to the repo metadata file. Required.")
name := flag.String("name", "", "The name used to identify the API in the README. Optional")
parentTagPrefix := flag.String("parent-tag-prefix", "", "The prefix for a git tag, should end in a '/'. Only required if parent is not the root module. Optional.")
parentTag := flag.String("parent-tag", "", "The newest tag from the parent module, this will override the lookup. If not specified the latest tag will be used. Optional.")
childTagVersion := flag.String("child-tag-version", "v0.1.0", "The tag version of the carved out child module. Should be in the form of vX.X.X with no prefix. Optional.")
dryRun := flag.Bool("dry-run", false, "If true no files or tags will be created. Optional.")
flag.Usage = func() {
fmt.Fprintf(flag.CommandLine.Output(), "Usage of %s:\n", os.Args[0])
flag.PrintDefaults()
fmt.Fprintf(flag.CommandLine.Output(), "\nExample\n\tcarver -parent=/Users/me/google-cloud-go -child=asset repo-metadata=/Users/me/google-cloud-go/internal/.repo-metadata-full.json\n")
}
flag.Parse()
rootMod, err := rootModInfo(*parent, *parentTagPrefix, *parentTag)
if err != nil {
log.Fatalf("unable to calculate root mod info: %v", err)
}
children := strings.Split(strings.TrimSpace(*child), ",")
var tags []string
for _, child := range children {
child := strings.TrimSpace(child)
childMod := childModInfo(rootMod, child, *childTagVersion)
c := &carver{
rootMod: rootMod,
childMod: childMod,
repoMetadataPath: *repoMetadataPath,
name: *name,
dryRun: *dryRun,
}
ts, err := c.Run()
if err != nil {
log.Println(err)
flag.Usage()
os.Exit(1)
}
tags = append(tags, ts...)
}
if err := gitCommit(rootMod.path, tags, *dryRun); err != nil {
log.Fatal(err)
}
log.Println("Successfully carved out modules. Please run the following commands after your changes are merged:")
for _, tag := range tags {
fmt.Fprintf(os.Stdout, "git tag %s $COMMIT_SHA\n", tag)
}
for _, tag := range tags {
fmt.Fprintf(os.Stdout, "git push origin refs/tags/%s\n", tag)
}
fmt.Fprintf(os.Stdout, "Once tags have propagated open a new PR tidying the new child mods go.sum entries.\n")
}
func (c *carver) Run() ([]string, error) {
if c.rootMod.path == "" || c.childMod.path == "" || c.repoMetadataPath == "" {
return nil, fmt.Errorf("all required flags were not provided")
}
if err := c.CreateChildCommonFiles(); err != nil {
return nil, fmt.Errorf("failed to create readme: %v", err)
}
if err := c.CreateChildModule(); err != nil {
return nil, fmt.Errorf("failed to create child module: %v", err)
}
if err := c.FixupSnippets(); err != nil {
return nil, fmt.Errorf("failed to update snippet module: %v", err)
}
var tags []string
once.Do(func() {
tags = append(tags, c.rootMod.Tag())
})
tags = append(tags, c.childMod.Tag())
return tags, nil
}
type modInfo struct {
// path is the filepath to the module locally.
path string
// importPath is the import path of the module.
importPath string
// futureTagVersion is the tag version that this module should be tagged
// after all operations are preformed.
futureTagVersion string
// tagPrefix is the prefix of the module used while tagging.
tagPrefix string
}
// Tag returns a formatted git tag for a module.
func (mi *modInfo) Tag() string {
if mi.tagPrefix == "" {
return mi.futureTagVersion
}
return fmt.Sprintf("%s/%s", mi.tagPrefix, mi.futureTagVersion)
}
func (mi *modInfo) PkgName() string {
ss := strings.Split(mi.importPath, "/")
return ss[len(ss)-1]
}
func rootModInfo(rootModPath, rootTagPrefix, rootTagVersion string) (*modInfo, error) {
log.Println("Looking up parent module import path")
cmd := exec.Command("go", "list", "-f", "{{.ImportPath}}")
cmd.Dir = rootModPath
b, err := cmd.Output()
if err != nil {
return nil, err
}
modName := string(bytes.TrimSpace(b))
if rootTagVersion != "" {
tag, err := bumpSemverPatch(rootTagVersion)
if err != nil {
return nil, err
}
return &modInfo{
path: rootModPath,
importPath: modName,
futureTagVersion: tag,
}, nil
}
log.Println("Looking up latest parent tag")
cmd = exec.Command("git", "tag")
cmd.Dir = rootModPath
b, err = cmd.Output()
if err != nil {
return nil, err
}
var relevantTags []string
for _, tag := range strings.Split(string(bytes.TrimSpace(b)), "\n") {
if rootTagPrefix != "" && strings.HasPrefix(tag, rootTagPrefix) {
relevantTags = append(relevantTags, tag)
continue
}
if rootTagPrefix == "" && !strings.Contains(tag, "/") && strings.HasPrefix(tag, "v") {
relevantTags = append(relevantTags, tag)
}
}
sortTags(relevantTags)
tag := relevantTags[0]
log.Println("Found latest tag: ", tag)
futureTag, err := bumpSemverPatch(tag)
if err != nil {
return nil, err
}
return &modInfo{
path: rootModPath,
importPath: modName,
futureTagVersion: futureTag,
}, nil
}
func childModInfo(rootMod *modInfo, childRelPath, childTagVersion string) *modInfo {
return &modInfo{
path: filepath.Join(rootMod.path, childRelPath),
importPath: filepath.Join(rootMod.importPath, childRelPath),
futureTagVersion: childTagVersion,
tagPrefix: childRelPath,
}
}
func (c *carver) CreateChildCommonFiles() error {
log.Printf("Reading metadata file from %q", c.repoMetadataPath)
metaFile, err := os.Open(c.repoMetadataPath)
if err != nil {
return fmt.Errorf("unable to open metadata file: %v", err)
}
meta, err := parseMetadata(metaFile)
if err != nil {
return err
}
readmePath := filepath.Join(c.childMod.path, "README.md")
log.Printf("Creating %q", readmePath)
readmeFile, err := c.newWriterCloser(readmePath)
if err != nil {
return err
}
defer readmeFile.Close()
t := template.Must(template.New("readme").Parse(readmeTmpl))
name := c.name
if name == "" {
name = meta[c.childMod.importPath]
if name == "" {
return fmt.Errorf("unable to determine a name from API metadata, please set -name flag")
}
}
readmeData := struct {
Name string
ImportPath string
}{
Name: name,
ImportPath: c.childMod.importPath,
}
if err := t.Execute(readmeFile, readmeData); err != nil {
return err
}
changesPath := filepath.Join(c.childMod.path, "CHANGES.md")
log.Printf("Creating %q", changesPath)
changesFile, err := c.newWriterCloser(changesPath)
if err != nil {
return err
}
defer changesFile.Close()
t2 := template.Must(template.New("changes").Parse(changesTmpl))
changesData := struct {
Package string
}{
Package: c.childMod.PkgName(),
}
return t2.Execute(changesFile, changesData)
}
func (c *carver) CreateChildModule() error {
fp := filepath.Join(c.childMod.path, "go_mod_tidy_hack.go")
log.Printf("Creating %q", fp)
f, err := c.newWriterCloser(fp)
if err != nil {
return err
}
defer f.Close()
t := template.Must(template.New("tidyhack").Parse(tidyHackTmpl))
data := struct {
Year int
RootMod string
Package string
}{
Year: time.Now().Year(),
RootMod: c.rootMod.importPath,
Package: c.childMod.PkgName(),
}
if err := t.Execute(f, data); err != nil {
return err
}
log.Printf("Creating child module in %q", c.childMod.path)
if c.dryRun {
return nil
}
cmd := exec.Command("go", "mod", "init", c.childMod.importPath)
cmd.Dir = c.childMod.path
if b, err := cmd.Output(); err != nil {
return fmt.Errorf("unable to init module: %s", b)
}
if err != nil {
return err
}
cmd = exec.Command("go", "mod", "edit", "-require", fmt.Sprintf("%s@%s", c.rootMod.importPath, c.rootMod.futureTagVersion))
cmd.Dir = c.childMod.path
if b, err := cmd.Output(); err != nil {
return fmt.Errorf("unable to require module: %s", b)
}
cmd = exec.Command("go", "mod", "edit", "-replace", fmt.Sprintf("%s@%s=%s", c.rootMod.importPath, c.rootMod.futureTagVersion, c.rootMod.path))
cmd.Dir = c.childMod.path
if b, err := cmd.Output(); err != nil {
return fmt.Errorf("unable to add replace module: %s", b)
}
cmd = exec.Command("go", "mod", "tidy")
cmd.Dir = c.childMod.path
if b, err := cmd.Output(); err != nil {
return fmt.Errorf("unable to tidy child module: %s", b)
}
cmd = exec.Command("go", "mod", "edit", "-dropreplace", fmt.Sprintf("%s@%s", c.rootMod.importPath, c.rootMod.futureTagVersion))
cmd.Dir = c.childMod.path
if b, err := cmd.Output(); err != nil {
return fmt.Errorf("unable to add replace module: %s", b)
}
cmd = exec.Command("go", "mod", "tidy")
cmd.Dir = c.rootMod.path
if b, err := cmd.Output(); err != nil {
return fmt.Errorf("unable to tidy parent module: %s", b)
}
return nil
}
func (c *carver) FixupSnippets() error {
log.Println("Fixing snippets")
snippetsModDir := filepath.Join(c.rootMod.path, "internal", "generated", "snippets")
childRelPath := strings.TrimPrefix(c.childMod.path, c.rootMod.path)
cmd := exec.Command("go", "mod", "edit", "-require", fmt.Sprintf("%s@%s", c.childMod.importPath, c.childMod.futureTagVersion))
cmd.Dir = snippetsModDir
if b, err := cmd.Output(); err != nil {
return fmt.Errorf("unable to require module: %s", b)
}
cmd = exec.Command("go", "mod", "edit", "-replace", fmt.Sprintf("%s@%s=../../..%s", c.childMod.importPath, c.childMod.futureTagVersion, childRelPath))
cmd.Dir = snippetsModDir
if b, err := cmd.Output(); err != nil {
return fmt.Errorf("unable to add replace module: %s", b)
}
cmd = exec.Command("go", "mod", "tidy")
cmd.Dir = snippetsModDir
if b, err := cmd.Output(); err != nil {
return fmt.Errorf("unable to tidy child module: %s", b)
}
return nil
}
func gitCommit(dir string, tags []string, dryRun bool) error {
log.Println("Commiting changes")
if !dryRun {
cmd := exec.Command("git", "add", "-A")
cmd.Dir = dir
if b, err := cmd.Output(); err != nil {
return fmt.Errorf("unable to add changes: %s", b)
}
var sb strings.Builder
sb.WriteString("chore: carve out sub-modules\n\nThis commit will be tagged:\n")
for _, tag := range tags {
sb.WriteString(fmt.Sprintf("\t- %s\n", tag))
}
cmd = exec.Command("git", "commit", "-m", sb.String())
cmd.Dir = dir
if b, err := cmd.Output(); err != nil {
return fmt.Errorf("unable to commit changes: %s", b)
}
}
return nil
}
// newWriterCloser is wrapper for creating a file. Used for testing and
// dry-runs.
func (c *carver) newWriterCloser(fp string) (io.WriteCloser, error) {
if c.dryRun {
return noopCloser{w: io.Discard}, nil
}
if c.w != nil {
return noopCloser{w: c.w}, nil
}
return os.Create(fp)
}
// sortTags does a best effort sort based on semver. It was made a function for
// testing. Only the top result will ever be used.
func sortTags(tags []string) {
sort.Slice(tags, func(i, j int) bool {
imatch := semverRegex.FindStringSubmatch(tags[i])
jmatch := semverRegex.FindStringSubmatch(tags[j])
if len(imatch) < 5 {
return false
}
if len(jmatch) < 5 {
return true
}
// Matches must be numbers due to regex they are parsed from.
iM, _ := strconv.Atoi(imatch[1])
jM, _ := strconv.Atoi(jmatch[1])
im, _ := strconv.Atoi(imatch[2])
jm, _ := strconv.Atoi(jmatch[2])
ip, _ := strconv.Atoi(imatch[3])
jp, _ := strconv.Atoi(jmatch[3])
// weight each level of semver for comparison
iTotal := iM*marjorWeight + im*minorWeight + ip*patchWeight
jTotal := jM*marjorWeight + jm*minorWeight + jp*patchWeight
// de-rank all prereleases by a major version
if imatch[4] != "" {
iTotal -= marjorWeight
}
if jmatch[4] != "" {
jTotal -= marjorWeight
}
return iTotal > jTotal
})
}
type noopCloser struct {
w io.Writer
}
func (n noopCloser) Write(p []byte) (int, error) {
return n.w.Write(p)
}
func (n noopCloser) Close() error { return nil }
func bumpSemverPatch(tag string) (string, error) {
splitTag := semverRegex.FindStringSubmatch(tag)
if len(splitTag) < 5 {
return "", fmt.Errorf("invalid tag layout: %q", tag)
}
var maj, min, pat int
var err error
if maj, err = strconv.Atoi(splitTag[1]); err != nil {
return "", fmt.Errorf("invalid tag layout: %q", tag)
}
if min, err = strconv.Atoi(splitTag[2]); err != nil {
return "", fmt.Errorf("invalid tag layout: %q", tag)
}
if pat, err = strconv.Atoi(splitTag[3]); err != nil {
return "", fmt.Errorf("invalid tag layout: %q", tag)
}
if strings.Contains(tag, "/") {
splitTag := strings.Split(tag, "/")
return fmt.Sprintf("%s/v%d.%d.%d", strings.Join(splitTag[:len(splitTag)-1], "/"), maj, min, pat+1), nil
}
return fmt.Sprintf("v%d.%d.%d", maj, min, pat+1), nil
}
// parseMetadata creates a mapping of potential modules to API full name.
func parseMetadata(r io.Reader) (map[string]string, error) {
m := map[string]struct {
Description string `json:"description"`
}{}
b, err := ioutil.ReadAll(r)
if err != nil {
return nil, err
}
if err := json.Unmarshal(b, &m); err != nil {
return nil, err
}
m2 := map[string]string{}
for k, v := range m {
k2 := k
if i := strings.Index(k2, "/apiv"); i > 0 {
k2 = k2[:i]
}
m2[k2] = v.Description
}
return m2, nil
}