Skip to content

Commit 98320b4

Browse files
eaftancushon
eaftan
authored andcommitted
Open-source google-java-format-diff.py.
------------- Created by MOE: http://code.google.com/p/moe-java MOE_MIGRATED_REVID=97680935
1 parent 0cb2fcd commit 98320b4

File tree

2 files changed

+183
-1
lines changed

2 files changed

+183
-1
lines changed

LICENSE

Lines changed: 71 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
The following Apache 2.0 license applies to all code in this package except
2+
google-java-format-diff.py.
13

24
Apache License
35
Version 2.0, January 2004
@@ -199,4 +201,72 @@
199201
distributed under the License is distributed on an "AS IS" BASIS,
200202
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201203
See the License for the specific language governing permissions and
202-
limitations under the License.
204+
limitations under the License.
205+
206+
------------------------------------------------------------------------------
207+
208+
The following NCSA license applies only to google-java-format-diff.py.
209+
210+
==============================================================================
211+
LLVM Release License
212+
==============================================================================
213+
University of Illinois/NCSA
214+
Open Source License
215+
216+
Copyright (c) 2007-2015 University of Illinois at Urbana-Champaign.
217+
All rights reserved.
218+
219+
Developed by:
220+
221+
LLVM Team
222+
223+
University of Illinois at Urbana-Champaign
224+
225+
http://llvm.org
226+
227+
Permission is hereby granted, free of charge, to any person obtaining a copy of
228+
this software and associated documentation files (the "Software"), to deal with
229+
the Software without restriction, including without limitation the rights to
230+
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
231+
of the Software, and to permit persons to whom the Software is furnished to do
232+
so, subject to the following conditions:
233+
234+
* Redistributions of source code must retain the above copyright notice,
235+
this list of conditions and the following disclaimers.
236+
237+
* Redistributions in binary form must reproduce the above copyright notice,
238+
this list of conditions and the following disclaimers in the
239+
documentation and/or other materials provided with the distribution.
240+
241+
* Neither the names of the LLVM Team, University of Illinois at
242+
Urbana-Champaign, nor the names of its contributors may be used to
243+
endorse or promote products derived from this Software without specific
244+
prior written permission.
245+
246+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
247+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
248+
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
249+
CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
250+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
251+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
252+
SOFTWARE.
253+
254+
==============================================================================
255+
The LLVM software contains code written by third parties. Such software will
256+
have its own individual LICENSE.TXT file in the directory in which it appears.
257+
This file will describe the copyrights, license, and restrictions which apply
258+
to that code.
259+
260+
The disclaimer of warranty in the University of Illinois Open Source License
261+
applies to all code in the LLVM Distribution, and nothing in any of the
262+
other licenses gives permission to use the names of the LLVM Team or the
263+
University of Illinois to endorse or promote products derived from this
264+
Software.
265+
266+
The following pieces of software have additional or alternate copyrights,
267+
licenses, and/or restrictions:
268+
269+
Program Directory
270+
------- ---------
271+
<none yet>
272+

scripts/google-java-format-diff.py

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
#!/usr/bin/env python
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+
r"""
13+
google-java-format Diff Reformatter
14+
============================
15+
16+
This script reads input from a unified diff and reformats all the changed
17+
lines. This is useful to reformat all the lines touched by a specific patch.
18+
Example 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+
25+
import argparse
26+
import difflib
27+
import re
28+
import string
29+
import subprocess
30+
import StringIO
31+
import sys
32+
33+
binary = '/usr/bin/google-java-format'
34+
35+
def main():
36+
parser = argparse.ArgumentParser(description=
37+
'Reformat changed lines in diff. Without -i '
38+
'option just output the diff that would be '
39+
'introduced.')
40+
parser.add_argument('-i', action='store_true', default=False,
41+
help='apply edits to files instead of displaying a diff')
42+
43+
parser.add_argument('-p', metavar='NUM', default=0,
44+
help='strip the smallest prefix containing P slashes')
45+
parser.add_argument('-regex', metavar='PATTERN', default=None,
46+
help='custom pattern selecting file paths to reformat '
47+
'(case sensitive, overrides -iregex)')
48+
parser.add_argument('-iregex', metavar='PATTERN', default=r'.*\.java',
49+
help='custom pattern selecting file paths to reformat '
50+
'(case insensitive, overridden by -regex)')
51+
parser.add_argument('-v', '--verbose', action='store_true',
52+
help='be more verbose, ineffective without -i')
53+
args = parser.parse_args()
54+
55+
# Extract changed lines for each file.
56+
filename = None
57+
lines_by_file = {}
58+
59+
for line in sys.stdin:
60+
match = re.search('^\+\+\+\ (.*?/){%s}(\S*)' % args.p, line)
61+
if match:
62+
filename = match.group(2)
63+
if filename == None:
64+
continue
65+
66+
if args.regex is not None:
67+
if not re.match('^%s$' % args.regex, filename):
68+
continue
69+
else:
70+
if not re.match('^%s$' % args.iregex, filename, re.IGNORECASE):
71+
continue
72+
73+
match = re.search('^@@.*\+(\d+)(,(\d+))?', line)
74+
if match:
75+
start_line = int(match.group(1))
76+
line_count = 1
77+
if match.group(3):
78+
line_count = int(match.group(3))
79+
if line_count == 0:
80+
continue
81+
end_line = start_line + line_count - 1;
82+
lines_by_file.setdefault(filename, []).extend(
83+
['-lines', str(start_line) + ':' + str(end_line)])
84+
85+
# Reformat files containing changes in place.
86+
for filename, lines in lines_by_file.iteritems():
87+
if args.i and args.verbose:
88+
print 'Formatting', filename
89+
command = [binary]
90+
if args.i:
91+
command.append('-i')
92+
command.extend(lines)
93+
command.append(filename)
94+
p = subprocess.Popen(command, stdout=subprocess.PIPE,
95+
stderr=None, stdin=subprocess.PIPE)
96+
stdout, stderr = p.communicate()
97+
if p.returncode != 0:
98+
sys.exit(p.returncode);
99+
100+
if not args.i:
101+
with open(filename) as f:
102+
code = f.readlines()
103+
formatted_code = StringIO.StringIO(stdout).readlines()
104+
diff = difflib.unified_diff(code, formatted_code,
105+
filename, filename,
106+
'(before formatting)', '(after formatting)')
107+
diff_string = string.join(diff, '')
108+
if len(diff_string) > 0:
109+
sys.stdout.write(diff_string)
110+
111+
if __name__ == '__main__':
112+
main()

0 commit comments

Comments
 (0)