forked from 99designs/smartling
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathget_git_branch.go
56 lines (47 loc) · 893 Bytes
/
get_git_branch.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
package main
import (
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/reconquest/hierr-go"
)
func getGitBranch() (string, error) {
dir, err := os.Getwd()
if err != nil {
return "", hierr.Errorf(
err,
"unable to get current working directory",
)
}
for {
if dir == "/" {
return "", hierr.Errorf(
err,
"no git repository can be found containing current directory",
)
}
_, err := os.Stat(filepath.Join(dir, ".git"))
if err != nil {
if !os.IsNotExist(err) {
return "", hierr.Errorf(
err,
`unable to get stats for "%s"`,
dir,
)
}
dir = filepath.Dir(dir)
continue
} else {
break
}
}
head, err := ioutil.ReadFile(filepath.Join(dir, ".git", "HEAD"))
if err != nil {
return "", hierr.Errorf(
err,
"unable to read git HEAD",
)
}
return filepath.Base(strings.TrimSpace(string(head))), nil
}