-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.go
124 lines (112 loc) · 2.17 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
package main
import (
"context"
"errors"
"flag"
"fmt"
"io"
"log"
"os"
"os/exec"
"strings"
"github.com/Masterminds/semver"
"github.com/haya14busa/go-versionsort"
)
type Level int
const (
PATCH Level = iota
MINOR
MAJOR
CURRENT // Do not bump and show the latest version.
)
func main() {
if err := run(os.Stdout); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func usage() {
fmt.Fprintln(os.Stderr, `Usage: bump [major,minor,patch (default=patch)]
bump returns next semantic version tag`)
flag.PrintDefaults()
fmt.Fprintln(os.Stderr, "https://github.com/haya14busa/bump")
os.Exit(2)
}
func run(w io.Writer) error {
flag.Usage = usage
flag.Parse()
ctx := context.Background()
tags, err := tags(ctx)
if err != nil {
return err
}
if len(tags) == 0 {
return errors.New("existing tag not found")
}
latest := latestSemVer(tags)
next, err := nextTag(latest, bumpLevel(flag.Args()))
if err != nil {
return err
}
fmt.Fprintln(w, next)
return nil
}
func nextTag(latest string, level Level) (string, error) {
latestVer, err := semver.NewVersion(latest)
if err != nil {
return "", err
}
next := nextSemVer(latestVer, level)
return next.Original(), nil
}
func tags(ctx context.Context) ([]string, error) {
cmd := exec.CommandContext(ctx, "git", "tag", "--merged")
b, err := cmd.CombinedOutput()
if err != nil {
return nil, fmt.Errorf("failed to run `git tag`: %v", err)
}
if len(b) == 0 {
return nil, nil
}
return strings.Split(string(b), "\n"), nil
}
func latestSemVer(tags []string) string {
latest := ""
for _, tag := range tags {
if versionsort.Less(latest, tag) {
latest = tag
}
}
return latest
}
func nextSemVer(v *semver.Version, level Level) semver.Version {
switch level {
case PATCH:
return v.IncPatch()
case MINOR:
return v.IncMinor()
case MAJOR:
return v.IncMajor()
case CURRENT:
// Do nothing.
return *v
}
log.Fatalf("unknown level: %v", level)
return v.IncPatch()
}
func bumpLevel(args []string) Level {
if len(args) == 0 {
return PATCH
}
switch args[0] {
case "patch":
return PATCH
case "minor":
return MINOR
case "major":
return MAJOR
case "current":
return CURRENT
}
return PATCH
}