prompt/git.go (view raw)
1package main
2
3import (
4 "os"
5 "path/filepath"
6
7 git "github.com/libgit2/git2go/v31"
8)
9
10// Recursively traverse up until we find .git
11// and return the git repo path.
12func getGitDir() string {
13 cwd, _ := os.Getwd()
14 for {
15 dirs, _ := os.ReadDir(cwd)
16 for _, d := range dirs {
17 if ".git" == d.Name() {
18 return cwd
19 } else if cwd == "/" {
20 return ""
21 }
22 }
23 cwd = filepath.Dir(cwd)
24 }
25}
26
27// Returns the current git branch or current ref sha.
28func gitBranch(repo *git.Repository) string {
29 ref, _ := repo.Head()
30 if ref.IsBranch() {
31 name, _ := ref.Branch().Name()
32 return name
33 } else {
34 return ref.Target().String()[:8]
35 }
36}
37
38// Returns • if clean, else ×.
39func gitStatus(repo *git.Repository) string {
40 sl, _ := repo.StatusList(&git.StatusOptions{
41 Show: git.StatusShowIndexAndWorkdir,
42 Flags: git.StatusOptIncludeUntracked,
43 })
44 n, _ := sl.EntryCount()
45 if n != 0 {
46 return red("×")
47 } else {
48 return green("•")
49 }
50}