hgkw/kwexpander.py
author Christian Ebert <blacktrash@gmx.net>
Sun, 17 Dec 2006 13:38:28 +0100
branchupdatehook
changeset 26 bda0dec1aaf1
parent 25 aa3fbe81e9ad
child 29 bda83c13da42
permissions -rw-r--r--
Reparse cmdline to avoid expansion in uncommitted files

# $Hg$

from mercurial.i18n import _
from mercurial import util
import re

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

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

    # look for <Dollar>Hg<Dollar>
    kwtrigger = '%sHg$' % '$'

    def wwritekw(ui, repo, f, text):
        '''Writes text with kwupdates keywords to f in working directory.'''
        ui.note(_('expanding keywords in %s\n' % f))
    #   # backup file (?)
    #   absfile = repo.wjoin(f)
    #   util.copyfile(absfile, absfile+'.kwbak')
        repo.wfile(f, 'w').write(text)

    # only check files that have hgkwencode assigned as encode filter
    files = []
    # python2.4: files = set()
    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) 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(node)[1:3]
    user = util.shortuser(user)
    date = util.datestr(date=date, format=util.defaultdateformats[2])
                                               # %Y-%m-%d %H:%M

    # collect filenames that were changed by hg update
    kwupdates = []

    for f in files:

        text = repo.wfile(f).read()
        kwrepl = '%sHg: %s,v %s %s %s $' % ('$', f, cid, date, user)

        if update and text.find(kwtrigger) > -1:
            text = text.replace(kwtrigger, kwrepl)
            wwritekw(ui, repo, f, text)
            kwupdates.append(f)
        
        elif not update:
            re_kw = re.compile(r'[$]Hg(: %s,v [a-z0-9]{12} [^$]+? )?\$' % f)
            text, kwct = re_kw.subn(kwrepl, text)
            if kwct:
                wwritekw(ui, repo, f, text)

    if kwupdates:
        # cheat hg to believe that updated files were not modified
        repo.dirstate.update(kwupdates, 'n')

    return False