blob: 8e9c803be4f2228a494fe5cba15427e0033b5eb2 [file] [log] [blame]
Simon Hertereee38cb2015-09-22 12:56:43 +02001#!/usr/bin/env python2.7
eaftan98320b42015-07-07 09:54:29 -07002#
3#===- google-java-format-diff.py - google-java-format Diff Reformatter -----===#
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
Jake Wharton4ccbc362015-08-25 19:57:00 -040012"""
eaftan98320b42015-07-07 09:54:29 -070013google-java-format 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 HEAD^ | google-java-format-diff.py -p1 -i
21 svn diff --diff-cmd=diff -x-U0 | google-java-format-diff.py -i
22
23"""
24
25import argparse
26import difflib
27import re
28import string
29import subprocess
30import StringIO
31import sys
Scott Bessler09f47092015-12-10 14:57:45 -080032from distutils.spawn import find_executable
eaftan98320b42015-07-07 09:54:29 -070033
Scott Bessler09f47092015-12-10 14:57:45 -080034binary = find_executable('google-java-format') or '/usr/bin/google-java-format'
eaftan98320b42015-07-07 09:54:29 -070035
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
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=r'.*\.java',
50 help='custom pattern selecting file paths to reformat '
51 '(case insensitive, overridden by -regex)')
52 parser.add_argument('-v', '--verbose', action='store_true',
53 help='be more verbose, ineffective without -i')
Michal Bendowski8309e082016-06-03 17:35:08 +010054 parser.add_argument('-a', '--aosp', action='store_true',
55 help='use AOSP style instead of Google Style (4-space indentation)')
eaftan98320b42015-07-07 09:54:29 -070056 args = parser.parse_args()
57
58 # Extract changed lines for each file.
59 filename = None
60 lines_by_file = {}
61
62 for line in sys.stdin:
63 match = re.search('^\+\+\+\ (.*?/){%s}(\S*)' % args.p, line)
64 if match:
65 filename = match.group(2)
66 if filename == None:
67 continue
68
69 if args.regex is not None:
70 if not re.match('^%s$' % args.regex, filename):
71 continue
72 else:
73 if not re.match('^%s$' % args.iregex, filename, re.IGNORECASE):
74 continue
75
76 match = re.search('^@@.*\+(\d+)(,(\d+))?', line)
77 if match:
78 start_line = int(match.group(1))
79 line_count = 1
80 if match.group(3):
81 line_count = int(match.group(3))
82 if line_count == 0:
83 continue
84 end_line = start_line + line_count - 1;
85 lines_by_file.setdefault(filename, []).extend(
86 ['-lines', str(start_line) + ':' + str(end_line)])
87
88 # Reformat files containing changes in place.
89 for filename, lines in lines_by_file.iteritems():
90 if args.i and args.verbose:
91 print 'Formatting', filename
92 command = [binary]
93 if args.i:
94 command.append('-i')
Michal Bendowski8309e082016-06-03 17:35:08 +010095 if args.aosp:
96 command.append('--aosp')
eaftan98320b42015-07-07 09:54:29 -070097 command.extend(lines)
98 command.append(filename)
99 p = subprocess.Popen(command, stdout=subprocess.PIPE,
100 stderr=None, stdin=subprocess.PIPE)
101 stdout, stderr = p.communicate()
102 if p.returncode != 0:
103 sys.exit(p.returncode);
104
105 if not args.i:
106 with open(filename) as f:
107 code = f.readlines()
108 formatted_code = StringIO.StringIO(stdout).readlines()
109 diff = difflib.unified_diff(code, formatted_code,
110 filename, filename,
111 '(before formatting)', '(after formatting)')
112 diff_string = string.join(diff, '')
113 if len(diff_string) > 0:
114 sys.stdout.write(diff_string)
115
116if __name__ == '__main__':
117 main()