all repos — dotfiles @ f713de8850ef33ed54eb44bbec2af3fd797ad8b7

my *nix dotfiles

prompt/git.go (view raw)

 1package main
 2
 3import (
 4	"os"
 5	"path/filepath"
 6
 7	git "github.com/libgit2/git2go/v33"
 8)
 9
10// Recursively traverse up until we find .git
11// and return the git repo path.
12func getGitDir(cwd string) string {
13	for {
14		dirs, _ := os.ReadDir(cwd)
15		for _, d := range dirs {
16			if ".git" == d.Name() {
17				return cwd
18			} else if cwd == "/" {
19				return ""
20			}
21		}
22		cwd = filepath.Dir(cwd)
23	}
24}
25
26// Returns the current git branch or current ref sha.
27func getGitBranch(repo *git.Repository, ch chan<- string) {
28	ref, _ := repo.Head()
29	// Quick hack to fix crash when ref is nil;
30	// i.e., new repo with no commits.
31	if ref == nil {
32		ch <- "no commit"
33	}
34	if ref.IsBranch() {
35		name, _ := ref.Branch().Name()
36		ch <- name
37	} else {
38		ch <- ref.Target().String()[:8]
39	}
40}
41
42// Returns • if clean, else ×.
43func getGitStatus(repo *git.Repository, ch chan<- string) {
44	sl, _ := repo.StatusList(&git.StatusOptions{
45		Show:  git.StatusShowIndexAndWorkdir,
46		Flags: git.StatusOptIncludeUntracked,
47	})
48	n, _ := sl.EntryCount()
49	if n != 0 {
50		ch <- "×"
51	} else {
52		ch <- "•"
53	}
54}