Saturday, April 21, 2012

bash git prompts or I forgot again my git branch

To have your command prompt indicates in which branch you are :
(mybranch) root:~$

source : http://blog.piwai.info/2011/10/09/roooh-jai-encore-oublie-ma-branche-git/
source : http://www.git-attitude.fr/2010/07/14/le-prompt-bash-qui-change-la-vie-avec-git/

If you want to view how many commit you are ahead or behind from origin/master add this bash script to your .bashrc file

If you are ahead of 2 commit and behind of one commit from origin/master, you will have something like : (mybranch+2-1) root:~$
# git branch name in prompt
c_red=`tput setaf 1`
c_green=`tput setaf 2`
c_sgr0=`tput sgr0`

# http://stackoverflow.com/questions/1593051/how-to-programmatically-determine-the-current-checked-out-git-branch

parse_git_branch () {
  if git rev-parse --git-dir >/dev/null 2>&1
  then
# TODO ?          gitver=$(git rev-parse --symbolic-full-name --abbrev-ref HEAD)
          gitver=$(git branch 2>/dev/null| sed -n '/^\*/s/^\* //p')
  else
          return 0
  fi
  
  git_has_current_branch_remotes_origin=$( git branch -a | grep "remotes/origin/$gitver" | wc -l )
  git_has_remotes_origin=$( git branch -a | grep "remotes/origin" | wc -l )

  if test $git_has_current_branch_remotes_origin = 0
  then
          git_head_to_origin=""
  else
          git_ahead=$(git log origin/$gitver..HEAD --oneline | wc -l)
          git_behind=$(git log HEAD..origin/$gitver --oneline | wc -l)
          
          if [ $git_ahead != 0 ]
          then
                git_ahead_msg="+"$git_ahead
          fi

          if [ $git_behind != 0 ]
          then
                git_behind_msg="-"$git_behind
          fi
  fi
   
  echo -e "($gitver$git_ahead_msg$git_behind_msg) "
}

branch_color () {
        if git rev-parse --git-dir >/dev/null 2>&1
        then
                color=""
                if git diff --quiet 2>/dev/null >&2
                then
                        color="${c_green}"
                else
                        color=${c_red}
                fi
        else
                return 0
        fi
        echo -ne $color
}

PS1="\[\$(branch_color)\]\$(parse_git_branch)\[$(tput sgr0)\]$PS1"

No comments:

Post a Comment