Thursday, September 18, 2008

Hack of the day: displaying the repository location in your bash prompt

I usually want to keep track of which repository/branch the current directory is pointing at, so I wrote the following bash script to display it in the prompt. The script can handle Git and Subversion.

function is_git_repo()
{
if [ $PWD = / ]; then
return 1;
elif [ -d $PWD/.git ]; then
return 0;
else
(cd ..; is_git_repo)
fi
}

function display_vc_location()
{
if [ -d $PWD/.svn ]; then
SVNLOC=$(svn info $PWD | sed -ne 's@URL: \(.*\)@\1@p' | cut -d/ -f4-)
SVNREV=$(svn info $PWD | sed -ne 's@Revision: \(.*\)@\1@p')
echo svn\($SVNLOC@$SVNREV\)
elif is_git_repo; then
GITLOC=$(git branch -a | grep -e '^*' | cut -d' ' -f2-)
echo git\($GITLOC\)
fi
}

Add it to your PS1 variable, like this:

PS1="... \$(display_vc_location) ..."

Exercise: extract both URL and revision without running svn info twice.

2 comments:

Anonymous said...

> GITLOC=$(git branch -a | grep -e '^*' | cut -d' ' -f2-)

Use sed instead:

git branch | sed -ne 's/\* \(.*\)/\1/p'

Or maybe this:

git symbolic-ref HEAD | sed 's#refs/heads/##'

You can use "git rev-parse" to check if you are in a git repo also.

Matt Doar said...

For extra points, colorize it as in p.89 of "Practical Development Environments" (O'Reilly, 2005)

PS1="[\u@\h\$(\
if [ -d CVS ]; then \
if [ -e CVS/Tag ]; then \
cat CVS/Tag | sed -e 's/^T/ /' | sed -e 's/^N/ /' \
| sed -e 's/^D/ Date /' | sed -e 's/_branch/\[\033]12;blue\007\]/';
\
else \
echo ' \[\033]12;black\007\]MAIN' ; \
fi; \
else \
echo '\[\033]12;black\007\]' ; \
fi) \W]\\$ "