May 11, 2009

Adding Perforce connection details to your Bash shell prompt

Traceability

Like other shells, Bash offers its users a wide range of customization options, one of which is the ability to change what the prompt says. Moving between different computers, you're bound to see a variety of different information presented to you.

Commonly you'll find the current path, day/time or the number of unread mail messages you've got. But since the prompt is just a user-supplied function, it could be any text that you like. The fancier you get with it, the more the prompt becomes a custom interface to the work you're doing.

A web search for "bash prompt" will give you lots of detailed information about how to customize it. Since many of us spend a lot of time working with source control tools, it can be useful to have the prompt tell us something about what we're doing. As an example of how to do this with Perforce, I've made a custom prompt that displays your current workspace and server using only client-side commands.

Here's what the end result looks like. I'm using P4CONFIG files to keep track of my connection settings, so as I move between directories, the workspace/server combination changes.

Perforce Bash prompt

And on to the code:

#!/bin/bashfunction get_p4set
 { 
    echo `p4 set$1| sed -e "s/$1=//" -e 's/ (.*)$//'2>&1`;return0;
 }

  function p4prompt
 { 
     localNOCOLOR="\[33[0m\]"localYELLOW="\e[0;33m"localGRAY="\[33[0;37m\]"localCYAN="\[33[0;36m\]"nP4CLIENT=`get_p4set P4CLIENT`
     nP4PORT=`get_p4set P4PORT`

     if[${#nP4CLIENT} -eq 0]thennP4CLIENT="__client_unset__"fiif[${#nP4PORT} -eq 0]then# "p4" actually defaults to using "perforce:1666", so the# P4PORT is never really "unset".nP4PORT="__server_unset__"fiPS1="$GRAY[$CYAN\${nP4CLIENT}$GRAY@$YELLOW\${nP4PORT}$GRAY] \\${PWD} $NOCOLOR->   "
 }

  PROMPT_COMMAND=p4prompt 

The first Perforce-specific part of this is the "get_p4set" function, which extracts a string from p4 set. It should work with normal HOST:PORT combinations as well as for ZeroConf names. The second piece is where the results are checked for their length. If they're zero, it means they're really just unset, and the P4 client will use default values (such as a P4PORT of "perforce:1666"), but since that's not really informative, dummy values are instead inserted.

To try this code out, just save it to a file, then source it into your current environment:

. /path/to/p4prompt.sh

If you want to make it more permanent, you can add it to your "~/.bashrc" file. I've also uploaded a copy to the Public Depot, here: p4prompt.sh Adding the connection details is really only the most simple thing you can do. There are lots of other interesting possibilities, such as displaying the number of jobs assigned to you:

p4 jobs -r -e 'ownedby=jgibson status=open' | wc -l