hgkw/kwexpander.py
author Christian Ebert <blacktrash@gmx.net>
Thu, 14 Dec 2006 08:57:40 +0100
branchupdatehook
changeset 5 85d1f5bf7cfc
child 21 536c1797202d
permissions -rw-r--r--
updatehook branch: add kwexpander and updatekw modules WARNING: Do not use this branch for production! Update hook changes to working directory are detected by hg. The only /hook/ to escape hg's attention seems to be pretxcommit. And that probably only due to bug. Kept branch for archiving purposes.

# $Hg: kwexpander.py,v$

from mercurial.i18n import gettext as _
from mercurial.demandload import demandload
demandload(globals(), 'mercurial:util')
demandload(globals(), 'os.path re sys')

# name of keyword encode filter:
kwencodefilter = 'hgkwencode'

def expandkw(ui, repo, parent1, node, candidates):
    '''Important: returns False on success, True on failure.'''

    files = []
    for pat, cmd in repo.ui.configitems('encode'):
        if cmd.endswith(kwencodefilter):
            mf = util.matcher(repo.root, '', [pat], [], [])[1]
            for candidate in candidates:
                if mf(candidate):
                    files.append(candidate)

    if not files: # nothing to do
        return False

    user, date = repo.changelog.read(parent1)[1:3]
    user = util.shortuser(user)
    date = util.datestr(date=date, format=util.defaultdateformats[2])
                                                 # %Y-%m-%d %H:%M
    re_kwcheck = re.compile(r'[$]Hg: (.*?),v.*?\$')

    for fn in files:

        data = repo.wopener(fn, 'rb').read()
        bn = os.path.basename(fn)

        # check for keywords with incorrect basename
        # eg. if you forgot to update basename manually after "hg mv"
        failures = [m for m in map(str, re_kwcheck.findall(data)) if m != bn]
        if failures:
            failures = ['%sHg: %s,v$' % ('$', nobn) for nobn in failures]
            ui.warn(_('%d incorrect basenames in file %s:\n'
                '%s\nplease correct to %sHg: %s,v$\n'
                % (len(failures), fn, ', '.join(failures), '$', bn)))
            return True

        # substitute <Dollar>(Hg|Id): <basename>,v.*<Dollar>
        re_kw = re.compile(r'([$]Hg: %s,v).*?\$' % bn)
        data, kwct = re_kw.subn(r'\1 %s %s %s $' % (node, date, user), data)

        if kwct:
            # backup file and write with expanded keyword
            ui.note(_('expanding keywords in %s\n' % fn))
            util.copyfile(fn, fn+'~')
            repo.wopener(fn, 'wb').write(data)

    return False