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 -i
33 # Change this to the full path if clang-format is not on the path.
34 binary = 'clang-format'
38 parser = argparse.ArgumentParser(description=
39 'Reformat changed lines in diff. Without -i '
40 'option just output the diff that would be '
42 parser.add_argument('-i', action='store_true', default=False,
43 help='apply edits to files instead of displaying a diff')
44 parser.add_argument('-p', metavar='NUM', default=0,
45 help='strip the smallest prefix containing P slashes')
46 parser.add_argument('-regex', metavar='PATTERN', default=None,
47 help='custom pattern selecting file paths to reformat '
48 '(case sensitive, overrides -iregex)')
49 parser.add_argument('-iregex', metavar='PATTERN', default=
50 r'.*\.(cpp|cc|c\+\+|cxx|c|cl|h|hpp|m|mm|inc|js)',
51 help='custom pattern selecting file paths to reformat '
52 '(case insensitive, overridden by -regex)')
56 'formatting style to apply (LLVM, Google, Chromium, Mozilla, WebKit)')
57 args = parser.parse_args()
59 # Extract changed lines for each file.
62 for line in sys.stdin:
63 match = re.search('^\+\+\+\ (.*?/){%s}(\S*)' % args.p, line)
65 filename = match.group(2)
69 if args.regex is not None:
70 if not re.match('^%s$' % args.regex, filename):
73 if not re.match('^%s$' % args.iregex, filename, re.IGNORECASE):
76 match = re.search('^@@.*\+(\d+)(,(\d+))?', line)
78 start_line = int(match.group(1))
81 line_count = int(match.group(3))
84 end_line = start_line + line_count - 1;
85 lines_by_file.setdefault(filename, []).extend(
86 ['-lines', str(start_line) + ':' + str(end_line)])
88 # Reformat files containing changes in place.
89 for filename, lines in lines_by_file.iteritems():
90 command = [binary, filename]
95 command.extend(['-style', args.style])
96 p = subprocess.Popen(command, stdout=subprocess.PIPE,
97 stderr=None, stdin=subprocess.PIPE)
98 stdout, stderr = p.communicate()
100 sys.exit(p.returncode);
103 with open(filename) as f:
105 formatted_code = StringIO.StringIO(stdout).readlines()
106 diff = difflib.unified_diff(code, formatted_code,
108 '(before formatting)', '(after formatting)')
109 diff_string = string.join(diff, '')
110 if len(diff_string) > 0:
111 sys.stdout.write(diff_string)
113 if __name__ == '__main__':