Reading Mercurial History into Python

June 15, 2010

I wanted to read my mercurial repository history into python, so that I could display it in a Django web front end. Here's the process by which we can read in the history and put it into a tuple of (revision number, changeset, user, date, comment)

import subprocess
import datetime

lProcess = subprocess.Popen(["hg","history"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
lOutput = lProcess.stdout.readlines()
lHistory = []
for row in lOutput:
  if row.startswith('changeset:'):
    lChangeSet = row[10:].strip()
    lRevision = lChangeSet[:lChangeSet.find(':')].strip()
  elif row.startswith('user:'):
    lUser = row[10:].strip()
  elif row.startswith('date:'):
    lDateText = row[10:].strip()[:-5].strip()
    lDate = datetime.datetime.strptime(lDateText, "%a %b %d %H:%M:%S %Y")
  elif row.startswith('summary:'):
    lSummary = row[10:].strip()
  elif row =='\n':
    lHistory.append((lRevision, lChangeSet, lUser, lDate, lSummary))

print lHistory