Tom's Blog

From tech to non-tech

Mercurial: Put the Branch Name in Your Face

| Comments

I happened to push some code to the wrong Mercurial branch (Yikes!) today. Nothing too bad but one of my colleagues pointed out to me that if I had been using a GUI then it is way more difficult. I’m a commandline line guy and I like it this way!

Luckily I knew what to do, there is a feature that I have enabled for git that just does that, it shows the branch name in your face and I set out to do the same for Mercurial. Let me share the solution and you might also like it. I’ve also made a shot how it looks like for me.

To achieve this you first need to install the hg-prompt Mercurial plugin. This little plugin gives you access to meta info about the repository and easy to use from shell scripts.

Secondly you need to re-configure your PS1 environment variable. I created a function that would add the extra information and then I use it in the PS1 definition.

# the bash function
function hg_prompt_info {
  hg prompt --angle-brackets "<%{$fg[green]%}@%{$fg[yellow]%}\
%{$fg[magenta]%}<branch>%{$reset_color%}> " 2>/dev/null

# And the usage of the function. I don't set PS1 directly because
# I'm in a theme of oh-my-zsh but for vanilla bash it is similar
PROMPT='%{$fg[$NCOLOR]%}%n%{$fg[green]%}@%m%{$reset_color%} %~ \
%{$fg[red]%}%(!.#.»)%{$reset_color%} '
PROMPT2='%{$fg[red]%}\ %{$reset_color%}'

So now whenever you are in a folder with a Mercurial repository the shell will show you the branch. Hopefully this helps you to commit to the correct branch!