blob: e9e7133be4ff6ecfa0bbf56cb2b4a669ed413f0e [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
eaftan98320b42015-07-07 09:54:29 -070034def main():
35 parser = argparse.ArgumentParser(description=
36 'Reformat changed lines in diff. Without -i '
37 'option just output the diff that would be '
38 'introduced.')
39 parser.add_argument('-i', action='store_true', default=False,
40 help='apply edits to files instead of displaying a diff')
41
42 parser.add_argument('-p', metavar='NUM', default=0,
43 help='strip the smallest prefix containing P slashes')
44 parser.add_argument('-regex', metavar='PATTERN', default=None,
45 help='custom pattern selecting file paths to reformat '
46 '(case sensitive, overrides -iregex)')
47 parser.add_argument('-iregex', metavar='PATTERN', default=r'.*\.java',
48 help='custom pattern selecting file paths to reformat '
49 '(case insensitive, overridden by -regex)')
50 parser.add_argument('-v', '--verbose', action='store_true',
51 help='be more verbose, ineffective without -i')
Michal Bendowski8309e082016-06-03 17:35:08 +010052 parser.add_argument('-a', '--aosp', action='store_true',
53 help='use AOSP style instead of Google Style (4-space indentation)')
Jeff Davidsoncfd66b22016-12-15 17:24:15 -080054 parser.add_argument('--skip-sorting-imports', action='store_true',
55 help='do not fix the import order')
zhin3fcb71a2018-10-25 13:13:09 -070056 parser.add_argument('-b', '--binary', help='path to google-java-format binary')
eaftan98320b42015-07-07 09:54:29 -070057 args = parser.parse_args()
58
59 # Extract changed lines for each file.
60 filename = None
61 lines_by_file = {}
62
63 for line in sys.stdin:
64 match = re.search('^\+\+\+\ (.*?/){%s}(\S*)' % args.p, line)
65 if match:
66 filename = match.group(2)
67 if filename == None:
68 continue
69
70 if args.regex is not None:
71 if not re.match('^%s$' % args.regex, filename):
72 continue
73 else:
74 if not re.match('^%s$' % args.iregex, filename, re.IGNORECASE):
75 continue
76
77 match = re.search('^@@.*\+(\d+)(,(\d+))?', line)
78 if match:
79 start_line = int(match.group(1))
80 line_count = 1
81 if match.group(3):
82 line_count = int(match.group(3))
83 if line_count == 0:
84 continue
85 end_line = start_line + line_count - 1;
86 lines_by_file.setdefault(filename, []).extend(
87 ['-lines', str(start_line) + ':' + str(end_line)])
88
zhin3fcb71a2018-10-25 13:13:09 -070089 if args.binary:
90 binary = args.binary
91 else:
92 binary = find_executable('google-java-format') or '/usr/bin/google-java-format'
93
eaftan98320b42015-07-07 09:54:29 -070094 # Reformat files containing changes in place.
95 for filename, lines in lines_by_file.iteritems():
96 if args.i and args.verbose:
97 print 'Formatting', filename
98 command = [binary]
99 if args.i:
100 command.append('-i')
Michal Bendowski8309e082016-06-03 17:35:08 +0100101 if args.aosp:
102 command.append('--aosp')
Jeff Davidsoncfd66b22016-12-15 17:24:15 -0800103 if args.skip_sorting_imports:
104 command.append('--skip-sorting-imports')
eaftan98320b42015-07-07 09:54:29 -0700105 command.extend(lines)
106 command.append(filename)
107 p = subprocess.Popen(command, stdout=subprocess.PIPE,
108 stderr=None, stdin=subprocess.PIPE)
109 stdout, stderr = p.communicate()
110 if p.returncode != 0:
111 sys.exit(p.returncode);
112
113 if not args.i:
114 with open(filename) as f:
115 code = f.readlines()
116 formatted_code = StringIO.StringIO(stdout).readlines()
117 diff = difflib.unified_diff(code, formatted_code,
118 filename, filename,
119 '(before formatting)', '(after formatting)')
120 diff_string = string.join(diff, '')
121 if len(diff_string) > 0:
122 sys.stdout.write(diff_string)
123
124if __name__ == '__main__':
125 main()