Created
July 6, 2012 14:27
-
-
Save mcls/3060463 to your computer and use it in GitHub Desktop.
Regex blacklist for git diff in git pre-commit hook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from subprocess import * | |
import sys | |
import re | |
# Add Regex to blacklist here | |
blacklist = [ | |
"\+[ ]+NSLog.+" # Prevent NSLog's from being added | |
] | |
def matches_blacklisted_regex(text): | |
return len(re.findall("|".join(blacklist), text)) > 0 | |
def compile_pattern(): | |
# Always check for 'diff' and '@@' so we know which file and lines contain | |
# the blacklisted code | |
regex = r"^diff.*|^@@.*|" + "|".join(blacklist) | |
return re.compile(regex, re.MULTILINE) | |
# Print the diff displaying only the lines containing illegal statements | |
def print_filtered_diff(diff_output): | |
pattern = compile_pattern() | |
res = pattern.findall( str(diff_output) ) | |
for r in res: | |
# Insert extra newline for clarity | |
if r.startswith("diff"): | |
print "" | |
print r | |
def check_blacklist(): | |
# --no-color or else regex won't work properly | |
diff_output = Popen(["git", "diff","--no-color"], stdout=PIPE).communicate()[0] | |
if ( matches_blacklisted_regex(diff_output) ): | |
print "" | |
print "WARNING: git diff contains blacklisted code" | |
print "-------------------------------------------" | |
print_filtered_diff(diff_output) | |
print "" | |
sys.exit(1) | |
check_blacklist() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment