# $Hg: pretxnkw.py,v$
from mercurial.i18n import gettext as _
from mercurial.demandload import demandload
demandload(globals(), 'hgkw:kwutil mercurial:util os.path 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 filename in files:
data = repo.wfile(filename).read()
bn = os.path.basename(filename)
# 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), filename, ', '.join(failures), '$', bn)))
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' % filename))
absname = os.path.join(repo.root, filename)
util.copyfile(absname, absname+'~')
repo.wfile(filename, 'w').write(data)
return False