small pixel drawing of a pufferfish dotfiles

make prompt aware of git roots
Jes Olson jolson@digitalocean.com
Wed, 24 Nov 2021 14:30:34 -0600
commit

ab07bf437599a30056c034514d389d3bc6c0e730

parent

3e21fa3143f517af4f6540f41a08464cd4d16df3

2 files changed, 40 insertions(+), 11 deletions(-)

jump to
M bin/prompt.gobin/prompt.go

@@ -3,28 +3,57 @@

import ( "fmt" "os" + "os/exec" + "path/filepath" "strings" "time" ) -func main() { - cwd, _ := os.Getwd() - host, _ := os.Hostname() +// getRepoRoot returns the full path to the root +// of the closest git dir +func getRepoRoot(pwd string) string { + var rootPath string + + path, err := exec.Command("git", "rev-parse", "--show-toplevel").Output() + if err != nil { + rootPath = "~" + } else { + rootPath = strings.TrimSpace(string(path)) + } + return rootPath +} + +func resolveEmoji(hostname string) string { emoji := "💀" - if host == "zora" { + if hostname == "zora" { emoji = "🍣" - } else if host == "nostromo" { + } else if hostname == "nostromo" { emoji = "🛸" } + return emoji +} + +func main() { + cwd, _ := os.Getwd() + host, _ := os.Hostname() home := os.Getenv("HOME") - var parts []string - if strings.HasPrefix(cwd, home) { - cwd = "~" + cwd[len(home):] + now := time.Now().Format("15:04:05") + emoji := resolveEmoji(host) + fmt.Printf("%s %s ", now, emoji) + + gitRoot := getRepoRoot(cwd) + + var prefix string + if gitRoot == home { + prefix = "~" + } else { + prefix = filepath.Base(gitRoot) } - now := time.Now().Format("15:04:05") - fmt.Printf("[%s] %s%s ", now, emoji, host) + suffix := cwd[len(gitRoot):] + fmt.Printf("%s", prefix) - parts = strings.Split(cwd, "/") + var parts []string + parts = strings.Split(suffix, "/") for i, part := range parts { if i == len(parts)-1 { fmt.Printf("%s", part)