blob: ce4c1d6e0a7656e72030c4cf36f4e5f47c9851b5 [file] [log] [blame]
ed509e8b92014-09-02 20:59:13 +00001#!/usr/bin/env python
djasper7f663602013-03-20 09:53:23 +00002#
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
12r"""
13ClangFormat Diff Reformatter
14============================
15
16This script reads input from a unified diff and reformats all the changed
17lines. This is useful to reformat all the lines touched by a specific patch.
djasper78395352014-05-14 09:36:11 +000018Example usage for git/svn users:
djasper7f663602013-03-20 09:53:23 +000019
sylvestread8850a2016-12-03 23:22:45 +000020 git diff -U0 --no-color HEAD^ | clang-format-diff.py -p1 -i
djasper78395352014-05-14 09:36:11 +000021 svn diff --diff-cmd=diff -x-U0 | clang-format-diff.py -i
djasper7f663602013-03-20 09:53:23 +000022
23"""
24
25import argparse
alexfhc770b672013-10-11 21:32:01 +000026import difflib
djasper7f663602013-03-20 09:53:23 +000027import re
28import subprocess
29import sys
krasimire863ca52018-08-03 10:04:58 +000030try:
31 from StringIO import StringIO
32except ImportError:
33 from io import StringIO
djasper7f663602013-03-20 09:53:23 +000034
35
djasper7f663602013-03-20 09:53:23 +000036def main():
37 parser = argparse.ArgumentParser(description=
alexfhc770b672013-10-11 21:32:01 +000038 'Reformat changed lines in diff. Without -i '
alp9b6f1cb2013-12-04 00:48:22 +000039 'option just output the diff that would be '
alexfhc770b672013-10-11 21:32:01 +000040 'introduced.')
41 parser.add_argument('-i', action='store_true', default=False,
42 help='apply edits to files instead of displaying a diff')
alpcfbd31f2013-12-10 13:51:53 +000043 parser.add_argument('-p', metavar='NUM', default=0,
djasper7f663602013-03-20 09:53:23 +000044 help='strip the smallest prefix containing P slashes')
alp51f6d9a2013-12-18 21:34:07 +000045 parser.add_argument('-regex', metavar='PATTERN', default=None,
alexfh1b8fbd82013-12-16 10:57:30 +000046 help='custom pattern selecting file paths to reformat '
djasper1d353c92013-12-19 10:21:37 +000047 '(case sensitive, overrides -iregex)')
alexfh1b8fbd82013-12-16 10:57:30 +000048 parser.add_argument('-iregex', metavar='PATTERN', default=
djaspercab68412015-03-11 14:58:38 +000049 r'.*\.(cpp|cc|c\+\+|cxx|c|cl|h|hpp|m|mm|inc|js|ts|proto'
djasper81edd552014-12-08 19:39:03 +000050 r'|protodevel|java)',
alexfh1b8fbd82013-12-16 10:57:30 +000051 help='custom pattern selecting file paths to reformat '
djasper1d353c92013-12-19 10:21:37 +000052 '(case insensitive, overridden by -regex)')
djasperea5da0e2015-10-07 17:00:20 +000053 parser.add_argument('-sort-includes', action='store_true', default=False,
54 help='let clang-format sort include blocks')
djasperceb88712014-11-14 13:27:28 +000055 parser.add_argument('-v', '--verbose', action='store_true',
56 help='be more verbose, ineffective without -i')
djaspera72164d2016-01-20 18:55:57 +000057 parser.add_argument('-style',
58 help='formatting style to apply (LLVM, Google, Chromium, '
59 'Mozilla, WebKit)')
60 parser.add_argument('-binary', default='clang-format',
61 help='location of binary to use for clang-format')
djasper7f663602013-03-20 09:53:23 +000062 args = parser.parse_args()
63
djasper75c32192013-09-18 12:14:09 +000064 # Extract changed lines for each file.
djasper7f663602013-03-20 09:53:23 +000065 filename = None
djasper75c32192013-09-18 12:14:09 +000066 lines_by_file = {}
djasper7f663602013-03-20 09:53:23 +000067 for line in sys.stdin:
68 match = re.search('^\+\+\+\ (.*?/){%s}(\S*)' % args.p, line)
69 if match:
70 filename = match.group(2)
71 if filename == None:
72 continue
73
alp51f6d9a2013-12-18 21:34:07 +000074 if args.regex is not None:
75 if not re.match('^%s$' % args.regex, filename):
alexfh1b8fbd82013-12-16 10:57:30 +000076 continue
77 else:
alp51f6d9a2013-12-18 21:34:07 +000078 if not re.match('^%s$' % args.iregex, filename, re.IGNORECASE):
alexfh1b8fbd82013-12-16 10:57:30 +000079 continue
djasper75c32192013-09-18 12:14:09 +000080
djasper7f663602013-03-20 09:53:23 +000081 match = re.search('^@@.*\+(\d+)(,(\d+))?', line)
82 if match:
djasper75c32192013-09-18 12:14:09 +000083 start_line = int(match.group(1))
djaspere3eb0582013-10-02 13:59:03 +000084 line_count = 1
djasper7f663602013-03-20 09:53:23 +000085 if match.group(3):
djaspere3eb0582013-10-02 13:59:03 +000086 line_count = int(match.group(3))
87 if line_count == 0:
88 continue
krasimire863ca52018-08-03 10:04:58 +000089 end_line = start_line + line_count - 1
djasper75c32192013-09-18 12:14:09 +000090 lines_by_file.setdefault(filename, []).extend(
91 ['-lines', str(start_line) + ':' + str(end_line)])
djasper7f663602013-03-20 09:53:23 +000092
djasper75c32192013-09-18 12:14:09 +000093 # Reformat files containing changes in place.
krasimire863ca52018-08-03 10:04:58 +000094 for filename, lines in lines_by_file.items():
djasperceb88712014-11-14 13:27:28 +000095 if args.i and args.verbose:
krasimire863ca52018-08-03 10:04:58 +000096 print('Formatting {}'.format(filename))
djaspera72164d2016-01-20 18:55:57 +000097 command = [args.binary, filename]
alexfhc770b672013-10-11 21:32:01 +000098 if args.i:
99 command.append('-i')
djasperea5da0e2015-10-07 17:00:20 +0000100 if args.sort_includes:
101 command.append('-sort-includes')
djasper75c32192013-09-18 12:14:09 +0000102 command.extend(lines)
103 if args.style:
djasperc49abf92013-09-21 10:05:02 +0000104 command.extend(['-style', args.style])
krasimire863ca52018-08-03 10:04:58 +0000105 p = subprocess.Popen(command,
106 stdout=subprocess.PIPE,
107 stderr=None,
108 stdin=subprocess.PIPE,
109 universal_newlines=True)
djasper75c32192013-09-18 12:14:09 +0000110 stdout, stderr = p.communicate()
djasper60dad2e2013-10-08 15:54:36 +0000111 if p.returncode != 0:
krasimire863ca52018-08-03 10:04:58 +0000112 sys.exit(p.returncode)
djasper7f663602013-03-20 09:53:23 +0000113
alexfhc770b672013-10-11 21:32:01 +0000114 if not args.i:
115 with open(filename) as f:
116 code = f.readlines()
krasimire863ca52018-08-03 10:04:58 +0000117 formatted_code = StringIO(stdout).readlines()
alexfhc770b672013-10-11 21:32:01 +0000118 diff = difflib.unified_diff(code, formatted_code,
119 filename, filename,
120 '(before formatting)', '(after formatting)')
krasimire863ca52018-08-03 10:04:58 +0000121 diff_string = ''.join(diff)
alexfhc770b672013-10-11 21:32:01 +0000122 if len(diff_string) > 0:
alp367218e2013-12-05 08:14:54 +0000123 sys.stdout.write(diff_string)
djasper7f663602013-03-20 09:53:23 +0000124
125if __name__ == '__main__':
126 main()