From 917759108c232f4ca72493325d004859cdb55855 Mon Sep 17 00:00:00 2001 From: Colin Walters Date: Mon, 9 Aug 2010 11:05:15 -0400 Subject: [git-un-diff-whitespace] Don't write out unmodified files --- bin/git-un-diff-whitespace | 47 ++++++++++++++++++++++++++++++++++------------ 1 file changed, 35 insertions(+), 12 deletions(-) diff --git a/bin/git-un-diff-whitespace b/bin/git-un-diff-whitespace index 4e71f04..5e0549d 100755 --- a/bin/git-un-diff-whitespace +++ b/bin/git-un-diff-whitespace @@ -8,15 +8,25 @@ # Copyright 2010 Colin Walters # Licensed under the new-BSD license (http://www.opensource.org/licenses/bsd-license.php) -import os,sys,re,subprocess +import os,sys,re,subprocess,hashlib hunk_re = re.compile(r'^@@ -\d+,\d+ \+(\d+),(\d+) @@') ws_re = re.compile(r'^(.*?)[ \t]+$') -file_re = re.compile(r'^\-\-\- b/(.+)') +file_re = re.compile(r'^\+\+\+ b/(.+)') + +def hashfile(path): + h = hashlib.sha1() + f = open(path) + b = f.read(8192) + while b != '': + h.update(b) + b = f.read(8192) + f.close() + return h.hexdigest() def strip_whitespace_regions(filename, hunks): if len(hunks) == 0: - return + return False filename_t = filename + '.tmp' tmpf = open(filename_t, 'w') f = open(filename) @@ -38,8 +48,15 @@ def strip_whitespace_regions(filename, hunks): i = i+1 tmpf.close() f.close() - os.rename(filename_t, filename) - print "wrote " + filename + old = hashfile(filename) + new = hashfile(filename_t) + if old != new: + os.rename(filename_t, filename) + print "wrote " + filename + return True + else: + os.unlink(filename_t) + return False def main(): toplevel = subprocess.Popen(['git', 'rev-parse', '--show-toplevel'], stdout=subprocess.PIPE).communicate()[0] @@ -52,10 +69,10 @@ def main(): stderr=sys.stderr) diff_lines = commit_proc.stdout.readlines() commit_proc.wait() - subprocess.check_call(['git', 'reset', 'HEAD^'], stdout=sys.stdout, stderr=sys.stderr) curfile = None hunks = [] files = [] + modified_files = [] for line in diff_lines: if curfile is not None: match = hunk_re.match(line) @@ -65,16 +82,22 @@ def main(): match = file_re.match(line) if match: filename = match.group(1) - strip_whitespace_regions(curfile, hunks) + modified = strip_whitespace_regions(curfile, hunks) curfile = filename files.append(filename) + if modified: + modified_files.append(filename) hunks = [] if curfile: - strip_whitespace_regions(curfile, hunks) - add_args = ['git', 'add'] - add_args.extend(files) - subprocess.check_call(add_args, stdout=sys.stdout, stderr=sys.stderr) - subprocess.check_call(['git', 'commit', '-c', 'ORIG_HEAD'], stdout=sys.stdout, stderr=sys.stderr) + modified = strip_whitespace_regions(curfile, hunks) + if modified: + modified_files.append(curfile) + if modified_files: + add_args = ['git', 'add'] + add_args.extend(modified_files) + subprocess.check_call(add_args, stdout=sys.stdout, stderr=sys.stderr) + else: + print "No trailing whitespace found in HEAD" if __name__ == '__main__': main() -- cgit