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

Alexander Kornienko alexfh at google.com
Tue Oct 8 01:34:13 PDT 2013


  Changed the default behavior to just display diff. Changed the option to -i, which asks the script to actually apply the changes.

Hi djasper,

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

CHANGE SINCE LAST DIFF
  http://llvm-reviews.chandlerc.com/D1840?vs=4680&id=4731#toc

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
@@ -17,13 +17,16 @@
 lines. This is useful to reformat all the lines touched by a specific patch.
 Example usage for git users:
 
-  git diff -U0 HEAD^ | clang-format-diff.py -p1
+  git diff -U0 HEAD^ | clang-format-diff.py -p1 -i
 
 """
 
 import argparse
+import difflib
 import re
+import string
 import subprocess
+import StringIO
 import sys
 
 
@@ -33,7 +36,11 @@
 
 def main():
   parser = argparse.ArgumentParser(description=
-                                   'Reformat changed lines in diff.')
+                                   'Reformat changed lines in diff. Without -i '
+                                   'option just output the diff that would be'
+                                   'introduced.')
+  parser.add_argument('-i', action='store_true', default=False,
+                      help='apply edits to files instead of displaying a diff')
   parser.add_argument('-p', default=0,
                       help='strip the smallest prefix containing P slashes')
   parser.add_argument(
@@ -71,7 +78,9 @@
 
   # Reformat files containing changes in place.
   for filename, lines in lines_by_file.iteritems():
-    command = [binary, '-i', filename]
+    command = [binary, filename]
+    if args.i:
+      command.append('-i')
     command.extend(lines)
     if args.style:
       command.extend(['-style', args.style])
@@ -83,6 +92,16 @@
       print stderr
       return
 
+    if not args.i:
+      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.2.patch
Type: text/x-patch
Size: 2076 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/cfe-commits/attachments/20131008/9569b3df/attachment.bin>


More information about the cfe-commits mailing list