Commits

markant committed d9097e6

Fixed the PEP8 hook. Somehow missed the bad OR. Added a hook for optimizing images on commits.

  • Participants
  • Parent commits f946c29

Comments (0)

Files changed (2)

+#!/usr/bin/python
+"""
+A mercurial hook that runs prior to commit.  It requires the
+command line program optipng which will optimize all
+PNG, BMP, GIF, PNM or TIFF images.
+"""
+from subprocess import Popen, PIPE, STDOUT
+import re
+import sys
+
+
+VALID_FILE_TYPES = ('.png', '.bmp', '.gif', '.pnm', 'tiff')
+OPTIMIZED_RE = re.compile("([0-9\.]+)%") # 13.85% decrease
+
+
+def get_command_output(cmd):
+    """
+    Captures and returns the output of cmd passed in
+    """
+    return Popen(cmd.split(), stdout=PIPE, stderr=STDOUT).communicate()[0]
+
+
+def hook(ui, repo, **kwargs):
+    """
+    Optimizes any PNG, BMP, GIF, PNM or TIFF files prior to commit
+    """
+    cmd = "optipng %s"
+    changes = repo.status()
+    modified = changes[0]
+    added = changes[1]
+    files = added + modified
+    for imgfile in files:
+        if imgfile[-4:].lower() in VALID_FILE_TYPES:
+            output = get_command_output(cmd % (imgfile, ))
+            match = OPTIMIZED_RE.search(output)
+            if match:
+                ui.status("\nImage %s optimized, savings of %s\n" % (imgfile,
+                    match.group()))
+    return 0
     files = added + modified
     errors = []
     for pyfile in files:
-        if pyfile[-2:] != 'py' or 'tests' in pyfile:
+        if pyfile[-2:] != 'py' or 'tests' in pyfile or 'external' in pyfile:
             continue
         output = get_command_output("/usr/local/bin/pep8 %s" % (pyfile, ))
         if output:
             for error in output.split("\n")[:-1]:
                 errors.append(error)
     if errors:
-        sys.stderr.write("The following files are not PEP8 compliant:\n")
-        sys.stderr.write("\n".join(errors))
-        sys.stderr.write("\n")
+        ui.warn("\nThe following files are not PEP8 compliant:\n")
+        ui.warn("\n".join(errors))
+        ui.warn("\n\n")
         return -1
     return 0