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