-
Notifications
You must be signed in to change notification settings - Fork 40
/
values.go
78 lines (69 loc) · 1.85 KB
/
values.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
package main
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"time"
)
const versionFile = "VERSION"
// GetFlags collects data to be passed as ldflags.
func GetFlags(dir string, args []string) (map[string]string, error) {
repo := git{dir}
gitBranch := repo.Branch()
gitCommit, err := repo.Commit()
if err != nil {
return nil, fmt.Errorf("failed to get commit: %v", err)
}
gitState, err := repo.State()
if err != nil {
return nil, fmt.Errorf("failed to get repository state: %v", err)
}
gitSummary, err := repo.Summary()
if err != nil {
return nil, fmt.Errorf("failed to get repository summary: %v", err)
}
// prefix keys with package to be used by ldflags -X
pkg := defaultPackage
if value, ok := collectGovvvDirective(args, flPackage); ok {
pkg = value
}
v := map[string]string{
pkg + ".BuildDate": date(),
pkg + ".GitCommit": gitCommit,
pkg + ".GitBranch": gitBranch,
pkg + ".GitState": gitState,
pkg + ".GitSummary": gitSummary,
}
// calculate the version
if value, ok := collectGovvvDirective(args, flVersion); ok {
v[pkg+".Version"] = value
} else {
value, err := versionFromFile(dir)
if err != nil {
return nil, err
} else if value != "" {
v[pkg+".Version"] = value
}
}
return v, nil
}
// date returns the UTC date formatted in RFC 3339 layout.
func date() string {
return time.Now().UTC().Format(time.RFC3339)
}
// versionFromFile looks for a file named VERSION in dir if it exists and
// returns its contents by trimming the whitespace around it. If the file
// does not exist, it does not return any errors
func versionFromFile(dir string) (string, error) {
fp := filepath.Join(dir, versionFile)
b, err := ioutil.ReadFile(fp)
if os.IsNotExist(err) {
return "", nil
}
if err != nil {
return "", fmt.Errorf("failed to read version file %s: %v", fp, err)
}
return string(bytes.TrimSpace(b)), nil
}