hgkw/kwexpander.py
author Christian Ebert <blacktrash@gmx.net>
Tue, 19 Dec 2006 15:41:45 +0100
branchextension
changeset 36 b3ace8cc5a33
parent 35 a730c9d4ec05
permissions -rw-r--r--
Change config opt "expand" to accept filename patterns Not nice yet; but passes tests together with pretxnkw. TODO: Find out what filelog.add() does exactly.

from mercurial.i18n import _
from mercurial import util
import os.path, re

def expandkw(ui, repo, rev, cid, candidates, update=False):
    '''Expands logged <Dollar>Hg<Dollar> in working directory.'''

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

    # update only needs string search for encoded keyword
    # as hgkwencode always runs before
    kwstr = '$Hg$'

    # pretxncommit looks for both encoded and decoded keywords
    re_kw = re.compile(r'\$Hg[^$]*?\$')

    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, at least when commiting (?)
        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
    files = candidates

    user, date = repo.changelog.read(rev)[1:3]
    user = util.shortuser(user)
    date = util.datestr(date=date, format=util.defaultdateformats[0])
                                               # %Y-%m-%d %H:%M:%S

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

    for f in files:

        text = repo.wfile(f).read()
        if not util.binary(text):

            # TODO for update:
            # walk back through file history onto last add/modify
            # like "hg log -l1 f"
            kw = '$Hg: %s,v %s %s %s $' % (
                    os.path.basename(f), cid, date, user)

            if update and text.find(kwstr) > -1:
                text = text.replace(kwstr, kw)
                wwritekw(ui, repo, f, text)
                kwupdates.append(f)
            
            elif not update:
                text, kwct = re_kw.subn(kw, 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')