-
Notifications
You must be signed in to change notification settings - Fork 313
/
Copy pathrelease.go
90 lines (75 loc) · 1.63 KB
/
release.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
package main
import (
"errors"
"fmt"
"os"
"os/exec"
"strings"
"github.com/Masterminds/semver/v3"
"github.com/spf13/pflag"
)
var (
versionFile = "VERSION"
versionFlag bool
commitFlag bool
)
func init() {
pflag.BoolVarP(&versionFlag, "version", "v", false, "resolved version number")
pflag.Parse()
}
func main() {
if err := release(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func release() error {
if len(pflag.Args()) != 1 {
return errors.New("error: expected version number")
}
version, err := getVersion()
if err != nil {
return err
}
if err := bumpVersion(version, pflag.Arg(0)); err != nil {
return err
}
if versionFlag {
fmt.Println(version)
return nil
}
if err := writeVersionFile(version); err != nil {
return fmt.Errorf("failed to write version file: %w", err)
}
return nil
}
func getVersion() (*semver.Version, error) {
cmd := exec.Command("git", "tag", "-l", "[0-9]*.[0-9]*.[0-9]*", "--sort=-v:refname")
b, err := cmd.Output()
if err != nil {
return nil, err
}
tags := strings.Split(strings.TrimSpace(string(b)), "\n")
if len(tags) == 0 || tags[0] == "" {
return nil, errors.New("error: no tags found")
}
return semver.NewVersion(tags[0])
}
func bumpVersion(version *semver.Version, verb string) error {
switch verb {
case "major":
*version = version.IncMajor()
case "minor":
*version = version.IncMinor()
case "patch":
*version = version.IncPatch()
case "current":
// do nothing
default:
*version = *semver.MustParse(verb)
}
return nil
}
func writeVersionFile(version *semver.Version) error {
return os.WriteFile(versionFile, []byte(version.String()), 0644)
}