# My python hook for mercurial

In our hg workflow we use default as testing branch and stable as the one that contains stable code. All changes are made in feature-branches that are started from latest stable. This hook checks if there is a "direct" commit to default or stable (they are denied, only merges may change contents of default and stable) or that new feature branch has been started from default (which is denied by conventions too).

Any proposal to make it more "pythonic" (or just better)?

from mercurial import context

def check(ui, repo, hooktype, node=None, source=None, **kwargs):
for rev in xrange(repo[node].rev(), len(repo)):
ctx = context.changectx(repo, rev)
parents = ctx.parents()

if len(parents) == 1:
if ctx.branch() in ['default', 'stable']:
ui.warn('!!! You cannot commit directly to %s at %s !!!' % (ctx.branch(), ctx.hex()))
return True

if parents[0].branch() == 'default':
ui.warn('!!! You cannot start your private branch from default at %s !!!' % (ctx.hex()))
return True

return False

• The correct word is pythonic not pythonish. Aug 30 '11 at 12:06
• @Winston Ewert: fixed ;-) Aug 30 '11 at 12:08

    for rev in xrange(repo[node].rev(), len(repo)):
ctx = context.changectx(repo, rev)


In Python, I generally try to avoid iterating using xrange. I prefer to iterate over what I'm interested in.

def revisions(repo, start, end):
for revision_number in xrange(start, end):
yield context.changectx(repo, revision_number)

for rev in revisions(repo, repo[node].rev(), len(repo)):
...


Although I'm not sure its worthwhile in this case.

The only other issue is your use of abbreviations like repo and rev. They aren't that bad because its pretty clear from the context what they stand for. But I'd write them fully out.

• I think you mean for revision_number in xrange(start, end): in that second snippet. Aug 31 '11 at 1:15