xref: /minix3/external/bsd/llvm/dist/clang/tools/clang-format/clang-format-diff.py (revision ebfedea0ce5bbe81e252ddf32d732e40fb633fae)
1#!/usr/bin/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 users:
19
20  git diff -U0 HEAD^ | clang-format-diff.py -p1 -i
21
22"""
23
24import argparse
25import difflib
26import re
27import string
28import subprocess
29import StringIO
30import sys
31
32
33# Change this to the full path if clang-format is not on the path.
34binary = 'clang-format'
35
36
37def main():
38  parser = argparse.ArgumentParser(description=
39                                   'Reformat changed lines in diff. Without -i '
40                                   'option just output the diff that would be'
41                                   'introduced.')
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', default=0,
45                      help='strip the smallest prefix containing P slashes')
46  parser.add_argument(
47      '-style',
48      help=
49      'formatting style to apply (LLVM, Google, Chromium, Mozilla, WebKit)')
50  args = parser.parse_args()
51
52  # Extract changed lines for each file.
53  filename = None
54  lines_by_file = {}
55  for line in sys.stdin:
56    match = re.search('^\+\+\+\ (.*?/){%s}(\S*)' % args.p, line)
57    if match:
58      filename = match.group(2)
59    if filename == None:
60      continue
61
62    # FIXME: Add other types containing C++/ObjC code.
63    if not (filename.endswith(".cpp") or filename.endswith(".cc") or
64            filename.endswith(".h")):
65      continue
66
67    match = re.search('^@@.*\+(\d+)(,(\d+))?', line)
68    if match:
69      start_line = int(match.group(1))
70      line_count = 1
71      if match.group(3):
72        line_count = int(match.group(3))
73      if line_count == 0:
74        continue
75      end_line = start_line + line_count - 1;
76      lines_by_file.setdefault(filename, []).extend(
77          ['-lines', str(start_line) + ':' + str(end_line)])
78
79  # Reformat files containing changes in place.
80  for filename, lines in lines_by_file.iteritems():
81    command = [binary, filename]
82    if args.i:
83      command.append('-i')
84    command.extend(lines)
85    if args.style:
86      command.extend(['-style', args.style])
87    p = subprocess.Popen(command, stdout=subprocess.PIPE,
88                         stderr=subprocess.PIPE,
89                         stdin=subprocess.PIPE)
90    stdout, stderr = p.communicate()
91    if stderr:
92      print stderr
93    if p.returncode != 0:
94      sys.exit(p.returncode);
95
96    if not args.i:
97      with open(filename) as f:
98        code = f.readlines()
99      formatted_code = StringIO.StringIO(stdout).readlines()
100      diff = difflib.unified_diff(code, formatted_code,
101                                  filename, filename,
102                                  '(before formatting)', '(after formatting)')
103      diff_string = string.join(diff, '')
104      if len(diff_string) > 0:
105        print diff_string
106
107if __name__ == '__main__':
108  main()
109