1 # Copyright 2013 The Chromium Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file.
5 """Script that is used by PRESUBMIT.py to run style checks on Java files."""
12 CHROMIUM_SRC
= os
.path
.normpath(
13 os
.path
.join(os
.path
.dirname(__file__
),
14 os
.pardir
, os
.pardir
, os
.pardir
))
15 CHECKSTYLE_ROOT
= os
.path
.join(CHROMIUM_SRC
, 'third_party', 'checkstyle',
16 'checkstyle-6.5-all.jar')
19 def RunCheckstyle(input_api
, output_api
, style_file
, black_list
=None):
20 if not os
.path
.exists(style_file
):
21 file_error
= (' Java checkstyle configuration file is missing: '
23 return [output_api
.PresubmitError(file_error
)]
25 # Filter out non-Java files and files that were deleted.
26 java_files
= [x
.AbsoluteLocalPath() for x
in input_api
.AffectedSourceFiles(
27 lambda f
: input_api
.FilterSourceFile(f
, black_list
=black_list
))
28 if os
.path
.splitext(x
.LocalPath())[1] == '.java']
33 checkstyle_env
= os
.environ
.copy()
34 checkstyle_env
['JAVA_CMD'] = 'java'
36 check
= subprocess
.Popen(['java', '-cp',
38 'com.puppycrawl.tools.checkstyle.Main', '-c',
39 style_file
, '-f', 'xml'] + java_files
,
40 stdout
=subprocess
.PIPE
, env
=checkstyle_env
)
41 stdout
, _
= check
.communicate()
44 if e
.errno
== errno
.ENOENT
:
45 install_error
= (' checkstyle is not installed. Please run '
46 'build/install-build-deps-android.sh')
47 return [output_api
.PresubmitPromptWarning(install_error
)]
52 local_path
= input_api
.PresubmitLocalPath()
53 root
= xml
.dom
.minidom
.parseString(stdout
)
54 for fileElement
in root
.getElementsByTagName('file'):
55 fileName
= fileElement
.attributes
['name'].value
56 fileName
= os
.path
.relpath(fileName
, local_path
)
57 errors
= fileElement
.getElementsByTagName('error')
59 line
= error
.attributes
['line'].value
61 if error
.hasAttribute('column'):
62 column
= '%s:' % (error
.attributes
['column'].value
)
63 message
= error
.attributes
['message'].value
64 result
= ' %s:%s:%s %s' % (fileName
, line
, column
, message
)
66 severity
= error
.attributes
['severity'].value
67 if severity
== 'error':
68 result_errors
.append(result
)
69 elif severity
== 'warning':
70 result_warnings
.append(result
)
74 result
.append(output_api
.PresubmitPromptWarning('\n'.join(result_warnings
)))
76 result
.append(output_api
.PresubmitError('\n'.join(result_errors
)))