all repos — dotfiles @ 00d32a23d655b84389cab7ade2d0e25066343dc6

my *nix dotfiles

prompt/prompt.go (view raw)

 1package main
 2
 3import (
 4	"fmt"
 5	"os"
 6	"path/filepath"
 7	"strings"
 8
 9	git "github.com/libgit2/git2go/v31"
10)
11
12const (
13	promptSym = "▲"
14)
15
16var (
17	red   = color("\033[31m%s\033[0m")
18	green = color("\033[32m%s\033[0m")
19	cyan  = color("\033[36m%s\033[0m")
20)
21
22func color(s string) func(...interface{}) string {
23	return func(args ...interface{}) string {
24		return fmt.Sprintf(s, fmt.Sprint(args...))
25	}
26}
27
28// Truncates the current working directory:
29//   /home/icy/foo/bar -> ~/f/bar
30func trimPath(cwd, home string) string {
31
32	var path string
33	if strings.HasPrefix(cwd, home) {
34		path = "~" + strings.TrimPrefix(cwd, home)
35	} else {
36		// If path doesn't contain $HOME, return the
37		// entire path as is.
38		path = cwd
39		return path
40	}
41	items := strings.Split(path, "/")
42	truncItems := []string{}
43	for i, item := range items {
44		if i == (len(items) - 1) {
45			truncItems = append(truncItems, item)
46			break
47		}
48		truncItems = append(truncItems, item[:1])
49	}
50	return filepath.Join(truncItems...)
51}
52
53func makePrompt() string {
54	cwd, _ := os.Getwd()
55	home := os.Getenv("HOME")
56	gitDir := getGitDir()
57	if len(gitDir) > 0 {
58		repo, _ := git.OpenRepository(getGitDir())
59		return fmt.Sprintf(
60			"\n%s (%s %s)\n%s",
61			cyan(trimPath(cwd, home)),
62			gitBranch(repo),
63			gitStatus(repo),
64			promptSym,
65		)
66	}
67	return fmt.Sprintf(
68		"\n%s\n%s",
69		cyan(trimPath(cwd, home)),
70		promptSym,
71	)
72}
73
74func main() {
75	fmt.Println(makePrompt())
76}