blob: 65a6cbaf9456fbeb284bde711b76396a33bd3807 [file] [log] [blame]
[email protected]a18130a2012-01-03 17:52:081# Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]ca8d1982009-02-19 16:33:122# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5"""Top-level presubmit script for Chromium.
6
[email protected]f1293792009-07-31 18:09:567See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
[email protected]50d7d721e2009-11-15 17:56:188for more details about the presubmit API built into gcl.
[email protected]ca8d1982009-02-19 16:33:129"""
10
[email protected]eea609a2011-11-18 13:10:1211
[email protected]9d16ad12011-12-14 20:49:4712import re
[email protected]55f9f382012-07-31 11:02:1813import sys
[email protected]9d16ad12011-12-14 20:49:4714
15
[email protected]379e7dd2010-01-28 17:39:2116_EXCLUDED_PATHS = (
[email protected]3e4eb112011-01-18 03:29:5417 r"^breakpad[\\\/].*",
[email protected]40d1dbb2012-10-26 07:18:0018 r"^native_client_sdk[\\\/]src[\\\/]build_tools[\\\/]make_rules.py",
19 r"^native_client_sdk[\\\/]src[\\\/]build_tools[\\\/]make_simple.py",
[email protected]8886ffcb2013-02-12 04:56:2820 r"^native_client_sdk[\\\/]src[\\\/]tools[\\\/].*.mk",
[email protected]a18130a2012-01-03 17:52:0821 r"^net[\\\/]tools[\\\/]spdyshark[\\\/].*",
[email protected]3e4eb112011-01-18 03:29:5422 r"^skia[\\\/].*",
23 r"^v8[\\\/].*",
24 r".*MakeFile$",
[email protected]1084ccc2012-03-14 03:22:5325 r".+_autogen\.h$",
[email protected]ce145c02012-09-06 09:49:3426 r".+[\\\/]pnacl_shim\.c$",
[email protected]e07b6ac72013-08-20 00:30:4227 r"^gpu[\\\/]config[\\\/].*_list_json\.cc$",
[email protected]d2600602014-02-19 00:09:1928 r"^chrome[\\\/]browser[\\\/]resources[\\\/]pdf[\\\/]index.js"
[email protected]4306417642009-06-11 00:33:4029)
[email protected]ca8d1982009-02-19 16:33:1230
jochen9ea8fdbc2014-09-25 13:21:3531# The NetscapePlugIn library is excluded from pan-project as it will soon
32# be deleted together with the rest of the NPAPI and it's not worthwhile to
33# update the coding style until then.
[email protected]3de922f2013-12-20 13:27:3834_TESTRUNNER_PATHS = (
[email protected]de28fed2e2014-02-01 14:36:3235 r"^content[\\\/]shell[\\\/]tools[\\\/]plugin[\\\/].*",
[email protected]3de922f2013-12-20 13:27:3836)
37
[email protected]06e6d0ff2012-12-11 01:36:4438# Fragment of a regular expression that matches C++ and Objective-C++
39# implementation files.
40_IMPLEMENTATION_EXTENSIONS = r'\.(cc|cpp|cxx|mm)$'
41
42# Regular expression that matches code only used for test binaries
43# (best effort).
44_TEST_CODE_EXCLUDED_PATHS = (
joaodasilva718f87672014-08-30 09:25:4945 r'.*[\\\/](fake_|test_|mock_).+%s' % _IMPLEMENTATION_EXTENSIONS,
[email protected]06e6d0ff2012-12-11 01:36:4446 r'.+_test_(base|support|util)%s' % _IMPLEMENTATION_EXTENSIONS,
[email protected]6e04f8c2014-01-29 18:08:3247 r'.+_(api|browser|kif|perf|pixel|unit|ui)?test(_[a-z]+)?%s' %
[email protected]e2d7e6f2013-04-23 12:57:1248 _IMPLEMENTATION_EXTENSIONS,
[email protected]06e6d0ff2012-12-11 01:36:4449 r'.+profile_sync_service_harness%s' % _IMPLEMENTATION_EXTENSIONS,
joaodasilva718f87672014-08-30 09:25:4950 r'.*[\\\/](test|tool(s)?)[\\\/].*',
[email protected]ef070cc2013-05-03 11:53:0551 # content_shell is used for running layout tests.
joaodasilva718f87672014-08-30 09:25:4952 r'content[\\\/]shell[\\\/].*',
[email protected]06e6d0ff2012-12-11 01:36:4453 # At request of folks maintaining this folder.
joaodasilva718f87672014-08-30 09:25:4954 r'chrome[\\\/]browser[\\\/]automation[\\\/].*',
[email protected]7b054982013-11-27 00:44:4755 # Non-production example code.
joaodasilva718f87672014-08-30 09:25:4956 r'mojo[\\\/]examples[\\\/].*',
[email protected]8176de12014-06-20 19:07:0857 # Launcher for running iOS tests on the simulator.
joaodasilva718f87672014-08-30 09:25:4958 r'testing[\\\/]iossim[\\\/]iossim\.mm$',
[email protected]06e6d0ff2012-12-11 01:36:4459)
[email protected]ca8d1982009-02-19 16:33:1260
[email protected]eea609a2011-11-18 13:10:1261_TEST_ONLY_WARNING = (
62 'You might be calling functions intended only for testing from\n'
63 'production code. It is OK to ignore this warning if you know what\n'
64 'you are doing, as the heuristics used to detect the situation are\n'
[email protected]b0149772014-03-27 16:47:5865 'not perfect. The commit queue will not block on this warning.')
[email protected]eea609a2011-11-18 13:10:1266
67
[email protected]cf9b78f2012-11-14 11:40:2868_INCLUDE_ORDER_WARNING = (
69 'Your #include order seems to be broken. Send mail to\n'
70 '[email protected] if this is not the case.')
71
72
[email protected]127f18ec2012-06-16 05:05:5973_BANNED_OBJC_FUNCTIONS = (
74 (
75 'addTrackingRect:',
[email protected]23e6cbc2012-06-16 18:51:2076 (
77 'The use of -[NSView addTrackingRect:owner:userData:assumeInside:] is'
[email protected]127f18ec2012-06-16 05:05:5978 'prohibited. Please use CrTrackingArea instead.',
79 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
80 ),
81 False,
82 ),
83 (
[email protected]eaae1972014-04-16 04:17:2684 r'/NSTrackingArea\W',
[email protected]23e6cbc2012-06-16 18:51:2085 (
86 'The use of NSTrackingAreas is prohibited. Please use CrTrackingArea',
[email protected]127f18ec2012-06-16 05:05:5987 'instead.',
88 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
89 ),
90 False,
91 ),
92 (
93 'convertPointFromBase:',
[email protected]23e6cbc2012-06-16 18:51:2094 (
95 'The use of -[NSView convertPointFromBase:] is almost certainly wrong.',
[email protected]127f18ec2012-06-16 05:05:5996 'Please use |convertPoint:(point) fromView:nil| instead.',
97 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
98 ),
99 True,
100 ),
101 (
102 'convertPointToBase:',
[email protected]23e6cbc2012-06-16 18:51:20103 (
104 'The use of -[NSView convertPointToBase:] is almost certainly wrong.',
[email protected]127f18ec2012-06-16 05:05:59105 'Please use |convertPoint:(point) toView:nil| instead.',
106 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
107 ),
108 True,
109 ),
110 (
111 'convertRectFromBase:',
[email protected]23e6cbc2012-06-16 18:51:20112 (
113 'The use of -[NSView convertRectFromBase:] is almost certainly wrong.',
[email protected]127f18ec2012-06-16 05:05:59114 'Please use |convertRect:(point) fromView:nil| instead.',
115 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
116 ),
117 True,
118 ),
119 (
120 'convertRectToBase:',
[email protected]23e6cbc2012-06-16 18:51:20121 (
122 'The use of -[NSView convertRectToBase:] is almost certainly wrong.',
[email protected]127f18ec2012-06-16 05:05:59123 'Please use |convertRect:(point) toView:nil| instead.',
124 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
125 ),
126 True,
127 ),
128 (
129 'convertSizeFromBase:',
[email protected]23e6cbc2012-06-16 18:51:20130 (
131 'The use of -[NSView convertSizeFromBase:] is almost certainly wrong.',
[email protected]127f18ec2012-06-16 05:05:59132 'Please use |convertSize:(point) fromView:nil| instead.',
133 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
134 ),
135 True,
136 ),
137 (
138 'convertSizeToBase:',
[email protected]23e6cbc2012-06-16 18:51:20139 (
140 'The use of -[NSView convertSizeToBase:] is almost certainly wrong.',
[email protected]127f18ec2012-06-16 05:05:59141 'Please use |convertSize:(point) toView:nil| instead.',
142 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
143 ),
144 True,
145 ),
146)
147
148
149_BANNED_CPP_FUNCTIONS = (
[email protected]23e6cbc2012-06-16 18:51:20150 # Make sure that gtest's FRIEND_TEST() macro is not used; the
151 # FRIEND_TEST_ALL_PREFIXES() macro from base/gtest_prod_util.h should be
[email protected]e00ccc92012-11-01 17:32:30152 # used instead since that allows for FLAKY_ and DISABLED_ prefixes.
[email protected]23e6cbc2012-06-16 18:51:20153 (
154 'FRIEND_TEST(',
155 (
[email protected]e3c945502012-06-26 20:01:49156 'Chromium code should not use gtest\'s FRIEND_TEST() macro. Include',
[email protected]23e6cbc2012-06-16 18:51:20157 'base/gtest_prod_util.h and use FRIEND_TEST_ALL_PREFIXES() instead.',
158 ),
159 False,
[email protected]7345da02012-11-27 14:31:49160 (),
[email protected]23e6cbc2012-06-16 18:51:20161 ),
162 (
163 'ScopedAllowIO',
164 (
[email protected]e3c945502012-06-26 20:01:49165 'New code should not use ScopedAllowIO. Post a task to the blocking',
166 'pool or the FILE thread instead.',
[email protected]23e6cbc2012-06-16 18:51:20167 ),
[email protected]e3c945502012-06-26 20:01:49168 True,
[email protected]7345da02012-11-27 14:31:49169 (
thestig75844fdb2014-09-09 19:47:10170 r"^base[\\\/]process[\\\/]process_metrics_linux\.cc$",
[email protected]b01b9e22014-06-03 22:20:19171 r"^chrome[\\\/]browser[\\\/]chromeos[\\\/]boot_times_loader\.cc$",
philipj3f9d5bde2014-08-28 14:09:09172 r"^components[\\\/]crash[\\\/]app[\\\/]breakpad_mac\.mm$",
[email protected]de7d61ff2013-08-20 11:30:41173 r"^content[\\\/]shell[\\\/]browser[\\\/]shell_browser_main\.cc$",
174 r"^content[\\\/]shell[\\\/]browser[\\\/]shell_message_filter\.cc$",
[email protected]ac1df702014-03-21 20:45:27175 r"^mojo[\\\/]system[\\\/]raw_shared_buffer_posix\.cc$",
[email protected]398ad132013-04-02 15:11:01176 r"^net[\\\/]disk_cache[\\\/]cache_util\.cc$",
[email protected]1f52a572014-05-12 23:21:54177 r"^net[\\\/]url_request[\\\/]test_url_fetcher_factory\.cc$",
[email protected]7345da02012-11-27 14:31:49178 ),
[email protected]23e6cbc2012-06-16 18:51:20179 ),
[email protected]52657f62013-05-20 05:30:31180 (
181 'SkRefPtr',
182 (
183 'The use of SkRefPtr is prohibited. ',
184 'Please use skia::RefPtr instead.'
185 ),
186 True,
187 (),
188 ),
189 (
190 'SkAutoRef',
191 (
192 'The indirect use of SkRefPtr via SkAutoRef is prohibited. ',
193 'Please use skia::RefPtr instead.'
194 ),
195 True,
196 (),
197 ),
198 (
199 'SkAutoTUnref',
200 (
201 'The use of SkAutoTUnref is dangerous because it implicitly ',
202 'converts to a raw pointer. Please use skia::RefPtr instead.'
203 ),
204 True,
205 (),
206 ),
207 (
208 'SkAutoUnref',
209 (
210 'The indirect use of SkAutoTUnref through SkAutoUnref is dangerous ',
211 'because it implicitly converts to a raw pointer. ',
212 'Please use skia::RefPtr instead.'
213 ),
214 True,
215 (),
216 ),
[email protected]d89eec82013-12-03 14:10:59217 (
218 r'/HANDLE_EINTR\(.*close',
219 (
220 'HANDLE_EINTR(close) is invalid. If close fails with EINTR, the file',
221 'descriptor will be closed, and it is incorrect to retry the close.',
222 'Either call close directly and ignore its return value, or wrap close',
223 'in IGNORE_EINTR to use its return value. See http://crbug.com/269623'
224 ),
225 True,
226 (),
227 ),
228 (
229 r'/IGNORE_EINTR\((?!.*close)',
230 (
231 'IGNORE_EINTR is only valid when wrapping close. To wrap other system',
232 'calls, use HANDLE_EINTR. See http://crbug.com/269623',
233 ),
234 True,
235 (
236 # Files that #define IGNORE_EINTR.
237 r'^base[\\\/]posix[\\\/]eintr_wrapper\.h$',
238 r'^ppapi[\\\/]tests[\\\/]test_broker\.cc$',
239 ),
240 ),
[email protected]ec5b3f02014-04-04 18:43:43241 (
242 r'/v8::Extension\(',
243 (
244 'Do not introduce new v8::Extensions into the code base, use',
245 'gin::Wrappable instead. See http://crbug.com/334679',
246 ),
247 True,
[email protected]f55c90ee62014-04-12 00:50:03248 (
joaodasilva718f87672014-08-30 09:25:49249 r'extensions[\\\/]renderer[\\\/]safe_builtins\.*',
[email protected]f55c90ee62014-04-12 00:50:03250 ),
[email protected]ec5b3f02014-04-04 18:43:43251 ),
[email protected]127f18ec2012-06-16 05:05:59252)
253
mlamouria82272622014-09-16 18:45:04254_IPC_ENUM_TRAITS_DEPRECATED = (
255 'You are using IPC_ENUM_TRAITS() in your code. It has been deprecated.\n'
256 'See http://www.chromium.org/Home/chromium-security/education/security-tips-for-ipc')
257
[email protected]127f18ec2012-06-16 05:05:59258
[email protected]b00342e7f2013-03-26 16:21:54259_VALID_OS_MACROS = (
260 # Please keep sorted.
261 'OS_ANDROID',
[email protected]f4440b42014-03-19 05:47:01262 'OS_ANDROID_HOST',
[email protected]b00342e7f2013-03-26 16:21:54263 'OS_BSD',
264 'OS_CAT', # For testing.
265 'OS_CHROMEOS',
266 'OS_FREEBSD',
267 'OS_IOS',
268 'OS_LINUX',
269 'OS_MACOSX',
270 'OS_NACL',
271 'OS_OPENBSD',
272 'OS_POSIX',
[email protected]eda7afa12014-02-06 12:27:37273 'OS_QNX',
[email protected]b00342e7f2013-03-26 16:21:54274 'OS_SOLARIS',
[email protected]b00342e7f2013-03-26 16:21:54275 'OS_WIN',
276)
277
278
[email protected]55459852011-08-10 15:17:19279def _CheckNoProductionCodeUsingTestOnlyFunctions(input_api, output_api):
280 """Attempts to prevent use of functions intended only for testing in
281 non-testing code. For now this is just a best-effort implementation
282 that ignores header files and may have some false positives. A
283 better implementation would probably need a proper C++ parser.
284 """
285 # We only scan .cc files and the like, as the declaration of
286 # for-testing functions in header files are hard to distinguish from
287 # calls to such functions without a proper C++ parser.
[email protected]06e6d0ff2012-12-11 01:36:44288 file_inclusion_pattern = r'.+%s' % _IMPLEMENTATION_EXTENSIONS
[email protected]55459852011-08-10 15:17:19289
[email protected]23501822014-05-14 02:06:09290 base_function_pattern = r'[ :]test::[^\s]+|ForTest(ing)?|for_test(ing)?'
[email protected]55459852011-08-10 15:17:19291 inclusion_pattern = input_api.re.compile(r'(%s)\s*\(' % base_function_pattern)
[email protected]23501822014-05-14 02:06:09292 comment_pattern = input_api.re.compile(r'//.*(%s)' % base_function_pattern)
[email protected]55459852011-08-10 15:17:19293 exclusion_pattern = input_api.re.compile(
294 r'::[A-Za-z0-9_]+(%s)|(%s)[^;]+\{' % (
295 base_function_pattern, base_function_pattern))
296
297 def FilterFile(affected_file):
[email protected]06e6d0ff2012-12-11 01:36:44298 black_list = (_EXCLUDED_PATHS +
299 _TEST_CODE_EXCLUDED_PATHS +
300 input_api.DEFAULT_BLACK_LIST)
[email protected]55459852011-08-10 15:17:19301 return input_api.FilterSourceFile(
302 affected_file,
303 white_list=(file_inclusion_pattern, ),
304 black_list=black_list)
305
306 problems = []
307 for f in input_api.AffectedSourceFiles(FilterFile):
308 local_path = f.LocalPath()
[email protected]825d27182014-01-02 21:24:24309 for line_number, line in f.ChangedContents():
[email protected]2fdd1f362013-01-16 03:56:03310 if (inclusion_pattern.search(line) and
[email protected]de4f7d22013-05-23 14:27:46311 not comment_pattern.search(line) and
[email protected]2fdd1f362013-01-16 03:56:03312 not exclusion_pattern.search(line)):
[email protected]55459852011-08-10 15:17:19313 problems.append(
[email protected]2fdd1f362013-01-16 03:56:03314 '%s:%d\n %s' % (local_path, line_number, line.strip()))
[email protected]55459852011-08-10 15:17:19315
316 if problems:
[email protected]f7051d52013-04-02 18:31:42317 return [output_api.PresubmitPromptOrNotify(_TEST_ONLY_WARNING, problems)]
[email protected]2fdd1f362013-01-16 03:56:03318 else:
319 return []
[email protected]55459852011-08-10 15:17:19320
321
[email protected]10689ca2011-09-02 02:31:54322def _CheckNoIOStreamInHeaders(input_api, output_api):
323 """Checks to make sure no .h files include <iostream>."""
324 files = []
325 pattern = input_api.re.compile(r'^#include\s*<iostream>',
326 input_api.re.MULTILINE)
327 for f in input_api.AffectedSourceFiles(input_api.FilterSourceFile):
328 if not f.LocalPath().endswith('.h'):
329 continue
330 contents = input_api.ReadFile(f)
331 if pattern.search(contents):
332 files.append(f)
333
334 if len(files):
335 return [ output_api.PresubmitError(
[email protected]6c063c62012-07-11 19:11:06336 'Do not #include <iostream> in header files, since it inserts static '
337 'initialization into every file including the header. Instead, '
[email protected]10689ca2011-09-02 02:31:54338 '#include <ostream>. See http://crbug.com/94794',
339 files) ]
340 return []
341
342
[email protected]72df4e782012-06-21 16:28:18343def _CheckNoUNIT_TESTInSourceFiles(input_api, output_api):
344 """Checks to make sure no source files use UNIT_TEST"""
345 problems = []
346 for f in input_api.AffectedFiles():
347 if (not f.LocalPath().endswith(('.cc', '.mm'))):
348 continue
349
350 for line_num, line in f.ChangedContents():
[email protected]549f86a2013-11-19 13:00:04351 if 'UNIT_TEST ' in line or line.endswith('UNIT_TEST'):
[email protected]72df4e782012-06-21 16:28:18352 problems.append(' %s:%d' % (f.LocalPath(), line_num))
353
354 if not problems:
355 return []
356 return [output_api.PresubmitPromptWarning('UNIT_TEST is only for headers.\n' +
357 '\n'.join(problems))]
358
359
[email protected]8ea5d4b2011-09-13 21:49:22360def _CheckNoNewWStrings(input_api, output_api):
361 """Checks to make sure we don't introduce use of wstrings."""
[email protected]55463aa62011-10-12 00:48:27362 problems = []
[email protected]8ea5d4b2011-09-13 21:49:22363 for f in input_api.AffectedFiles():
[email protected]b5c24292011-11-28 14:38:20364 if (not f.LocalPath().endswith(('.cc', '.h')) or
[email protected]24be83c2013-08-29 23:01:23365 f.LocalPath().endswith(('test.cc', '_win.cc', '_win.h'))):
[email protected]b5c24292011-11-28 14:38:20366 continue
[email protected]8ea5d4b2011-09-13 21:49:22367
[email protected]a11dbe9b2012-08-07 01:32:58368 allowWString = False
[email protected]b5c24292011-11-28 14:38:20369 for line_num, line in f.ChangedContents():
[email protected]a11dbe9b2012-08-07 01:32:58370 if 'presubmit: allow wstring' in line:
371 allowWString = True
372 elif not allowWString and 'wstring' in line:
[email protected]55463aa62011-10-12 00:48:27373 problems.append(' %s:%d' % (f.LocalPath(), line_num))
[email protected]a11dbe9b2012-08-07 01:32:58374 allowWString = False
375 else:
376 allowWString = False
[email protected]8ea5d4b2011-09-13 21:49:22377
[email protected]55463aa62011-10-12 00:48:27378 if not problems:
379 return []
380 return [output_api.PresubmitPromptWarning('New code should not use wstrings.'
[email protected]a11dbe9b2012-08-07 01:32:58381 ' If you are calling a cross-platform API that accepts a wstring, '
382 'fix the API.\n' +
[email protected]55463aa62011-10-12 00:48:27383 '\n'.join(problems))]
[email protected]8ea5d4b2011-09-13 21:49:22384
385
[email protected]2a8ac9c2011-10-19 17:20:44386def _CheckNoDEPSGIT(input_api, output_api):
387 """Make sure .DEPS.git is never modified manually."""
388 if any(f.LocalPath().endswith('.DEPS.git') for f in
389 input_api.AffectedFiles()):
390 return [output_api.PresubmitError(
391 'Never commit changes to .DEPS.git. This file is maintained by an\n'
392 'automated system based on what\'s in DEPS and your changes will be\n'
393 'overwritten.\n'
[email protected]cb706912014-06-28 20:46:34394 'See https://sites.google.com/a/chromium.org/dev/developers/how-tos/get-the-code#Rolling_DEPS\n'
[email protected]2a8ac9c2011-10-19 17:20:44395 'for more information')]
396 return []
397
398
tandriief664692014-09-23 14:51:47399def _CheckValidHostsInDEPS(input_api, output_api):
400 """Checks that DEPS file deps are from allowed_hosts."""
401 # Run only if DEPS file has been modified to annoy fewer bystanders.
402 if all(f.LocalPath() != 'DEPS' for f in input_api.AffectedFiles()):
403 return []
404 # Outsource work to gclient verify
405 try:
406 input_api.subprocess.check_output(['gclient', 'verify'])
407 return []
408 except input_api.subprocess.CalledProcessError, error:
409 return [output_api.PresubmitError(
410 'DEPS file must have only git dependencies.',
411 long_text=error.output)]
412
413
[email protected]127f18ec2012-06-16 05:05:59414def _CheckNoBannedFunctions(input_api, output_api):
415 """Make sure that banned functions are not used."""
416 warnings = []
417 errors = []
418
419 file_filter = lambda f: f.LocalPath().endswith(('.mm', '.m', '.h'))
420 for f in input_api.AffectedFiles(file_filter=file_filter):
421 for line_num, line in f.ChangedContents():
422 for func_name, message, error in _BANNED_OBJC_FUNCTIONS:
[email protected]eaae1972014-04-16 04:17:26423 matched = False
424 if func_name[0:1] == '/':
425 regex = func_name[1:]
426 if input_api.re.search(regex, line):
427 matched = True
428 elif func_name in line:
429 matched = True
430 if matched:
[email protected]127f18ec2012-06-16 05:05:59431 problems = warnings;
432 if error:
433 problems = errors;
434 problems.append(' %s:%d:' % (f.LocalPath(), line_num))
435 for message_line in message:
436 problems.append(' %s' % message_line)
437
438 file_filter = lambda f: f.LocalPath().endswith(('.cc', '.mm', '.h'))
439 for f in input_api.AffectedFiles(file_filter=file_filter):
440 for line_num, line in f.ChangedContents():
[email protected]7345da02012-11-27 14:31:49441 for func_name, message, error, excluded_paths in _BANNED_CPP_FUNCTIONS:
442 def IsBlacklisted(affected_file, blacklist):
443 local_path = affected_file.LocalPath()
444 for item in blacklist:
445 if input_api.re.match(item, local_path):
446 return True
447 return False
448 if IsBlacklisted(f, excluded_paths):
449 continue
[email protected]d89eec82013-12-03 14:10:59450 matched = False
451 if func_name[0:1] == '/':
452 regex = func_name[1:]
453 if input_api.re.search(regex, line):
454 matched = True
455 elif func_name in line:
456 matched = True
457 if matched:
[email protected]127f18ec2012-06-16 05:05:59458 problems = warnings;
459 if error:
460 problems = errors;
461 problems.append(' %s:%d:' % (f.LocalPath(), line_num))
462 for message_line in message:
463 problems.append(' %s' % message_line)
464
465 result = []
466 if (warnings):
467 result.append(output_api.PresubmitPromptWarning(
468 'Banned functions were used.\n' + '\n'.join(warnings)))
469 if (errors):
470 result.append(output_api.PresubmitError(
471 'Banned functions were used.\n' + '\n'.join(errors)))
472 return result
473
474
[email protected]6c063c62012-07-11 19:11:06475def _CheckNoPragmaOnce(input_api, output_api):
476 """Make sure that banned functions are not used."""
477 files = []
478 pattern = input_api.re.compile(r'^#pragma\s+once',
479 input_api.re.MULTILINE)
480 for f in input_api.AffectedSourceFiles(input_api.FilterSourceFile):
481 if not f.LocalPath().endswith('.h'):
482 continue
483 contents = input_api.ReadFile(f)
484 if pattern.search(contents):
485 files.append(f)
486
487 if files:
488 return [output_api.PresubmitError(
489 'Do not use #pragma once in header files.\n'
490 'See http://www.chromium.org/developers/coding-style#TOC-File-headers',
491 files)]
492 return []
493
[email protected]127f18ec2012-06-16 05:05:59494
[email protected]e7479052012-09-19 00:26:12495def _CheckNoTrinaryTrueFalse(input_api, output_api):
496 """Checks to make sure we don't introduce use of foo ? true : false."""
497 problems = []
498 pattern = input_api.re.compile(r'\?\s*(true|false)\s*:\s*(true|false)')
499 for f in input_api.AffectedFiles():
500 if not f.LocalPath().endswith(('.cc', '.h', '.inl', '.m', '.mm')):
501 continue
502
503 for line_num, line in f.ChangedContents():
504 if pattern.match(line):
505 problems.append(' %s:%d' % (f.LocalPath(), line_num))
506
507 if not problems:
508 return []
509 return [output_api.PresubmitPromptWarning(
510 'Please consider avoiding the "? true : false" pattern if possible.\n' +
511 '\n'.join(problems))]
512
513
[email protected]55f9f382012-07-31 11:02:18514def _CheckUnwantedDependencies(input_api, output_api):
515 """Runs checkdeps on #include statements added in this
516 change. Breaking - rules is an error, breaking ! rules is a
517 warning.
518 """
519 # We need to wait until we have an input_api object and use this
520 # roundabout construct to import checkdeps because this file is
521 # eval-ed and thus doesn't have __file__.
522 original_sys_path = sys.path
523 try:
524 sys.path = sys.path + [input_api.os_path.join(
[email protected]5298cc982014-05-29 20:53:47525 input_api.PresubmitLocalPath(), 'buildtools', 'checkdeps')]
[email protected]55f9f382012-07-31 11:02:18526 import checkdeps
527 from cpp_checker import CppChecker
528 from rules import Rule
529 finally:
530 # Restore sys.path to what it was before.
531 sys.path = original_sys_path
532
533 added_includes = []
534 for f in input_api.AffectedFiles():
535 if not CppChecker.IsCppFile(f.LocalPath()):
536 continue
537
538 changed_lines = [line for line_num, line in f.ChangedContents()]
539 added_includes.append([f.LocalPath(), changed_lines])
540
[email protected]26385172013-05-09 23:11:35541 deps_checker = checkdeps.DepsChecker(input_api.PresubmitLocalPath())
[email protected]55f9f382012-07-31 11:02:18542
543 error_descriptions = []
544 warning_descriptions = []
545 for path, rule_type, rule_description in deps_checker.CheckAddedCppIncludes(
546 added_includes):
547 description_with_path = '%s\n %s' % (path, rule_description)
548 if rule_type == Rule.DISALLOW:
549 error_descriptions.append(description_with_path)
550 else:
551 warning_descriptions.append(description_with_path)
552
553 results = []
554 if error_descriptions:
555 results.append(output_api.PresubmitError(
556 'You added one or more #includes that violate checkdeps rules.',
557 error_descriptions))
558 if warning_descriptions:
[email protected]f7051d52013-04-02 18:31:42559 results.append(output_api.PresubmitPromptOrNotify(
[email protected]55f9f382012-07-31 11:02:18560 'You added one or more #includes of files that are temporarily\n'
561 'allowed but being removed. Can you avoid introducing the\n'
562 '#include? See relevant DEPS file(s) for details and contacts.',
563 warning_descriptions))
564 return results
565
566
[email protected]fbcafe5a2012-08-08 15:31:22567def _CheckFilePermissions(input_api, output_api):
568 """Check that all files have their permissions properly set."""
[email protected]791507202014-02-03 23:19:15569 if input_api.platform == 'win32':
570 return []
[email protected]fbcafe5a2012-08-08 15:31:22571 args = [sys.executable, 'tools/checkperms/checkperms.py', '--root',
572 input_api.change.RepositoryRoot()]
573 for f in input_api.AffectedFiles():
574 args += ['--file', f.LocalPath()]
[email protected]f0d330f2014-01-30 01:44:34575 checkperms = input_api.subprocess.Popen(args,
576 stdout=input_api.subprocess.PIPE)
577 errors = checkperms.communicate()[0].strip()
[email protected]fbcafe5a2012-08-08 15:31:22578 if errors:
[email protected]f0d330f2014-01-30 01:44:34579 return [output_api.PresubmitError('checkperms.py failed.',
580 errors.splitlines())]
581 return []
[email protected]fbcafe5a2012-08-08 15:31:22582
583
[email protected]c8278b32012-10-30 20:35:49584def _CheckNoAuraWindowPropertyHInHeaders(input_api, output_api):
585 """Makes sure we don't include ui/aura/window_property.h
586 in header files.
587 """
588 pattern = input_api.re.compile(r'^#include\s*"ui/aura/window_property.h"')
589 errors = []
590 for f in input_api.AffectedFiles():
591 if not f.LocalPath().endswith('.h'):
592 continue
593 for line_num, line in f.ChangedContents():
594 if pattern.match(line):
595 errors.append(' %s:%d' % (f.LocalPath(), line_num))
596
597 results = []
598 if errors:
599 results.append(output_api.PresubmitError(
600 'Header files should not include ui/aura/window_property.h', errors))
601 return results
602
603
[email protected]cf9b78f2012-11-14 11:40:28604def _CheckIncludeOrderForScope(scope, input_api, file_path, changed_linenums):
605 """Checks that the lines in scope occur in the right order.
606
607 1. C system files in alphabetical order
608 2. C++ system files in alphabetical order
609 3. Project's .h files
610 """
611
612 c_system_include_pattern = input_api.re.compile(r'\s*#include <.*\.h>')
613 cpp_system_include_pattern = input_api.re.compile(r'\s*#include <.*>')
614 custom_include_pattern = input_api.re.compile(r'\s*#include ".*')
615
616 C_SYSTEM_INCLUDES, CPP_SYSTEM_INCLUDES, CUSTOM_INCLUDES = range(3)
617
618 state = C_SYSTEM_INCLUDES
619
620 previous_line = ''
[email protected]728b9bb2012-11-14 20:38:57621 previous_line_num = 0
[email protected]cf9b78f2012-11-14 11:40:28622 problem_linenums = []
623 for line_num, line in scope:
624 if c_system_include_pattern.match(line):
625 if state != C_SYSTEM_INCLUDES:
[email protected]728b9bb2012-11-14 20:38:57626 problem_linenums.append((line_num, previous_line_num))
[email protected]cf9b78f2012-11-14 11:40:28627 elif previous_line and previous_line > line:
[email protected]728b9bb2012-11-14 20:38:57628 problem_linenums.append((line_num, previous_line_num))
[email protected]cf9b78f2012-11-14 11:40:28629 elif cpp_system_include_pattern.match(line):
630 if state == C_SYSTEM_INCLUDES:
631 state = CPP_SYSTEM_INCLUDES
632 elif state == CUSTOM_INCLUDES:
[email protected]728b9bb2012-11-14 20:38:57633 problem_linenums.append((line_num, previous_line_num))
[email protected]cf9b78f2012-11-14 11:40:28634 elif previous_line and previous_line > line:
[email protected]728b9bb2012-11-14 20:38:57635 problem_linenums.append((line_num, previous_line_num))
[email protected]cf9b78f2012-11-14 11:40:28636 elif custom_include_pattern.match(line):
637 if state != CUSTOM_INCLUDES:
638 state = CUSTOM_INCLUDES
639 elif previous_line and previous_line > line:
[email protected]728b9bb2012-11-14 20:38:57640 problem_linenums.append((line_num, previous_line_num))
[email protected]cf9b78f2012-11-14 11:40:28641 else:
642 problem_linenums.append(line_num)
643 previous_line = line
[email protected]728b9bb2012-11-14 20:38:57644 previous_line_num = line_num
[email protected]cf9b78f2012-11-14 11:40:28645
646 warnings = []
[email protected]728b9bb2012-11-14 20:38:57647 for (line_num, previous_line_num) in problem_linenums:
648 if line_num in changed_linenums or previous_line_num in changed_linenums:
[email protected]cf9b78f2012-11-14 11:40:28649 warnings.append(' %s:%d' % (file_path, line_num))
650 return warnings
651
652
[email protected]ac294a12012-12-06 16:38:43653def _CheckIncludeOrderInFile(input_api, f, changed_linenums):
[email protected]cf9b78f2012-11-14 11:40:28654 """Checks the #include order for the given file f."""
655
[email protected]2299dcf2012-11-15 19:56:24656 system_include_pattern = input_api.re.compile(r'\s*#include \<.*')
[email protected]23093b62013-09-20 12:16:30657 # Exclude the following includes from the check:
658 # 1) #include <.../...>, e.g., <sys/...> includes often need to appear in a
659 # specific order.
660 # 2) <atlbase.h>, "build/build_config.h"
661 excluded_include_pattern = input_api.re.compile(
662 r'\s*#include (\<.*/.*|\<atlbase\.h\>|"build/build_config.h")')
[email protected]2299dcf2012-11-15 19:56:24663 custom_include_pattern = input_api.re.compile(r'\s*#include "(?P<FILE>.*)"')
[email protected]3e83618c2013-10-09 22:32:33664 # Match the final or penultimate token if it is xxxtest so we can ignore it
665 # when considering the special first include.
666 test_file_tag_pattern = input_api.re.compile(
667 r'_[a-z]+test(?=(_[a-zA-Z0-9]+)?\.)')
[email protected]0e5c1852012-12-18 20:17:11668 if_pattern = input_api.re.compile(
669 r'\s*#\s*(if|elif|else|endif|define|undef).*')
670 # Some files need specialized order of includes; exclude such files from this
671 # check.
672 uncheckable_includes_pattern = input_api.re.compile(
673 r'\s*#include '
674 '("ipc/.*macros\.h"|<windows\.h>|".*gl.*autogen.h")\s*')
[email protected]cf9b78f2012-11-14 11:40:28675
676 contents = f.NewContents()
677 warnings = []
678 line_num = 0
679
[email protected]ac294a12012-12-06 16:38:43680 # Handle the special first include. If the first include file is
681 # some/path/file.h, the corresponding including file can be some/path/file.cc,
682 # some/other/path/file.cc, some/path/file_platform.cc, some/path/file-suffix.h
683 # etc. It's also possible that no special first include exists.
[email protected]3e83618c2013-10-09 22:32:33684 # If the included file is some/path/file_platform.h the including file could
685 # also be some/path/file_xxxtest_platform.h.
686 including_file_base_name = test_file_tag_pattern.sub(
687 '', input_api.os_path.basename(f.LocalPath()))
688
[email protected]ac294a12012-12-06 16:38:43689 for line in contents:
690 line_num += 1
691 if system_include_pattern.match(line):
692 # No special first include -> process the line again along with normal
693 # includes.
694 line_num -= 1
695 break
696 match = custom_include_pattern.match(line)
697 if match:
698 match_dict = match.groupdict()
[email protected]3e83618c2013-10-09 22:32:33699 header_basename = test_file_tag_pattern.sub(
700 '', input_api.os_path.basename(match_dict['FILE'])).replace('.h', '')
701
702 if header_basename not in including_file_base_name:
[email protected]2299dcf2012-11-15 19:56:24703 # No special first include -> process the line again along with normal
704 # includes.
705 line_num -= 1
[email protected]ac294a12012-12-06 16:38:43706 break
[email protected]cf9b78f2012-11-14 11:40:28707
708 # Split into scopes: Each region between #if and #endif is its own scope.
709 scopes = []
710 current_scope = []
711 for line in contents[line_num:]:
712 line_num += 1
[email protected]0e5c1852012-12-18 20:17:11713 if uncheckable_includes_pattern.match(line):
[email protected]4436c9e2014-01-07 23:19:54714 continue
[email protected]2309b0fa02012-11-16 12:18:27715 if if_pattern.match(line):
[email protected]cf9b78f2012-11-14 11:40:28716 scopes.append(current_scope)
717 current_scope = []
[email protected]962f117e2012-11-22 18:11:56718 elif ((system_include_pattern.match(line) or
719 custom_include_pattern.match(line)) and
720 not excluded_include_pattern.match(line)):
[email protected]cf9b78f2012-11-14 11:40:28721 current_scope.append((line_num, line))
722 scopes.append(current_scope)
723
724 for scope in scopes:
725 warnings.extend(_CheckIncludeOrderForScope(scope, input_api, f.LocalPath(),
726 changed_linenums))
727 return warnings
728
729
730def _CheckIncludeOrder(input_api, output_api):
731 """Checks that the #include order is correct.
732
733 1. The corresponding header for source files.
734 2. C system files in alphabetical order
735 3. C++ system files in alphabetical order
736 4. Project's .h files in alphabetical order
737
[email protected]ac294a12012-12-06 16:38:43738 Each region separated by #if, #elif, #else, #endif, #define and #undef follows
739 these rules separately.
[email protected]cf9b78f2012-11-14 11:40:28740 """
[email protected]e120b012014-08-15 19:08:35741 def FileFilterIncludeOrder(affected_file):
742 black_list = (_EXCLUDED_PATHS + input_api.DEFAULT_BLACK_LIST)
743 return input_api.FilterSourceFile(affected_file, black_list=black_list)
[email protected]cf9b78f2012-11-14 11:40:28744
745 warnings = []
[email protected]e120b012014-08-15 19:08:35746 for f in input_api.AffectedFiles(file_filter=FileFilterIncludeOrder):
[email protected]ac294a12012-12-06 16:38:43747 if f.LocalPath().endswith(('.cc', '.h')):
748 changed_linenums = set(line_num for line_num, _ in f.ChangedContents())
749 warnings.extend(_CheckIncludeOrderInFile(input_api, f, changed_linenums))
[email protected]cf9b78f2012-11-14 11:40:28750
751 results = []
752 if warnings:
[email protected]f7051d52013-04-02 18:31:42753 results.append(output_api.PresubmitPromptOrNotify(_INCLUDE_ORDER_WARNING,
[email protected]120cf540d2012-12-10 17:55:53754 warnings))
[email protected]cf9b78f2012-11-14 11:40:28755 return results
756
757
[email protected]70ca77752012-11-20 03:45:03758def _CheckForVersionControlConflictsInFile(input_api, f):
759 pattern = input_api.re.compile('^(?:<<<<<<<|>>>>>>>) |^=======$')
760 errors = []
761 for line_num, line in f.ChangedContents():
762 if pattern.match(line):
763 errors.append(' %s:%d %s' % (f.LocalPath(), line_num, line))
764 return errors
765
766
767def _CheckForVersionControlConflicts(input_api, output_api):
768 """Usually this is not intentional and will cause a compile failure."""
769 errors = []
770 for f in input_api.AffectedFiles():
771 errors.extend(_CheckForVersionControlConflictsInFile(input_api, f))
772
773 results = []
774 if errors:
775 results.append(output_api.PresubmitError(
776 'Version control conflict markers found, please resolve.', errors))
777 return results
778
779
[email protected]06e6d0ff2012-12-11 01:36:44780def _CheckHardcodedGoogleHostsInLowerLayers(input_api, output_api):
781 def FilterFile(affected_file):
782 """Filter function for use with input_api.AffectedSourceFiles,
783 below. This filters out everything except non-test files from
784 top-level directories that generally speaking should not hard-code
785 service URLs (e.g. src/android_webview/, src/content/ and others).
786 """
787 return input_api.FilterSourceFile(
788 affected_file,
[email protected]78bb39d62012-12-11 15:11:56789 white_list=(r'^(android_webview|base|content|net)[\\\/].*', ),
[email protected]06e6d0ff2012-12-11 01:36:44790 black_list=(_EXCLUDED_PATHS +
791 _TEST_CODE_EXCLUDED_PATHS +
792 input_api.DEFAULT_BLACK_LIST))
793
[email protected]de4f7d22013-05-23 14:27:46794 base_pattern = '"[^"]*google\.com[^"]*"'
795 comment_pattern = input_api.re.compile('//.*%s' % base_pattern)
796 pattern = input_api.re.compile(base_pattern)
[email protected]06e6d0ff2012-12-11 01:36:44797 problems = [] # items are (filename, line_number, line)
798 for f in input_api.AffectedSourceFiles(FilterFile):
799 for line_num, line in f.ChangedContents():
[email protected]de4f7d22013-05-23 14:27:46800 if not comment_pattern.search(line) and pattern.search(line):
[email protected]06e6d0ff2012-12-11 01:36:44801 problems.append((f.LocalPath(), line_num, line))
802
803 if problems:
[email protected]f7051d52013-04-02 18:31:42804 return [output_api.PresubmitPromptOrNotify(
[email protected]06e6d0ff2012-12-11 01:36:44805 'Most layers below src/chrome/ should not hardcode service URLs.\n'
[email protected]b0149772014-03-27 16:47:58806 'Are you sure this is correct?',
[email protected]06e6d0ff2012-12-11 01:36:44807 [' %s:%d: %s' % (
808 problem[0], problem[1], problem[2]) for problem in problems])]
[email protected]2fdd1f362013-01-16 03:56:03809 else:
810 return []
[email protected]06e6d0ff2012-12-11 01:36:44811
812
[email protected]d2530012013-01-25 16:39:27813def _CheckNoAbbreviationInPngFileName(input_api, output_api):
814 """Makes sure there are no abbreviations in the name of PNG files.
815 """
[email protected]4053a48e2013-01-25 21:43:04816 pattern = input_api.re.compile(r'.*_[a-z]_.*\.png$|.*_[a-z]\.png$')
[email protected]d2530012013-01-25 16:39:27817 errors = []
818 for f in input_api.AffectedFiles(include_deletes=False):
819 if pattern.match(f.LocalPath()):
820 errors.append(' %s' % f.LocalPath())
821
822 results = []
823 if errors:
824 results.append(output_api.PresubmitError(
825 'The name of PNG files should not have abbreviations. \n'
826 'Use _hover.png, _center.png, instead of _h.png, _c.png.\n'
827 'Contact [email protected] if you have questions.', errors))
828 return results
829
830
[email protected]14a6131c2014-01-08 01:15:41831def _FilesToCheckForIncomingDeps(re, changed_lines):
[email protected]f32e2d1e2013-07-26 21:39:08832 """Helper method for _CheckAddedDepsHaveTargetApprovals. Returns
[email protected]14a6131c2014-01-08 01:15:41833 a set of DEPS entries that we should look up.
834
835 For a directory (rather than a specific filename) we fake a path to
836 a specific filename by adding /DEPS. This is chosen as a file that
837 will seldom or never be subject to per-file include_rules.
838 """
[email protected]2b438d62013-11-14 17:54:14839 # We ignore deps entries on auto-generated directories.
840 AUTO_GENERATED_DIRS = ['grit', 'jni']
[email protected]f32e2d1e2013-07-26 21:39:08841
842 # This pattern grabs the path without basename in the first
843 # parentheses, and the basename (if present) in the second. It
844 # relies on the simple heuristic that if there is a basename it will
845 # be a header file ending in ".h".
846 pattern = re.compile(
847 r"""['"]\+([^'"]+?)(/[a-zA-Z0-9_]+\.h)?['"].*""")
[email protected]2b438d62013-11-14 17:54:14848 results = set()
[email protected]f32e2d1e2013-07-26 21:39:08849 for changed_line in changed_lines:
850 m = pattern.match(changed_line)
851 if m:
852 path = m.group(1)
[email protected]2b438d62013-11-14 17:54:14853 if path.split('/')[0] not in AUTO_GENERATED_DIRS:
[email protected]14a6131c2014-01-08 01:15:41854 if m.group(2):
855 results.add('%s%s' % (path, m.group(2)))
856 else:
857 results.add('%s/DEPS' % path)
[email protected]f32e2d1e2013-07-26 21:39:08858 return results
859
860
[email protected]e871964c2013-05-13 14:14:55861def _CheckAddedDepsHaveTargetApprovals(input_api, output_api):
862 """When a dependency prefixed with + is added to a DEPS file, we
863 want to make sure that the change is reviewed by an OWNER of the
864 target file or directory, to avoid layering violations from being
865 introduced. This check verifies that this happens.
866 """
867 changed_lines = set()
868 for f in input_api.AffectedFiles():
869 filename = input_api.os_path.basename(f.LocalPath())
870 if filename == 'DEPS':
871 changed_lines |= set(line.strip()
872 for line_num, line
873 in f.ChangedContents())
874 if not changed_lines:
875 return []
876
[email protected]14a6131c2014-01-08 01:15:41877 virtual_depended_on_files = _FilesToCheckForIncomingDeps(input_api.re,
878 changed_lines)
[email protected]e871964c2013-05-13 14:14:55879 if not virtual_depended_on_files:
880 return []
881
882 if input_api.is_committing:
883 if input_api.tbr:
884 return [output_api.PresubmitNotifyResult(
885 '--tbr was specified, skipping OWNERS check for DEPS additions')]
886 if not input_api.change.issue:
887 return [output_api.PresubmitError(
888 "DEPS approval by OWNERS check failed: this change has "
889 "no Rietveld issue number, so we can't check it for approvals.")]
890 output = output_api.PresubmitError
891 else:
892 output = output_api.PresubmitNotifyResult
893
894 owners_db = input_api.owners_db
895 owner_email, reviewers = input_api.canned_checks._RietveldOwnerAndReviewers(
896 input_api,
897 owners_db.email_regexp,
898 approval_needed=input_api.is_committing)
899
900 owner_email = owner_email or input_api.change.author_email
901
[email protected]de4f7d22013-05-23 14:27:46902 reviewers_plus_owner = set(reviewers)
[email protected]e71c6082013-05-22 02:28:51903 if owner_email:
[email protected]de4f7d22013-05-23 14:27:46904 reviewers_plus_owner.add(owner_email)
[email protected]e871964c2013-05-13 14:14:55905 missing_files = owners_db.files_not_covered_by(virtual_depended_on_files,
906 reviewers_plus_owner)
[email protected]14a6131c2014-01-08 01:15:41907
908 # We strip the /DEPS part that was added by
909 # _FilesToCheckForIncomingDeps to fake a path to a file in a
910 # directory.
911 def StripDeps(path):
912 start_deps = path.rfind('/DEPS')
913 if start_deps != -1:
914 return path[:start_deps]
915 else:
916 return path
917 unapproved_dependencies = ["'+%s'," % StripDeps(path)
[email protected]e871964c2013-05-13 14:14:55918 for path in missing_files]
919
920 if unapproved_dependencies:
921 output_list = [
[email protected]14a6131c2014-01-08 01:15:41922 output('Missing LGTM from OWNERS of dependencies added to DEPS:\n %s' %
[email protected]e871964c2013-05-13 14:14:55923 '\n '.join(sorted(unapproved_dependencies)))]
924 if not input_api.is_committing:
925 suggested_owners = owners_db.reviewers_for(missing_files, owner_email)
926 output_list.append(output(
927 'Suggested missing target path OWNERS:\n %s' %
928 '\n '.join(suggested_owners or [])))
929 return output_list
930
931 return []
932
933
[email protected]85218562013-11-22 07:41:40934def _CheckSpamLogging(input_api, output_api):
935 file_inclusion_pattern = r'.+%s' % _IMPLEMENTATION_EXTENSIONS
936 black_list = (_EXCLUDED_PATHS +
937 _TEST_CODE_EXCLUDED_PATHS +
938 input_api.DEFAULT_BLACK_LIST +
[email protected]6f742dd02013-11-26 23:19:50939 (r"^base[\\\/]logging\.h$",
[email protected]80f360a2014-01-23 01:36:19940 r"^base[\\\/]logging\.cc$",
[email protected]8dc338c2013-12-09 16:28:48941 r"^chrome[\\\/]app[\\\/]chrome_main_delegate\.cc$",
[email protected]6e268db2013-12-04 01:41:46942 r"^chrome[\\\/]browser[\\\/]chrome_browser_main\.cc$",
[email protected]4de75262013-12-18 23:16:12943 r"^chrome[\\\/]browser[\\\/]ui[\\\/]startup[\\\/]"
944 r"startup_browser_creator\.cc$",
[email protected]fe0e6e12013-12-04 05:52:58945 r"^chrome[\\\/]installer[\\\/]setup[\\\/].*",
[email protected]8cf6f842014-08-08 21:33:16946 r"chrome[\\\/]browser[\\\/]diagnostics[\\\/]" +
[email protected]f5b9a3f342014-08-08 22:06:03947 r"diagnostics_writer\.cc$",
[email protected]9f13b602014-08-07 02:59:15948 r"^chrome_elf[\\\/]dll_hash[\\\/]dll_hash_main\.cc$",
949 r"^chromecast[\\\/]",
950 r"^cloud_print[\\\/]",
[email protected]9056e732014-01-08 06:25:25951 r"^content[\\\/]common[\\\/]gpu[\\\/]client[\\\/]"
952 r"gl_helper_benchmark\.cc$",
thestigc9e38a22014-09-13 01:02:11953 r"^courgette[\\\/]courgette_tool\.cc$",
[email protected]9f13b602014-08-07 02:59:15954 r"^extensions[\\\/]renderer[\\\/]logging_native_handler\.cc$",
[email protected]9c36d922014-03-24 16:47:52955 r"^native_client_sdk[\\\/]",
[email protected]cdbdced2013-11-27 21:35:50956 r"^remoting[\\\/]base[\\\/]logging\.h$",
[email protected]67c96ab2013-12-17 02:05:36957 r"^remoting[\\\/]host[\\\/].*",
[email protected]8232f8fd2013-12-14 00:52:31958 r"^sandbox[\\\/]linux[\\\/].*",
[email protected]0b7a21e2014-02-11 18:38:13959 r"^tools[\\\/]",
thestig22dfc4012014-09-05 08:29:44960 r"^ui[\\\/]aura[\\\/]bench[\\\/]bench_main\.cc$",
961 r"^webkit[\\\/]browser[\\\/]fileapi[\\\/]" +
962 r"dump_file_system.cc$",))
[email protected]85218562013-11-22 07:41:40963 source_file_filter = lambda x: input_api.FilterSourceFile(
964 x, white_list=(file_inclusion_pattern,), black_list=black_list)
965
966 log_info = []
967 printf = []
968
969 for f in input_api.AffectedSourceFiles(source_file_filter):
970 contents = input_api.ReadFile(f, 'rb')
971 if re.search(r"\bD?LOG\s*\(\s*INFO\s*\)", contents):
972 log_info.append(f.LocalPath())
[email protected]18b466b2013-12-02 22:01:37973 elif re.search(r"\bD?LOG_IF\s*\(\s*INFO\s*,", contents):
[email protected]85210652013-11-28 05:50:13974 log_info.append(f.LocalPath())
[email protected]18b466b2013-12-02 22:01:37975
976 if re.search(r"\bprintf\(", contents):
977 printf.append(f.LocalPath())
978 elif re.search(r"\bfprintf\((stdout|stderr)", contents):
[email protected]85218562013-11-22 07:41:40979 printf.append(f.LocalPath())
980
981 if log_info:
982 return [output_api.PresubmitError(
983 'These files spam the console log with LOG(INFO):',
984 items=log_info)]
985 if printf:
986 return [output_api.PresubmitError(
987 'These files spam the console log with printf/fprintf:',
988 items=printf)]
989 return []
990
991
[email protected]49aa76a2013-12-04 06:59:16992def _CheckForAnonymousVariables(input_api, output_api):
993 """These types are all expected to hold locks while in scope and
994 so should never be anonymous (which causes them to be immediately
995 destroyed)."""
996 they_who_must_be_named = [
997 'base::AutoLock',
998 'base::AutoReset',
999 'base::AutoUnlock',
1000 'SkAutoAlphaRestore',
1001 'SkAutoBitmapShaderInstall',
1002 'SkAutoBlitterChoose',
1003 'SkAutoBounderCommit',
1004 'SkAutoCallProc',
1005 'SkAutoCanvasRestore',
1006 'SkAutoCommentBlock',
1007 'SkAutoDescriptor',
1008 'SkAutoDisableDirectionCheck',
1009 'SkAutoDisableOvalCheck',
1010 'SkAutoFree',
1011 'SkAutoGlyphCache',
1012 'SkAutoHDC',
1013 'SkAutoLockColors',
1014 'SkAutoLockPixels',
1015 'SkAutoMalloc',
1016 'SkAutoMaskFreeImage',
1017 'SkAutoMutexAcquire',
1018 'SkAutoPathBoundsUpdate',
1019 'SkAutoPDFRelease',
1020 'SkAutoRasterClipValidate',
1021 'SkAutoRef',
1022 'SkAutoTime',
1023 'SkAutoTrace',
1024 'SkAutoUnref',
1025 ]
1026 anonymous = r'(%s)\s*[({]' % '|'.join(they_who_must_be_named)
1027 # bad: base::AutoLock(lock.get());
1028 # not bad: base::AutoLock lock(lock.get());
1029 bad_pattern = input_api.re.compile(anonymous)
1030 # good: new base::AutoLock(lock.get())
1031 good_pattern = input_api.re.compile(r'\bnew\s*' + anonymous)
1032 errors = []
1033
1034 for f in input_api.AffectedFiles():
1035 if not f.LocalPath().endswith(('.cc', '.h', '.inl', '.m', '.mm')):
1036 continue
1037 for linenum, line in f.ChangedContents():
1038 if bad_pattern.search(line) and not good_pattern.search(line):
1039 errors.append('%s:%d' % (f.LocalPath(), linenum))
1040
1041 if errors:
1042 return [output_api.PresubmitError(
1043 'These lines create anonymous variables that need to be named:',
1044 items=errors)]
1045 return []
1046
1047
[email protected]5fe0f8742013-11-29 01:04:591048def _CheckCygwinShell(input_api, output_api):
1049 source_file_filter = lambda x: input_api.FilterSourceFile(
1050 x, white_list=(r'.+\.(gyp|gypi)$',))
1051 cygwin_shell = []
1052
1053 for f in input_api.AffectedSourceFiles(source_file_filter):
1054 for linenum, line in f.ChangedContents():
1055 if 'msvs_cygwin_shell' in line:
1056 cygwin_shell.append(f.LocalPath())
1057 break
1058
1059 if cygwin_shell:
1060 return [output_api.PresubmitError(
1061 'These files should not use msvs_cygwin_shell (the default is 0):',
1062 items=cygwin_shell)]
1063 return []
1064
[email protected]85218562013-11-22 07:41:401065
[email protected]999261d2014-03-03 20:08:081066def _CheckUserActionUpdate(input_api, output_api):
1067 """Checks if any new user action has been added."""
[email protected]2f92dec2014-03-07 19:21:521068 if any('actions.xml' == input_api.os_path.basename(f) for f in
[email protected]999261d2014-03-03 20:08:081069 input_api.LocalPaths()):
[email protected]2f92dec2014-03-07 19:21:521070 # If actions.xml is already included in the changelist, the PRESUBMIT
1071 # for actions.xml will do a more complete presubmit check.
[email protected]999261d2014-03-03 20:08:081072 return []
1073
[email protected]999261d2014-03-03 20:08:081074 file_filter = lambda f: f.LocalPath().endswith(('.cc', '.mm'))
1075 action_re = r'[^a-zA-Z]UserMetricsAction\("([^"]*)'
[email protected]2f92dec2014-03-07 19:21:521076 current_actions = None
[email protected]999261d2014-03-03 20:08:081077 for f in input_api.AffectedFiles(file_filter=file_filter):
1078 for line_num, line in f.ChangedContents():
1079 match = input_api.re.search(action_re, line)
1080 if match:
[email protected]2f92dec2014-03-07 19:21:521081 # Loads contents in tools/metrics/actions/actions.xml to memory. It's
1082 # loaded only once.
1083 if not current_actions:
1084 with open('tools/metrics/actions/actions.xml') as actions_f:
1085 current_actions = actions_f.read()
1086 # Search for the matched user action name in |current_actions|.
[email protected]999261d2014-03-03 20:08:081087 for action_name in match.groups():
[email protected]2f92dec2014-03-07 19:21:521088 action = 'name="{0}"'.format(action_name)
1089 if action not in current_actions:
[email protected]999261d2014-03-03 20:08:081090 return [output_api.PresubmitPromptWarning(
1091 'File %s line %d: %s is missing in '
[email protected]2f92dec2014-03-07 19:21:521092 'tools/metrics/actions/actions.xml. Please run '
1093 'tools/metrics/actions/extract_actions.py to update.'
[email protected]999261d2014-03-03 20:08:081094 % (f.LocalPath(), line_num, action_name))]
1095 return []
1096
1097
[email protected]99171a92014-06-03 08:44:471098def _GetJSONParseError(input_api, filename, eat_comments=True):
1099 try:
1100 contents = input_api.ReadFile(filename)
1101 if eat_comments:
1102 json_comment_eater = input_api.os_path.join(
1103 input_api.PresubmitLocalPath(),
1104 'tools', 'json_comment_eater', 'json_comment_eater.py')
1105 process = input_api.subprocess.Popen(
1106 [input_api.python_executable, json_comment_eater],
1107 stdin=input_api.subprocess.PIPE,
1108 stdout=input_api.subprocess.PIPE,
1109 universal_newlines=True)
1110 (contents, _) = process.communicate(input=contents)
1111
1112 input_api.json.loads(contents)
1113 except ValueError as e:
1114 return e
1115 return None
1116
1117
1118def _GetIDLParseError(input_api, filename):
1119 try:
1120 contents = input_api.ReadFile(filename)
1121 idl_schema = input_api.os_path.join(
1122 input_api.PresubmitLocalPath(),
1123 'tools', 'json_schema_compiler', 'idl_schema.py')
1124 process = input_api.subprocess.Popen(
1125 [input_api.python_executable, idl_schema],
1126 stdin=input_api.subprocess.PIPE,
1127 stdout=input_api.subprocess.PIPE,
1128 stderr=input_api.subprocess.PIPE,
1129 universal_newlines=True)
1130 (_, error) = process.communicate(input=contents)
1131 return error or None
1132 except ValueError as e:
1133 return e
1134
1135
1136def _CheckParseErrors(input_api, output_api):
1137 """Check that IDL and JSON files do not contain syntax errors."""
1138 actions = {
1139 '.idl': _GetIDLParseError,
1140 '.json': _GetJSONParseError,
1141 }
1142 # These paths contain test data and other known invalid JSON files.
1143 excluded_patterns = [
joaodasilva718f87672014-08-30 09:25:491144 r'test[\\\/]data[\\\/]',
1145 r'^components[\\\/]policy[\\\/]resources[\\\/]policy_templates\.json$',
[email protected]99171a92014-06-03 08:44:471146 ]
1147 # Most JSON files are preprocessed and support comments, but these do not.
1148 json_no_comments_patterns = [
joaodasilva718f87672014-08-30 09:25:491149 r'^testing[\\\/]',
[email protected]99171a92014-06-03 08:44:471150 ]
1151 # Only run IDL checker on files in these directories.
1152 idl_included_patterns = [
joaodasilva718f87672014-08-30 09:25:491153 r'^chrome[\\\/]common[\\\/]extensions[\\\/]api[\\\/]',
1154 r'^extensions[\\\/]common[\\\/]api[\\\/]',
[email protected]99171a92014-06-03 08:44:471155 ]
1156
1157 def get_action(affected_file):
1158 filename = affected_file.LocalPath()
1159 return actions.get(input_api.os_path.splitext(filename)[1])
1160
1161 def MatchesFile(patterns, path):
1162 for pattern in patterns:
1163 if input_api.re.search(pattern, path):
1164 return True
1165 return False
1166
1167 def FilterFile(affected_file):
1168 action = get_action(affected_file)
1169 if not action:
1170 return False
1171 path = affected_file.LocalPath()
1172
1173 if MatchesFile(excluded_patterns, path):
1174 return False
1175
1176 if (action == _GetIDLParseError and
1177 not MatchesFile(idl_included_patterns, path)):
1178 return False
1179 return True
1180
1181 results = []
1182 for affected_file in input_api.AffectedFiles(
1183 file_filter=FilterFile, include_deletes=False):
1184 action = get_action(affected_file)
1185 kwargs = {}
1186 if (action == _GetJSONParseError and
1187 MatchesFile(json_no_comments_patterns, affected_file.LocalPath())):
1188 kwargs['eat_comments'] = False
1189 parse_error = action(input_api,
1190 affected_file.AbsoluteLocalPath(),
1191 **kwargs)
1192 if parse_error:
1193 results.append(output_api.PresubmitError('%s could not be parsed: %s' %
1194 (affected_file.LocalPath(), parse_error)))
1195 return results
1196
1197
[email protected]760deea2013-12-10 19:33:491198def _CheckJavaStyle(input_api, output_api):
1199 """Runs checkstyle on changed java files and returns errors if any exist."""
1200 original_sys_path = sys.path
1201 try:
1202 sys.path = sys.path + [input_api.os_path.join(
1203 input_api.PresubmitLocalPath(), 'tools', 'android', 'checkstyle')]
1204 import checkstyle
1205 finally:
1206 # Restore sys.path to what it was before.
1207 sys.path = original_sys_path
1208
1209 return checkstyle.RunCheckstyle(
1210 input_api, output_api, 'tools/android/checkstyle/chromium-style-5.0.xml')
1211
1212
[email protected]fd20b902014-05-09 02:14:531213_DEPRECATED_CSS = [
1214 # Values
1215 ( "-webkit-box", "flex" ),
1216 ( "-webkit-inline-box", "inline-flex" ),
1217 ( "-webkit-flex", "flex" ),
1218 ( "-webkit-inline-flex", "inline-flex" ),
1219 ( "-webkit-min-content", "min-content" ),
1220 ( "-webkit-max-content", "max-content" ),
1221
1222 # Properties
1223 ( "-webkit-background-clip", "background-clip" ),
1224 ( "-webkit-background-origin", "background-origin" ),
1225 ( "-webkit-background-size", "background-size" ),
1226 ( "-webkit-box-shadow", "box-shadow" ),
1227
1228 # Functions
1229 ( "-webkit-gradient", "gradient" ),
1230 ( "-webkit-repeating-gradient", "repeating-gradient" ),
1231 ( "-webkit-linear-gradient", "linear-gradient" ),
1232 ( "-webkit-repeating-linear-gradient", "repeating-linear-gradient" ),
1233 ( "-webkit-radial-gradient", "radial-gradient" ),
1234 ( "-webkit-repeating-radial-gradient", "repeating-radial-gradient" ),
1235]
1236
1237def _CheckNoDeprecatedCSS(input_api, output_api):
1238 """ Make sure that we don't use deprecated CSS
[email protected]9a48e3f82014-05-22 00:06:251239 properties, functions or values. Our external
1240 documentation is ignored by the hooks as it
1241 needs to be consumed by WebKit. """
[email protected]fd20b902014-05-09 02:14:531242 results = []
[email protected]9a48e3f82014-05-22 00:06:251243 file_inclusion_pattern = (r".+\.css$")
1244 black_list = (_EXCLUDED_PATHS +
1245 _TEST_CODE_EXCLUDED_PATHS +
1246 input_api.DEFAULT_BLACK_LIST +
1247 (r"^chrome/common/extensions/docs",
1248 r"^chrome/docs",
1249 r"^native_client_sdk"))
1250 file_filter = lambda f: input_api.FilterSourceFile(
1251 f, white_list=file_inclusion_pattern, black_list=black_list)
[email protected]fd20b902014-05-09 02:14:531252 for fpath in input_api.AffectedFiles(file_filter=file_filter):
1253 for line_num, line in fpath.ChangedContents():
1254 for (deprecated_value, value) in _DEPRECATED_CSS:
1255 if input_api.re.search(deprecated_value, line):
1256 results.append(output_api.PresubmitError(
1257 "%s:%d: Use of deprecated CSS %s, use %s instead" %
1258 (fpath.LocalPath(), line_num, deprecated_value, value)))
1259 return results
1260
[email protected]22c9bd72011-03-27 16:47:391261def _CommonChecks(input_api, output_api):
1262 """Checks common to both upload and commit."""
1263 results = []
1264 results.extend(input_api.canned_checks.PanProjectChecks(
[email protected]3de922f2013-12-20 13:27:381265 input_api, output_api,
1266 excluded_paths=_EXCLUDED_PATHS + _TESTRUNNER_PATHS))
[email protected]66daa702011-05-28 14:41:461267 results.extend(_CheckAuthorizedAuthor(input_api, output_api))
[email protected]55459852011-08-10 15:17:191268 results.extend(
[email protected]760deea2013-12-10 19:33:491269 _CheckNoProductionCodeUsingTestOnlyFunctions(input_api, output_api))
[email protected]10689ca2011-09-02 02:31:541270 results.extend(_CheckNoIOStreamInHeaders(input_api, output_api))
[email protected]72df4e782012-06-21 16:28:181271 results.extend(_CheckNoUNIT_TESTInSourceFiles(input_api, output_api))
[email protected]8ea5d4b2011-09-13 21:49:221272 results.extend(_CheckNoNewWStrings(input_api, output_api))
[email protected]2a8ac9c2011-10-19 17:20:441273 results.extend(_CheckNoDEPSGIT(input_api, output_api))
[email protected]127f18ec2012-06-16 05:05:591274 results.extend(_CheckNoBannedFunctions(input_api, output_api))
[email protected]6c063c62012-07-11 19:11:061275 results.extend(_CheckNoPragmaOnce(input_api, output_api))
[email protected]e7479052012-09-19 00:26:121276 results.extend(_CheckNoTrinaryTrueFalse(input_api, output_api))
[email protected]55f9f382012-07-31 11:02:181277 results.extend(_CheckUnwantedDependencies(input_api, output_api))
[email protected]fbcafe5a2012-08-08 15:31:221278 results.extend(_CheckFilePermissions(input_api, output_api))
[email protected]c8278b32012-10-30 20:35:491279 results.extend(_CheckNoAuraWindowPropertyHInHeaders(input_api, output_api))
[email protected]2309b0fa02012-11-16 12:18:271280 results.extend(_CheckIncludeOrder(input_api, output_api))
[email protected]70ca77752012-11-20 03:45:031281 results.extend(_CheckForVersionControlConflicts(input_api, output_api))
[email protected]b8079ae4a2012-12-05 19:56:491282 results.extend(_CheckPatchFiles(input_api, output_api))
[email protected]06e6d0ff2012-12-11 01:36:441283 results.extend(_CheckHardcodedGoogleHostsInLowerLayers(input_api, output_api))
[email protected]d2530012013-01-25 16:39:271284 results.extend(_CheckNoAbbreviationInPngFileName(input_api, output_api))
[email protected]b00342e7f2013-03-26 16:21:541285 results.extend(_CheckForInvalidOSMacros(input_api, output_api))
lliabraa35bab3932014-10-01 12:16:441286 results.extend(_CheckForInvalidIfDefinedMacros(input_api, output_api))
[email protected]e871964c2013-05-13 14:14:551287 results.extend(_CheckAddedDepsHaveTargetApprovals(input_api, output_api))
[email protected]9f919cc2013-07-31 03:04:041288 results.extend(
1289 input_api.canned_checks.CheckChangeHasNoTabs(
1290 input_api,
1291 output_api,
1292 source_file_filter=lambda x: x.LocalPath().endswith('.grd')))
[email protected]85218562013-11-22 07:41:401293 results.extend(_CheckSpamLogging(input_api, output_api))
[email protected]49aa76a2013-12-04 06:59:161294 results.extend(_CheckForAnonymousVariables(input_api, output_api))
[email protected]5fe0f8742013-11-29 01:04:591295 results.extend(_CheckCygwinShell(input_api, output_api))
[email protected]999261d2014-03-03 20:08:081296 results.extend(_CheckUserActionUpdate(input_api, output_api))
[email protected]fd20b902014-05-09 02:14:531297 results.extend(_CheckNoDeprecatedCSS(input_api, output_api))
[email protected]99171a92014-06-03 08:44:471298 results.extend(_CheckParseErrors(input_api, output_api))
mlamouria82272622014-09-16 18:45:041299 results.extend(_CheckForIPCRules(input_api, output_api))
[email protected]2299dcf2012-11-15 19:56:241300
1301 if any('PRESUBMIT.py' == f.LocalPath() for f in input_api.AffectedFiles()):
1302 results.extend(input_api.canned_checks.RunUnitTestsInDirectory(
1303 input_api, output_api,
1304 input_api.PresubmitLocalPath(),
[email protected]6be63382013-01-21 15:42:381305 whitelist=[r'^PRESUBMIT_test\.py$']))
[email protected]22c9bd72011-03-27 16:47:391306 return results
[email protected]1f7b4172010-01-28 01:17:341307
[email protected]b337cb5b2011-01-23 21:24:051308
[email protected]66daa702011-05-28 14:41:461309def _CheckAuthorizedAuthor(input_api, output_api):
1310 """For non-googler/chromites committers, verify the author's email address is
1311 in AUTHORS.
1312 """
[email protected]9bb9cb82011-06-13 20:43:011313 # TODO(maruel): Add it to input_api?
1314 import fnmatch
1315
[email protected]66daa702011-05-28 14:41:461316 author = input_api.change.author_email
[email protected]9bb9cb82011-06-13 20:43:011317 if not author:
1318 input_api.logging.info('No author, skipping AUTHOR check')
[email protected]66daa702011-05-28 14:41:461319 return []
[email protected]c99663292011-05-31 19:46:081320 authors_path = input_api.os_path.join(
[email protected]66daa702011-05-28 14:41:461321 input_api.PresubmitLocalPath(), 'AUTHORS')
1322 valid_authors = (
1323 input_api.re.match(r'[^#]+\s+\<(.+?)\>\s*$', line)
1324 for line in open(authors_path))
[email protected]ac54b132011-06-06 18:11:181325 valid_authors = [item.group(1).lower() for item in valid_authors if item]
[email protected]d8b50be2011-06-15 14:19:441326 if not any(fnmatch.fnmatch(author.lower(), valid) for valid in valid_authors):
[email protected]5861efb2013-01-07 18:33:231327 input_api.logging.info('Valid authors are %s', ', '.join(valid_authors))
[email protected]66daa702011-05-28 14:41:461328 return [output_api.PresubmitPromptWarning(
1329 ('%s is not in AUTHORS file. If you are a new contributor, please visit'
1330 '\n'
1331 'http://www.chromium.org/developers/contributing-code and read the '
1332 '"Legal" section\n'
1333 'If you are a chromite, verify the contributor signed the CLA.') %
1334 author)]
1335 return []
1336
1337
[email protected]b8079ae4a2012-12-05 19:56:491338def _CheckPatchFiles(input_api, output_api):
1339 problems = [f.LocalPath() for f in input_api.AffectedFiles()
1340 if f.LocalPath().endswith(('.orig', '.rej'))]
1341 if problems:
1342 return [output_api.PresubmitError(
1343 "Don't commit .rej and .orig files.", problems)]
[email protected]2fdd1f362013-01-16 03:56:031344 else:
1345 return []
[email protected]b8079ae4a2012-12-05 19:56:491346
1347
[email protected]b00342e7f2013-03-26 16:21:541348def _DidYouMeanOSMacro(bad_macro):
1349 try:
1350 return {'A': 'OS_ANDROID',
1351 'B': 'OS_BSD',
1352 'C': 'OS_CHROMEOS',
1353 'F': 'OS_FREEBSD',
1354 'L': 'OS_LINUX',
1355 'M': 'OS_MACOSX',
1356 'N': 'OS_NACL',
1357 'O': 'OS_OPENBSD',
1358 'P': 'OS_POSIX',
1359 'S': 'OS_SOLARIS',
1360 'W': 'OS_WIN'}[bad_macro[3].upper()]
1361 except KeyError:
1362 return ''
1363
1364
1365def _CheckForInvalidOSMacrosInFile(input_api, f):
1366 """Check for sensible looking, totally invalid OS macros."""
1367 preprocessor_statement = input_api.re.compile(r'^\s*#')
1368 os_macro = input_api.re.compile(r'defined\((OS_[^)]+)\)')
1369 results = []
1370 for lnum, line in f.ChangedContents():
1371 if preprocessor_statement.search(line):
1372 for match in os_macro.finditer(line):
1373 if not match.group(1) in _VALID_OS_MACROS:
1374 good = _DidYouMeanOSMacro(match.group(1))
1375 did_you_mean = ' (did you mean %s?)' % good if good else ''
1376 results.append(' %s:%d %s%s' % (f.LocalPath(),
1377 lnum,
1378 match.group(1),
1379 did_you_mean))
1380 return results
1381
1382
1383def _CheckForInvalidOSMacros(input_api, output_api):
1384 """Check all affected files for invalid OS macros."""
1385 bad_macros = []
1386 for f in input_api.AffectedFiles():
1387 if not f.LocalPath().endswith(('.py', '.js', '.html', '.css')):
1388 bad_macros.extend(_CheckForInvalidOSMacrosInFile(input_api, f))
1389
1390 if not bad_macros:
1391 return []
1392
1393 return [output_api.PresubmitError(
1394 'Possibly invalid OS macro[s] found. Please fix your code\n'
1395 'or add your macro to src/PRESUBMIT.py.', bad_macros)]
1396
lliabraa35bab3932014-10-01 12:16:441397
1398def _CheckForInvalidIfDefinedMacrosInFile(input_api, f):
1399 """Check all affected files for invalid "if defined" macros."""
1400 ALWAYS_DEFINED_MACROS = (
1401 "TARGET_CPU_PPC",
1402 "TARGET_CPU_PPC64",
1403 "TARGET_CPU_68K",
1404 "TARGET_CPU_X86",
1405 "TARGET_CPU_ARM",
1406 "TARGET_CPU_MIPS",
1407 "TARGET_CPU_SPARC",
1408 "TARGET_CPU_ALPHA",
1409 "TARGET_IPHONE_SIMULATOR",
1410 "TARGET_OS_EMBEDDED",
1411 "TARGET_OS_IPHONE",
1412 "TARGET_OS_MAC",
1413 "TARGET_OS_UNIX",
1414 "TARGET_OS_WIN32",
1415 )
1416 ifdef_macro = input_api.re.compile(r'^\s*#.*(?:ifdef\s|defined\()([^\s\)]+)')
1417 results = []
1418 for lnum, line in f.ChangedContents():
1419 for match in ifdef_macro.finditer(line):
1420 if match.group(1) in ALWAYS_DEFINED_MACROS:
1421 always_defined = ' %s is always defined. ' % match.group(1)
1422 did_you_mean = 'Did you mean \'#if %s\'?' % match.group(1)
1423 results.append(' %s:%d %s\n\t%s' % (f.LocalPath(),
1424 lnum,
1425 always_defined,
1426 did_you_mean))
1427 return results
1428
1429
1430def _CheckForInvalidIfDefinedMacros(input_api, output_api):
1431 """Check all affected files for invalid "if defined" macros."""
1432 bad_macros = []
1433 for f in input_api.AffectedFiles():
1434 if f.LocalPath().endswith(('.h', '.c', '.cc', '.m', '.mm')):
1435 bad_macros.extend(_CheckForInvalidIfDefinedMacrosInFile(input_api, f))
1436
1437 if not bad_macros:
1438 return []
1439
1440 return [output_api.PresubmitError(
1441 'Found ifdef check on always-defined macro[s]. Please fix your code\n'
1442 'or check the list of ALWAYS_DEFINED_MACROS in src/PRESUBMIT.py.',
1443 bad_macros)]
1444
1445
mlamouria82272622014-09-16 18:45:041446def _CheckForIPCRules(input_api, output_api):
1447 """Check for same IPC rules described in
1448 http://www.chromium.org/Home/chromium-security/education/security-tips-for-ipc
1449 """
1450 base_pattern = r'IPC_ENUM_TRAITS\('
1451 inclusion_pattern = input_api.re.compile(r'(%s)' % base_pattern)
1452 comment_pattern = input_api.re.compile(r'//.*(%s)' % base_pattern)
1453
1454 problems = []
1455 for f in input_api.AffectedSourceFiles(None):
1456 local_path = f.LocalPath()
1457 if not local_path.endswith('.h'):
1458 continue
1459 for line_number, line in f.ChangedContents():
1460 if inclusion_pattern.search(line) and not comment_pattern.search(line):
1461 problems.append(
1462 '%s:%d\n %s' % (local_path, line_number, line.strip()))
1463
1464 if problems:
1465 return [output_api.PresubmitPromptWarning(
1466 _IPC_ENUM_TRAITS_DEPRECATED, problems)]
1467 else:
1468 return []
1469
[email protected]b00342e7f2013-03-26 16:21:541470
[email protected]1f7b4172010-01-28 01:17:341471def CheckChangeOnUpload(input_api, output_api):
1472 results = []
1473 results.extend(_CommonChecks(input_api, output_api))
tandriief664692014-09-23 14:51:471474 results.extend(_CheckValidHostsInDEPS(input_api, output_api))
[email protected]ae69ae72014-02-20 13:09:361475 results.extend(_CheckJavaStyle(input_api, output_api))
[email protected]fe5f57c52009-06-05 14:25:541476 return results
[email protected]ca8d1982009-02-19 16:33:121477
1478
[email protected]1bfb8322014-04-23 01:02:411479def GetTryServerMasterForBot(bot):
1480 """Returns the Try Server master for the given bot.
1481
[email protected]0bb112362014-07-26 04:38:321482 It tries to guess the master from the bot name, but may still fail
1483 and return None. There is no longer a default master.
1484 """
1485 # Potentially ambiguous bot names are listed explicitly.
1486 master_map = {
[email protected]1bfb8322014-04-23 01:02:411487 'linux_gpu': 'tryserver.chromium.gpu',
[email protected]5c5f13042014-05-09 21:28:301488 'mac_gpu': 'tryserver.chromium.gpu',
[email protected]d263d5b2014-04-30 01:15:551489 'win_gpu': 'tryserver.chromium.gpu',
[email protected]0bb112362014-07-26 04:38:321490 'chromium_presubmit': 'tryserver.chromium.linux',
1491 'blink_presubmit': 'tryserver.chromium.linux',
1492 'tools_build_presubmit': 'tryserver.chromium.linux',
[email protected]1bfb8322014-04-23 01:02:411493 }
[email protected]0bb112362014-07-26 04:38:321494 master = master_map.get(bot)
1495 if not master:
1496 if 'gpu' in bot:
1497 master = 'tryserver.chromium.gpu'
1498 elif 'linux' in bot or 'android' in bot or 'presubmit' in bot:
1499 master = 'tryserver.chromium.linux'
1500 elif 'win' in bot:
1501 master = 'tryserver.chromium.win'
1502 elif 'mac' in bot or 'ios' in bot:
1503 master = 'tryserver.chromium.mac'
1504 return master
[email protected]1bfb8322014-04-23 01:02:411505
1506
[email protected]38c6a512013-12-18 23:48:011507def GetDefaultTryConfigs(bots=None):
1508 """Returns a list of ('bot', set(['tests']), optionally filtered by [bots].
1509
1510 To add tests to this list, they MUST be in the the corresponding master's
1511 gatekeeper config. For example, anything on master.chromium would be closed by
1512 tools/build/masters/master.chromium/master_gatekeeper_cfg.py.
1513
1514 If 'bots' is specified, will only return configurations for bots in that list.
1515 """
1516
1517 standard_tests = [
1518 'base_unittests',
1519 'browser_tests',
1520 'cacheinvalidation_unittests',
1521 'check_deps',
1522 'check_deps2git',
1523 'content_browsertests',
1524 'content_unittests',
1525 'crypto_unittests',
[email protected]38c6a512013-12-18 23:48:011526 'gpu_unittests',
1527 'interactive_ui_tests',
1528 'ipc_tests',
1529 'jingle_unittests',
1530 'media_unittests',
1531 'net_unittests',
1532 'ppapi_unittests',
1533 'printing_unittests',
1534 'sql_unittests',
1535 'sync_unit_tests',
1536 'unit_tests',
1537 # Broken in release.
1538 #'url_unittests',
1539 #'webkit_unit_tests',
1540 ]
1541
[email protected]38c6a512013-12-18 23:48:011542 builders_and_tests = {
1543 # TODO(maruel): Figure out a way to run 'sizes' where people can
1544 # effectively update the perf expectation correctly. This requires a
1545 # clobber=True build running 'sizes'. 'sizes' is not accurate with
1546 # incremental build. Reference:
1547 # http://chromium.org/developers/tree-sheriffs/perf-sheriffs.
1548 # TODO(maruel): An option would be to run 'sizes' but not count a failure
1549 # of this step as a try job failure.
1550 'android_aosp': ['compile'],
scottmgd4724062014-09-20 00:27:091551 'android_arm64_dbg_recipe': ['slave_steps'],
1552 'android_chromium_gn_compile_dbg': ['compile'],
[email protected]5a65d3042014-05-07 14:26:011553 'android_chromium_gn_compile_rel': ['compile'],
[email protected]38c6a512013-12-18 23:48:011554 'android_clang_dbg': ['slave_steps'],
scottmgd4724062014-09-20 00:27:091555 'android_clang_dbg_recipe': ['slave_steps'],
[email protected]5bd4f0cd2014-08-22 21:59:291556 'android_dbg_tests_recipe': ['slave_steps'],
[email protected]38c6a512013-12-18 23:48:011557 'cros_x86': ['defaulttests'],
1558 'ios_dbg_simulator': [
1559 'compile',
1560 'base_unittests',
1561 'content_unittests',
1562 'crypto_unittests',
1563 'url_unittests',
1564 'net_unittests',
1565 'sql_unittests',
1566 'ui_unittests',
1567 ],
1568 'ios_rel_device': ['compile'],
scottmgd4724062014-09-20 00:27:091569 'ios_rel_device_ninja': ['compile'],
[email protected]971b08ce2014-03-19 22:03:561570 'linux_asan': ['compile'],
1571 'mac_asan': ['compile'],
[email protected]38c6a512013-12-18 23:48:011572 #TODO(stip): Change the name of this builder to reflect that it's release.
[email protected]71afb4ec2014-02-07 02:45:131573 'linux_gtk': standard_tests,
[email protected]971b08ce2014-03-19 22:03:561574 'linux_chromeos_asan': ['compile'],
[email protected]d910b6082014-02-27 18:15:431575 'linux_chromium_chromeos_clang_dbg': ['defaulttests'],
[email protected]ce51953982014-08-07 15:43:241576 'linux_chromium_chromeos_rel_swarming': ['defaulttests'],
[email protected]d910b6082014-02-27 18:15:431577 'linux_chromium_compile_dbg': ['defaulttests'],
scottmgd4724062014-09-20 00:27:091578 'linux_chromium_gn_dbg': ['compile'],
[email protected]5a65d3042014-05-07 14:26:011579 'linux_chromium_gn_rel': ['defaulttests'],
[email protected]0bb112362014-07-26 04:38:321580 'linux_chromium_rel_swarming': ['defaulttests'],
[email protected]d910b6082014-02-27 18:15:431581 'linux_chromium_clang_dbg': ['defaulttests'],
[email protected]1bfb8322014-04-23 01:02:411582 'linux_gpu': ['defaulttests'],
[email protected]9780bac2014-01-11 00:12:021583 'linux_nacl_sdk_build': ['compile'],
[email protected]d910b6082014-02-27 18:15:431584 'mac_chromium_compile_dbg': ['defaulttests'],
[email protected]ce51953982014-08-07 15:43:241585 'mac_chromium_rel_swarming': ['defaulttests'],
[email protected]5c5f13042014-05-09 21:28:301586 'mac_gpu': ['defaulttests'],
[email protected]9780bac2014-01-11 00:12:021587 'mac_nacl_sdk_build': ['compile'],
[email protected]0094fa12014-03-13 03:18:281588 'win_chromium_compile_dbg': ['defaulttests'],
[email protected]c17144e42014-04-15 09:32:431589 'win_chromium_dbg': ['defaulttests'],
[email protected]02a7f6362014-08-13 02:04:161590 'win_chromium_rel_swarming': ['defaulttests'],
[email protected]c0f4e82b2014-08-15 23:35:341591 'win_chromium_x64_rel_swarming': ['defaulttests'],
[email protected]d263d5b2014-04-30 01:15:551592 'win_gpu': ['defaulttests'],
[email protected]9780bac2014-01-11 00:12:021593 'win_nacl_sdk_build': ['compile'],
danakjc89745a2014-09-16 01:33:031594 'win8_chromium_rel': ['defaulttests'],
[email protected]38c6a512013-12-18 23:48:011595 }
1596
[email protected]38c6a512013-12-18 23:48:011597 if bots:
[email protected]1bfb8322014-04-23 01:02:411598 filtered_builders_and_tests = dict((bot, set(builders_and_tests[bot]))
1599 for bot in bots)
[email protected]38c6a512013-12-18 23:48:011600 else:
[email protected]1bfb8322014-04-23 01:02:411601 filtered_builders_and_tests = dict(
1602 (bot, set(tests))
1603 for bot, tests in builders_and_tests.iteritems())
1604
1605 # Build up the mapping from tryserver master to bot/test.
1606 out = dict()
1607 for bot, tests in filtered_builders_and_tests.iteritems():
1608 out.setdefault(GetTryServerMasterForBot(bot), {})[bot] = tests
1609 return out
[email protected]38c6a512013-12-18 23:48:011610
1611
[email protected]ca8d1982009-02-19 16:33:121612def CheckChangeOnCommit(input_api, output_api):
[email protected]fe5f57c52009-06-05 14:25:541613 results = []
[email protected]1f7b4172010-01-28 01:17:341614 results.extend(_CommonChecks(input_api, output_api))
[email protected]dd805fe2009-10-01 08:11:511615 # TODO(thestig) temporarily disabled, doesn't work in third_party/
1616 #results.extend(input_api.canned_checks.CheckSvnModifiedDirectories(
1617 # input_api, output_api, sources))
[email protected]fe5f57c52009-06-05 14:25:541618 # Make sure the tree is 'open'.
[email protected]806e98e2010-03-19 17:49:271619 results.extend(input_api.canned_checks.CheckTreeIsOpen(
[email protected]7f238152009-08-12 19:00:341620 input_api,
1621 output_api,
[email protected]2fdd1f362013-01-16 03:56:031622 json_url='http://chromium-status.appspot.com/current?format=json'))
[email protected]806e98e2010-03-19 17:49:271623
[email protected]3e4eb112011-01-18 03:29:541624 results.extend(input_api.canned_checks.CheckChangeHasBugField(
1625 input_api, output_api))
[email protected]c4b47562011-12-05 23:39:411626 results.extend(input_api.canned_checks.CheckChangeHasDescription(
1627 input_api, output_api))
[email protected]fe5f57c52009-06-05 14:25:541628 return results
[email protected]ca8d1982009-02-19 16:33:121629
1630
[email protected]7468ac522014-03-12 23:35:571631def GetPreferredTryMasters(project, change):
[email protected]4ce995ea2012-06-27 02:13:101632 files = change.LocalPaths()
1633
joaodasilva718f87672014-08-30 09:25:491634 if not files or all(re.search(r'[\\\/]OWNERS$', f) for f in files):
[email protected]7468ac522014-03-12 23:35:571635 return {}
[email protected]3019c902012-06-29 00:09:031636
joaodasilva718f87672014-08-30 09:25:491637 if all(re.search(r'\.(m|mm)$|(^|[\\\/_])mac[\\\/_.]', f) for f in files):
[email protected]d96b1f42014-02-27 19:17:521638 return GetDefaultTryConfigs([
1639 'mac_chromium_compile_dbg',
[email protected]e6890ec2014-08-07 16:59:421640 'mac_chromium_rel_swarming',
[email protected]d96b1f42014-02-27 19:17:521641 ])
[email protected]d668899a2012-09-06 18:16:591642 if all(re.search('(^|[/_])win[/_.]', f) for f in files):
[email protected]02a7f6362014-08-13 02:04:161643 return GetDefaultTryConfigs([
1644 'win_chromium_dbg',
1645 'win_chromium_rel_swarming',
danakjc89745a2014-09-16 01:33:031646 'win8_chromium_rel',
[email protected]02a7f6362014-08-13 02:04:161647 ])
joaodasilva718f87672014-08-30 09:25:491648 if all(re.search(r'(^|[\\\/_])android[\\\/_.]', f) for f in files):
[email protected]38c6a512013-12-18 23:48:011649 return GetDefaultTryConfigs([
1650 'android_aosp',
1651 'android_clang_dbg',
[email protected]5bd4f0cd2014-08-22 21:59:291652 'android_dbg_tests_recipe',
[email protected]38c6a512013-12-18 23:48:011653 ])
joaodasilva718f87672014-08-30 09:25:491654 if all(re.search(r'[\\\/_]ios[\\\/_.]', f) for f in files):
[email protected]38c6a512013-12-18 23:48:011655 return GetDefaultTryConfigs(['ios_rel_device', 'ios_dbg_simulator'])
[email protected]4ce995ea2012-06-27 02:13:101656
[email protected]7468ac522014-03-12 23:35:571657 builders = [
scottmgd4724062014-09-20 00:27:091658 'android_arm64_dbg_recipe',
[email protected]5a65d3042014-05-07 14:26:011659 'android_chromium_gn_compile_rel',
scottmgd4724062014-09-20 00:27:091660 'android_chromium_gn_compile_dbg',
[email protected]3e2f0402012-11-02 16:28:011661 'android_clang_dbg',
scottmgd4724062014-09-20 00:27:091662 'android_clang_dbg_recipe',
[email protected]5bd4f0cd2014-08-22 21:59:291663 'android_dbg_tests_recipe',
[email protected]3e2f0402012-11-02 16:28:011664 'ios_dbg_simulator',
1665 'ios_rel_device',
scottmgd4724062014-09-20 00:27:091666 'ios_rel_device_ninja',
[email protected]e6890ec2014-08-07 16:59:421667 'linux_chromium_chromeos_rel_swarming',
[email protected]d96b1f42014-02-27 19:17:521668 'linux_chromium_clang_dbg',
scottmgd4724062014-09-20 00:27:091669 'linux_chromium_gn_dbg',
[email protected]5a65d3042014-05-07 14:26:011670 'linux_chromium_gn_rel',
[email protected]0bb112362014-07-26 04:38:321671 'linux_chromium_rel_swarming',
[email protected]1bfb8322014-04-23 01:02:411672 'linux_gpu',
[email protected]d96b1f42014-02-27 19:17:521673 'mac_chromium_compile_dbg',
[email protected]e6890ec2014-08-07 16:59:421674 'mac_chromium_rel_swarming',
[email protected]5c5f13042014-05-09 21:28:301675 'mac_gpu',
[email protected]0094fa12014-03-13 03:18:281676 'win_chromium_compile_dbg',
[email protected]02a7f6362014-08-13 02:04:161677 'win_chromium_rel_swarming',
[email protected]c0f4e82b2014-08-15 23:35:341678 'win_chromium_x64_rel_swarming',
[email protected]d263d5b2014-04-30 01:15:551679 'win_gpu',
danakjc89745a2014-09-16 01:33:031680 'win8_chromium_rel',
[email protected]7468ac522014-03-12 23:35:571681 ]
[email protected]911753b2012-08-02 12:11:541682
1683 # Match things like path/aura/file.cc and path/file_aura.cc.
[email protected]95c989162012-11-29 05:58:251684 # Same for chromeos.
joaodasilva718f87672014-08-30 09:25:491685 if any(re.search(r'[\\\/_](aura|chromeos)', f) for f in files):
[email protected]7468ac522014-03-12 23:35:571686 builders.extend([
1687 'linux_chromeos_asan',
1688 'linux_chromium_chromeos_clang_dbg'
1689 ])
[email protected]4ce995ea2012-06-27 02:13:101690
[email protected]e8df48f2013-09-30 20:07:541691 # If there are gyp changes to base, build, or chromeos, run a full cros build
1692 # in addition to the shorter linux_chromeos build. Changes to high level gyp
1693 # files have a much higher chance of breaking the cros build, which is
1694 # differnt from the linux_chromeos build that most chrome developers test
1695 # with.
1696 if any(re.search('^(base|build|chromeos).*\.gypi?$', f) for f in files):
[email protected]7468ac522014-03-12 23:35:571697 builders.extend(['cros_x86'])
[email protected]e8df48f2013-09-30 20:07:541698
[email protected]d95948ef2013-07-02 10:51:001699 # The AOSP bot doesn't build the chrome/ layer, so ignore any changes to it
1700 # unless they're .gyp(i) files as changes to those files can break the gyp
1701 # step on that bot.
1702 if (not all(re.search('^chrome', f) for f in files) or
1703 any(re.search('\.gypi?$', f) for f in files)):
[email protected]7468ac522014-03-12 23:35:571704 builders.extend(['android_aosp'])
[email protected]d95948ef2013-07-02 10:51:001705
[email protected]7468ac522014-03-12 23:35:571706 return GetDefaultTryConfigs(builders)