all repos — dotfiles @ 072682632638161b3664dd61077f4f686090273d

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() 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	// Quick hack to fix crash when ref is nil;
31	// i.e., new repo with no commits.
32	if ref == nil {
33		return "no commit"
34	}
35	if ref.IsBranch() {
36		name, _ := ref.Branch().Name()
37		return name
38	} else {
39		return ref.Target().String()[:8]
40	}
41}
42
43// Returns • if clean, else ×.
44func gitStatus(repo *git.Repository) string {
45	sl, _ := repo.StatusList(&git.StatusOptions{
46		Show:  git.StatusShowIndexAndWorkdir,
47		Flags: git.StatusOptIncludeUntracked,
48	})
49	n, _ := sl.EntryCount()
50	if n != 0 {
51		return "×"
52	} else {
53		return "・"
54	}
55}