3 #===- clang-format-diff.py - ClangFormat Diff Reformatter ----*- python -*--===#
5 # The LLVM Compiler Infrastructure
7 # This file is distributed under the University of Illinois Open Source
8 # License. See LICENSE.TXT for details.
10 #===------------------------------------------------------------------------===#
13 ClangFormat Diff Reformatter
14 ============================
16 This script reads input from a unified diff and reformats all the changed
17 lines. This is useful to reformat all the lines touched by a specific patch.
18 Example usage for git users:
20 git diff -U0 HEAD^ | clang-format-diff.py -p1
30 # Change this to the full path if clang-format is not on the path.
31 binary = 'clang-format'
34 def getOffsetLength(filename, line_number, line_count):
36 Calculates the field offset and length based on line number and count.
40 with open(filename, 'r') as f:
53 def formatRange(r, style):
55 Formats range 'r' according to style 'style'.
57 filename, line_number, line_count = r
58 # FIXME: Add other types containing C++/ObjC code.
59 if not (filename.endswith(".cpp") or filename.endswith(".cc") or
60 filename.endswith(".h")):
63 offset, length = getOffsetLength(filename, line_number, line_count)
64 with open(filename, 'r') as f:
66 command = [binary, '-offset', str(offset), '-length', str(length)]
68 command.extend(['-style', style])
69 p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
70 stdin=subprocess.PIPE)
71 stdout, stderr = p.communicate(input=text)
76 print 'Segfault occurred while formatting', filename
77 print 'Please report a bug on llvm.org/bugs.'
79 with open(filename, 'w') as f:
84 parser = argparse.ArgumentParser(description=
85 'Reformat changed lines in diff')
86 parser.add_argument('-p', default=1,
87 help='strip the smallest prefix containing P slashes')
88 parser.add_argument('-style',
89 help='formatting style to apply (LLVM, Google, Chromium)')
90 args = parser.parse_args()
95 for line in sys.stdin:
96 match = re.search('^\+\+\+\ (.*?/){%s}(\S*)' % args.p, line)
98 filename = match.group(2)
102 match = re.search('^@@.*\+(\d+)(,(\d+))?', line)
106 line_count = int(match.group(3))
107 ranges.append((filename, int(match.group(1)), line_count))
109 # Reverse the ranges so that the reformatting does not influence file offsets.
110 for r in reversed(ranges):
111 # Do the actual formatting.
112 formatRange(r, args.style)
115 if __name__ == '__main__':