-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgit.go
More file actions
63 lines (53 loc) · 1.42 KB
/
git.go
File metadata and controls
63 lines (53 loc) · 1.42 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
package main
import (
"fmt"
"os/exec"
"strings"
)
type Repo interface {
getUnpushedBranches() (map[string]string, error)
getUnpushedChanges() (int, error)
}
type GitRepo struct {
folder string
}
var _ Repo = (*GitRepo)(nil)
func runGit(folder string, commandAndArgs ...string) (string, error) {
cmd := exec.Command("git", commandAndArgs...)
cmd.Dir = folder
out, err := cmd.Output()
if err != nil {
return "", fmt.Errorf("error running git: %w", err)
}
return string(out), nil
}
var unpushedBranchesCommand = []string{"log", "--branches", "--not", "--remotes", `--pretty=format:"%h %d"`}
func (r *GitRepo) getUnpushedBranches() (map[string]string, error) {
out, err := runGit(r.folder, unpushedBranchesCommand...)
if err != nil {
return nil, fmt.Errorf("Error running git log: %w", err)
}
branches := make(map[string]string)
for _, line := range strings.Split(out, "\n") {
if line == "" {
continue
}
words := strings.Fields(line)
commit := words[0]
branch := words[1]
if !strings.HasPrefix(branch, "(") {
continue
}
branch = strings.Trim(branch, "()")
branches[branch] = commit
}
return branches, nil
}
var unpushedChangesCommand = []string{"status", "--porcelain"}
func (r *GitRepo) getUnpushedChanges() (int, error) {
out, err := runGit(r.folder, unpushedChangesCommand...)
if err != nil {
return -1, fmt.Errorf("error running git status: %w", err)
}
return strings.Count(out, "\n"), nil
}