forked from bosun-monitor/bosun
/
build.go
95 lines (82 loc) · 1.78 KB
/
build.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
package main
import (
"bytes"
"fmt"
"go/ast"
"go/parser"
"go/printer"
"go/token"
"io"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
)
func main() {
id := time.Now().UTC().Format("20060102150405")
base := filepath.Join(os.Getenv("GOPATH"), "src", "bosun.org")
os.Chdir(base)
rev, err := exec.Command("git", "rev-parse", "HEAD").Output()
if err != nil {
log.Fatal(err)
}
hash := fmt.Sprintf(`"%s"`, strings.TrimSpace(string(rev)))
rewrite("bosun", id, hash, base)
rewrite("scollector", id, hash, base)
fmt.Printf("version:\n hash: %s\n id: %s\n", hash, id)
}
func rewrite(name, id, hash, base string) {
cmdir := filepath.Join(base, "cmd", name)
path := filepath.Join(cmdir, "main.go")
mainfile, err := os.OpenFile(path, os.O_RDWR, 0660)
if err != nil {
log.Fatal(err)
}
defer mainfile.Close()
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, path, mainfile, parser.ParseComments)
if err != nil {
log.Fatal(err)
}
for _, d := range f.Decls {
d, ok := d.(*ast.GenDecl)
if !ok {
continue
}
if d.Tok != token.CONST {
continue
}
for _, spec := range d.Specs {
spec, ok := spec.(*ast.ValueSpec)
if !ok {
continue
}
if len(spec.Names) != 1 || len(spec.Values) != 1 {
continue
}
value, ok := spec.Values[0].(*ast.BasicLit)
if !ok {
continue
}
switch spec.Names[0].Name {
case "VersionDate":
value.Value = id
case "VersionID":
value.Value = hash
}
}
}
var config = printer.Config{Mode: printer.UseSpaces | printer.TabIndent, Tabwidth: 8}
var buf bytes.Buffer
if err := config.Fprint(&buf, fset, f); err != nil {
log.Fatal(err)
}
if _, err := mainfile.Seek(0, os.SEEK_SET); err != nil {
log.Fatal(err)
}
if _, err := io.Copy(mainfile, &buf); err != nil {
log.Fatal(err)
}
}