-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit.go
More file actions
101 lines (94 loc) Β· 1.94 KB
/
git.go
File metadata and controls
101 lines (94 loc) Β· 1.94 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
99
100
101
package main
import (
"bufio"
"context"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
)
func gitBranch(cwd string) (branch string, repoDir string) {
dir := cwd
for {
gitPath := filepath.Join(dir, ".git")
info, err := os.Stat(gitPath)
if err == nil {
var headPath string
if info.IsDir() {
headPath = filepath.Join(gitPath, "HEAD")
} else {
data, err := os.ReadFile(gitPath)
if err != nil {
return "", ""
}
gitDir := strings.TrimSpace(strings.TrimPrefix(string(data), "gitdir: "))
if !filepath.IsAbs(gitDir) {
gitDir = filepath.Join(dir, gitDir)
}
headPath = filepath.Join(gitDir, "HEAD")
}
data, err := os.ReadFile(headPath)
if err != nil {
return "", ""
}
head := strings.TrimSpace(string(data))
if strings.HasPrefix(head, "ref: refs/heads/") {
return head[16:], dir
}
if len(head) >= 8 {
return head[:8], dir
}
return "", ""
}
parent := filepath.Dir(dir)
if parent == dir {
return "", ""
}
dir = parent
}
}
func gitDirty(repoDir string) string {
ctx, cancel := context.WithTimeout(context.Background(), 150*time.Millisecond)
defer cancel()
cmd := exec.CommandContext(ctx, "git", "status", "--porcelain")
cmd.Dir = repoDir
out, err := cmd.Output()
if err != nil {
return ""
}
staged, modified, untracked := false, false, false
scanner := bufio.NewScanner(strings.NewReader(string(out)))
for scanner.Scan() {
line := scanner.Text()
if len(line) < 2 {
continue
}
x, y := line[0], line[1]
switch {
case x == '?':
untracked = true
default:
if x != ' ' {
staged = true
}
if y != ' ' {
modified = true
}
}
}
if !staged && !modified && !untracked {
return fc(cGreen, "β")
}
var parts []string
if staged {
parts = append(parts, fc(cGreen, "+"))
}
if modified {
parts = append(parts, fc(cRed, "!"))
}
if untracked {
parts = append(parts, fc(cYellow, "?"))
}
return strings.Join(parts, "")
}