|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# |
| 3 | +#===- clang-format-diff.py - ClangFormat Diff Reformatter ----*- python -*--===# |
| 4 | +# |
| 5 | +# The LLVM Compiler Infrastructure |
| 6 | +# |
| 7 | +# This file is distributed under the University of Illinois Open Source |
| 8 | +# License. See LICENSE.TXT for details. |
| 9 | +# |
| 10 | +#===------------------------------------------------------------------------===# |
| 11 | + |
| 12 | +# |
| 13 | +# Slightly modified to handle the definition of functions, which do not |
| 14 | +# require a space before the parenthesis |
| 15 | +# |
| 16 | + |
| 17 | +r""" |
| 18 | +ClangFormat Diff Reformatter |
| 19 | +============================ |
| 20 | +
|
| 21 | +This script reads input from a unified diff and reformats all the changed |
| 22 | +lines. This is useful to reformat all the lines touched by a specific patch. |
| 23 | +Example usage for git/svn users: |
| 24 | +
|
| 25 | + git diff -U0 --no-color HEAD^ | clang-format-diff.py -p1 -i |
| 26 | + svn diff --diff-cmd=diff -x-U0 | clang-format-diff.py -i |
| 27 | +
|
| 28 | +""" |
| 29 | + |
| 30 | +import argparse |
| 31 | +import difflib |
| 32 | +import re |
| 33 | +import subprocess |
| 34 | +import sys |
| 35 | +import tempfile |
| 36 | +import os |
| 37 | +from functools import reduce |
| 38 | +try: |
| 39 | + from StringIO import StringIO |
| 40 | +except ImportError: |
| 41 | + from io import StringIO |
| 42 | + |
| 43 | + |
| 44 | +def main(): |
| 45 | + parser = argparse.ArgumentParser(description= |
| 46 | + 'Reformat changed lines in diff. Without -i ' |
| 47 | + 'option just output the diff that would be ' |
| 48 | + 'introduced. Use something like: ' |
| 49 | + 'git diff master..my-branch | ./sys/clang-format-diff.py -p1 -i') |
| 50 | + parser.add_argument('-i', action='store_true', default=False, |
| 51 | + help='apply edits to files instead of displaying a diff') |
| 52 | + parser.add_argument('-p', metavar='NUM', default=0, |
| 53 | + help='strip the smallest prefix containing P slashes') |
| 54 | + parser.add_argument('-regex', metavar='PATTERN', default=None, |
| 55 | + help='custom pattern selecting file paths to reformat ' |
| 56 | + '(case sensitive, overrides -iregex)') |
| 57 | + parser.add_argument('-iregex', metavar='PATTERN', default= |
| 58 | + r'.*\.(cpp|cc|c\+\+|cxx|c|cl|h|hpp|m|mm|inc|js|ts|proto' |
| 59 | + r'|protodevel|java)', |
| 60 | + help='custom pattern selecting file paths to reformat ' |
| 61 | + '(case insensitive, overridden by -regex)') |
| 62 | + parser.add_argument('-sort-includes', action='store_true', default=False, |
| 63 | + help='let clang-format sort include blocks') |
| 64 | + parser.add_argument('-v', '--verbose', action='store_true', |
| 65 | + help='be more verbose, ineffective without -i') |
| 66 | + parser.add_argument('-style', |
| 67 | + help='formatting style to apply (LLVM, Google, Chromium, ' |
| 68 | + 'Mozilla, WebKit)') |
| 69 | + parser.add_argument('-binary', default='clang-format', |
| 70 | + help='location of binary to use for clang-format') |
| 71 | + args = parser.parse_args() |
| 72 | + |
| 73 | + # Extract changed lines for each file. |
| 74 | + filename = None |
| 75 | + lines_by_file = {} |
| 76 | + for line in sys.stdin: |
| 77 | + match = re.search('^\+\+\+\ (.*?/){%s}(\S*)' % args.p, line) |
| 78 | + if match: |
| 79 | + filename = match.group(2) |
| 80 | + if filename == None: |
| 81 | + continue |
| 82 | + |
| 83 | + if args.regex is not None: |
| 84 | + if not re.match('^%s$' % args.regex, filename): |
| 85 | + continue |
| 86 | + else: |
| 87 | + if not re.match('^%s$' % args.iregex, filename, re.IGNORECASE): |
| 88 | + continue |
| 89 | + |
| 90 | + match = re.search('^@@.*\+(\d+)(,(\d+))?', line) |
| 91 | + if match: |
| 92 | + start_line = int(match.group(1)) |
| 93 | + line_count = 1 |
| 94 | + if match.group(3): |
| 95 | + line_count = int(match.group(3)) |
| 96 | + if line_count == 0: |
| 97 | + continue |
| 98 | + end_line = start_line + line_count - 1 |
| 99 | + lines_by_file.setdefault(filename, []).append( |
| 100 | + [start_line, end_line]) |
| 101 | + |
| 102 | + # Reformat files containing changes in place. |
| 103 | + for filename, lines in lines_by_file.items(): |
| 104 | + command = [args.binary, filename] |
| 105 | + if args.sort_includes: |
| 106 | + command.append('-sort-includes') |
| 107 | + if lines: |
| 108 | + s = [('-lines', str(x[0]) + ':' + str(x[1])) for x in lines] |
| 109 | + s = reduce(lambda x, y: x + y, s) |
| 110 | + command.extend(s) |
| 111 | + if args.style: |
| 112 | + command.extend(['-style', args.style]) |
| 113 | + p = subprocess.Popen(command, |
| 114 | + stdout=subprocess.PIPE, |
| 115 | + stderr=None, |
| 116 | + stdin=subprocess.PIPE, |
| 117 | + universal_newlines=True) |
| 118 | + stdout, stderr = p.communicate() |
| 119 | + if p.returncode != 0: |
| 120 | + sys.exit(p.returncode) |
| 121 | + |
| 122 | + with open(filename) as f: |
| 123 | + code = f.readlines() |
| 124 | + formatted_code = StringIO(stdout).readlines() |
| 125 | + modified_lines = dict() |
| 126 | + if lines: |
| 127 | + for x in lines: |
| 128 | + for i in range(x[0], x[1] + 1): |
| 129 | + modified_lines[i] = True |
| 130 | + |
| 131 | + # handle functions definitions/declarations: do not use space before ( |
| 132 | + for i, l in enumerate(formatted_code): |
| 133 | + if lines and i + 1 not in modified_lines: |
| 134 | + continue |
| 135 | + |
| 136 | + if l.startswith('R_API ') or l.startswith('static '): |
| 137 | + formatted_code[i] = l.replace(' (', '(') |
| 138 | + |
| 139 | + diff = difflib.unified_diff(code, formatted_code, |
| 140 | + filename, filename, |
| 141 | + '(before formatting)', '(after formatting)') |
| 142 | + diff_string = ''.join(diff) |
| 143 | + if len(diff_string) > 0: |
| 144 | + if args.i: |
| 145 | + f = tempfile.NamedTemporaryFile(delete=False) |
| 146 | + f.write(diff_string.encode()) |
| 147 | + f.close() |
| 148 | + os.system('git apply -p0 < "%s"' % (f.name)) |
| 149 | + os.unlink(f.name) |
| 150 | + else: |
| 151 | + sys.stdout.write(diff_string) |
| 152 | + |
| 153 | +if __name__ == '__main__': |
| 154 | + main() |
0 commit comments