-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathgit.go
64 lines (57 loc) · 1.4 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
58
59
60
61
62
63
64
package main
import (
"bytes"
"fmt"
"os/exec"
"strings"
)
type git struct {
dir string
}
func (g git) exec(args ...string) (string, error) {
var errOut bytes.Buffer
c := exec.Command("git", args...)
c.Dir = g.dir
c.Stderr = &errOut
out, err := c.Output()
outStr := strings.TrimSpace(string(out))
if err != nil {
err = fmt.Errorf("git: error=%q stderr=%s", err, string(errOut.Bytes()))
}
return outStr, err
}
// Commit returns the short git commit hash.
func (g git) Commit() (string, error) {
return g.exec("rev-parse", "--short", "HEAD")
}
// State returns the repository state indicating whether
// it is "clean" or "dirty".
func (g git) State() (string, error) {
out, err := g.exec("status", "--porcelain")
if err != nil {
return "", err
}
if len(out) > 0 {
return "dirty", nil
}
return "clean", nil
}
// Branch returns the branch name. If it is detached,
// or an error occurs, returns "HEAD".
func (g git) Branch() string {
out, err := g.exec("symbolic-ref", "-q", "--short", "HEAD")
if err != nil {
// might be failed due to another reason, but assume it's
// exit code 1 from `git symbolic-ref` in detached state.
return "HEAD"
}
return out
}
// Summary returns the output of "git describe --tags --dirty --always".
func (g git) Summary() (string, error) {
out, err := g.exec("describe", "--tags", "--dirty", "--always")
if err != nil {
return "", err
}
return out, err
}