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""" 12This script reads input from a unified diff and reformats all the changed 13lines. This is useful to reformat all the lines touched by a specific patch. 14Example usage for git/svn users: 15 16 git diff -U0 --no-color HEAD^ | clang-format-diff.py -p1 -i 17 svn diff --diff-cmd=diff -x-U0 | clang-format-diff.py -i 18 19""" 20from __future__ import absolute_import, division, print_function 21 22import argparse 23import difflib 24import re 25import subprocess 26import sys 27 28if sys.version_info.major >= 3: 29 from io import StringIO 30else: 31 from io import BytesIO as StringIO 32 33 34def main(): 35 parser = argparse.ArgumentParser(description=__doc__, 36 formatter_class= 37 argparse.RawDescriptionHelpFormatter) 38 parser.add_argument('-i', action='store_true', default=False, 39 help='apply edits to files instead of displaying a diff') 40 parser.add_argument('-p', metavar='NUM', default=0, 41 help='strip the smallest prefix containing P slashes') 42 parser.add_argument('-regex', metavar='PATTERN', default=None, 43 help='custom pattern selecting file paths to reformat ' 44 '(case sensitive, overrides -iregex)') 45 parser.add_argument('-iregex', metavar='PATTERN', default= 46 r'.*\.(cpp|cc|c\+\+|cxx|c|cl|h|hh|hpp|m|mm|inc|js|ts|proto' 47 r'|protodevel|java|cs)', 48 help='custom pattern selecting file paths to reformat ' 49 '(case insensitive, overridden by -regex)') 50 parser.add_argument('-sort-includes', action='store_true', default=False, 51 help='let clang-format sort include blocks') 52 parser.add_argument('-v', '--verbose', action='store_true', 53 help='be more verbose, ineffective without -i') 54 parser.add_argument('-style', 55 help='formatting style to apply (LLVM, Google, Chromium, ' 56 'Mozilla, WebKit)') 57 parser.add_argument('-binary', default='clang-format', 58 help='location of binary to use for clang-format') 59 args = parser.parse_args() 60 61 # Extract changed lines for each file. 62 filename = None 63 lines_by_file = {} 64 for line in sys.stdin: 65 match = re.search(r'^\+\+\+\ (.*?/){%s}(\S*)' % args.p, line) 66 if match: 67 filename = match.group(2) 68 if filename == None: 69 continue 70 71 if args.regex is not None: 72 if not re.match('^%s$' % args.regex, filename): 73 continue 74 else: 75 if not re.match('^%s$' % args.iregex, filename, re.IGNORECASE): 76 continue 77 78 match = re.search(r'^@@.*\+(\d+)(,(\d+))?', line) 79 if match: 80 start_line = int(match.group(1)) 81 line_count = 1 82 if match.group(3): 83 line_count = int(match.group(3)) 84 if line_count == 0: 85 continue 86 end_line = start_line + line_count - 1 87 lines_by_file.setdefault(filename, []).extend( 88 ['-lines', str(start_line) + ':' + str(end_line)]) 89 90 # Reformat files containing changes in place. 91 for filename, lines in lines_by_file.items(): 92 if args.i and args.verbose: 93 print('Formatting {}'.format(filename)) 94 command = [args.binary, filename] 95 if args.i: 96 command.append('-i') 97 if args.sort_includes: 98 command.append('-sort-includes') 99 command.extend(lines) 100 if args.style: 101 command.extend(['-style', args.style]) 102 p = subprocess.Popen(command, 103 stdout=subprocess.PIPE, 104 stderr=None, 105 stdin=subprocess.PIPE, 106 universal_newlines=True) 107 stdout, stderr = p.communicate() 108 if p.returncode != 0: 109 sys.exit(p.returncode) 110 111 if not args.i: 112 with open(filename) as f: 113 code = f.readlines() 114 formatted_code = StringIO(stdout).readlines() 115 diff = difflib.unified_diff(code, formatted_code, 116 filename, filename, 117 '(before formatting)', '(after formatting)') 118 diff_string = ''.join(diff) 119 if len(diff_string) > 0: 120 sys.stdout.write(diff_string) 121 122if __name__ == '__main__': 123 main() 124