-
Notifications
You must be signed in to change notification settings - Fork 221
/
Copy pathstate.go
83 lines (69 loc) · 1.44 KB
/
state.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
package git
import (
"bufio"
"os"
"path/filepath"
"regexp"
)
type State struct {
Branch, Step string
}
const (
NilStep string = ""
MergeStep string = "merge"
RebaseStep string = "rebase"
)
var refBranchRegexp = regexp.MustCompile(`^ref:\s*refs/heads/(.+)$`)
func (r *Repository) State() State {
branch := r.Branch()
if r.isMergeState() {
return State{
Branch: branch,
Step: MergeStep,
}
}
if r.isRebaseState() {
return State{
Branch: branch,
Step: RebaseStep,
}
}
return State{
Branch: branch,
Step: NilStep,
}
}
func (r *Repository) Branch() string {
headFile := filepath.Join(r.GitPath, "HEAD")
if _, err := r.Fs.Stat(headFile); os.IsNotExist(err) {
return ""
}
file, err := r.Fs.Open(headFile)
if err != nil {
return ""
}
defer file.Close()
scanner := bufio.NewScanner(file)
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
match := refBranchRegexp.FindStringSubmatch(scanner.Text())
if len(match) > 1 {
return match[1]
}
}
return ""
}
func (r *Repository) isMergeState() bool {
if _, err := r.Fs.Stat(filepath.Join(r.GitPath, "MERGE_HEAD")); os.IsNotExist(err) {
return false
}
return true
}
func (r *Repository) isRebaseState() bool {
if _, mergeErr := r.Fs.Stat(filepath.Join(r.GitPath, "rebase-merge")); os.IsNotExist(mergeErr) {
if _, applyErr := r.Fs.Stat(filepath.Join(r.GitPath, "rebase-apply")); os.IsNotExist(applyErr) {
return false
}
}
return true
}