Boboss

Bash shell git coloration

Mar 28th, 2013
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.87 KB | None | 0 0
  1.  
  2. # START : git, coloration
  3.  
  4. if [ -z "$PS1_ORIG" ]; then
  5.     PS1_ORIG=$PS1
  6.     OLD_PROMPT_COMMAND=$PROMPT_COMMAND
  7. fi
  8.  
  9. RED='\001\033[31m\002'
  10. YELLOW='\001\033[33m\002'
  11. GREEN='\001\033[32m\002'
  12. BLUE='\001\033[34m\002'
  13. DARK_BLUE='\001\033[36m\002'
  14. COLOR_NONE='\001\033[00m\002'
  15.  
  16. function parse_git_branch {
  17.     local AHEAD='↑'
  18.     local LATE='↓'
  19.     local DIVERGE='↕'
  20.     local NOT_CLEAN='⚡'
  21.  
  22.     git rev-parse --git-dir &> /dev/null
  23.  
  24.     if [ $? != 0 ]; then
  25.         echo "NOT_A_GIT_REPO"
  26.     else
  27.         git_status="$(git status 2> /dev/null)"
  28.         branch_pattern="^# On branch ([^${IFS}]*)"
  29.         remote_pattern="# Your branch is (.*)"
  30.         diverge_pattern="# Your branch and (.*) have diverged"
  31.  
  32.         if [[ ! ${git_status} =~ "working directory clean" ]]; then
  33.             state="${RED}${NOT_CLEAN}"
  34.         fi
  35.  
  36.         # add an else if or two here if you want to get more specific
  37.         if [[ ${git_status} =~ ${remote_pattern} ]]; then
  38.             if [[ ${BASH_REMATCH[1]} =~ "ahead of" ]]; then
  39.                 remote="${YELLOW}${AHEAD}"
  40.             else
  41.                 remote="${YELLOW}${LATE}"
  42.             fi
  43.         fi
  44.  
  45.         if [[ ${git_status} =~ ${diverge_pattern} ]]; then
  46.             remote="${YELLOW}${DIVERGE}"
  47.         fi
  48.  
  49.         if [[ ${git_status} =~ ${branch_pattern} ]]; then
  50.             branch=${BASH_REMATCH[1]}
  51.             echo " (${branch})${remote}${state}"
  52.         fi
  53.     fi
  54. }
  55.  
  56. function prompt_func() {
  57.     previous_return_value=$?;
  58.     local git_result=$(parse_git_branch)
  59.  
  60.     if [ "$git_result" == "NOT_A_GIT_REPO" ]; then
  61.         eval ${OLD_PROMPT_COMMAND}
  62.         PS1=$PS1_ORIG
  63.     else
  64.         local GIT_TOPLEVEL=$(git rev-parse --show-toplevel)
  65.         local prompt="${BLUE}[${RED}${PWD/#${GIT_TOPLEVEL%/*}/}${GREEN}${git_result}${BLUE}]${COLOR_NONE}"
  66.         local SEP="➔"
  67.  
  68.         eval ${OLD_PROMPT_COMMAND} #Set the title value
  69.  
  70.         if test $previous_return_value -eq 0; then
  71.             PS1="${prompt}${SEP}${COLOR_NONE} "
  72.         else
  73.             PS1="${prompt}${RED}${SEP}${COLOR_NONE} "
  74.         fi
  75.     fi
  76. }
  77.  
  78. PROMPT_COMMAND=prompt_func
  79.  
  80. # END : git, coloration
Advertisement
Add Comment
Please, Sign In to add comment