Friday, September 23, 2011

Powershell and Hg Magic

I moved a bunch of files that were in an hg repo and did an hg addremove -s 100.  They all should have been recorded as renames, but hg summary showed me that 1 of them wasn't.  But which one?

Powershell to the rescue!
$s = (hg st -a -C) -join "`n"
[regex]::matches($s, '^A.*$\n^A.*', "Multiline")
Lets break this down:
  • hg st -a -C: lists all added files including what file they were copied from.  Hg st considers a rename to be a copy and a remove.  For each renamed file this will output two lines:
    A <file\path\here>
  • $s = (...) -join "`n": takes the array of strings resulting from the hg st command and joins it into one big string in the $s variable.
  • [regex]::matches($s, '...', 'Multiline'): Runs a multiline regex on the string
  • '^A.*$\n^A.*': Regex matches a line that starts with an A, followed by anything to the end of the line, followed by a line break, followed by another line that starts with A, followed by anything.  In otherwords, this will match if two lines of output both start with A.  In this case, that means the first line is the line that was not recorded as a rename!