forked from project-stacker/stacker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
git.go
57 lines (47 loc) · 1.36 KB
/
git.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
package stacker
import (
"os/exec"
"strings"
"github.com/apex/log"
)
// gitHash generates a version string similar to git describe --always
func gitHash(path string, short bool) (string, error) {
// Get hash
args := []string{"-C", path, "rev-parse", "HEAD"}
if short {
args = []string{"-C", path, "rev-parse", "--short", "HEAD"}
}
output, err := exec.Command("git", args...).CombinedOutput()
if err != nil {
return "", err
}
return strings.TrimSpace(string(output)), nil
}
// GitVersion generates a version string similar to what git describe --always
// does, with -dirty on the end if the git repo had local changes.
func GitVersion(path string) (string, error) {
var vers string
// Obtain commit hash
args := []string{"-C", path, "describe", "--tags"}
output, err := exec.Command("git", args...).CombinedOutput()
if err == nil {
vers = strings.TrimSpace(string(output))
} else {
log.Debug("'git describe --tags' failed, falling back to hash")
vers, err = gitHash(path, false)
if err != nil {
return "", err
}
}
// Check if there are local changes
args = []string{"-C", path, "status", "--porcelain", "--untracked-files=no"}
output, err = exec.Command("git", args...).CombinedOutput()
if err != nil {
return "", err
}
if len(output) == 0 {
// Commit is clean, no local changes found
return vers, nil
}
return vers + "-dirty", nil
}