my dotz
1package main
2
3import (
4 "fmt"
5 "os"
6 "os/exec"
7 "path/filepath"
8 "strings"
9)
10
11func main() {
12 wd, err := os.Getwd()
13 if err != nil {
14 fmt.Print("$ ")
15 return
16 }
17 cwd, err := filepath.EvalSymlinks(wd)
18 if err != nil {
19 fmt.Print("$ ")
20 return
21 }
22 emoji := resolveEmoji()
23
24 var promptRoot string
25 gitRoot := gitRoot()
26 if gitRoot == os.Getenv("HOME") {
27 promptRoot = "~"
28 } else {
29 promptRoot = filepath.Base(gitRoot)
30 }
31 // subtract the git toplevel "/home/j3s"
32 // from the cwd "/home/j3s/code/nongitdir"
33 // to get the suffix "/code/nongitdir"
34 // os.cwd gets the symlink, git does not
35 suffix := cwd[len(gitRoot):]
36 fmt.Printf("%s %s", emoji, promptRoot)
37
38 var parts []string
39 parts = strings.Split(suffix, "/")
40 for i, part := range parts {
41 if i == len(parts)-1 {
42 fmt.Printf("%s", part)
43 } else {
44 if len(part) != 0 {
45 fmt.Printf("%c/", part[0])
46 } else {
47 fmt.Printf("/")
48 }
49 }
50 }
51}
52
53func resolveEmoji() string {
54 hostname, _ := os.Hostname()
55 if hostname == "zora" {
56 return "🌸"
57 }
58 if hostname == "rose" {
59 return "🌹"
60 }
61 return "💀"
62}
63
64// getRepoRoot returns the full path to the root
65// of the closest git dir
66func gitRoot() string {
67 path, err := exec.Command("git", "rev-parse", "--show-toplevel").Output()
68 if err != nil {
69 // assume the error means there's no git
70 // dir above us, or git isn't installed.
71 return "/"
72 }
73 return strings.TrimSpace(string(path))
74}