1 | #!/usr/bin/env python |
2 | # |
3 | #===- clang-format-diff.py - ClangFormat Diff Reformatter ----*- python -*--===# |
4 | # |
5 | # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
6 | # See https://llvm.org/LICENSE.txt for license information. |
7 | # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
8 | # |
9 | #===------------------------------------------------------------------------===# |
10 | |
11 | r""" |
12 | ClangFormat Diff Reformatter |
13 | ============================ |
14 | |
15 | This script reads input from a unified diff and reformats all the changed |
16 | lines. This is useful to reformat all the lines touched by a specific patch. |
17 | Example usage for git/svn users: |
18 | |
19 | git diff -U0 --no-color HEAD^ | clang-format-diff.py -p1 -i |
20 | svn diff --diff-cmd=diff -x-U0 | clang-format-diff.py -i |
21 | |
22 | """ |
23 | from __future__ import absolute_import, division, print_function |
24 | |
25 | import argparse |
26 | import difflib |
27 | import re |
28 | import subprocess |
29 | import sys |
30 | |
31 | if sys.version_info.major >= 3: |
32 | from io import StringIO |
33 | else: |
34 | from io import BytesIO as StringIO |
35 | |
36 | |
37 | def main(): |
38 | parser = argparse.ArgumentParser(description= |
39 | 'Reformat changed lines in diff. Without -i ' |
40 | 'option just output the diff that would be ' |
41 | 'introduced.') |
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|ts|proto' |
51 | r'|protodevel|java)', |
52 | help='custom pattern selecting file paths to reformat ' |
53 | '(case insensitive, overridden by -regex)') |
54 | parser.add_argument('-sort-includes', action='store_true', default=False, |
55 | help='let clang-format sort include blocks') |
56 | parser.add_argument('-v', '--verbose', action='store_true', |
57 | help='be more verbose, ineffective without -i') |
58 | parser.add_argument('-style', |
59 | help='formatting style to apply (LLVM, Google, Chromium, ' |
60 | 'Mozilla, WebKit)') |
61 | parser.add_argument('-binary', default='clang-format', |
62 | help='location of binary to use for clang-format') |
63 | args = parser.parse_args() |
64 | |
65 | # Extract changed lines for each file. |
66 | filename = None |
67 | lines_by_file = {} |
68 | for line in sys.stdin: |
69 | match = re.search(r'^\+\+\+\ (.*?/){%s}(\S*)' % args.p, line) |
70 | if match: |
71 | filename = match.group(2) |
72 | if filename == None: |
73 | continue |
74 | |
75 | if args.regex is not None: |
76 | if not re.match('^%s$' % args.regex, filename): |
77 | continue |
78 | else: |
79 | if not re.match('^%s$' % args.iregex, filename, re.IGNORECASE): |
80 | continue |
81 | |
82 | match = re.search(r'^@@.*\+(\d+)(,(\d+))?', line) |
83 | if match: |
84 | start_line = int(match.group(1)) |
85 | line_count = 1 |
86 | if match.group(3): |
87 | line_count = int(match.group(3)) |
88 | if line_count == 0: |
89 | continue |
90 | end_line = start_line + line_count - 1 |
91 | lines_by_file.setdefault(filename, []).extend( |
92 | ['-lines', str(start_line) + ':' + str(end_line)]) |
93 | |
94 | # Reformat files containing changes in place. |
95 | for filename, lines in lines_by_file.items(): |
96 | if args.i and args.verbose: |
97 | print('Formatting {}'.format(filename)) |
98 | command = [args.binary, filename] |
99 | if args.i: |
100 | command.append('-i') |
101 | if args.sort_includes: |
102 | command.append('-sort-includes') |
103 | command.extend(lines) |
104 | if args.style: |
105 | command.extend(['-style', args.style]) |
106 | p = subprocess.Popen(command, |
107 | stdout=subprocess.PIPE, |
108 | stderr=None, |
109 | stdin=subprocess.PIPE, |
110 | universal_newlines=True) |
111 | stdout, stderr = p.communicate() |
112 | if p.returncode != 0: |
113 | sys.exit(p.returncode) |
114 | |
115 | if not args.i: |
116 | with open(filename) as f: |
117 | code = f.readlines() |
118 | formatted_code = StringIO(stdout).readlines() |
119 | diff = difflib.unified_diff(code, formatted_code, |
120 | filename, filename, |
121 | '(before formatting)', '(after formatting)') |
122 | diff_string = ''.join(diff) |
123 | if len(diff_string) > 0: |
124 | sys.stdout.write(diff_string) |
125 | |
126 | if __name__ == '__main__': |
127 | main() |
128 | |