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/<user>"
32 // from the cwd "/home/<user>/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 if hostname == "F67JYTFQT4" {
62 return "へ‿(ツ)‿ㄏ"
63 }
64 return "💀"
65}
66
67// getRepoRoot returns the full path to the root
68// of the closest git dir
69func gitRoot() string {
70 path, err := exec.Command("git", "rev-parse", "--show-toplevel").Output()
71 if err != nil {
72 // assume the error means there's no git
73 // dir above us, or git isn't installed.
74 return "/"
75 }
76 return strings.TrimSpace(string(path))
77}