blob: 2efe9f856fb9611d3124912055940128df2687a9 [file] [log] [blame]
Ben Murdoch097c5b22016-05-18 11:27:45 +01001#!/usr/bin/env python
2#
3# Copyright (c) 2013 The Chromium Authors. All rights reserved.
4# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6
7"""Runs Android's lint tool."""
8
9
10import argparse
11import os
12import re
13import sys
14import traceback
15from xml.dom import minidom
16
17from util import build_utils
18
19_LINT_MD_URL = 'https://chromium.googlesource.com/chromium/src/+/master/build/android/docs/lint.md' # pylint: disable=line-too-long
20_SRC_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__),
21 '..', '..', '..'))
22
23
24def _OnStaleMd5(lint_path, config_path, processed_config_path,
25 manifest_path, result_path, product_dir, sources, jar_path,
26 cache_dir, android_sdk_version, resource_dir=None,
27 classpath=None, can_fail_build=False, silent=False):
28 def _RelativizePath(path):
29 """Returns relative path to top-level src dir.
30
31 Args:
32 path: A path relative to cwd.
33 """
34 return os.path.relpath(os.path.abspath(path), _SRC_ROOT)
35
36 def _ProcessConfigFile():
37 if not config_path or not processed_config_path:
38 return
39 if not build_utils.IsTimeStale(processed_config_path, [config_path]):
40 return
41
42 with open(config_path, 'rb') as f:
43 content = f.read().replace(
44 'PRODUCT_DIR', _RelativizePath(product_dir))
45
46 with open(processed_config_path, 'wb') as f:
47 f.write(content)
48
49 def _ProcessResultFile():
50 with open(result_path, 'rb') as f:
51 content = f.read().replace(
52 _RelativizePath(product_dir), 'PRODUCT_DIR')
53
54 with open(result_path, 'wb') as f:
55 f.write(content)
56
57 def _ParseAndShowResultFile():
58 dom = minidom.parse(result_path)
59 issues = dom.getElementsByTagName('issue')
60 if not silent:
61 print >> sys.stderr
62 for issue in issues:
63 issue_id = issue.attributes['id'].value
64 message = issue.attributes['message'].value
65 location_elem = issue.getElementsByTagName('location')[0]
66 path = location_elem.attributes['file'].value
67 line = location_elem.getAttribute('line')
68 if line:
69 error = '%s:%s %s: %s [warning]' % (path, line, message, issue_id)
70 else:
71 # Issues in class files don't have a line number.
72 error = '%s %s: %s [warning]' % (path, message, issue_id)
73 print >> sys.stderr, error.encode('utf-8')
74 for attr in ['errorLine1', 'errorLine2']:
75 error_line = issue.getAttribute(attr)
76 if error_line:
77 print >> sys.stderr, error_line.encode('utf-8')
78 return len(issues)
79
80 with build_utils.TempDir() as temp_dir:
81 _ProcessConfigFile()
82
83 cmd = [
84 _RelativizePath(lint_path), '-Werror', '--exitcode', '--showall',
85 '--xml', _RelativizePath(result_path),
86 ]
87 if jar_path:
88 # --classpath is just for .class files for this one target.
89 cmd.extend(['--classpath', _RelativizePath(jar_path)])
90 if processed_config_path:
91 cmd.extend(['--config', _RelativizePath(processed_config_path)])
92 if resource_dir:
93 cmd.extend(['--resources', _RelativizePath(resource_dir)])
94 if classpath:
95 # --libraries is the classpath (excluding active target).
96 cp = ':'.join(_RelativizePath(p) for p in classpath)
97 cmd.extend(['--libraries', cp])
98
99 # There may be multiple source files with the same basename (but in
100 # different directories). It is difficult to determine what part of the path
101 # corresponds to the java package, and so instead just link the source files
102 # into temporary directories (creating a new one whenever there is a name
103 # conflict).
104 src_dirs = []
105 def NewSourceDir():
106 new_dir = os.path.join(temp_dir, str(len(src_dirs)))
107 os.mkdir(new_dir)
108 src_dirs.append(new_dir)
109 return new_dir
110
111 def PathInDir(d, src):
112 return os.path.join(d, os.path.basename(src))
113
114 for src in sources:
115 src_dir = None
116 for d in src_dirs:
117 if not os.path.exists(PathInDir(d, src)):
118 src_dir = d
119 break
120 if not src_dir:
121 src_dir = NewSourceDir()
122 cmd.extend(['--sources', _RelativizePath(src_dir)])
123 os.symlink(os.path.abspath(src), PathInDir(src_dir, src))
124
125 project_dir = NewSourceDir()
126 if android_sdk_version:
127 # Create dummy project.properies file in a temporary "project" directory.
128 # It is the only way to add Android SDK to the Lint's classpath. Proper
129 # classpath is necessary for most source-level checks.
130 with open(os.path.join(project_dir, 'project.properties'), 'w') \
131 as propfile:
132 print >> propfile, 'target=android-{}'.format(android_sdk_version)
133
134 # Put the manifest in a temporary directory in order to avoid lint detecting
135 # sibling res/ and src/ directories (which should be pass explicitly if they
136 # are to be included).
137 if manifest_path:
138 os.symlink(os.path.abspath(manifest_path),
139 PathInDir(project_dir, manifest_path))
140 cmd.append(project_dir)
141
142 if os.path.exists(result_path):
143 os.remove(result_path)
144
145 env = {}
146 stderr_filter = None
147 if cache_dir:
148 env['_JAVA_OPTIONS'] = '-Duser.home=%s' % _RelativizePath(cache_dir)
149 # When _JAVA_OPTIONS is set, java prints to stderr:
150 # Picked up _JAVA_OPTIONS: ...
151 #
152 # We drop all lines that contain _JAVA_OPTIONS from the output
153 stderr_filter = lambda l: re.sub(r'.*_JAVA_OPTIONS.*\n?', '', l)
154
155 try:
156 build_utils.CheckOutput(cmd, cwd=_SRC_ROOT, env=env or None,
157 stderr_filter=stderr_filter)
158 except build_utils.CalledProcessError:
159 # There is a problem with lint usage
160 if not os.path.exists(result_path):
161 raise
162
163 # Sometimes produces empty (almost) files:
164 if os.path.getsize(result_path) < 10:
165 if can_fail_build:
166 raise
167 elif not silent:
168 traceback.print_exc()
169 return
170
171 # There are actual lint issues
172 try:
173 num_issues = _ParseAndShowResultFile()
174 except Exception: # pylint: disable=broad-except
175 if not silent:
176 print 'Lint created unparseable xml file...'
177 print 'File contents:'
178 with open(result_path) as f:
179 print f.read()
180 if not can_fail_build:
181 return
182
183 if can_fail_build and not silent:
184 traceback.print_exc()
185
186 # There are actual lint issues
187 try:
188 num_issues = _ParseAndShowResultFile()
189 except Exception: # pylint: disable=broad-except
190 if not silent:
191 print 'Lint created unparseable xml file...'
192 print 'File contents:'
193 with open(result_path) as f:
194 print f.read()
195 raise
196
197 _ProcessResultFile()
198 msg = ('\nLint found %d new issues.\n'
199 ' - For full explanation, please refer to %s\n'
200 ' - For more information about lint and how to fix lint issues,'
201 ' please refer to %s\n' %
202 (num_issues,
203 _RelativizePath(result_path),
204 _LINT_MD_URL))
205 if not silent:
206 print >> sys.stderr, msg
207 if can_fail_build:
208 raise Exception('Lint failed.')
209
210
211def main():
212 parser = argparse.ArgumentParser()
213 build_utils.AddDepfileOption(parser)
214
215 parser.add_argument('--lint-path', required=True,
216 help='Path to lint executable.')
217 parser.add_argument('--product-dir', required=True,
218 help='Path to product dir.')
219 parser.add_argument('--result-path', required=True,
220 help='Path to XML lint result file.')
221 parser.add_argument('--cache-dir', required=True,
222 help='Path to the directory in which the android cache '
223 'directory tree should be stored.')
224 parser.add_argument('--platform-xml-path', required=True,
225 help='Path to api-platforms.xml')
226 parser.add_argument('--android-sdk-version',
227 help='Version (API level) of the Android SDK used for '
228 'building.')
229 parser.add_argument('--create-cache', action='store_true',
230 help='Mark the lint cache file as an output rather than '
231 'an input.')
232 parser.add_argument('--can-fail-build', action='store_true',
233 help='If set, script will exit with nonzero exit status'
234 ' if lint errors are present')
235 parser.add_argument('--config-path',
236 help='Path to lint suppressions file.')
237 parser.add_argument('--enable', action='store_true',
238 help='Run lint instead of just touching stamp.')
239 parser.add_argument('--jar-path',
240 help='Jar file containing class files.')
241 parser.add_argument('--java-files',
242 help='Paths to java files.')
243 parser.add_argument('--manifest-path',
244 help='Path to AndroidManifest.xml')
245 parser.add_argument('--classpath', default=[], action='append',
246 help='GYP-list of classpath .jar files')
247 parser.add_argument('--processed-config-path',
248 help='Path to processed lint suppressions file.')
249 parser.add_argument('--resource-dir',
250 help='Path to resource dir.')
251 parser.add_argument('--silent', action='store_true',
252 help='If set, script will not log anything.')
253 parser.add_argument('--src-dirs',
254 help='Directories containing java files.')
255 parser.add_argument('--stamp',
256 help='Path to touch on success.')
257
258 args = parser.parse_args(build_utils.ExpandFileArgs(sys.argv[1:]))
259
260 if args.enable:
261 sources = []
262 if args.src_dirs:
263 src_dirs = build_utils.ParseGypList(args.src_dirs)
264 sources = build_utils.FindInDirectories(src_dirs, '*.java')
265 elif args.java_files:
266 sources = build_utils.ParseGypList(args.java_files)
267
268 if args.config_path and not args.processed_config_path:
269 parser.error('--config-path specified without --processed-config-path')
270 elif args.processed_config_path and not args.config_path:
271 parser.error('--processed-config-path specified without --config-path')
272
273 input_paths = [
274 args.lint_path,
275 args.platform_xml_path,
276 ]
277 if args.config_path:
278 input_paths.append(args.config_path)
279 if args.jar_path:
280 input_paths.append(args.jar_path)
281 if args.manifest_path:
282 input_paths.append(args.manifest_path)
283 if args.resource_dir:
284 input_paths.extend(build_utils.FindInDirectory(args.resource_dir, '*'))
285 if sources:
286 input_paths.extend(sources)
287 classpath = []
288 for gyp_list in args.classpath:
289 classpath.extend(build_utils.ParseGypList(gyp_list))
290 input_paths.extend(classpath)
291
292 input_strings = []
293 if args.android_sdk_version:
294 input_strings.append(args.android_sdk_version)
295 if args.processed_config_path:
296 input_strings.append(args.processed_config_path)
297
298 output_paths = [ args.result_path ]
299
300 build_utils.CallAndWriteDepfileIfStale(
301 lambda: _OnStaleMd5(args.lint_path,
302 args.config_path,
303 args.processed_config_path,
304 args.manifest_path, args.result_path,
305 args.product_dir, sources,
306 args.jar_path,
307 args.cache_dir,
308 args.android_sdk_version,
309 resource_dir=args.resource_dir,
310 classpath=classpath,
311 can_fail_build=args.can_fail_build,
312 silent=args.silent),
313 args,
314 input_paths=input_paths,
315 input_strings=input_strings,
316 output_paths=output_paths,
317 depfile_deps=classpath)
318
319
320if __name__ == '__main__':
321 sys.exit(main())