-
Notifications
You must be signed in to change notification settings - Fork 4
/
gen.go
103 lines (83 loc) · 1.97 KB
/
gen.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
// +build ignore
// This program generates git.go. It can be invoked by running `go generate`
package main
import (
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"text/template"
"time"
)
var tmpl = template.Must(template.New("").Parse(`// Code generated by go generate; DO NOT EDIT.
// This file was generated at: {{.Timestamp}}
// This file is in sync with: {{.CommitSHA}}
package cmd
import (
"fmt"
"runtime"
"github.com/AlbinoGeek/sc2-rsu/sc2replaystats"
)
// PROGRAM is the human readable product name
const PROGRAM = "{{.Program}}"
// VERSION is the human readable product version
const VERSION = "{{.Version}}"
func init() {
sc2replaystats.ClientIdentifier = fmt.Sprintf("%s-%s", PROGRAM, runtime.GOOS)
}
`))
func getCommitSHA() string {
str, err := ioutil.ReadFile(".git/FETCH_HEAD")
if err != nil {
return "unknown-commit"
}
return strings.Split(string(str), "\t")[0]
}
func getPackageName() string {
_, b, _, _ := runtime.Caller(0)
return filepath.Base(filepath.Dir(b))
}
func getVersion() string {
// If the `git` tool is available, we can get our version number reliably
cmd := exec.Command("git", "describe", "--match", "v*", "--always", "--tags")
// Should return a string like "v0.3.65-g3a407d2"
// "v" tag "." commits_since_tag "-g" commit_sha
out, err := cmd.CombinedOutput()
// Otherwise, return the commit SHA of HEAD
if err != nil {
return fmt.Sprintf("git-%s", getCommitSHA())
}
return strings.Trim(string(out), " \t\r\n")
}
func main() {
if len(os.Args) > 1 {
if os.Args[1] == "PROGRAM" {
fmt.Println(getPackageName())
}
if os.Args[1] == "VERSION" {
fmt.Println(getVersion())
}
return
}
f, err := os.Create("cmd/PROGRAM.go")
if err != nil {
panic(err)
}
tmpl.Execute(f, struct {
CommitSHA string
Program string
Timestamp string
Version string
}{
getCommitSHA(),
getPackageName(),
time.Now().String(),
getVersion(),
})
if err := f.Close(); err != nil {
panic(err)
}
}