]> git.lizzy.rs Git - micro.git/blob - tools/build-version.go
8aaffa3d8521364e1fa90c26c8e8164d355ec838
[micro.git] / tools / build-version.go
1 package main
2
3 import (
4         "fmt"
5         "os/exec"
6         "strings"
7
8         "github.com/blang/semver"
9 )
10
11 func getTag(match ...string) (string, *semver.PRVersion) {
12         args := append([]string{
13                 "describe", "--tags",
14         }, match...)
15         if tag, err := exec.Command("git", args...).Output(); err != nil {
16                 return "", nil
17         } else {
18                 tagParts := strings.Split(string(tag), "-")
19                 if len(tagParts) == 3 {
20                         if ahead, err := semver.NewPRVersion(tagParts[1]); err == nil {
21                                 return tagParts[0], &ahead
22                         }
23                 } else if len(tagParts) == 4 {
24                         if ahead, err := semver.NewPRVersion(tagParts[2]); err == nil {
25                                 return tagParts[0] + "-" + tagParts[1], &ahead
26                         }
27                 }
28
29                 return string(tag), nil
30         }
31 }
32
33 func main() {
34         if tags, err := exec.Command("git", "tag").Output(); err != nil || len(tags) == 0 {
35                 // no tags found -- fetch them
36                 exec.Command("git", "fetch", "--tags").Run()
37         }
38         // Find the last vX.X.X Tag and get how many builds we are ahead of it.
39         versionStr, ahead := getTag("--match", "v*")
40         version, err := semver.ParseTolerant(versionStr)
41         if err != nil {
42                 // no version tag found so just return what ever we can find.
43                 fmt.Println("0.0.0-unknown")
44                 return
45         }
46         // Get the tag of the current revision.
47         tag, _ := getTag("--exact-match")
48         if tag == versionStr {
49                 // Seems that we are going to build a release.
50                 // So the version number should already be correct.
51                 fmt.Println(version.String())
52                 return
53         }
54
55         // If we don't have any tag assume "dev"
56         if tag == "" || strings.HasPrefix(tag, "nightly") {
57                 tag = "dev"
58         }
59         // Get the most likely next version:
60         if !strings.Contains(version.String(), "rc") {
61                 version.Patch = version.Patch + 1
62         }
63
64         if pr, err := semver.NewPRVersion(tag); err == nil {
65                 // append the tag as pre-release name
66                 version.Pre = append(version.Pre, pr)
67         }
68
69         if ahead != nil {
70                 // if we know how many commits we are ahead of the last release, append that too.
71                 version.Pre = append(version.Pre, *ahead)
72         }
73
74         fmt.Println(version.String())
75 }