hgkw/kwexpander.py
author Christian Ebert <blacktrash@gmx.net>
Thu, 14 Dec 2006 10:33:35 +0100
branchupdatehook
changeset 7 e5f131217f87
parent 5 85d1f5bf7cfc
child 21 536c1797202d
permissions -rw-r--r--
Add pretxnkw module for updatehook branch

# $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