forked from tcnksm/ghr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
git.go
62 lines (51 loc) · 1.31 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
package main
import (
"bytes"
"fmt"
"io/ioutil"
"os/exec"
"regexp"
"strings"
)
var RepoNameRegexp = regexp.MustCompile(`.+/([^/]+)\.git$`)
func GetRepoName() (string, error) {
url, err := gitRemote()
if err != nil || url == "" {
return "", fmt.Errorf("Cound not retrieve remote repository url\n")
}
repo := retrieveRepoName(url)
if repo == "" {
return "", fmt.Errorf("Cound not retrieve repository name\n")
}
return repo, nil
}
func GetOwnerName() (string, error) {
owner, err := gitOwner()
if err != nil || owner == "" {
return "", fmt.Errorf("Cound not retrieve git user name\n")
}
return owner, err
}
func retrieveRepoName(url string) string {
matched := RepoNameRegexp.FindStringSubmatch(url)
return matched[1]
}
// git config --local remote.origin.url
func gitRemote() (string, error) {
return gitConfig("--local", "remote.origin.url")
}
// git config --global user.name
func gitOwner() (string, error) {
return gitConfig("--global", "user.name")
}
func gitConfig(args ...string) (string, error) {
gitArgs := append([]string{"config", "--get", "--null"}, args...)
var stdout bytes.Buffer
cmd := exec.Command("git", gitArgs...)
cmd.Stdout = &stdout
cmd.Stderr = ioutil.Discard
if err := cmd.Run(); err != nil {
return "", err
}
return strings.TrimRight(stdout.String(), "\000"), nil
}