[docs] Add LICENSE.txt to the root of the mono-repo
[llvm-project.git] / clang / tools / clang-format / clang-format-diff.py
blob1f6ff0fe295f88d165e79b6571c22fd36f4561f2
1 #!/usr/bin/env python3
3 #===- clang-format-diff.py - ClangFormat Diff Reformatter ----*- python -*--===#
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
9 #===------------------------------------------------------------------------===#
11 """
12 This script reads input from a unified diff and reformats all the changed
13 lines. This is useful to reformat all the lines touched by a specific patch.
14 Example usage for git/svn users:
16 git diff -U0 --no-color --relative HEAD^ | clang-format-diff.py -p1 -i
17 svn diff --diff-cmd=diff -x-U0 | clang-format-diff.py -i
19 It should be noted that the filename contained in the diff is used unmodified
20 to determine the source file to update. Users calling this script directly
21 should be careful to ensure that the path in the diff is correct relative to the
22 current working directory.
23 """
24 from __future__ import absolute_import, division, print_function
26 import argparse
27 import difflib
28 import re
29 import subprocess
30 import sys
32 if sys.version_info.major >= 3:
33 from io import StringIO
34 else:
35 from io import BytesIO as StringIO
38 def main():
39 parser = argparse.ArgumentParser(description=__doc__,
40 formatter_class=
41 argparse.RawDescriptionHelpFormatter)
42 parser.add_argument('-i', action='store_true', default=False,
43 help='apply edits to files instead of displaying a diff')
44 parser.add_argument('-p', metavar='NUM', default=0,
45 help='strip the smallest prefix containing P slashes')
46 parser.add_argument('-regex', metavar='PATTERN', default=None,
47 help='custom pattern selecting file paths to reformat '
48 '(case sensitive, overrides -iregex)')
49 parser.add_argument('-iregex', metavar='PATTERN', default=
50 r'.*\.(cpp|cc|c\+\+|cxx|cppm|ccm|cxxm|c\+\+m|c|cl|h|hh|hpp|hxx'
51 r'|m|mm|inc|js|ts|proto|protodevel|java|cs|json)',
52 help='custom pattern selecting file paths to reformat '
53 '(case insensitive, overridden by -regex)')
54 parser.add_argument('-sort-includes', action='store_true', default=False,
55 help='let clang-format sort include blocks')
56 parser.add_argument('-v', '--verbose', action='store_true',
57 help='be more verbose, ineffective without -i')
58 parser.add_argument('-style',
59 help='formatting style to apply (LLVM, GNU, Google, Chromium, '
60 'Microsoft, Mozilla, WebKit)')
61 parser.add_argument('-fallback-style',
62 help='The name of the predefined style used as a'
63 'fallback in case clang-format is invoked with'
64 '-style=file, but can not find the .clang-format'
65 'file to use.')
66 parser.add_argument('-binary', default='clang-format',
67 help='location of binary to use for clang-format')
68 args = parser.parse_args()
70 # Extract changed lines for each file.
71 filename = None
72 lines_by_file = {}
73 for line in sys.stdin:
74 match = re.search(r'^\+\+\+\ (.*?/){%s}(\S*)' % args.p, line)
75 if match:
76 filename = match.group(2)
77 if filename is None:
78 continue
80 if args.regex is not None:
81 if not re.match('^%s$' % args.regex, filename):
82 continue
83 else:
84 if not re.match('^%s$' % args.iregex, filename, re.IGNORECASE):
85 continue
87 match = re.search(r'^@@.*\+(\d+)(,(\d+))?', line)
88 if match:
89 start_line = int(match.group(1))
90 line_count = 1
91 if match.group(3):
92 line_count = int(match.group(3))
93 # Also format lines range if line_count is 0 in case of deleting
94 # surrounding statements.
95 end_line = start_line
96 if line_count != 0:
97 end_line += line_count - 1
98 lines_by_file.setdefault(filename, []).extend(
99 ['-lines', str(start_line) + ':' + str(end_line)])
101 # Reformat files containing changes in place.
102 for filename, lines in lines_by_file.items():
103 if args.i and args.verbose:
104 print('Formatting {}'.format(filename))
105 command = [args.binary, filename]
106 if args.i:
107 command.append('-i')
108 if args.sort_includes:
109 command.append('-sort-includes')
110 command.extend(lines)
111 if args.style:
112 command.extend(['-style', args.style])
113 if args.fallback_style:
114 command.extend(['-fallback-style', args.fallback_style])
116 try:
117 p = subprocess.Popen(command,
118 stdout=subprocess.PIPE,
119 stderr=None,
120 stdin=subprocess.PIPE,
121 universal_newlines=True)
122 except OSError as e:
123 # Give the user more context when clang-format isn't
124 # found/isn't executable, etc.
125 raise RuntimeError(
126 'Failed to run "%s" - %s"' % (" ".join(command), e.strerror))
128 stdout, stderr = p.communicate()
129 if p.returncode != 0:
130 sys.exit(p.returncode)
132 if not args.i:
133 with open(filename) as f:
134 code = f.readlines()
135 formatted_code = StringIO(stdout).readlines()
136 diff = difflib.unified_diff(code, formatted_code,
137 filename, filename,
138 '(before formatting)', '(after formatting)')
139 diff_string = ''.join(diff)
140 if len(diff_string) > 0:
141 sys.stdout.write(diff_string)
143 if __name__ == '__main__':
144 main()