blob: 958cd8b427ce0c774b671da76770a9026ddca4f8 [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')
eaftan98320b42015-07-07 09:54:29 -070061 args = parser.parse_args()
62
63 # Extract changed lines for each file.
64 filename = None
65 lines_by_file = {}
66
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
zhin3fcb71a2018-10-25 13:13:09 -070093 if args.binary:
94 binary = args.binary
95 else:
96 binary = find_executable('google-java-format') or '/usr/bin/google-java-format'
97
eaftan98320b42015-07-07 09:54:29 -070098 # Reformat files containing changes in place.
99 for filename, lines in lines_by_file.iteritems():
100 if args.i and args.verbose:
101 print 'Formatting', filename
102 command = [binary]
103 if args.i:
104 command.append('-i')
Michal Bendowski8309e082016-06-03 17:35:08 +0100105 if args.aosp:
106 command.append('--aosp')
Jeff Davidsoncfd66b22016-12-15 17:24:15 -0800107 if args.skip_sorting_imports:
108 command.append('--skip-sorting-imports')
eaftan98320b42015-07-07 09:54:29 -0700109 command.extend(lines)
110 command.append(filename)
111 p = subprocess.Popen(command, stdout=subprocess.PIPE,
112 stderr=None, stdin=subprocess.PIPE)
113 stdout, stderr = p.communicate()
114 if p.returncode != 0:
115 sys.exit(p.returncode);
116
117 if not args.i:
118 with open(filename) as f:
119 code = f.readlines()
120 formatted_code = StringIO.StringIO(stdout).readlines()
121 diff = difflib.unified_diff(code, formatted_code,
122 filename, filename,
123 '(before formatting)', '(after formatting)')
124 diff_string = string.join(diff, '')
125 if len(diff_string) > 0:
126 sys.stdout.write(diff_string)
127
128if __name__ == '__main__':
129 main()