small pixel drawing of a pufferfish dotfiles

bin/prompt.go

package main

import (
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"time"
)

// getRepoRoot returns the full path to the root
// of the closest git dir
func gitTopLevel() string {
	path, err := exec.Command("git", "rev-parse", "--show-toplevel").Output()
	if err != nil {
		// assume the error means there's no git
		// dir above us
		return "/"
	}
	return strings.TrimSpace(string(path))
}

func resolveEmoji(hostname string) string {
	emoji := "💀"
	if hostname == "zora" {
		emoji = "🌸"
	} else if hostname == "nostromo" {
		emoji = "🛸"
	}
	return emoji
}

func main() {
	wd, _ := os.Getwd()
	cwd, _ := filepath.EvalSymlinks(wd)
	host, _ := os.Hostname()
	home := os.Getenv("HOME")
	now := time.Now().Format("15:04:05")
	emoji := resolveEmoji(host)
	fmt.Printf("%s %s ", now, emoji)

	var promptRoot string
	gitTop := gitTopLevel()
	if gitTop == home {
		promptRoot = "~"
	} else {
		promptRoot = filepath.Base(gitTop)
	}
	// subtract the git toplevel "/home/j3s"
	// from the cwd "/home/j3s/code/nongitdir"
	// to get the suffix "/code/nongitdir"
	// os.cwd gets the symlink, git does not
	suffix := cwd[len(gitTop):]
	fmt.Printf("%s", promptRoot)

	var parts []string
	parts = strings.Split(suffix, "/")
	for i, part := range parts {
		if i == len(parts)-1 {
			fmt.Printf("%s", part)
		} else {
			if len(part) != 0 {
				fmt.Printf("%c/", part[0])
			} else {
				fmt.Printf("/")
			}
		}
	}
}