hgkw/pretxnkw.py
author Christian Ebert <blacktrash@gmx.net>
Thu, 21 Dec 2006 16:00:45 +0100
branchmodular
changeset 46 67e9fb23a32b
parent 45 5acf520f2115
permissions -rw-r--r--
Make keyword.py depend on resurrected kwutil.py This makes pretxnkw perhaps a bit slower, but is more readable.

from hgkw import kwutil
from mercurial.i18n import _
from mercurial import cmdutil, commands, util
import re, sys

def pretxnkw(ui, repo, hooktype, **args):
    '''Collects candidates for keyword expansion on commit
    and expands keywords in working dir.
    NOTE: for use in combination with hgext.keyword!'''

    if hooktype != 'pretxncommit':
        # bail out with error
        return True

    # reparse args, opts again as pretxncommit hook is silent about them
    cmd, sysargs, globalopts, cmdopts = commands.parse(ui, sys.argv[1:])[1:]
    # exclude tag and import
    if repr(cmd).split()[1] in ('tag', 'import_'):
        return False
    files, match, anypats = cmdutil.matchpats(repo, sysargs, cmdopts)

    # validity checks should have been done already
    modified, added = repo.status(files=files, match=match)[:2]
    candidates = [f for f in modified + added if not f.startswith('.hg')]

    if not candidates:
        return False

    # only check files that have hgkwencode assigned as encode filter
    files = []
    # python2.4: files = set()
    for pat, opt in repo.ui.configitems('keyword'):
        if opt == 'expand':
            mf = util.matcher(repo.root, '', [pat], [], [])[1]
            for candidate in candidates:
                if mf(candidate) and candidate not in files:
                    files.append(candidate)
                # python2.4:
                # if mf(candidate): files.add(candidate)

    if not files: # nothing to do
        return False

    user, date = repo.changelog.read(repo.changelog.tip())[1:3]
    re_kw = re.compile(r'\$(%s)(: [^$]+? )?\$' % kwutil.hgkeywords)

    for f in files:
        data = repo.wfile(f).read()
        if not util.binary(data):

            def kwexpand(matchobj):
                return kwutil.kwexpand(matchobj,
                        repo, args['node'][:12], f, date, user)

            data, kwct = re_kw.subn(kwexpand, data)
            if kwct:
                ui.note(_('expanding keywords in %s\n' % f))
                # backup file?
                repo.wfile(f, 'w').write(data)