blob: 4c6724b907fa4faab66d93b06519ede0cb2ab4c2 [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
tvanderlippe7aec9212019-02-26 08:13:04 -080023For perforce users:
24
25 P4DIFF="git --no-pager diff --no-index" p4 diff | ./google-java-format-diff.py -i -p7
26
eaftan98320b42015-07-07 09:54:29 -070027"""
28
29import argparse
30import difflib
31import re
32import string
33import subprocess
34import StringIO
35import sys
Scott Bessler09f47092015-12-10 14:57:45 -080036from distutils.spawn import find_executable
eaftan98320b42015-07-07 09:54:29 -070037
eaftan98320b42015-07-07 09:54:29 -070038def main():
39 parser = argparse.ArgumentParser(description=
40 'Reformat changed lines in diff. Without -i '
41 'option just output the diff that would be '
42 'introduced.')
43 parser.add_argument('-i', action='store_true', default=False,
44 help='apply edits to files instead of displaying a diff')
45
46 parser.add_argument('-p', metavar='NUM', default=0,
47 help='strip the smallest prefix containing P slashes')
48 parser.add_argument('-regex', metavar='PATTERN', default=None,
49 help='custom pattern selecting file paths to reformat '
50 '(case sensitive, overrides -iregex)')
51 parser.add_argument('-iregex', metavar='PATTERN', default=r'.*\.java',
52 help='custom pattern selecting file paths to reformat '
53 '(case insensitive, overridden by -regex)')
54 parser.add_argument('-v', '--verbose', action='store_true',
55 help='be more verbose, ineffective without -i')
Michal Bendowski8309e082016-06-03 17:35:08 +010056 parser.add_argument('-a', '--aosp', action='store_true',
57 help='use AOSP style instead of Google Style (4-space indentation)')
Jeff Davidsoncfd66b22016-12-15 17:24:15 -080058 parser.add_argument('--skip-sorting-imports', action='store_true',
59 help='do not fix the import order')
zhin3fcb71a2018-10-25 13:13:09 -070060 parser.add_argument('-b', '--binary', help='path to google-java-format binary')
Simon Sorianofa113c62019-04-23 09:01:02 -070061 parser.add_argument('--google-java-format-jar', metavar='ABSOLUTE_PATH', default=None,
62 help='use a custom google-java-format jar')
63
eaftan98320b42015-07-07 09:54:29 -070064 args = parser.parse_args()
65
66 # Extract changed lines for each file.
67 filename = None
68 lines_by_file = {}
69
70 for line in sys.stdin:
71 match = re.search('^\+\+\+\ (.*?/){%s}(\S*)' % args.p, line)
72 if match:
73 filename = match.group(2)
74 if filename == None:
75 continue
76
77 if args.regex is not None:
78 if not re.match('^%s$' % args.regex, filename):
79 continue
80 else:
81 if not re.match('^%s$' % args.iregex, filename, re.IGNORECASE):
82 continue
83
84 match = re.search('^@@.*\+(\d+)(,(\d+))?', line)
85 if match:
86 start_line = int(match.group(1))
87 line_count = 1
88 if match.group(3):
89 line_count = int(match.group(3))
90 if line_count == 0:
91 continue
92 end_line = start_line + line_count - 1;
93 lines_by_file.setdefault(filename, []).extend(
94 ['-lines', str(start_line) + ':' + str(end_line)])
95
zhin3fcb71a2018-10-25 13:13:09 -070096 if args.binary:
Simon Sorianofa113c62019-04-23 09:01:02 -070097 base_command = [args.binary]
98 elif args.google_java_format_jar:
99 base_command = ['java', '-jar', args.google_java_format_jar]
zhin3fcb71a2018-10-25 13:13:09 -0700100 else:
101 binary = find_executable('google-java-format') or '/usr/bin/google-java-format'
Simon Sorianofa113c62019-04-23 09:01:02 -0700102 base_command = [binary]
zhin3fcb71a2018-10-25 13:13:09 -0700103
eaftan98320b42015-07-07 09:54:29 -0700104 # Reformat files containing changes in place.
105 for filename, lines in lines_by_file.iteritems():
106 if args.i and args.verbose:
107 print 'Formatting', filename
Simon Sorianofa113c62019-04-23 09:01:02 -0700108 command = base_command[:]
eaftan98320b42015-07-07 09:54:29 -0700109 if args.i:
110 command.append('-i')
Michal Bendowski8309e082016-06-03 17:35:08 +0100111 if args.aosp:
112 command.append('--aosp')
Jeff Davidsoncfd66b22016-12-15 17:24:15 -0800113 if args.skip_sorting_imports:
114 command.append('--skip-sorting-imports')
eaftan98320b42015-07-07 09:54:29 -0700115 command.extend(lines)
116 command.append(filename)
117 p = subprocess.Popen(command, stdout=subprocess.PIPE,
118 stderr=None, stdin=subprocess.PIPE)
119 stdout, stderr = p.communicate()
120 if p.returncode != 0:
121 sys.exit(p.returncode);
122
123 if not args.i:
124 with open(filename) as f:
125 code = f.readlines()
126 formatted_code = StringIO.StringIO(stdout).readlines()
127 diff = difflib.unified_diff(code, formatted_code,
128 filename, filename,
129 '(before formatting)', '(after formatting)')
130 diff_string = string.join(diff, '')
131 if len(diff_string) > 0:
132 sys.stdout.write(diff_string)
133
134if __name__ == '__main__':
135 main()