blob: d6d351041611f11d5b6c8378830429e0b58eb44c [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"""
serge_sans_paille05613342018-12-18 16:07:37 +000024from __future__ import absolute_import, division, print_function
djasper7f663602013-03-20 09:53:23 +000025
26import argparse
alexfhc770b672013-10-11 21:32:01 +000027import difflib
djasper7f663602013-03-20 09:53:23 +000028import re
29import subprocess
30import sys
serge_sans_paille2757fe92019-01-03 14:26:56 +000031
32if sys.version_info.major >= 3:
33 from io import StringIO
34else:
35 from io import BytesIO as StringIO
djasper7f663602013-03-20 09:53:23 +000036
37
djasper7f663602013-03-20 09:53:23 +000038def main():
39 parser = argparse.ArgumentParser(description=
alexfhc770b672013-10-11 21:32:01 +000040 'Reformat changed lines in diff. Without -i '
alp9b6f1cb2013-12-04 00:48:22 +000041 'option just output the diff that would be '
alexfhc770b672013-10-11 21:32:01 +000042 'introduced.')
43 parser.add_argument('-i', action='store_true', default=False,
44 help='apply edits to files instead of displaying a diff')
alpcfbd31f2013-12-10 13:51:53 +000045 parser.add_argument('-p', metavar='NUM', default=0,
djasper7f663602013-03-20 09:53:23 +000046 help='strip the smallest prefix containing P slashes')
alp51f6d9a2013-12-18 21:34:07 +000047 parser.add_argument('-regex', metavar='PATTERN', default=None,
alexfh1b8fbd82013-12-16 10:57:30 +000048 help='custom pattern selecting file paths to reformat '
djasper1d353c92013-12-19 10:21:37 +000049 '(case sensitive, overrides -iregex)')
alexfh1b8fbd82013-12-16 10:57:30 +000050 parser.add_argument('-iregex', metavar='PATTERN', default=
djaspercab68412015-03-11 14:58:38 +000051 r'.*\.(cpp|cc|c\+\+|cxx|c|cl|h|hpp|m|mm|inc|js|ts|proto'
djasper81edd552014-12-08 19:39:03 +000052 r'|protodevel|java)',
alexfh1b8fbd82013-12-16 10:57:30 +000053 help='custom pattern selecting file paths to reformat '
djasper1d353c92013-12-19 10:21:37 +000054 '(case insensitive, overridden by -regex)')
djasperea5da0e2015-10-07 17:00:20 +000055 parser.add_argument('-sort-includes', action='store_true', default=False,
56 help='let clang-format sort include blocks')
djasperceb88712014-11-14 13:27:28 +000057 parser.add_argument('-v', '--verbose', action='store_true',
58 help='be more verbose, ineffective without -i')
djaspera72164d2016-01-20 18:55:57 +000059 parser.add_argument('-style',
60 help='formatting style to apply (LLVM, Google, Chromium, '
61 'Mozilla, WebKit)')
62 parser.add_argument('-binary', default='clang-format',
63 help='location of binary to use for clang-format')
djasper7f663602013-03-20 09:53:23 +000064 args = parser.parse_args()
65
djasper75c32192013-09-18 12:14:09 +000066 # Extract changed lines for each file.
djasper7f663602013-03-20 09:53:23 +000067 filename = None
djasper75c32192013-09-18 12:14:09 +000068 lines_by_file = {}
djasper7f663602013-03-20 09:53:23 +000069 for line in sys.stdin:
70 match = re.search('^\+\+\+\ (.*?/){%s}(\S*)' % args.p, line)
71 if match:
72 filename = match.group(2)
73 if filename == None:
74 continue
75
alp51f6d9a2013-12-18 21:34:07 +000076 if args.regex is not None:
77 if not re.match('^%s$' % args.regex, filename):
alexfh1b8fbd82013-12-16 10:57:30 +000078 continue
79 else:
alp51f6d9a2013-12-18 21:34:07 +000080 if not re.match('^%s$' % args.iregex, filename, re.IGNORECASE):
alexfh1b8fbd82013-12-16 10:57:30 +000081 continue
djasper75c32192013-09-18 12:14:09 +000082
djasper7f663602013-03-20 09:53:23 +000083 match = re.search('^@@.*\+(\d+)(,(\d+))?', line)
84 if match:
djasper75c32192013-09-18 12:14:09 +000085 start_line = int(match.group(1))
djaspere3eb0582013-10-02 13:59:03 +000086 line_count = 1
djasper7f663602013-03-20 09:53:23 +000087 if match.group(3):
djaspere3eb0582013-10-02 13:59:03 +000088 line_count = int(match.group(3))
89 if line_count == 0:
90 continue
krasimire863ca52018-08-03 10:04:58 +000091 end_line = start_line + line_count - 1
djasper75c32192013-09-18 12:14:09 +000092 lines_by_file.setdefault(filename, []).extend(
93 ['-lines', str(start_line) + ':' + str(end_line)])
djasper7f663602013-03-20 09:53:23 +000094
djasper75c32192013-09-18 12:14:09 +000095 # Reformat files containing changes in place.
krasimire863ca52018-08-03 10:04:58 +000096 for filename, lines in lines_by_file.items():
djasperceb88712014-11-14 13:27:28 +000097 if args.i and args.verbose:
krasimire863ca52018-08-03 10:04:58 +000098 print('Formatting {}'.format(filename))
djaspera72164d2016-01-20 18:55:57 +000099 command = [args.binary, filename]
alexfhc770b672013-10-11 21:32:01 +0000100 if args.i:
101 command.append('-i')
djasperea5da0e2015-10-07 17:00:20 +0000102 if args.sort_includes:
103 command.append('-sort-includes')
djasper75c32192013-09-18 12:14:09 +0000104 command.extend(lines)
105 if args.style:
djasperc49abf92013-09-21 10:05:02 +0000106 command.extend(['-style', args.style])
krasimire863ca52018-08-03 10:04:58 +0000107 p = subprocess.Popen(command,
108 stdout=subprocess.PIPE,
109 stderr=None,
110 stdin=subprocess.PIPE,
111 universal_newlines=True)
djasper75c32192013-09-18 12:14:09 +0000112 stdout, stderr = p.communicate()
djasper60dad2e2013-10-08 15:54:36 +0000113 if p.returncode != 0:
krasimire863ca52018-08-03 10:04:58 +0000114 sys.exit(p.returncode)
djasper7f663602013-03-20 09:53:23 +0000115
alexfhc770b672013-10-11 21:32:01 +0000116 if not args.i:
117 with open(filename) as f:
118 code = f.readlines()
krasimire863ca52018-08-03 10:04:58 +0000119 formatted_code = StringIO(stdout).readlines()
alexfhc770b672013-10-11 21:32:01 +0000120 diff = difflib.unified_diff(code, formatted_code,
121 filename, filename,
122 '(before formatting)', '(after formatting)')
krasimire863ca52018-08-03 10:04:58 +0000123 diff_string = ''.join(diff)
alexfhc770b672013-10-11 21:32:01 +0000124 if len(diff_string) > 0:
alp367218e2013-12-05 08:14:54 +0000125 sys.stdout.write(diff_string)
djasper7f663602013-03-20 09:53:23 +0000126
127if __name__ == '__main__':
128 main()