blob: 3ba0abefc9f5fcd0ad8d19bb36abf0825a9d1be6 [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#
chandlerc079ee0b2019-01-19 08:50:56 +00005# 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
djasper7f663602013-03-20 09:53:23 +00008#
9#===------------------------------------------------------------------------===#
10
11r"""
12ClangFormat Diff Reformatter
13============================
14
15This script reads input from a unified diff and reformats all the changed
16lines. This is useful to reformat all the lines touched by a specific patch.
djasper78395352014-05-14 09:36:11 +000017Example usage for git/svn users:
djasper7f663602013-03-20 09:53:23 +000018
sylvestread8850a2016-12-03 23:22:45 +000019 git diff -U0 --no-color HEAD^ | clang-format-diff.py -p1 -i
djasper78395352014-05-14 09:36:11 +000020 svn diff --diff-cmd=diff -x-U0 | clang-format-diff.py -i
djasper7f663602013-03-20 09:53:23 +000021
22"""
serge_sans_paille05613342018-12-18 16:07:37 +000023from __future__ import absolute_import, division, print_function
djasper7f663602013-03-20 09:53:23 +000024
25import argparse
alexfhc770b672013-10-11 21:32:01 +000026import difflib
djasper7f663602013-03-20 09:53:23 +000027import re
28import subprocess
29import sys
serge_sans_paille2757fe92019-01-03 14:26:56 +000030
31if sys.version_info.major >= 3:
32 from io import StringIO
33else:
34 from io import BytesIO as StringIO
djasper7f663602013-03-20 09:53:23 +000035
36
djasper7f663602013-03-20 09:53:23 +000037def main():
38 parser = argparse.ArgumentParser(description=
alexfhc770b672013-10-11 21:32:01 +000039 'Reformat changed lines in diff. Without -i '
alp9b6f1cb2013-12-04 00:48:22 +000040 'option just output the diff that would be '
alexfhc770b672013-10-11 21:32:01 +000041 'introduced.')
42 parser.add_argument('-i', action='store_true', default=False,
43 help='apply edits to files instead of displaying a diff')
alpcfbd31f2013-12-10 13:51:53 +000044 parser.add_argument('-p', metavar='NUM', default=0,
djasper7f663602013-03-20 09:53:23 +000045 help='strip the smallest prefix containing P slashes')
alp51f6d9a2013-12-18 21:34:07 +000046 parser.add_argument('-regex', metavar='PATTERN', default=None,
alexfh1b8fbd82013-12-16 10:57:30 +000047 help='custom pattern selecting file paths to reformat '
djasper1d353c92013-12-19 10:21:37 +000048 '(case sensitive, overrides -iregex)')
alexfh1b8fbd82013-12-16 10:57:30 +000049 parser.add_argument('-iregex', metavar='PATTERN', default=
djaspercab68412015-03-11 14:58:38 +000050 r'.*\.(cpp|cc|c\+\+|cxx|c|cl|h|hpp|m|mm|inc|js|ts|proto'
djasper81edd552014-12-08 19:39:03 +000051 r'|protodevel|java)',
alexfh1b8fbd82013-12-16 10:57:30 +000052 help='custom pattern selecting file paths to reformat '
djasper1d353c92013-12-19 10:21:37 +000053 '(case insensitive, overridden by -regex)')
djasperea5da0e2015-10-07 17:00:20 +000054 parser.add_argument('-sort-includes', action='store_true', default=False,
55 help='let clang-format sort include blocks')
djasperceb88712014-11-14 13:27:28 +000056 parser.add_argument('-v', '--verbose', action='store_true',
57 help='be more verbose, ineffective without -i')
djaspera72164d2016-01-20 18:55:57 +000058 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')
djasper7f663602013-03-20 09:53:23 +000063 args = parser.parse_args()
64
djasper75c32192013-09-18 12:14:09 +000065 # Extract changed lines for each file.
djasper7f663602013-03-20 09:53:23 +000066 filename = None
djasper75c32192013-09-18 12:14:09 +000067 lines_by_file = {}
djasper7f663602013-03-20 09:53:23 +000068 for line in sys.stdin:
serge_sans_paillea3caf452019-02-11 15:03:17 +000069 match = re.search(r'^\+\+\+\ (.*?/){%s}(\S*)' % args.p, line)
djasper7f663602013-03-20 09:53:23 +000070 if match:
71 filename = match.group(2)
72 if filename == None:
73 continue
74
alp51f6d9a2013-12-18 21:34:07 +000075 if args.regex is not None:
76 if not re.match('^%s$' % args.regex, filename):
alexfh1b8fbd82013-12-16 10:57:30 +000077 continue
78 else:
alp51f6d9a2013-12-18 21:34:07 +000079 if not re.match('^%s$' % args.iregex, filename, re.IGNORECASE):
alexfh1b8fbd82013-12-16 10:57:30 +000080 continue
djasper75c32192013-09-18 12:14:09 +000081
serge_sans_paillea3caf452019-02-11 15:03:17 +000082 match = re.search(r'^@@.*\+(\d+)(,(\d+))?', line)
djasper7f663602013-03-20 09:53:23 +000083 if match:
djasper75c32192013-09-18 12:14:09 +000084 start_line = int(match.group(1))
djaspere3eb0582013-10-02 13:59:03 +000085 line_count = 1
djasper7f663602013-03-20 09:53:23 +000086 if match.group(3):
djaspere3eb0582013-10-02 13:59:03 +000087 line_count = int(match.group(3))
88 if line_count == 0:
89 continue
krasimire863ca52018-08-03 10:04:58 +000090 end_line = start_line + line_count - 1
djasper75c32192013-09-18 12:14:09 +000091 lines_by_file.setdefault(filename, []).extend(
92 ['-lines', str(start_line) + ':' + str(end_line)])
djasper7f663602013-03-20 09:53:23 +000093
djasper75c32192013-09-18 12:14:09 +000094 # Reformat files containing changes in place.
krasimire863ca52018-08-03 10:04:58 +000095 for filename, lines in lines_by_file.items():
djasperceb88712014-11-14 13:27:28 +000096 if args.i and args.verbose:
krasimire863ca52018-08-03 10:04:58 +000097 print('Formatting {}'.format(filename))
djaspera72164d2016-01-20 18:55:57 +000098 command = [args.binary, filename]
alexfhc770b672013-10-11 21:32:01 +000099 if args.i:
100 command.append('-i')
djasperea5da0e2015-10-07 17:00:20 +0000101 if args.sort_includes:
102 command.append('-sort-includes')
djasper75c32192013-09-18 12:14:09 +0000103 command.extend(lines)
104 if args.style:
djasperc49abf92013-09-21 10:05:02 +0000105 command.extend(['-style', args.style])
krasimire863ca52018-08-03 10:04:58 +0000106 p = subprocess.Popen(command,
107 stdout=subprocess.PIPE,
108 stderr=None,
109 stdin=subprocess.PIPE,
110 universal_newlines=True)
djasper75c32192013-09-18 12:14:09 +0000111 stdout, stderr = p.communicate()
djasper60dad2e2013-10-08 15:54:36 +0000112 if p.returncode != 0:
krasimire863ca52018-08-03 10:04:58 +0000113 sys.exit(p.returncode)
djasper7f663602013-03-20 09:53:23 +0000114
alexfhc770b672013-10-11 21:32:01 +0000115 if not args.i:
116 with open(filename) as f:
117 code = f.readlines()
krasimire863ca52018-08-03 10:04:58 +0000118 formatted_code = StringIO(stdout).readlines()
alexfhc770b672013-10-11 21:32:01 +0000119 diff = difflib.unified_diff(code, formatted_code,
120 filename, filename,
121 '(before formatting)', '(after formatting)')
krasimire863ca52018-08-03 10:04:58 +0000122 diff_string = ''.join(diff)
alexfhc770b672013-10-11 21:32:01 +0000123 if len(diff_string) > 0:
alp367218e2013-12-05 08:14:54 +0000124 sys.stdout.write(diff_string)
djasper7f663602013-03-20 09:53:23 +0000125
126if __name__ == '__main__':
127 main()