-
Notifications
You must be signed in to change notification settings - Fork 2
/
git.go
103 lines (90 loc) · 2.65 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
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
96
97
98
99
100
101
102
103
package main
import (
"bufio"
"bytes"
"fmt"
"os/exec"
"regexp"
"strings"
)
// https://github.com/example/example.git
// git@github.com:example/example.git
var matchGitHubURL = regexp.MustCompile(`^(?:git@github.com(?:-[^:]+)?:|https?://github.com/)([^/]+)/(.*)(\.git)$`)
// git config --get remote.origin.url
func gitGetGitHubURL() (string, string, error) {
try := func(remote string) (string, error) {
cmd := exec.Command("git", "config", "--get", fmt.Sprintf("remote.%s.url", remote))
output, err := cmd.CombinedOutput()
lg.dbg("git config --get remote.%s.url:\n%s---", remote, string(output))
if err != nil {
if len(output) == 0 {
// Probably no remote
// FIXME Add check to see if we're in a git repository
return "", nil
}
return "", fmt.Errorf("git: %v: %s", err, firstLine(output))
}
return string(bytes.TrimSpace(output)), nil
}
for _, remote := range []string{"origin", "github"} {
remote, err := try(remote)
if err != nil {
return "", "", err
}
if match := matchGitHubURL.FindStringSubmatch(remote); match != nil {
return match[1], match[2], nil
}
}
return "", "", nil
}
// git describe --tags --exact-match
func gitGetTag() (string, error) {
cmd := exec.Command("git", "describe", "--tags", "--exact-match")
output, err := cmd.CombinedOutput()
lg.dbg("git describe --tags --exact-match:\n%s---", string(output))
if err != nil {
if bytes.HasPrefix(output, []byte("fatal: no tag exactly matches")) {
output = nil
} else if bytes.HasPrefix(output, []byte("fatal: No names found, cannot describe anything")) {
output = nil
} else {
return "", fmt.Errorf("git: %v: %s", err, firstLine(output))
}
}
tags := strings.Fields(string(output))
if len(tags) == 0 {
return "", nil
}
return tags[0], nil
}
func firstLine(lines []byte) string {
if len(lines) == 0 {
return ""
}
scanner := bufio.NewScanner(bytes.NewReader(lines))
scanner.Scan()
return scanner.Text()
}
// git rev-list <tag>
func gitGetTagCommit(tag string) (string, error) {
cmd := exec.Command("git", "rev-list", tag)
output, err := cmd.CombinedOutput()
lg.dbg("git rev-list:\n%s---", string(output))
if err != nil {
return "", fmt.Errorf("git: %v: %s", err, firstLine(output))
}
return firstLine(output), nil
}
//func gitGetProgramName() (string, error) {
// return "gphr", nil
// cmd := exec.Command("go", "build", "-n")
// output, err := cmd.Output()
// if err != nil {
// return "", err
// }
// if match := matchBuiltPackage.FindAllSubmatch(output, -1); match != nil {
// pkg := string(match[len(match)-1][1])
// return filepath.Base(pkg), nil
// }
// return "", nil // TODO err?
//}