blob: c9c3dc35c2645c29885bcf94e0d46dd957923c26 [file] [log] [blame]
Søren Gjesseffc06192022-06-03 11:11:27 +02001#!/usr/bin/env python3
2#
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
12"""
13google-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
23For perforce users:
24
25 P4DIFF="git --no-pager diff --no-index" p4 diff | ./google-java-format-diff.py -i -p7
26
27"""
28
29import argparse
30import difflib
31import re
32import string
33import subprocess
34import io
35import os
36import sys
37from shutil import which
38
39def main():
40 parser = argparse.ArgumentParser(description=
41 'Reformat changed lines in diff. Without -i '
42 'option just output the diff that would be '
43 'introduced.')
44 parser.add_argument('-i', action='store_true', default=False,
45 help='apply edits to files instead of displaying a diff')
46
47 parser.add_argument('-p', metavar='NUM', default=0,
48 help='strip the smallest prefix containing P slashes')
49 parser.add_argument('-regex', metavar='PATTERN', default=None,
50 help='custom pattern selecting file paths to reformat '
51 '(case sensitive, overrides -iregex)')
52 parser.add_argument('-iregex', metavar='PATTERN', default=r'.*\.java',
53 help='custom pattern selecting file paths to reformat '
54 '(case insensitive, overridden by -regex)')
55 parser.add_argument('-v', '--verbose', action='store_true',
56 help='be more verbose, ineffective without -i')
57 parser.add_argument('-a', '--aosp', action='store_true',
58 help='use AOSP style instead of Google Style (4-space indentation)')
59 parser.add_argument('--skip-sorting-imports', action='store_true',
60 help='do not fix the import order')
61 parser.add_argument('--skip-removing-unused-imports', action='store_true',
62 help='do not remove ununsed imports')
63 parser.add_argument(
64 '--skip-javadoc-formatting',
65 action='store_true',
66 default=False,
67 help='do not reformat javadoc')
68 parser.add_argument('-b', '--binary', help='path to google-java-format binary')
69 parser.add_argument('--google-java-format-jar', metavar='ABSOLUTE_PATH', default=None,
70 help='use a custom google-java-format jar')
71
72 args = parser.parse_args()
73
74 # Extract changed lines for each file.
75 filename = None
76 lines_by_file = {}
77
78 for line in sys.stdin:
79 match = re.search('^\+\+\+\ (.*?/){%s}(\S*)' % args.p, line)
80 if match:
81 filename = match.group(2)
82 if filename == None:
83 continue
84
85 if args.regex is not None:
86 if not re.match('^%s$' % args.regex, filename):
87 continue
88 else:
89 if not re.match('^%s$' % args.iregex, filename, re.IGNORECASE):
90 continue
91
92 match = re.search('^@@.*\+(\d+)(,(\d+))?', line)
93 if match:
94 start_line = int(match.group(1))
95 line_count = 1
96 if match.group(3):
97 line_count = int(match.group(3))
98 if line_count == 0:
99 continue
100 end_line = start_line + line_count - 1;
101 lines_by_file.setdefault(filename, []).extend(
102 ['-lines', str(start_line) + ':' + str(end_line)])
103
104 if args.binary:
105 base_command = [args.binary]
106 elif args.google_java_format_jar:
107 base_command = [
108 os.path.join(
109 'third_party', 'openjdk', 'jdk-17', 'linux', 'bin', 'java'),
110 '-jar',
111 '--add-opens=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED',
112 '--add-opens=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED',
113 '--add-opens=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED',
114 '--add-opens=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED',
115 '--add-opens=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED',
116 '--add-opens=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED',
117 args.google_java_format_jar]
118 else:
119 binary = which('google-java-format') or '/usr/bin/google-java-format'
120 base_command = [binary]
121
122 # Reformat files containing changes in place.
123 for filename, lines in lines_by_file.items():
124 if args.i and args.verbose:
125 print('Formatting', filename)
126 command = base_command[:]
127 if args.i:
128 command.append('-i')
129 if args.aosp:
130 command.append('--aosp')
131 if args.skip_sorting_imports:
132 command.append('--skip-sorting-imports')
133 if args.skip_removing_unused_imports:
134 command.append('--skip-removing-unused-imports')
135 if args.skip_javadoc_formatting:
136 command.append('--skip-javadoc-formatting')
137 command.extend(lines)
138 command.append(filename)
139 p = subprocess.Popen(command, stdout=subprocess.PIPE,
140 stderr=None, stdin=subprocess.PIPE)
141 stdout, stderr = p.communicate()
142 if p.returncode != 0:
143 sys.exit(p.returncode);
144
145 if not args.i:
146 with open(filename) as f:
147 code = f.readlines()
148 formatted_code = io.StringIO(stdout.decode('utf-8')).readlines()
149 diff = difflib.unified_diff(code, formatted_code,
150 filename, filename,
151 '(before formatting)', '(after formatting)')
152 diff_string = ''.join(diff)
153 if len(diff_string) > 0:
154 sys.stdout.write(diff_string)
155
156if __name__ == '__main__':
157 main()