blob: 3124dd7ce792a5eb6dbaddf636ce54d0f375910e [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]fbcafe5a2012-08-08 15:31:2213import subprocess
[email protected]55f9f382012-07-31 11:02:1814import sys
[email protected]9d16ad12011-12-14 20:49:4715
16
[email protected]379e7dd2010-01-28 17:39:2117_EXCLUDED_PATHS = (
[email protected]3e4eb112011-01-18 03:29:5418 r"^breakpad[\\\/].*",
[email protected]40d1dbb2012-10-26 07:18:0019 r"^native_client_sdk[\\\/]src[\\\/]build_tools[\\\/]make_rules.py",
20 r"^native_client_sdk[\\\/]src[\\\/]build_tools[\\\/]make_simple.py",
[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]94f206c12012-08-25 00:09:1426 r"^cc[\\\/].*",
[email protected]39849c6c2012-09-14 22:15:5927 r"^webkit[\\\/]compositor_bindings[\\\/].*",
[email protected]ce145c02012-09-06 09:49:3428 r".+[\\\/]pnacl_shim\.c$",
[email protected]4306417642009-06-11 00:33:4029)
[email protected]ca8d1982009-02-19 16:33:1230
[email protected]06e6d0ff2012-12-11 01:36:4431# Fragment of a regular expression that matches file name suffixes
32# used to indicate different platforms.
33_PLATFORM_SPECIFIERS = r'(_(android|chromeos|gtk|mac|posix|win))?'
34
35# Fragment of a regular expression that matches C++ and Objective-C++
36# implementation files.
37_IMPLEMENTATION_EXTENSIONS = r'\.(cc|cpp|cxx|mm)$'
38
39# Regular expression that matches code only used for test binaries
40# (best effort).
41_TEST_CODE_EXCLUDED_PATHS = (
42 r'.*[/\\](fake_|test_|mock_).+%s' % _IMPLEMENTATION_EXTENSIONS,
43 r'.+_test_(base|support|util)%s' % _IMPLEMENTATION_EXTENSIONS,
44 r'.+_(api|browser|perf|unit|ui)?test%s%s' % (_PLATFORM_SPECIFIERS,
45 _IMPLEMENTATION_EXTENSIONS),
46 r'.+profile_sync_service_harness%s' % _IMPLEMENTATION_EXTENSIONS,
47 r'.*[/\\](test|tool(s)?)[/\\].*',
48 # At request of folks maintaining this folder.
49 r'chrome[/\\]browser[/\\]automation[/\\].*',
50)
[email protected]ca8d1982009-02-19 16:33:1251
[email protected]eea609a2011-11-18 13:10:1252_TEST_ONLY_WARNING = (
53 'You might be calling functions intended only for testing from\n'
54 'production code. It is OK to ignore this warning if you know what\n'
55 'you are doing, as the heuristics used to detect the situation are\n'
56 'not perfect. The commit queue will not block on this warning.\n'
57 'Email [email protected] if you have questions.')
58
59
[email protected]cf9b78f2012-11-14 11:40:2860_INCLUDE_ORDER_WARNING = (
61 'Your #include order seems to be broken. Send mail to\n'
62 '[email protected] if this is not the case.')
63
64
[email protected]127f18ec2012-06-16 05:05:5965_BANNED_OBJC_FUNCTIONS = (
66 (
67 'addTrackingRect:',
[email protected]23e6cbc2012-06-16 18:51:2068 (
69 'The use of -[NSView addTrackingRect:owner:userData:assumeInside:] is'
[email protected]127f18ec2012-06-16 05:05:5970 'prohibited. Please use CrTrackingArea instead.',
71 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
72 ),
73 False,
74 ),
75 (
76 'NSTrackingArea',
[email protected]23e6cbc2012-06-16 18:51:2077 (
78 'The use of NSTrackingAreas is prohibited. Please use CrTrackingArea',
[email protected]127f18ec2012-06-16 05:05:5979 'instead.',
80 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
81 ),
82 False,
83 ),
84 (
85 'convertPointFromBase:',
[email protected]23e6cbc2012-06-16 18:51:2086 (
87 'The use of -[NSView convertPointFromBase:] is almost certainly wrong.',
[email protected]127f18ec2012-06-16 05:05:5988 'Please use |convertPoint:(point) fromView:nil| instead.',
89 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
90 ),
91 True,
92 ),
93 (
94 'convertPointToBase:',
[email protected]23e6cbc2012-06-16 18:51:2095 (
96 'The use of -[NSView convertPointToBase:] is almost certainly wrong.',
[email protected]127f18ec2012-06-16 05:05:5997 'Please use |convertPoint:(point) toView:nil| instead.',
98 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
99 ),
100 True,
101 ),
102 (
103 'convertRectFromBase:',
[email protected]23e6cbc2012-06-16 18:51:20104 (
105 'The use of -[NSView convertRectFromBase:] is almost certainly wrong.',
[email protected]127f18ec2012-06-16 05:05:59106 'Please use |convertRect:(point) fromView:nil| instead.',
107 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
108 ),
109 True,
110 ),
111 (
112 'convertRectToBase:',
[email protected]23e6cbc2012-06-16 18:51:20113 (
114 'The use of -[NSView convertRectToBase:] is almost certainly wrong.',
[email protected]127f18ec2012-06-16 05:05:59115 'Please use |convertRect:(point) toView:nil| instead.',
116 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
117 ),
118 True,
119 ),
120 (
121 'convertSizeFromBase:',
[email protected]23e6cbc2012-06-16 18:51:20122 (
123 'The use of -[NSView convertSizeFromBase:] is almost certainly wrong.',
[email protected]127f18ec2012-06-16 05:05:59124 'Please use |convertSize:(point) fromView:nil| instead.',
125 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
126 ),
127 True,
128 ),
129 (
130 'convertSizeToBase:',
[email protected]23e6cbc2012-06-16 18:51:20131 (
132 'The use of -[NSView convertSizeToBase:] is almost certainly wrong.',
[email protected]127f18ec2012-06-16 05:05:59133 'Please use |convertSize:(point) toView:nil| instead.',
134 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
135 ),
136 True,
137 ),
138)
139
140
141_BANNED_CPP_FUNCTIONS = (
[email protected]23e6cbc2012-06-16 18:51:20142 # Make sure that gtest's FRIEND_TEST() macro is not used; the
143 # FRIEND_TEST_ALL_PREFIXES() macro from base/gtest_prod_util.h should be
[email protected]e00ccc92012-11-01 17:32:30144 # used instead since that allows for FLAKY_ and DISABLED_ prefixes.
[email protected]23e6cbc2012-06-16 18:51:20145 (
146 'FRIEND_TEST(',
147 (
[email protected]e3c945502012-06-26 20:01:49148 'Chromium code should not use gtest\'s FRIEND_TEST() macro. Include',
[email protected]23e6cbc2012-06-16 18:51:20149 'base/gtest_prod_util.h and use FRIEND_TEST_ALL_PREFIXES() instead.',
150 ),
151 False,
[email protected]7345da02012-11-27 14:31:49152 (),
[email protected]23e6cbc2012-06-16 18:51:20153 ),
154 (
155 'ScopedAllowIO',
156 (
[email protected]e3c945502012-06-26 20:01:49157 'New code should not use ScopedAllowIO. Post a task to the blocking',
158 'pool or the FILE thread instead.',
[email protected]23e6cbc2012-06-16 18:51:20159 ),
[email protected]e3c945502012-06-26 20:01:49160 True,
[email protected]7345da02012-11-27 14:31:49161 (
162 r"^content[\\\/]shell[\\\/]shell_browser_main\.cc$",
163 ),
[email protected]23e6cbc2012-06-16 18:51:20164 ),
165 (
166 'FilePathWatcher::Delegate',
167 (
[email protected]e3c945502012-06-26 20:01:49168 'New code should not use FilePathWatcher::Delegate. Use the callback',
[email protected]23e6cbc2012-06-16 18:51:20169 'interface instead.',
170 ),
171 False,
[email protected]7345da02012-11-27 14:31:49172 (),
[email protected]23e6cbc2012-06-16 18:51:20173 ),
[email protected]e3c945502012-06-26 20:01:49174 (
[email protected]73981ace2012-12-06 20:11:00175 'browser::FindOrCreateTabbedBrowserDeprecated',
[email protected]e3c945502012-06-26 20:01:49176 (
177 'This function is deprecated and we\'re working on removing it. Pass',
178 'more context to get a Browser*, like a WebContents, window, or session',
[email protected]1099dbd2012-11-01 19:56:02179 'id. Talk to robertshield@ for more information.',
[email protected]e3c945502012-06-26 20:01:49180 ),
181 True,
[email protected]7345da02012-11-27 14:31:49182 (),
[email protected]e3c945502012-06-26 20:01:49183 ),
184 (
[email protected]bb5eff1cc2012-11-01 20:46:29185 'RunAllPending()',
186 (
187 'This function is deprecated and we\'re working on removing it. Rename',
188 'to RunUntilIdle',
189 ),
190 True,
[email protected]7345da02012-11-27 14:31:49191 (),
[email protected]bb5eff1cc2012-11-01 20:46:29192 ),
[email protected]127f18ec2012-06-16 05:05:59193)
194
195
[email protected]eea609a2011-11-18 13:10:12196
[email protected]55459852011-08-10 15:17:19197def _CheckNoProductionCodeUsingTestOnlyFunctions(input_api, output_api):
198 """Attempts to prevent use of functions intended only for testing in
199 non-testing code. For now this is just a best-effort implementation
200 that ignores header files and may have some false positives. A
201 better implementation would probably need a proper C++ parser.
202 """
203 # We only scan .cc files and the like, as the declaration of
204 # for-testing functions in header files are hard to distinguish from
205 # calls to such functions without a proper C++ parser.
[email protected]06e6d0ff2012-12-11 01:36:44206 file_inclusion_pattern = r'.+%s' % _IMPLEMENTATION_EXTENSIONS
[email protected]55459852011-08-10 15:17:19207
208 base_function_pattern = r'ForTest(ing)?|for_test(ing)?'
209 inclusion_pattern = input_api.re.compile(r'(%s)\s*\(' % base_function_pattern)
210 exclusion_pattern = input_api.re.compile(
211 r'::[A-Za-z0-9_]+(%s)|(%s)[^;]+\{' % (
212 base_function_pattern, base_function_pattern))
213
214 def FilterFile(affected_file):
[email protected]06e6d0ff2012-12-11 01:36:44215 black_list = (_EXCLUDED_PATHS +
216 _TEST_CODE_EXCLUDED_PATHS +
217 input_api.DEFAULT_BLACK_LIST)
[email protected]55459852011-08-10 15:17:19218 return input_api.FilterSourceFile(
219 affected_file,
220 white_list=(file_inclusion_pattern, ),
221 black_list=black_list)
222
223 problems = []
224 for f in input_api.AffectedSourceFiles(FilterFile):
225 local_path = f.LocalPath()
226 lines = input_api.ReadFile(f).splitlines()
227 line_number = 0
228 for line in lines:
229 if (inclusion_pattern.search(line) and
230 not exclusion_pattern.search(line)):
231 problems.append(
232 '%s:%d\n %s' % (local_path, line_number, line.strip()))
233 line_number += 1
234
235 if problems:
[email protected]eea609a2011-11-18 13:10:12236 if not input_api.is_committing:
237 return [output_api.PresubmitPromptWarning(_TEST_ONLY_WARNING, problems)]
238 else:
239 # We don't warn on commit, to avoid stopping commits going through CQ.
240 return [output_api.PresubmitNotifyResult(_TEST_ONLY_WARNING, problems)]
[email protected]55459852011-08-10 15:17:19241 else:
242 return []
243
244
[email protected]10689ca2011-09-02 02:31:54245def _CheckNoIOStreamInHeaders(input_api, output_api):
246 """Checks to make sure no .h files include <iostream>."""
247 files = []
248 pattern = input_api.re.compile(r'^#include\s*<iostream>',
249 input_api.re.MULTILINE)
250 for f in input_api.AffectedSourceFiles(input_api.FilterSourceFile):
251 if not f.LocalPath().endswith('.h'):
252 continue
253 contents = input_api.ReadFile(f)
254 if pattern.search(contents):
255 files.append(f)
256
257 if len(files):
258 return [ output_api.PresubmitError(
[email protected]6c063c62012-07-11 19:11:06259 'Do not #include <iostream> in header files, since it inserts static '
260 'initialization into every file including the header. Instead, '
[email protected]10689ca2011-09-02 02:31:54261 '#include <ostream>. See http://crbug.com/94794',
262 files) ]
263 return []
264
265
[email protected]72df4e782012-06-21 16:28:18266def _CheckNoUNIT_TESTInSourceFiles(input_api, output_api):
267 """Checks to make sure no source files use UNIT_TEST"""
268 problems = []
269 for f in input_api.AffectedFiles():
270 if (not f.LocalPath().endswith(('.cc', '.mm'))):
271 continue
272
273 for line_num, line in f.ChangedContents():
274 if 'UNIT_TEST' in line:
275 problems.append(' %s:%d' % (f.LocalPath(), line_num))
276
277 if not problems:
278 return []
279 return [output_api.PresubmitPromptWarning('UNIT_TEST is only for headers.\n' +
280 '\n'.join(problems))]
281
282
[email protected]8ea5d4b2011-09-13 21:49:22283def _CheckNoNewWStrings(input_api, output_api):
284 """Checks to make sure we don't introduce use of wstrings."""
[email protected]55463aa62011-10-12 00:48:27285 problems = []
[email protected]8ea5d4b2011-09-13 21:49:22286 for f in input_api.AffectedFiles():
[email protected]b5c24292011-11-28 14:38:20287 if (not f.LocalPath().endswith(('.cc', '.h')) or
288 f.LocalPath().endswith('test.cc')):
289 continue
[email protected]8ea5d4b2011-09-13 21:49:22290
[email protected]a11dbe9b2012-08-07 01:32:58291 allowWString = False
[email protected]b5c24292011-11-28 14:38:20292 for line_num, line in f.ChangedContents():
[email protected]a11dbe9b2012-08-07 01:32:58293 if 'presubmit: allow wstring' in line:
294 allowWString = True
295 elif not allowWString and 'wstring' in line:
[email protected]55463aa62011-10-12 00:48:27296 problems.append(' %s:%d' % (f.LocalPath(), line_num))
[email protected]a11dbe9b2012-08-07 01:32:58297 allowWString = False
298 else:
299 allowWString = False
[email protected]8ea5d4b2011-09-13 21:49:22300
[email protected]55463aa62011-10-12 00:48:27301 if not problems:
302 return []
303 return [output_api.PresubmitPromptWarning('New code should not use wstrings.'
[email protected]a11dbe9b2012-08-07 01:32:58304 ' If you are calling a cross-platform API that accepts a wstring, '
305 'fix the API.\n' +
[email protected]55463aa62011-10-12 00:48:27306 '\n'.join(problems))]
[email protected]8ea5d4b2011-09-13 21:49:22307
308
[email protected]2a8ac9c2011-10-19 17:20:44309def _CheckNoDEPSGIT(input_api, output_api):
310 """Make sure .DEPS.git is never modified manually."""
311 if any(f.LocalPath().endswith('.DEPS.git') for f in
312 input_api.AffectedFiles()):
313 return [output_api.PresubmitError(
314 'Never commit changes to .DEPS.git. This file is maintained by an\n'
315 'automated system based on what\'s in DEPS and your changes will be\n'
316 'overwritten.\n'
317 'See http://code.google.com/p/chromium/wiki/UsingNewGit#Rolling_DEPS\n'
318 'for more information')]
319 return []
320
321
[email protected]127f18ec2012-06-16 05:05:59322def _CheckNoBannedFunctions(input_api, output_api):
323 """Make sure that banned functions are not used."""
324 warnings = []
325 errors = []
326
327 file_filter = lambda f: f.LocalPath().endswith(('.mm', '.m', '.h'))
328 for f in input_api.AffectedFiles(file_filter=file_filter):
329 for line_num, line in f.ChangedContents():
330 for func_name, message, error in _BANNED_OBJC_FUNCTIONS:
331 if func_name in line:
332 problems = warnings;
333 if error:
334 problems = errors;
335 problems.append(' %s:%d:' % (f.LocalPath(), line_num))
336 for message_line in message:
337 problems.append(' %s' % message_line)
338
339 file_filter = lambda f: f.LocalPath().endswith(('.cc', '.mm', '.h'))
340 for f in input_api.AffectedFiles(file_filter=file_filter):
341 for line_num, line in f.ChangedContents():
[email protected]7345da02012-11-27 14:31:49342 for func_name, message, error, excluded_paths in _BANNED_CPP_FUNCTIONS:
343 def IsBlacklisted(affected_file, blacklist):
344 local_path = affected_file.LocalPath()
345 for item in blacklist:
346 if input_api.re.match(item, local_path):
347 return True
348 return False
349 if IsBlacklisted(f, excluded_paths):
350 continue
[email protected]127f18ec2012-06-16 05:05:59351 if func_name in line:
352 problems = warnings;
353 if error:
354 problems = errors;
355 problems.append(' %s:%d:' % (f.LocalPath(), line_num))
356 for message_line in message:
357 problems.append(' %s' % message_line)
358
359 result = []
360 if (warnings):
361 result.append(output_api.PresubmitPromptWarning(
362 'Banned functions were used.\n' + '\n'.join(warnings)))
363 if (errors):
364 result.append(output_api.PresubmitError(
365 'Banned functions were used.\n' + '\n'.join(errors)))
366 return result
367
368
[email protected]6c063c62012-07-11 19:11:06369def _CheckNoPragmaOnce(input_api, output_api):
370 """Make sure that banned functions are not used."""
371 files = []
372 pattern = input_api.re.compile(r'^#pragma\s+once',
373 input_api.re.MULTILINE)
374 for f in input_api.AffectedSourceFiles(input_api.FilterSourceFile):
375 if not f.LocalPath().endswith('.h'):
376 continue
377 contents = input_api.ReadFile(f)
378 if pattern.search(contents):
379 files.append(f)
380
381 if files:
382 return [output_api.PresubmitError(
383 'Do not use #pragma once in header files.\n'
384 'See http://www.chromium.org/developers/coding-style#TOC-File-headers',
385 files)]
386 return []
387
[email protected]127f18ec2012-06-16 05:05:59388
[email protected]e7479052012-09-19 00:26:12389def _CheckNoTrinaryTrueFalse(input_api, output_api):
390 """Checks to make sure we don't introduce use of foo ? true : false."""
391 problems = []
392 pattern = input_api.re.compile(r'\?\s*(true|false)\s*:\s*(true|false)')
393 for f in input_api.AffectedFiles():
394 if not f.LocalPath().endswith(('.cc', '.h', '.inl', '.m', '.mm')):
395 continue
396
397 for line_num, line in f.ChangedContents():
398 if pattern.match(line):
399 problems.append(' %s:%d' % (f.LocalPath(), line_num))
400
401 if not problems:
402 return []
403 return [output_api.PresubmitPromptWarning(
404 'Please consider avoiding the "? true : false" pattern if possible.\n' +
405 '\n'.join(problems))]
406
407
[email protected]55f9f382012-07-31 11:02:18408def _CheckUnwantedDependencies(input_api, output_api):
409 """Runs checkdeps on #include statements added in this
410 change. Breaking - rules is an error, breaking ! rules is a
411 warning.
412 """
413 # We need to wait until we have an input_api object and use this
414 # roundabout construct to import checkdeps because this file is
415 # eval-ed and thus doesn't have __file__.
416 original_sys_path = sys.path
417 try:
418 sys.path = sys.path + [input_api.os_path.join(
419 input_api.PresubmitLocalPath(), 'tools', 'checkdeps')]
420 import checkdeps
421 from cpp_checker import CppChecker
422 from rules import Rule
423 finally:
424 # Restore sys.path to what it was before.
425 sys.path = original_sys_path
426
427 added_includes = []
428 for f in input_api.AffectedFiles():
429 if not CppChecker.IsCppFile(f.LocalPath()):
430 continue
431
432 changed_lines = [line for line_num, line in f.ChangedContents()]
433 added_includes.append([f.LocalPath(), changed_lines])
434
435 deps_checker = checkdeps.DepsChecker()
436
437 error_descriptions = []
438 warning_descriptions = []
439 for path, rule_type, rule_description in deps_checker.CheckAddedCppIncludes(
440 added_includes):
441 description_with_path = '%s\n %s' % (path, rule_description)
442 if rule_type == Rule.DISALLOW:
443 error_descriptions.append(description_with_path)
444 else:
445 warning_descriptions.append(description_with_path)
446
447 results = []
448 if error_descriptions:
449 results.append(output_api.PresubmitError(
450 'You added one or more #includes that violate checkdeps rules.',
451 error_descriptions))
452 if warning_descriptions:
[email protected]779caa52012-08-21 17:05:59453 if not input_api.is_committing:
454 warning_factory = output_api.PresubmitPromptWarning
455 else:
456 # We don't want to block use of the CQ when there is a warning
457 # of this kind, so we only show a message when committing.
458 warning_factory = output_api.PresubmitNotifyResult
459 results.append(warning_factory(
[email protected]55f9f382012-07-31 11:02:18460 'You added one or more #includes of files that are temporarily\n'
461 'allowed but being removed. Can you avoid introducing the\n'
462 '#include? See relevant DEPS file(s) for details and contacts.',
463 warning_descriptions))
464 return results
465
466
[email protected]fbcafe5a2012-08-08 15:31:22467def _CheckFilePermissions(input_api, output_api):
468 """Check that all files have their permissions properly set."""
469 args = [sys.executable, 'tools/checkperms/checkperms.py', '--root',
470 input_api.change.RepositoryRoot()]
471 for f in input_api.AffectedFiles():
472 args += ['--file', f.LocalPath()]
473 errors = []
474 (errors, stderrdata) = subprocess.Popen(args).communicate()
475
476 results = []
477 if errors:
[email protected]c8278b32012-10-30 20:35:49478 results.append(output_api.PresubmitError('checkperms.py failed.',
[email protected]fbcafe5a2012-08-08 15:31:22479 errors))
480 return results
481
482
[email protected]c8278b32012-10-30 20:35:49483def _CheckNoAuraWindowPropertyHInHeaders(input_api, output_api):
484 """Makes sure we don't include ui/aura/window_property.h
485 in header files.
486 """
487 pattern = input_api.re.compile(r'^#include\s*"ui/aura/window_property.h"')
488 errors = []
489 for f in input_api.AffectedFiles():
490 if not f.LocalPath().endswith('.h'):
491 continue
492 for line_num, line in f.ChangedContents():
493 if pattern.match(line):
494 errors.append(' %s:%d' % (f.LocalPath(), line_num))
495
496 results = []
497 if errors:
498 results.append(output_api.PresubmitError(
499 'Header files should not include ui/aura/window_property.h', errors))
500 return results
501
502
[email protected]cf9b78f2012-11-14 11:40:28503def _CheckIncludeOrderForScope(scope, input_api, file_path, changed_linenums):
504 """Checks that the lines in scope occur in the right order.
505
506 1. C system files in alphabetical order
507 2. C++ system files in alphabetical order
508 3. Project's .h files
509 """
510
511 c_system_include_pattern = input_api.re.compile(r'\s*#include <.*\.h>')
512 cpp_system_include_pattern = input_api.re.compile(r'\s*#include <.*>')
513 custom_include_pattern = input_api.re.compile(r'\s*#include ".*')
514
515 C_SYSTEM_INCLUDES, CPP_SYSTEM_INCLUDES, CUSTOM_INCLUDES = range(3)
516
517 state = C_SYSTEM_INCLUDES
518
519 previous_line = ''
[email protected]728b9bb2012-11-14 20:38:57520 previous_line_num = 0
[email protected]cf9b78f2012-11-14 11:40:28521 problem_linenums = []
522 for line_num, line in scope:
523 if c_system_include_pattern.match(line):
524 if state != C_SYSTEM_INCLUDES:
[email protected]728b9bb2012-11-14 20:38:57525 problem_linenums.append((line_num, previous_line_num))
[email protected]cf9b78f2012-11-14 11:40:28526 elif previous_line and previous_line > line:
[email protected]728b9bb2012-11-14 20:38:57527 problem_linenums.append((line_num, previous_line_num))
[email protected]cf9b78f2012-11-14 11:40:28528 elif cpp_system_include_pattern.match(line):
529 if state == C_SYSTEM_INCLUDES:
530 state = CPP_SYSTEM_INCLUDES
531 elif state == CUSTOM_INCLUDES:
[email protected]728b9bb2012-11-14 20:38:57532 problem_linenums.append((line_num, previous_line_num))
[email protected]cf9b78f2012-11-14 11:40:28533 elif previous_line and previous_line > line:
[email protected]728b9bb2012-11-14 20:38:57534 problem_linenums.append((line_num, previous_line_num))
[email protected]cf9b78f2012-11-14 11:40:28535 elif custom_include_pattern.match(line):
536 if state != CUSTOM_INCLUDES:
537 state = CUSTOM_INCLUDES
538 elif previous_line and previous_line > line:
[email protected]728b9bb2012-11-14 20:38:57539 problem_linenums.append((line_num, previous_line_num))
[email protected]cf9b78f2012-11-14 11:40:28540 else:
541 problem_linenums.append(line_num)
542 previous_line = line
[email protected]728b9bb2012-11-14 20:38:57543 previous_line_num = line_num
[email protected]cf9b78f2012-11-14 11:40:28544
545 warnings = []
[email protected]728b9bb2012-11-14 20:38:57546 for (line_num, previous_line_num) in problem_linenums:
547 if line_num in changed_linenums or previous_line_num in changed_linenums:
[email protected]cf9b78f2012-11-14 11:40:28548 warnings.append(' %s:%d' % (file_path, line_num))
549 return warnings
550
551
[email protected]ac294a12012-12-06 16:38:43552def _CheckIncludeOrderInFile(input_api, f, changed_linenums):
[email protected]cf9b78f2012-11-14 11:40:28553 """Checks the #include order for the given file f."""
554
[email protected]2299dcf2012-11-15 19:56:24555 system_include_pattern = input_api.re.compile(r'\s*#include \<.*')
[email protected]962f117e2012-11-22 18:11:56556 # Exclude #include <.../...> includes from the check; e.g., <sys/...> includes
557 # often need to appear in a specific order.
558 excluded_include_pattern = input_api.re.compile(r'\s*#include \<.*/.*')
[email protected]2299dcf2012-11-15 19:56:24559 custom_include_pattern = input_api.re.compile(r'\s*#include "(?P<FILE>.*)"')
[email protected]ac294a12012-12-06 16:38:43560 if_pattern = (
561 input_api.re.compile(r'\s*#\s*(if|elif|else|endif|define|undef).*'))
[email protected]cf9b78f2012-11-14 11:40:28562
563 contents = f.NewContents()
564 warnings = []
565 line_num = 0
566
[email protected]ac294a12012-12-06 16:38:43567 # Handle the special first include. If the first include file is
568 # some/path/file.h, the corresponding including file can be some/path/file.cc,
569 # some/other/path/file.cc, some/path/file_platform.cc, some/path/file-suffix.h
570 # etc. It's also possible that no special first include exists.
571 for line in contents:
572 line_num += 1
573 if system_include_pattern.match(line):
574 # No special first include -> process the line again along with normal
575 # includes.
576 line_num -= 1
577 break
578 match = custom_include_pattern.match(line)
579 if match:
580 match_dict = match.groupdict()
581 header_basename = input_api.os_path.basename(
582 match_dict['FILE']).replace('.h', '')
583 if header_basename not in input_api.os_path.basename(f.LocalPath()):
[email protected]2299dcf2012-11-15 19:56:24584 # No special first include -> process the line again along with normal
585 # includes.
586 line_num -= 1
[email protected]ac294a12012-12-06 16:38:43587 break
[email protected]cf9b78f2012-11-14 11:40:28588
589 # Split into scopes: Each region between #if and #endif is its own scope.
590 scopes = []
591 current_scope = []
592 for line in contents[line_num:]:
593 line_num += 1
[email protected]2309b0fa02012-11-16 12:18:27594 if if_pattern.match(line):
[email protected]cf9b78f2012-11-14 11:40:28595 scopes.append(current_scope)
596 current_scope = []
[email protected]962f117e2012-11-22 18:11:56597 elif ((system_include_pattern.match(line) or
598 custom_include_pattern.match(line)) and
599 not excluded_include_pattern.match(line)):
[email protected]cf9b78f2012-11-14 11:40:28600 current_scope.append((line_num, line))
601 scopes.append(current_scope)
602
603 for scope in scopes:
604 warnings.extend(_CheckIncludeOrderForScope(scope, input_api, f.LocalPath(),
605 changed_linenums))
606 return warnings
607
608
609def _CheckIncludeOrder(input_api, output_api):
610 """Checks that the #include order is correct.
611
612 1. The corresponding header for source files.
613 2. C system files in alphabetical order
614 3. C++ system files in alphabetical order
615 4. Project's .h files in alphabetical order
616
[email protected]ac294a12012-12-06 16:38:43617 Each region separated by #if, #elif, #else, #endif, #define and #undef follows
618 these rules separately.
[email protected]cf9b78f2012-11-14 11:40:28619 """
620
621 warnings = []
622 for f in input_api.AffectedFiles():
[email protected]ac294a12012-12-06 16:38:43623 if f.LocalPath().endswith(('.cc', '.h')):
624 changed_linenums = set(line_num for line_num, _ in f.ChangedContents())
625 warnings.extend(_CheckIncludeOrderInFile(input_api, f, changed_linenums))
[email protected]cf9b78f2012-11-14 11:40:28626
627 results = []
628 if warnings:
[email protected]120cf540d2012-12-10 17:55:53629 if not input_api.is_committing:
630 results.append(output_api.PresubmitPromptWarning(_INCLUDE_ORDER_WARNING,
631 warnings))
632 else:
633 # We don't warn on commit, to avoid stopping commits going through CQ.
634 results.append(output_api.PresubmitNotifyResult(_INCLUDE_ORDER_WARNING,
635 warnings))
[email protected]cf9b78f2012-11-14 11:40:28636 return results
637
638
[email protected]70ca77752012-11-20 03:45:03639def _CheckForVersionControlConflictsInFile(input_api, f):
640 pattern = input_api.re.compile('^(?:<<<<<<<|>>>>>>>) |^=======$')
641 errors = []
642 for line_num, line in f.ChangedContents():
643 if pattern.match(line):
644 errors.append(' %s:%d %s' % (f.LocalPath(), line_num, line))
645 return errors
646
647
648def _CheckForVersionControlConflicts(input_api, output_api):
649 """Usually this is not intentional and will cause a compile failure."""
650 errors = []
651 for f in input_api.AffectedFiles():
652 errors.extend(_CheckForVersionControlConflictsInFile(input_api, f))
653
654 results = []
655 if errors:
656 results.append(output_api.PresubmitError(
657 'Version control conflict markers found, please resolve.', errors))
658 return results
659
660
[email protected]06e6d0ff2012-12-11 01:36:44661def _CheckHardcodedGoogleHostsInLowerLayers(input_api, output_api):
662 def FilterFile(affected_file):
663 """Filter function for use with input_api.AffectedSourceFiles,
664 below. This filters out everything except non-test files from
665 top-level directories that generally speaking should not hard-code
666 service URLs (e.g. src/android_webview/, src/content/ and others).
667 """
668 return input_api.FilterSourceFile(
669 affected_file,
670 white_list=('^(android_webview|base|content|net)[\\\/].*'),
671 black_list=(_EXCLUDED_PATHS +
672 _TEST_CODE_EXCLUDED_PATHS +
673 input_api.DEFAULT_BLACK_LIST))
674
675 pattern = input_api.re.compile('"[^"]*google\.com[^"]*"')
676 problems = [] # items are (filename, line_number, line)
677 for f in input_api.AffectedSourceFiles(FilterFile):
678 for line_num, line in f.ChangedContents():
679 if pattern.search(line):
680 problems.append((f.LocalPath(), line_num, line))
681
682 if problems:
683 if not input_api.is_committing:
684 warning_factory = output_api.PresubmitPromptWarning
685 else:
686 # We don't want to block use of the CQ when there is a warning
687 # of this kind, so we only show a message when committing.
688 warning_factory = output_api.PresubmitNotifyResult
689 return [warning_factory(
690 'Most layers below src/chrome/ should not hardcode service URLs.\n'
691 'Are you sure this is correct? (Contact: [email protected])',
692 [' %s:%d: %s' % (
693 problem[0], problem[1], problem[2]) for problem in problems])]
694 else:
695 return []
696
697
[email protected]22c9bd72011-03-27 16:47:39698def _CommonChecks(input_api, output_api):
699 """Checks common to both upload and commit."""
700 results = []
701 results.extend(input_api.canned_checks.PanProjectChecks(
702 input_api, output_api, excluded_paths=_EXCLUDED_PATHS))
[email protected]66daa702011-05-28 14:41:46703 results.extend(_CheckAuthorizedAuthor(input_api, output_api))
[email protected]55459852011-08-10 15:17:19704 results.extend(
705 _CheckNoProductionCodeUsingTestOnlyFunctions(input_api, output_api))
[email protected]10689ca2011-09-02 02:31:54706 results.extend(_CheckNoIOStreamInHeaders(input_api, output_api))
[email protected]72df4e782012-06-21 16:28:18707 results.extend(_CheckNoUNIT_TESTInSourceFiles(input_api, output_api))
[email protected]8ea5d4b2011-09-13 21:49:22708 results.extend(_CheckNoNewWStrings(input_api, output_api))
[email protected]2a8ac9c2011-10-19 17:20:44709 results.extend(_CheckNoDEPSGIT(input_api, output_api))
[email protected]127f18ec2012-06-16 05:05:59710 results.extend(_CheckNoBannedFunctions(input_api, output_api))
[email protected]6c063c62012-07-11 19:11:06711 results.extend(_CheckNoPragmaOnce(input_api, output_api))
[email protected]e7479052012-09-19 00:26:12712 results.extend(_CheckNoTrinaryTrueFalse(input_api, output_api))
[email protected]55f9f382012-07-31 11:02:18713 results.extend(_CheckUnwantedDependencies(input_api, output_api))
[email protected]fbcafe5a2012-08-08 15:31:22714 results.extend(_CheckFilePermissions(input_api, output_api))
[email protected]c8278b32012-10-30 20:35:49715 results.extend(_CheckNoAuraWindowPropertyHInHeaders(input_api, output_api))
[email protected]2309b0fa02012-11-16 12:18:27716 results.extend(_CheckIncludeOrder(input_api, output_api))
[email protected]70ca77752012-11-20 03:45:03717 results.extend(_CheckForVersionControlConflicts(input_api, output_api))
[email protected]b8079ae4a2012-12-05 19:56:49718 results.extend(_CheckPatchFiles(input_api, output_api))
[email protected]06e6d0ff2012-12-11 01:36:44719 results.extend(_CheckHardcodedGoogleHostsInLowerLayers(input_api, output_api))
[email protected]2299dcf2012-11-15 19:56:24720
721 if any('PRESUBMIT.py' == f.LocalPath() for f in input_api.AffectedFiles()):
722 results.extend(input_api.canned_checks.RunUnitTestsInDirectory(
723 input_api, output_api,
724 input_api.PresubmitLocalPath(),
725 whitelist=[r'.+_test\.py$']))
[email protected]22c9bd72011-03-27 16:47:39726 return results
[email protected]1f7b4172010-01-28 01:17:34727
[email protected]b337cb5b2011-01-23 21:24:05728
729def _CheckSubversionConfig(input_api, output_api):
730 """Verifies the subversion config file is correctly setup.
731
732 Checks that autoprops are enabled, returns an error otherwise.
733 """
734 join = input_api.os_path.join
735 if input_api.platform == 'win32':
736 appdata = input_api.environ.get('APPDATA', '')
737 if not appdata:
738 return [output_api.PresubmitError('%APPDATA% is not configured.')]
739 path = join(appdata, 'Subversion', 'config')
740 else:
741 home = input_api.environ.get('HOME', '')
742 if not home:
743 return [output_api.PresubmitError('$HOME is not configured.')]
744 path = join(home, '.subversion', 'config')
745
746 error_msg = (
747 'Please look at http://dev.chromium.org/developers/coding-style to\n'
748 'configure your subversion configuration file. This enables automatic\n'
[email protected]c6a3c10b2011-01-24 16:14:20749 'properties to simplify the project maintenance.\n'
750 'Pro-tip: just download and install\n'
751 'http://src.chromium.org/viewvc/chrome/trunk/tools/build/slave/config\n')
[email protected]b337cb5b2011-01-23 21:24:05752
753 try:
754 lines = open(path, 'r').read().splitlines()
755 # Make sure auto-props is enabled and check for 2 Chromium standard
756 # auto-prop.
757 if (not '*.cc = svn:eol-style=LF' in lines or
758 not '*.pdf = svn:mime-type=application/pdf' in lines or
759 not 'enable-auto-props = yes' in lines):
760 return [
[email protected]79ed7e62011-02-21 21:08:53761 output_api.PresubmitNotifyResult(
[email protected]b337cb5b2011-01-23 21:24:05762 'It looks like you have not configured your subversion config '
[email protected]b5359c02011-02-01 20:29:56763 'file or it is not up-to-date.\n' + error_msg)
[email protected]b337cb5b2011-01-23 21:24:05764 ]
765 except (OSError, IOError):
766 return [
[email protected]79ed7e62011-02-21 21:08:53767 output_api.PresubmitNotifyResult(
[email protected]b337cb5b2011-01-23 21:24:05768 'Can\'t find your subversion config file.\n' + error_msg)
769 ]
770 return []
771
772
[email protected]66daa702011-05-28 14:41:46773def _CheckAuthorizedAuthor(input_api, output_api):
774 """For non-googler/chromites committers, verify the author's email address is
775 in AUTHORS.
776 """
[email protected]9bb9cb82011-06-13 20:43:01777 # TODO(maruel): Add it to input_api?
778 import fnmatch
779
[email protected]66daa702011-05-28 14:41:46780 author = input_api.change.author_email
[email protected]9bb9cb82011-06-13 20:43:01781 if not author:
782 input_api.logging.info('No author, skipping AUTHOR check')
[email protected]66daa702011-05-28 14:41:46783 return []
[email protected]c99663292011-05-31 19:46:08784 authors_path = input_api.os_path.join(
[email protected]66daa702011-05-28 14:41:46785 input_api.PresubmitLocalPath(), 'AUTHORS')
786 valid_authors = (
787 input_api.re.match(r'[^#]+\s+\<(.+?)\>\s*$', line)
788 for line in open(authors_path))
[email protected]ac54b132011-06-06 18:11:18789 valid_authors = [item.group(1).lower() for item in valid_authors if item]
[email protected]9bb9cb82011-06-13 20:43:01790 if input_api.verbose:
791 print 'Valid authors are %s' % ', '.join(valid_authors)
[email protected]d8b50be2011-06-15 14:19:44792 if not any(fnmatch.fnmatch(author.lower(), valid) for valid in valid_authors):
[email protected]66daa702011-05-28 14:41:46793 return [output_api.PresubmitPromptWarning(
794 ('%s is not in AUTHORS file. If you are a new contributor, please visit'
795 '\n'
796 'http://www.chromium.org/developers/contributing-code and read the '
797 '"Legal" section\n'
798 'If you are a chromite, verify the contributor signed the CLA.') %
799 author)]
800 return []
801
802
[email protected]b8079ae4a2012-12-05 19:56:49803def _CheckPatchFiles(input_api, output_api):
804 problems = [f.LocalPath() for f in input_api.AffectedFiles()
805 if f.LocalPath().endswith(('.orig', '.rej'))]
806 if problems:
807 return [output_api.PresubmitError(
808 "Don't commit .rej and .orig files.", problems)]
809 else:
810 return []
811
812
[email protected]1f7b4172010-01-28 01:17:34813def CheckChangeOnUpload(input_api, output_api):
814 results = []
815 results.extend(_CommonChecks(input_api, output_api))
[email protected]fe5f57c52009-06-05 14:25:54816 return results
[email protected]ca8d1982009-02-19 16:33:12817
818
819def CheckChangeOnCommit(input_api, output_api):
[email protected]fe5f57c52009-06-05 14:25:54820 results = []
[email protected]1f7b4172010-01-28 01:17:34821 results.extend(_CommonChecks(input_api, output_api))
[email protected]dd805fe2009-10-01 08:11:51822 # TODO(thestig) temporarily disabled, doesn't work in third_party/
823 #results.extend(input_api.canned_checks.CheckSvnModifiedDirectories(
824 # input_api, output_api, sources))
[email protected]fe5f57c52009-06-05 14:25:54825 # Make sure the tree is 'open'.
[email protected]806e98e2010-03-19 17:49:27826 results.extend(input_api.canned_checks.CheckTreeIsOpen(
[email protected]7f238152009-08-12 19:00:34827 input_api,
828 output_api,
[email protected]4efa42142010-08-26 01:29:26829 json_url='http://chromium-status.appspot.com/current?format=json'))
[email protected]806e98e2010-03-19 17:49:27830 results.extend(input_api.canned_checks.CheckRietveldTryJobExecution(input_api,
[email protected]4ddc5df2011-12-12 03:05:04831 output_api, 'http://codereview.chromium.org',
[email protected]c1ba4c52012-03-09 14:23:28832 ('win_rel', 'linux_rel', 'mac_rel, win:compile'),
833 '[email protected]'))
[email protected]806e98e2010-03-19 17:49:27834
[email protected]3e4eb112011-01-18 03:29:54835 results.extend(input_api.canned_checks.CheckChangeHasBugField(
836 input_api, output_api))
[email protected]c4b47562011-12-05 23:39:41837 results.extend(input_api.canned_checks.CheckChangeHasDescription(
838 input_api, output_api))
[email protected]b337cb5b2011-01-23 21:24:05839 results.extend(_CheckSubversionConfig(input_api, output_api))
[email protected]fe5f57c52009-06-05 14:25:54840 return results
[email protected]ca8d1982009-02-19 16:33:12841
842
[email protected]5efb2a822011-09-27 23:06:13843def GetPreferredTrySlaves(project, change):
[email protected]4ce995ea2012-06-27 02:13:10844 files = change.LocalPaths()
845
[email protected]3019c902012-06-29 00:09:03846 if not files:
847 return []
848
[email protected]d668899a2012-09-06 18:16:59849 if all(re.search('\.(m|mm)$|(^|[/_])mac[/_.]', f) for f in files):
[email protected]641f2e3e2012-09-03 11:16:24850 return ['mac_rel', 'mac_asan']
[email protected]d668899a2012-09-06 18:16:59851 if all(re.search('(^|[/_])win[/_.]', f) for f in files):
[email protected]4ce995ea2012-06-27 02:13:10852 return ['win_rel']
[email protected]d668899a2012-09-06 18:16:59853 if all(re.search('(^|[/_])android[/_.]', f) for f in files):
[email protected]3e2f0402012-11-02 16:28:01854 return ['android_dbg', 'android_clang_dbg']
[email protected]356aa542012-09-19 23:31:29855 if all(re.search('^native_client_sdk', f) for f in files):
856 return ['linux_nacl_sdk', 'win_nacl_sdk', 'mac_nacl_sdk']
[email protected]de142152012-10-03 23:02:45857 if all(re.search('[/_]ios[/_.]', f) for f in files):
858 return ['ios_rel_device', 'ios_dbg_simulator']
[email protected]4ce995ea2012-06-27 02:13:10859
[email protected]3e2f0402012-11-02 16:28:01860 trybots = [
861 'android_clang_dbg',
862 'android_dbg',
863 'ios_dbg_simulator',
864 'ios_rel_device',
865 'linux_asan',
[email protected]95c989162012-11-29 05:58:25866 'linux_aura',
[email protected]3e2f0402012-11-02 16:28:01867 'linux_chromeos',
868 'linux_clang:compile',
869 'linux_rel',
870 'mac_asan',
871 'mac_rel',
[email protected]95c989162012-11-29 05:58:25872 'win_aura',
[email protected]3e2f0402012-11-02 16:28:01873 'win_rel',
874 ]
[email protected]911753b2012-08-02 12:11:54875
876 # Match things like path/aura/file.cc and path/file_aura.cc.
[email protected]95c989162012-11-29 05:58:25877 # Same for chromeos.
878 if any(re.search('[/_](aura|chromeos)', f) for f in files):
[email protected]3e2f0402012-11-02 16:28:01879 trybots += ['linux_chromeos_clang:compile', 'linux_chromeos_asan']
[email protected]4ce995ea2012-06-27 02:13:10880
[email protected]4ce995ea2012-06-27 02:13:10881 return trybots