[PATCH] D48098: clang-format-diff: Switch to python3 by default, support python 2.7

Marco Falke via Phabricator via cfe-commits cfe-commits at lists.llvm.org
Tue Jun 12 14:40:47 PDT 2018


MarcoFalke created this revision.

Repository:
  rC Clang

https://reviews.llvm.org/D48098

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
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 #
 #===- clang-format-diff.py - ClangFormat Diff Reformatter ----*- python -*--===#
 #
@@ -24,10 +24,9 @@
 
 import argparse
 import difflib
+import io
 import re
-import string
 import subprocess
-import StringIO
 import sys
 
 
@@ -84,14 +83,14 @@
         line_count = int(match.group(3))
       if line_count == 0:
         continue
-      end_line = start_line + line_count - 1;
+      end_line = start_line + line_count - 1
       lines_by_file.setdefault(filename, []).extend(
           ['-lines', str(start_line) + ':' + str(end_line)])
 
   # Reformat files containing changes in place.
-  for filename, lines in lines_by_file.iteritems():
+  for filename, lines in lines_by_file.items():
     if args.i and args.verbose:
-      print 'Formatting', filename
+      print('Formatting {}'.format(filename))
     command = [args.binary, filename]
     if args.i:
       command.append('-i')
@@ -100,20 +99,23 @@
     command.extend(lines)
     if args.style:
       command.extend(['-style', args.style])
-    p = subprocess.Popen(command, stdout=subprocess.PIPE,
-                         stderr=None, stdin=subprocess.PIPE)
+    p = subprocess.Popen(command,
+                         stdout=subprocess.PIPE,
+                         stderr=None,
+                         stdin=subprocess.PIPE,
+                         universal_newlines=True)
     stdout, stderr = p.communicate()
     if p.returncode != 0:
-      sys.exit(p.returncode);
+      sys.exit(p.returncode)
 
     if not args.i:
-      with open(filename) as f:
+      with open(filename, encoding="utf8") as f:
         code = f.readlines()
-      formatted_code = StringIO.StringIO(stdout).readlines()
+      formatted_code = io.StringIO(stdout).readlines()
       diff = difflib.unified_diff(code, formatted_code,
                                   filename, filename,
                                   '(before formatting)', '(after formatting)')
-      diff_string = string.join(diff, '')
+      diff_string = ''.join(diff)
       if len(diff_string) > 0:
         sys.stdout.write(diff_string)
 


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D48098.151036.patch
Type: text/x-patch
Size: 2346 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/cfe-commits/attachments/20180612/ec29ef30/attachment.bin>


More information about the cfe-commits mailing list