-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
511 lines (448 loc) · 11 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
502
503
504
505
506
507
508
509
510
511
package main
import (
"bytes"
"errors"
"flag"
"fmt"
"html/template"
"io/ioutil"
"log"
"os"
"strconv"
"strings"
"time"
"github.com/Masterminds/semver"
git "github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/plumbing/object"
"github.com/octago/sflags/gen/gflag"
convcom "github.com/wfscheper/convcom"
)
//nolint: lll
const changelogTemplate = `
## {{ .Version }} ({{ simpleDate .LatestTagCommit.Committer.When }})
{{ range $type, $commits := .CommitsGrouped }}
### {{ mapConvComType $type }}
{{ range $commit := $commits }}
- {{ if $commit.Conv.Scope }}**{{ $commit.Conv.Scope }}:** {{ else }}{{ end }}{{ $commit.Conv.Description }} ({{ commitHash $commit.Git.Hash.String }})
{{- end }}
{{ end }}
`
var (
Version string
Commit string
Date string
)
type (
config struct {
// action
AutodetectBump bool `flag:"bump-auto" desc:"Bump version based on semantic commits"`
BumpMajor bool `flag:"bump-major" desc:"Bump major"`
BumpMinor bool `flag:"bump-minor" desc:"Bump minor"`
BumpPatch bool `flag:"bump-patch" desc:"Bump patch"`
// version file config
FileUpdate bool `flag:"file-update" desc:"Use version file"`
FilePath string `flag:"file-path" desc:"Version file path"`
// git tag config
GitTagUpdate bool `flag:"git-tag-update" desc:"Use git tags"`
// version config
VersionPrefix string `flag:"version-prefix" desc:"Version prefix"`
// changelog config
ChangelogUpdate bool `flag:"changelog-update" desc:"Update changelog"`
ChangelogPath string `flag:"changelog-path" desc:"Changelog file path"`
PrintVersion bool `flag:"version" desc:"print version"`
}
changelogEntry struct {
Version string
LatestTagCommit *object.Commit
Commits []*changelogCommit
CommitsGrouped map[string][]*changelogCommit
}
changelogCommit struct {
Git *object.Commit
Conv *convcom.Commit
}
)
// errDone is used to exit the git iterators early
var errDone = errors.New("done")
func autodetectBump(c *config) error {
// check if we should be autodetecting the bump
if !c.AutodetectBump {
return nil
}
// open repository
repo, err := git.PlainOpen(".")
if err != nil {
return err
}
// get head
head, err := repo.Head()
if err != nil {
return err
}
// find the latest tag
var latestTagCommit *object.Commit
tagRefs, err := repo.Tags()
if err != nil {
return err
}
err = tagRefs.ForEach(func(tagRef *plumbing.Reference) error {
rev := plumbing.Revision(tagRef.Name().String())
tagCommitHash, err := repo.ResolveRevision(rev) //nolint:govet
if err != nil {
return err
}
commit, err := repo.CommitObject(*tagCommitHash)
if err != nil {
return err
}
if latestTagCommit == nil {
latestTagCommit = commit
}
if commit.Committer.When.After(latestTagCommit.Committer.When) {
latestTagCommit = commit
}
return nil
})
if err != nil && err != errDone {
return err
}
// find commits since the latest tag
commitsSinceTag := []*object.Commit{}
commitIter, err := repo.Log(&git.LogOptions{})
if err != nil {
return err
}
err = commitIter.ForEach(func(commit *object.Commit) error {
// once we reach the commit of the latest tag, we're done
if commit.Hash == latestTagCommit.Hash {
return errDone
}
commitsSinceTag = append(commitsSinceTag, commit)
return nil
})
if err != nil && err != errDone {
return err
}
// check current head is the latest tag
if latestTagCommit.Hash == head.Hash() {
return errors.New("head is already tagged")
}
// go through the commits and figure out what we need to bump
c.BumpMajor = false
c.BumpMinor = false
c.BumpPatch = false
for _, commit := range commitsSinceTag {
if strings.Contains(commit.Message, "BREAKING") {
c.BumpMajor = true
}
}
return nil
}
func gitTagUpdate(c *config) error {
// check if we are updating git tags
if !c.GitTagUpdate {
return nil
}
// open repository
repo, err := git.PlainOpen(".")
if err != nil {
return err
}
// get head
head, err := repo.Head()
if err != nil {
return err
}
// find the latest tag
var latestTagCommit *object.Commit
var latestTagName string
tagRefs, err := repo.Tags()
if err != nil {
return err
}
err = tagRefs.ForEach(func(tagRef *plumbing.Reference) error {
rev := plumbing.Revision(tagRef.Name().String())
tagCommitHash, err := repo.ResolveRevision(rev) //nolint: govet
if err != nil {
return err
}
commit, err := repo.CommitObject(*tagCommitHash)
if err != nil {
return err
}
if latestTagCommit == nil {
latestTagCommit = commit
latestTagName = tagRef.Name().Short()
}
if commit.Committer.When.After(latestTagCommit.Committer.When) {
latestTagCommit = commit
latestTagName = tagRef.Name().Short()
}
return nil
})
if err != nil && err != errDone {
return err
}
// check current head is the latest tag
if latestTagCommit.Hash == head.Hash() {
return errors.New("head is already tagged")
}
// bump version
newVersion, err := bumpVersion(latestTagName, c)
if err != nil {
return err
}
// create new tag
_, err = repo.CreateTag(newVersion, head.Hash(), &git.CreateTagOptions{
Message: "chore(version): bump version to " + newVersion,
})
if err != nil {
return err
}
return nil
}
func changelogUpdate(c *config) error { //nolint: funlen,gocyclo
// check if we are updating changelog
if !c.ChangelogUpdate {
return nil
}
// open repository
repo, err := git.PlainOpen(".")
if err != nil {
return err
}
// get head
head, err := repo.Head()
if err != nil {
return err
}
// find the latest tag
var latestTagCommit *object.Commit
var latestTagName string
tagRefs, err := repo.Tags()
if err != nil {
return err
}
err = tagRefs.ForEach(func(tagRef *plumbing.Reference) error {
rev := plumbing.Revision(tagRef.Name().String())
tagCommitHash, err := repo.ResolveRevision(rev) //nolint: govet
if err != nil {
return err
}
commit, err := repo.CommitObject(*tagCommitHash)
if err != nil {
return err
}
if latestTagCommit == nil {
latestTagCommit = commit
latestTagName = tagRef.Name().Short()
}
if commit.Committer.When.After(latestTagCommit.Committer.When) {
latestTagCommit = commit
latestTagName = tagRef.Name().Short()
}
return nil
})
if err != nil && err != errDone {
return err
}
// check current head is the latest tag
if latestTagCommit.Hash == head.Hash() {
return errors.New("head is already tagged")
}
// bump version
newVersion, err := bumpVersion(latestTagName, c)
if err != nil {
return err
}
convComParser, err := convcom.New(&convcom.Config{})
if err != nil {
return err
}
// find commits since the latest tag
commitsSinceTag := []*changelogCommit{}
commitsSinceTagGrouped := map[string][]*changelogCommit{}
commitIter, err := repo.Log(&git.LogOptions{})
if err != nil {
return err
}
err = commitIter.ForEach(func(commit *object.Commit) error {
// once we reach the commit of the latest tag, we're done
if commit.Hash == latestTagCommit.Hash {
return errDone
}
convCommit, err := convComParser.Parse(commit.Message) //nolint: govet
if err != nil {
return err
}
changelogEntry := &changelogCommit{
Git: commit,
Conv: convCommit,
}
if convCommit.Type == "chore" {
return nil
}
commitType := convCommit.Type
if convCommit.IsBreaking {
commitType = "breaking"
}
commitsSinceTag = append(commitsSinceTag, changelogEntry)
if _, ok := commitsSinceTagGrouped[commitType]; !ok {
commitsSinceTagGrouped[commitType] = []*changelogCommit{}
}
commitsSinceTagGrouped[commitType] = append(
commitsSinceTagGrouped[commitType],
changelogEntry,
)
return nil
})
if err != nil && err != errDone {
return err
}
// check current head is the latest tag
if latestTagCommit.Hash == head.Hash() {
return errors.New("head is already tagged")
}
// go through the commits and figure out what we need to bump
tmpl, err := template.
New("changelog").
Funcs(template.FuncMap{
"simpleDate": func(t time.Time) string {
return t.Format("2006-01-02")
},
"commitHash": func(h string) string {
return h[:7]
},
"mapConvComType": func(t string) string {
switch t {
case "breaking":
return "Breaking Changes"
case "fix":
return "Bug Fixes"
case "feat":
return "Features"
case "build":
return "Build System"
case "ci":
return "Continuous Integration"
case "docs":
return "Documentation"
case "style":
return "Styling"
case "refactor":
return "Code Refactoring"
case "perf":
return "Performance Improvements"
case "test":
return "Tests"
default:
return t
}
},
}).
Parse(changelogTemplate)
if err != nil {
return err
}
// render template
var newBody bytes.Buffer
err = tmpl.Execute(&newBody, &changelogEntry{
Version: newVersion,
LatestTagCommit: latestTagCommit,
Commits: commitsSinceTag,
CommitsGrouped: commitsSinceTagGrouped,
})
if err != nil {
return err
}
// get existing file contents
changelogBody, err := ioutil.ReadFile(c.ChangelogPath)
if err != nil {
return err
}
// merge existing changelog with new
mergedBody := append(newBody.Bytes(), changelogBody...)
// and update file
return ioutil.WriteFile(c.ChangelogPath, mergedBody, 0o644) //nolint: gosec
}
func fileUpdate(c *config) error {
if !c.FileUpdate {
return nil
}
versionFileBody, err := ioutil.ReadFile(c.FilePath)
if err != nil {
return err
}
currentVersion := string(versionFileBody)
if currentVersion == "" {
currentVersion = c.VersionPrefix + "0.0.0"
}
newVersion, err := bumpVersion(currentVersion, c)
if err != nil {
return err
}
//nolint: gosec
return ioutil.WriteFile(c.FilePath, []byte(newVersion), 0o644)
}
func bumpAtLeastMinor(c *config) error {
if !c.BumpMajor && !c.BumpMinor && !c.BumpPatch {
c.BumpPatch = true
}
return nil
}
func bumpVersion(currentVersion string, c *config) (string, error) {
cleanCurrentVersionString := currentVersion[len(c.VersionPrefix):]
cleanCurrentVersion, err := semver.NewVersion(cleanCurrentVersionString)
if err != nil {
return "", err
}
cleanNewVersion := *cleanCurrentVersion
if c.BumpMajor {
cleanNewVersion = cleanNewVersion.IncMajor()
}
if c.BumpMinor {
cleanNewVersion = cleanNewVersion.IncMinor()
}
if c.BumpPatch {
cleanNewVersion = cleanNewVersion.IncPatch()
}
return c.VersionPrefix + cleanNewVersion.String(), nil
}
func printVersion() {
if Date != "" {
ts, err := strconv.Atoi(Date)
if err == nil {
Date = time.Unix(int64(ts), 0).UTC().String()
}
}
fmt.Printf("conver %s (%s, %s)\n", Version, Commit, Date)
}
func main() {
c := &config{
FilePath: "VERSION",
VersionPrefix: "v",
ChangelogPath: "CHANGELOG",
}
err := gflag.ParseToDef(c)
if err != nil {
log.Fatalf("err: %v", err)
}
flag.Parse()
if c.PrintVersion {
printVersion()
os.Exit(0)
}
actions := []func(*config) error{
autodetectBump,
bumpAtLeastMinor,
changelogUpdate,
fileUpdate,
gitTagUpdate,
}
for _, action := range actions {
if err := action(c); err != nil {
log.Fatalf("err: %v", err)
}
}
}