-
Notifications
You must be signed in to change notification settings - Fork 7
/
git.go
74 lines (63 loc) · 1.55 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
package porcelain
import (
"bytes"
"errors"
"io"
"log"
"os/exec"
"strconv"
"strings"
"syscall"
)
const notRepoStatus string = "exit status 128"
var ErrNotAGitRepo error = errors.New("not a git repo")
func GetGitOutput(cwd string) (io.Reader, error) {
if ok, err := IsInsideWorkTree(cwd); err != nil {
if err == ErrNotAGitRepo {
return nil, ErrNotAGitRepo
}
log.Printf("error detecting work tree: %s", err)
return nil, err
} else if !ok {
return nil, ErrNotAGitRepo
}
var buf = new(bytes.Buffer)
cmd := exec.Command("git", "status", "--porcelain=v2", "--branch")
cmd.Stdout = buf
cmd.Dir = cwd
log.Printf("running %q", cmd.Args)
if err := cmd.Run(); err != nil {
return nil, err
}
return buf, nil
}
func PathToGitDir(cwd string) (string, error) {
cmd := exec.Command("git", "rev-parse", "--absolute-git-dir")
cmd.Dir = cwd
log.Printf("running %q", cmd.Args)
out, err := cmd.Output()
if err != nil {
return "", err
}
return strings.TrimSpace(string(out)), nil
}
func IsInsideWorkTree(cwd string) (bool, error) {
cmd := exec.Command("git", "rev-parse", "--is-inside-work-tree")
cmd.Dir = cwd
log.Printf("running %q", cmd.Args)
out, err := cmd.Output()
if err != nil {
if exiterr, ok := err.(*exec.ExitError); ok {
if status, ok := exiterr.Sys().(syscall.WaitStatus); ok {
if status.ExitStatus() == 128 {
return false, ErrNotAGitRepo
}
}
}
if cmd.ProcessState.String() == notRepoStatus {
return false, ErrNotAGitRepo
}
return false, err
}
return strconv.ParseBool(strings.TrimSpace(string(out)))
}