Add pretxnkw module for commits decodefilter
authorChristian Ebert <blacktrash@gmx.net>
Thu, 14 Dec 2006 10:18:41 +0100
branchdecodefilter
changeset 6 3ee39807daa5
parent 4 7e618d820490
child 8 180d8484503a
Add pretxnkw module for commits
hgkw/pretxnkw.py
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hgkw/pretxnkw.py	Thu Dec 14 10:18:41 2006 +0100
@@ -0,0 +1,61 @@
+# $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()[1:3]
+    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.wopener(filename, 'rb').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))
+            util.copyfile(filename, filename+'~')
+            repo.wopener(filename, 'wb').write(data)
+
+    return False