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/svn users:
20 git diff -U0 --no-color HEAD^ | clang-format-diff.py -p1 -i
21 svn diff --diff-cmd=diff -x-U0 | clang-format-diff.py -i
24 from __future__ import absolute_import, division, print_function
32 if sys.version_info.major >= 3:
33 from io import StringIO
35 from io import BytesIO as StringIO
39 parser = argparse.ArgumentParser(description=
40 'Reformat changed lines in diff. Without -i '
41 'option just output the diff that would be '
43 parser.add_argument('-i', action='store_true', default=False,
44 help='apply edits to files instead of displaying a diff')
45 parser.add_argument('-p', metavar='NUM', default=0,
46 help='strip the smallest prefix containing P slashes')
47 parser.add_argument('-regex', metavar='PATTERN', default=None,
48 help='custom pattern selecting file paths to reformat '
49 '(case sensitive, overrides -iregex)')
50 parser.add_argument('-iregex', metavar='PATTERN', default=
51 r'.*\.(cpp|cc|c\+\+|cxx|c|cl|h|hpp|m|mm|inc|js|ts|proto'
53 help='custom pattern selecting file paths to reformat '
54 '(case insensitive, overridden by -regex)')
55 parser.add_argument('-sort-includes', action='store_true', default=False,
56 help='let clang-format sort include blocks')
57 parser.add_argument('-v', '--verbose', action='store_true',
58 help='be more verbose, ineffective without -i')
59 parser.add_argument('-style',
60 help='formatting style to apply (LLVM, Google, Chromium, '
62 parser.add_argument('-binary', default='clang-format',
63 help='location of binary to use for clang-format')
64 args = parser.parse_args()
66 # Extract changed lines for each file.
69 for line in sys.stdin:
70 match = re.search('^\+\+\+\ (.*?/){%s}(\S*)' % args.p, line)
72 filename = match.group(2)
76 if args.regex is not None:
77 if not re.match('^%s$' % args.regex, filename):
80 if not re.match('^%s$' % args.iregex, filename, re.IGNORECASE):
83 match = re.search('^@@.*\+(\d+)(,(\d+))?', line)
85 start_line = int(match.group(1))
88 line_count = int(match.group(3))
91 end_line = start_line + line_count - 1
92 lines_by_file.setdefault(filename, []).extend(
93 ['-lines', str(start_line) + ':' + str(end_line)])
95 # Reformat files containing changes in place.
96 for filename, lines in lines_by_file.items():
97 if args.i and args.verbose:
98 print('Formatting {}'.format(filename))
99 command = [args.binary, filename]
102 if args.sort_includes:
103 command.append('-sort-includes')
104 command.extend(lines)
106 command.extend(['-style', args.style])
107 p = subprocess.Popen(command,
108 stdout=subprocess.PIPE,
110 stdin=subprocess.PIPE,
111 universal_newlines=True)
112 stdout, stderr = p.communicate()
113 if p.returncode != 0:
114 sys.exit(p.returncode)
117 with open(filename) as f:
119 formatted_code = StringIO(stdout).readlines()
120 diff = difflib.unified_diff(code, formatted_code,
122 '(before formatting)', '(after formatting)')
123 diff_string = ''.join(diff)
124 if len(diff_string) > 0:
125 sys.stdout.write(diff_string)
127 if __name__ == '__main__':