-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit.go
More file actions
98 lines (90 loc) · 2.04 KB
/
git.go
File metadata and controls
98 lines (90 loc) · 2.04 KB
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
// git.go — git command wrappers and repo discovery
package main
import (
"os"
"os/exec"
"path/filepath"
"strings"
)
type Repo struct {
Name string `json:"name"`
Path string `json:"path"`
}
// DiscoverRepos finds all git repos under given directories (1-depth).
func DiscoverRepos(dirs []string) []Repo {
var repos []Repo
for _, dir := range dirs {
dir = expandHome(dir)
entries, err := os.ReadDir(dir)
if err != nil {
continue
}
for _, e := range entries {
if !e.IsDir() {
continue
}
p := filepath.Join(dir, e.Name())
if isGitRepo(p) {
repos = append(repos, Repo{Name: e.Name(), Path: p})
}
}
}
return repos
}
func isGitRepo(path string) bool {
info, err := os.Stat(filepath.Join(path, ".git"))
if err != nil {
return false
}
return info.IsDir()
}
// gitLog runs git log with given format and args, returns lines.
func gitLog(repoPath string, extraArgs ...string) []string {
args := append([]string{"-C", repoPath, "log"}, extraArgs...)
cmd := exec.Command("git", args...)
out, err := cmd.Output()
if err != nil {
return nil
}
s := strings.TrimSpace(string(out))
if s == "" {
return nil
}
return strings.Split(s, "\n")
}
// gitRevList returns line count (commit count).
func gitRevListCount(repoPath string, extraArgs ...string) int {
args := append([]string{"-C", repoPath, "rev-list", "--count"}, extraArgs...)
cmd := exec.Command("git", args...)
out, err := cmd.Output()
if err != nil {
return 0
}
s := strings.TrimSpace(string(out))
n := 0
for _, c := range s {
if c >= '0' && c <= '9' {
n = n*10 + int(c-'0')
}
}
return n
}
// gitCurrentBranch returns the current branch name.
func gitCurrentBranch(repoPath string) string {
cmd := exec.Command("git", "-C", repoPath, "rev-parse", "--abbrev-ref", "HEAD")
out, err := cmd.Output()
if err != nil {
return ""
}
return strings.TrimSpace(string(out))
}
func expandHome(p string) string {
if strings.HasPrefix(p, "~/") {
home, err := os.UserHomeDir()
if err != nil {
return p
}
return filepath.Join(home, p[2:])
}
return p
}