package main import ( "fmt" "os" "os/exec" "strings" "text/template" ) func syscmd(name string, arg ...string) string { cmd := exec.Command(name, arg...) out, err := cmd.CombinedOutput() if err != nil { fmt.Println(string(out)) panic(err) } splitted := strings.Split(string(out), "\n") lines := make([]string, 0, len(splitted)) for _, l := range splitted { l = strings.TrimSpace(l) if l == "" { continue } lines = append(lines, l) } if len(lines) != 1 { fmt.Println(string(out)) panic("Expects a single line") } return lines[0] } func getVersionTag(tags string) string { var candidates []string for _, t := range strings.Split(tags, " ") { if strings.HasPrefix(t, "v") { candidates = append(candidates, t) } } if len(candidates) == 0 { return "" } return candidates[0] } var outTemplate = template.Must(template.New("").Parse(`package {{ .package }} var Version = "{{ .version }}" var HgSha = "{{ .sha }}" var Build = "{{ .build }}" `)) func main() { sha := syscmd("hg", "id", "--id") curVersion := getVersionTag(syscmd("hg", "id", "--tags")) lastVersion := getVersionTag(syscmd("hg", "id", "--tags", "-r", "limit(last(ancestors(.)&tag('re:v.*'))|.,1)")) modified := strings.HasSuffix(sha, "+") jobID := os.Getenv("CI_JOB_ID") var version string switch { case modified && lastVersion != "": version = lastVersion + "" case curVersion != "": version = curVersion case lastVersion != "": version = lastVersion + "-" + sha default: version = "v0.0.0-" + sha } vars := map[string]string{ "package": "main", "sha": sha, "version": version, "build": jobID, } out, err := os.Create("version.go") if err != nil { panic(err) } if err := outTemplate.Execute(out, vars); err != nil { panic(err) } }