hgkw/pretxnkw.py
author Christian Ebert <blacktrash@gmx.net>
Thu, 14 Dec 2006 16:27:30 +0100
branchdecodefilter
changeset 13 d6c0f391a662
parent 11 56a61a5c696d
permissions -rw-r--r--
Short "f" for "filename" iteration variable

# $Hg: hgkw/pretxnkw.py,v$

from mercurial.i18n import gettext as _
from mercurial.demandload import demandload
demandload(globals(), 'hgkw:kwutil mercurial:util re')

kwencodefilter = 'hgkwencode'

def pretxnkw(ui=None, repo=None, hooktype='', **args):
    '''Important: returns False on success, True on failure.'''

    node = args['node'][0:12]

    if not ui or not repo or not node or hooktype != 'pretxncommit':
        # bail out with error
        return True

    modified, added = repo.status()[:2]
    candidates = modified + added

    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

    re_kw = kwutil.rekw()
    kword = kwutil.mkkw(repo, tip=True, node=node)

    re_kwcheck = re.compile(r'[$]Hg: (.*?),v.*?\$')

    for f in files:

        data = repo.wfile(f).read()

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

        # substitute <Dollar>(Hg|Id): <basename>,v.*<Dollar>
        data, kwct = re_kw.subn(kword, data)

        if kwct:
            # backup file and write with expanded keyword
            ui.note(_('expanding keywords in %s\n' % f))
            absname = repo.wjoin(f)
            util.copyfile(absname, absname+'~')
            repo.wfile(f, 'w').write(data)

    return False