hgkw/pretxnkw.py
author Christian Ebert <blacktrash@gmx.net>
Wed, 20 Dec 2006 17:41:19 +0100
branchextension
changeset 42 ba000e29ecf3
parent 41 e1c539e1282b
child 44 dc6e7d0e607f
permissions -rw-r--r--
Implement near CVS compability with more than one keyword Keywords are set as local vars in kwexpand() and then eval'd. TODO: (sticky) tag?

from mercurial.i18n import _
from mercurial import cmdutil, commands, util
import os.path, re, sys

hgkeywords = 'Id|Header|Author|Date|Revision|RCSFile|Source'

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
    sysargs, globalopts, cmdopts = commands.parse(ui, sys.argv[1:])[2:]
    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 = modified + added

    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]
    strdate = util.datestr(date=date)
    shortuser = util.shortuser(user)
    shortdate = util.datestr(date=date, format=util.defaultdateformats[0])
                                               # %Y-%m-%d %H:%M:%S

    re_kw = re.compile(r'\$(%s)(: [^$]+? )?\$' % hgkeywords)

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

            def kwexpand(matchobj):
                RCSFile = os.path.basename(f)+',v'
                Source = os.path.join(repo.root, f)+',v'
                Revision = args['node'][:12]
                Date = strdate
                Author = user
                revdateauth = '%s %s %s' % (Revision, shortdate, shortuser)
                Header = '%s %s' % (Source, revdateauth)
                Id = '%s %s' % (RCSFile, revdateauth)
                return '$%s: %s $' % (
                        matchobj.group(1), eval(matchobj.group(1)))

            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)