[PATCH] Added option to clang-format-diff.py to just output diff without changing files.

Alexander Kornienko alexfh at google.com
Fri Oct 4 11:49:25 PDT 2013


Hi djasper,

now it's possible to use
svn diff|clang-format-diff.py -n|patch -p0
instead of
svn diff|clang-format-diff.py
;)

http://llvm-reviews.chandlerc.com/D1840

Files:
  tools/clang-format/clang-format-diff.py

Index: tools/clang-format/clang-format-diff.py
===================================================================
--- tools/clang-format/clang-format-diff.py
+++ tools/clang-format/clang-format-diff.py
@@ -22,8 +22,11 @@
 """
 
 import argparse
+import difflib
 import re
+import string
 import subprocess
+import StringIO
 import sys
 
 
@@ -34,6 +37,9 @@
 def main():
   parser = argparse.ArgumentParser(description=
                                    'Reformat changed lines in diff.')
+  parser.add_argument('-n', action='store_true', default=False,
+                      help='don\'t change files, instead display what diffs'
+                           'clang-format would introduce')
   parser.add_argument('-p', default=0,
                       help='strip the smallest prefix containing P slashes')
   parser.add_argument(
@@ -71,7 +77,9 @@
 
   # Reformat files containing changes in place.
   for filename, lines in lines_by_file.iteritems():
-    command = [binary, '-i', filename]
+    command = [binary, filename]
+    if not args.n:
+      command.append('-i')
     command.extend(lines)
     if args.style:
       command.extend(['-style', args.style])
@@ -83,6 +91,16 @@
       print stderr
       return
 
+    if args.n:
+      with open(filename) as f:
+        code = f.readlines()
+      formatted_code = StringIO.StringIO(stdout).readlines()
+      diff = difflib.unified_diff(code, formatted_code,
+                                  filename, filename,
+                                  '(before formatting)', '(after formatting)')
+      diff_string = string.join(diff, '')
+      if len(diff_string) > 0:
+        print diff_string
 
 if __name__ == '__main__':
   main()
-------------- next part --------------
A non-text attachment was scrubbed...
Name: D1840.1.patch
Type: text/x-patch
Size: 1703 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/cfe-commits/attachments/20131004/917dea0c/attachment.bin>


More information about the cfe-commits mailing list