HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

My python hook for mercurial

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
mercurialforpythonhook

Problem

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

Solution

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.

Code Snippets

for rev in xrange(repo[node].rev(), len(repo)):
        ctx = context.changectx(repo, rev)
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)):
    ...

Context

StackExchange Code Review Q#4494, answer score: 5

Revisions (0)

No revisions yet.