Wednesday, November 24, 2010

Bash and source control (updated)

Just a quick note for myself and for those of you who do coding and use bash: Do you you want to have a pretty and infromative prompt like:


fer@pilgrim ~/src/oinak.github.com (git:master → 212069f) $

or like
fer@pilgrim ~/src/oinak.github.com (svn:/trunk → 4480) $

Look for the place where your ~/.bashrc file establishes the value of the PS1 special environment variable, comment it out and put this in its place:
 1   #parse_git_branch () {
 2   #  echo -n "$(git name-rev HEAD 2> /dev/null | sed 's#HEAD\ \(.*\)# (git:\1#') → $(git log -1 --pretty=format:%h))"
 3   #}
 4 
 5   # more elegant solution edited to include @mrdias suggestion
 6   parse_git_branch () {
 7     echo -n "$(git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (git:\1/') → $(git log -1 --pretty=format:%h))"
 8   }
 9   parse_svn_branch() {
10     local s=
11     s=" ($(parse_svn_url | sed -e 's#^'"$(parse_svn_repository_root)"'##g' | awk '{print "svn:"$1"" }') → $(parse_svn_revision))"
12     echo -n "$s"
13   }
14   parse_svn_url() {
15     svn info 2>/dev/null | sed -ne 's#^URL: ##p'
16   }
17   parse_svn_repository_root() {
18     svn info 2>/dev/null | sed -ne 's#^Root of the repository: ##p'
19   }
20   parse_svn_revision() {
21     svn info | sed -n -e '/^Revision: \([0-9]*\).*$/s//\1/p'
22   }
23 
24   scm_ps1() {
25     if [[ -d ".svn" ]] ; then
26         echo "$(parse_svn_branch)"
27     elif [[ -d ".git" ]] ; then
28         echo "$(parse_git_branch)"
29     fi
30   }
31 
32   RED="\[\033[0;31m\]"
33   RED_BOLD="\[\033[01;31m\]"
34   GREEN="\[\033[0;32m\]"
35   GREEN_BOLD="\[\033[01;32m\]"
36   YELLOW="\[\033[0;33m\]"
37   YELLOW_BOLD="\[\033[01;33m\]"
38   BLUE="\[\033[0;34m\]"
39   BLUE_BOLD="\[\033[01;34m\]"
40   BLACK="\[\033[0;38m\]"
41 
42   export PS1="$YELLOW_BOLD\u$BLACK@$GREEN_BOLD\h $BLUE_BOLD\w$RED\$(scm_ps1)$BLACK$ "


I hope the function names and color constants help you to understand what is going on and allow you to customize it to your own needs and taste.

Good night and happy hacking.

25 Nov 2010 (UPDATE):

I have edited parse_git_branch function as @mdias suggested

No comments:

Post a Comment