all repos — dotfiles @ 18e1d649416cd7eb75c56215cf6b044eeeadcbdc

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
16// Truncates the current working directory:
17//   /home/icy/foo/bar -> ~/f/bar
18func trimPath(cwd, home string) string {
19
20	var path string
21	if strings.HasPrefix(cwd, home) {
22		path = "~" + strings.TrimPrefix(cwd, home)
23	} else {
24		// If path doesn't contain $HOME, return the
25		// entire path as is.
26		path = cwd
27		return path
28	}
29	items := strings.Split(path, "/")
30	truncItems := []string{}
31	for i, item := range items {
32		if i == (len(items) - 1) {
33			truncItems = append(truncItems, item)
34			break
35		}
36		truncItems = append(truncItems, item[:1])
37	}
38	return filepath.Join(truncItems...)
39}
40
41func makePrompt() string {
42	cwd, _ := os.Getwd()
43	home := os.Getenv("HOME")
44	gitDir := getGitDir()
45	if len(gitDir) > 0 {
46		repo, _ := git.OpenRepository(getGitDir())
47		return fmt.Sprintf(
48			"\n%s (%s %s)\n%s",
49			trimPath(cwd, home),
50			gitBranch(repo),
51			gitStatus(repo),
52			promptSym,
53		)
54	}
55	return fmt.Sprintf(
56		"\n%s\n%s",
57		trimPath(cwd, home),
58		promptSym,
59	)
60}
61
62func main() {
63	fmt.Println(makePrompt())
64}