Robert Carpenter

robert@tumblerlock.io — Boulder, Colorado

Fast Git Prompt Details

Written: March, 2015

Abstract: My first foray into real AWK programming came because I wanted a fast way to render git repository status into my prompt. Prompt functions available around the internet didn't have the rigor, detail, or speed I wanted and I'd been wanting to really learn to write AWK for many years.

Compiling Status: valid, I run it hundreds of times a day.

Repository: on github, as part of my dotfiles repository.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
    function gitstatus
      git status --porcelain -b ^ /dev/null | awk '
        BEGIN {
          status["untracked"] = 0
          status["modifications"] = 0
          status["unmerged"] = 0
        }
        $1 ~ /##/ {
          split($2, branch_names, ".")
        }
        $1 ~ /\?\?/       { status["untracked"] ++     }
        $1 ~ /M/          { status["modifications"] ++ }
        $1 ~ /[DAU][DAU]/ { status["unmerged"] ++ }
        END {
          print branch_names[1]
          print status["untracked"]
          print status["modifications"]
          print status["unmerged"]
        }
       '
    end
  

In use for the relevant part of my prompt function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
    function fish_prompt
      set -l stats (gitstatus)
      set -l dirty (math $stats[3] + $stats[2] + $stats[4])

      # ! for modified files
      if test $dirty -gt 0
        echo -s -n (set_color red) ! (set_color normal)
      end

      # branch name
      if test $stats[1]
        echo -s -n (set_color cyan) $stats[1] " " (set_color normal)
      end

      # prompt line
      echo -s (set_color normal)

      echo -s -n (set_color $fish_color_cwd) (prompt_pwd) (set_color normal)
      echo -s -n $
    end