April 7, 2015

Command Prompt Hacks for Git and Perforce Helix DVCS

Media & Entertainment

GIT

When I started using Git, I immediately came across the problem that I did not know which branch I was currently in. Using Perforce I do not tend to swap branches that often since I can shelve my changes if I need to swap what I am working on, but in Git I easily work in 3 or 4 branches in parallel. Hence my problem of knowing which branch is currently active.

An IDE like Eclipse with EGit or IntelliJ highlights which branch I am in, but running git branch every time I need to commit a change is tedious. Fortunately, I am not the only one with this problem and a little Internet search helped me to find a simple solution, a command prompt hack (for bash, my preferred shell):

function parse_git_branch () {

    git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/' 
} 
function set_prompt (){

  export PS1="\u@\h:\w\$(parse_git_branch)\$ "

}

export PROMPT_COMMAND=set_prompt

The result of this hack can be seen here:

sknop@marsupilami:~/git/sudoku (master)$

Not sure about you, but I find this immensely more readable, and ever since I used this hack I have not committed to the wrong branch anymore.

PERFORCE DVCS

Now of course I am swapping to Perforce’s new Helix DVCS support, and I immediately came across the same problem. The new command p4 switch makes it so easy to create new branches and swap between them that I immediately sought to repeat the same hack as I did for Git. This turned out to be very simple indeed:

function parse_p4_branch () {

    P4INITROOT=`p4 set | grep P4INITROOT`

    if [ $? -eq 0 ]; then

        p4 switch 2> /dev/null | sed -e 's/\(.*\)/ (\1)/'

    fi

}

Note that I only enable the hack if P4INITROOT is set to avoid swamping non-DVCS servers with unnecessary commands. With this little function my command prompt now became

function set_prompt () {

    export PS1="\u@\h:\w\$(parse_p4_branch)\$ "

}

My command prompt now looks mostly identical to when I used Git:

sknop@marsupilami:~/dvcs/local (master)$

I can even combine both hacks together into the same prompt to enable both Git and P4 branch hints. You can see an example in the workshop here.

Why don’t you download and try Perforce Helix DVCS as part of the 2015.1 release now? I am writing a series of blog articles on the new DVCS features to highlight what great things you can do with it.

Happy Hacking!