A Mercurial PowerShell Prompt

Since switching to Mercurial I often use the “hg summary” command.

hg summary [--remote] aliases: sum summarize working directory state This generates a brief summary of the working directory state, including parents, branch, commit status, and available updates. With the –remote option, this will check the default paths for incoming and outgoing changes. This can be time-consuming.

When you execute this command in a directory that is under source control you will see something like this:

parent: 35:008279cba4b4 tip This is the commit message of the last checkin branch: default commit: 1 modified, 1 unknown update: (current)


I am usually most interested in which branch I am currently working in and what is the current status of my working directory.  Since I use PowerShell as my command line I decided to overwrite the default PowerShell prompt (PS >) with some of the data from the “hg summary” command.

To do this I added the following code to my PowerShell profile:

if (test-path function:\prompt)       { 
  $oldPrompt = ls function: | ? {$_.Name -eq "prompt"}
  remove-item -force function:\prompt 
  } 
  
function prompt() {
  $host.ui.rawui.WindowTitle = (get-location).Path
  
  $summary = hg summary 2>&1
  if($summary.Exception -eq $null) {
    $regex = "(?si)(parent:(?<parent>.*?)(\n|\r)+.*?)(branch:(?<branch>.*)\s)(commit:(?<commit>.*)\s)(update:(?<update>.*))";
    $summary = [System.String]::Join([System.Environment]::NewLine,$summary)
    $res = $summary -match $regex
    $format = "hg b:{0} c:{1}" -f $matches["branch"].Trim(), $matches["commit"].Trim()
    write-host ($format) -NoNewLine 
    write-host (">") -NoNewLine 
  }
  else {
    & $oldPrompt
  }
 
  return " "
 
}

With this in place when you are in a directory that is not controlled by Mercurial you will see the normal prompt.  But once you enter a source controlled directory the prompt will look like:

image

This quickly shows me that I am in the default branch and I have 1 file modified and 1 unknown file in my directory.

After committing it will show:

image

Which shows that the current working directory is in a clean state.

This entry was posted in Mercurial, PowerShell. Bookmark the permalink.

Leave a Reply