blob: 07674afb624f8aecade2e008bfbbb2abca6a9da1 [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 ),
[email protected]127f18ec2012-06-16 05:05:59165)
166
167
[email protected]55459852011-08-10 15:17:19168def _CheckNoProductionCodeUsingTestOnlyFunctions(input_api, output_api):
169 """Attempts to prevent use of functions intended only for testing in
170 non-testing code. For now this is just a best-effort implementation
171 that ignores header files and may have some false positives. A
172 better implementation would probably need a proper C++ parser.
173 """
174 # We only scan .cc files and the like, as the declaration of
175 # for-testing functions in header files are hard to distinguish from
176 # calls to such functions without a proper C++ parser.
[email protected]06e6d0ff2012-12-11 01:36:44177 file_inclusion_pattern = r'.+%s' % _IMPLEMENTATION_EXTENSIONS
[email protected]55459852011-08-10 15:17:19178
179 base_function_pattern = r'ForTest(ing)?|for_test(ing)?'
180 inclusion_pattern = input_api.re.compile(r'(%s)\s*\(' % base_function_pattern)
181 exclusion_pattern = input_api.re.compile(
182 r'::[A-Za-z0-9_]+(%s)|(%s)[^;]+\{' % (
183 base_function_pattern, base_function_pattern))
184
185 def FilterFile(affected_file):
[email protected]06e6d0ff2012-12-11 01:36:44186 black_list = (_EXCLUDED_PATHS +
187 _TEST_CODE_EXCLUDED_PATHS +
188 input_api.DEFAULT_BLACK_LIST)
[email protected]55459852011-08-10 15:17:19189 return input_api.FilterSourceFile(
190 affected_file,
191 white_list=(file_inclusion_pattern, ),
192 black_list=black_list)
193
194 problems = []
195 for f in input_api.AffectedSourceFiles(FilterFile):
196 local_path = f.LocalPath()
[email protected]2fdd1f362013-01-16 03:56:03197 lines = input_api.ReadFile(f).splitlines()
198 line_number = 0
199 for line in lines:
200 if (inclusion_pattern.search(line) and
201 not exclusion_pattern.search(line)):
[email protected]55459852011-08-10 15:17:19202 problems.append(
[email protected]2fdd1f362013-01-16 03:56:03203 '%s:%d\n %s' % (local_path, line_number, line.strip()))
204 line_number += 1
[email protected]55459852011-08-10 15:17:19205
206 if problems:
[email protected]2fdd1f362013-01-16 03:56:03207 if not input_api.is_committing:
208 return [output_api.PresubmitPromptWarning(_TEST_ONLY_WARNING, problems)]
209 else:
[email protected]eea609a2011-11-18 13:10:12210 # We don't warn on commit, to avoid stopping commits going through CQ.
211 return [output_api.PresubmitNotifyResult(_TEST_ONLY_WARNING, problems)]
[email protected]2fdd1f362013-01-16 03:56:03212 else:
213 return []
[email protected]55459852011-08-10 15:17:19214
215
[email protected]10689ca2011-09-02 02:31:54216def _CheckNoIOStreamInHeaders(input_api, output_api):
217 """Checks to make sure no .h files include <iostream>."""
218 files = []
219 pattern = input_api.re.compile(r'^#include\s*<iostream>',
220 input_api.re.MULTILINE)
221 for f in input_api.AffectedSourceFiles(input_api.FilterSourceFile):
222 if not f.LocalPath().endswith('.h'):
223 continue
224 contents = input_api.ReadFile(f)
225 if pattern.search(contents):
226 files.append(f)
227
228 if len(files):
229 return [ output_api.PresubmitError(
[email protected]6c063c62012-07-11 19:11:06230 'Do not #include <iostream> in header files, since it inserts static '
231 'initialization into every file including the header. Instead, '
[email protected]10689ca2011-09-02 02:31:54232 '#include <ostream>. See http://crbug.com/94794',
233 files) ]
234 return []
235
236
[email protected]72df4e782012-06-21 16:28:18237def _CheckNoUNIT_TESTInSourceFiles(input_api, output_api):
238 """Checks to make sure no source files use UNIT_TEST"""
239 problems = []
240 for f in input_api.AffectedFiles():
241 if (not f.LocalPath().endswith(('.cc', '.mm'))):
242 continue
243
244 for line_num, line in f.ChangedContents():
245 if 'UNIT_TEST' in line:
246 problems.append(' %s:%d' % (f.LocalPath(), line_num))
247
248 if not problems:
249 return []
250 return [output_api.PresubmitPromptWarning('UNIT_TEST is only for headers.\n' +
251 '\n'.join(problems))]
252
253
[email protected]8ea5d4b2011-09-13 21:49:22254def _CheckNoNewWStrings(input_api, output_api):
255 """Checks to make sure we don't introduce use of wstrings."""
[email protected]55463aa62011-10-12 00:48:27256 problems = []
[email protected]8ea5d4b2011-09-13 21:49:22257 for f in input_api.AffectedFiles():
[email protected]b5c24292011-11-28 14:38:20258 if (not f.LocalPath().endswith(('.cc', '.h')) or
259 f.LocalPath().endswith('test.cc')):
260 continue
[email protected]8ea5d4b2011-09-13 21:49:22261
[email protected]a11dbe9b2012-08-07 01:32:58262 allowWString = False
[email protected]b5c24292011-11-28 14:38:20263 for line_num, line in f.ChangedContents():
[email protected]a11dbe9b2012-08-07 01:32:58264 if 'presubmit: allow wstring' in line:
265 allowWString = True
266 elif not allowWString and 'wstring' in line:
[email protected]55463aa62011-10-12 00:48:27267 problems.append(' %s:%d' % (f.LocalPath(), line_num))
[email protected]a11dbe9b2012-08-07 01:32:58268 allowWString = False
269 else:
270 allowWString = False
[email protected]8ea5d4b2011-09-13 21:49:22271
[email protected]55463aa62011-10-12 00:48:27272 if not problems:
273 return []
274 return [output_api.PresubmitPromptWarning('New code should not use wstrings.'
[email protected]a11dbe9b2012-08-07 01:32:58275 ' If you are calling a cross-platform API that accepts a wstring, '
276 'fix the API.\n' +
[email protected]55463aa62011-10-12 00:48:27277 '\n'.join(problems))]
[email protected]8ea5d4b2011-09-13 21:49:22278
279
[email protected]2a8ac9c2011-10-19 17:20:44280def _CheckNoDEPSGIT(input_api, output_api):
281 """Make sure .DEPS.git is never modified manually."""
282 if any(f.LocalPath().endswith('.DEPS.git') for f in
283 input_api.AffectedFiles()):
284 return [output_api.PresubmitError(
285 'Never commit changes to .DEPS.git. This file is maintained by an\n'
286 'automated system based on what\'s in DEPS and your changes will be\n'
287 'overwritten.\n'
288 'See http://code.google.com/p/chromium/wiki/UsingNewGit#Rolling_DEPS\n'
289 'for more information')]
290 return []
291
292
[email protected]127f18ec2012-06-16 05:05:59293def _CheckNoBannedFunctions(input_api, output_api):
294 """Make sure that banned functions are not used."""
295 warnings = []
296 errors = []
297
298 file_filter = lambda f: f.LocalPath().endswith(('.mm', '.m', '.h'))
299 for f in input_api.AffectedFiles(file_filter=file_filter):
300 for line_num, line in f.ChangedContents():
301 for func_name, message, error in _BANNED_OBJC_FUNCTIONS:
302 if func_name in line:
303 problems = warnings;
304 if error:
305 problems = errors;
306 problems.append(' %s:%d:' % (f.LocalPath(), line_num))
307 for message_line in message:
308 problems.append(' %s' % message_line)
309
310 file_filter = lambda f: f.LocalPath().endswith(('.cc', '.mm', '.h'))
311 for f in input_api.AffectedFiles(file_filter=file_filter):
312 for line_num, line in f.ChangedContents():
[email protected]7345da02012-11-27 14:31:49313 for func_name, message, error, excluded_paths in _BANNED_CPP_FUNCTIONS:
314 def IsBlacklisted(affected_file, blacklist):
315 local_path = affected_file.LocalPath()
316 for item in blacklist:
317 if input_api.re.match(item, local_path):
318 return True
319 return False
320 if IsBlacklisted(f, excluded_paths):
321 continue
[email protected]127f18ec2012-06-16 05:05:59322 if func_name in line:
323 problems = warnings;
324 if error:
325 problems = errors;
326 problems.append(' %s:%d:' % (f.LocalPath(), line_num))
327 for message_line in message:
328 problems.append(' %s' % message_line)
329
330 result = []
331 if (warnings):
332 result.append(output_api.PresubmitPromptWarning(
333 'Banned functions were used.\n' + '\n'.join(warnings)))
334 if (errors):
335 result.append(output_api.PresubmitError(
336 'Banned functions were used.\n' + '\n'.join(errors)))
337 return result
338
339
[email protected]6c063c62012-07-11 19:11:06340def _CheckNoPragmaOnce(input_api, output_api):
341 """Make sure that banned functions are not used."""
342 files = []
343 pattern = input_api.re.compile(r'^#pragma\s+once',
344 input_api.re.MULTILINE)
345 for f in input_api.AffectedSourceFiles(input_api.FilterSourceFile):
346 if not f.LocalPath().endswith('.h'):
347 continue
348 contents = input_api.ReadFile(f)
349 if pattern.search(contents):
350 files.append(f)
351
352 if files:
353 return [output_api.PresubmitError(
354 'Do not use #pragma once in header files.\n'
355 'See http://www.chromium.org/developers/coding-style#TOC-File-headers',
356 files)]
357 return []
358
[email protected]127f18ec2012-06-16 05:05:59359
[email protected]e7479052012-09-19 00:26:12360def _CheckNoTrinaryTrueFalse(input_api, output_api):
361 """Checks to make sure we don't introduce use of foo ? true : false."""
362 problems = []
363 pattern = input_api.re.compile(r'\?\s*(true|false)\s*:\s*(true|false)')
364 for f in input_api.AffectedFiles():
365 if not f.LocalPath().endswith(('.cc', '.h', '.inl', '.m', '.mm')):
366 continue
367
368 for line_num, line in f.ChangedContents():
369 if pattern.match(line):
370 problems.append(' %s:%d' % (f.LocalPath(), line_num))
371
372 if not problems:
373 return []
374 return [output_api.PresubmitPromptWarning(
375 'Please consider avoiding the "? true : false" pattern if possible.\n' +
376 '\n'.join(problems))]
377
378
[email protected]55f9f382012-07-31 11:02:18379def _CheckUnwantedDependencies(input_api, output_api):
380 """Runs checkdeps on #include statements added in this
381 change. Breaking - rules is an error, breaking ! rules is a
382 warning.
383 """
384 # We need to wait until we have an input_api object and use this
385 # roundabout construct to import checkdeps because this file is
386 # eval-ed and thus doesn't have __file__.
387 original_sys_path = sys.path
388 try:
389 sys.path = sys.path + [input_api.os_path.join(
390 input_api.PresubmitLocalPath(), 'tools', 'checkdeps')]
391 import checkdeps
392 from cpp_checker import CppChecker
393 from rules import Rule
394 finally:
395 # Restore sys.path to what it was before.
396 sys.path = original_sys_path
397
398 added_includes = []
399 for f in input_api.AffectedFiles():
400 if not CppChecker.IsCppFile(f.LocalPath()):
401 continue
402
403 changed_lines = [line for line_num, line in f.ChangedContents()]
404 added_includes.append([f.LocalPath(), changed_lines])
405
406 deps_checker = checkdeps.DepsChecker()
407
408 error_descriptions = []
409 warning_descriptions = []
410 for path, rule_type, rule_description in deps_checker.CheckAddedCppIncludes(
411 added_includes):
412 description_with_path = '%s\n %s' % (path, rule_description)
413 if rule_type == Rule.DISALLOW:
414 error_descriptions.append(description_with_path)
415 else:
416 warning_descriptions.append(description_with_path)
417
418 results = []
419 if error_descriptions:
420 results.append(output_api.PresubmitError(
421 'You added one or more #includes that violate checkdeps rules.',
422 error_descriptions))
423 if warning_descriptions:
[email protected]2fdd1f362013-01-16 03:56:03424 if not input_api.is_committing:
425 warning_factory = output_api.PresubmitPromptWarning
426 else:
[email protected]779caa52012-08-21 17:05:59427 # We don't want to block use of the CQ when there is a warning
428 # of this kind, so we only show a message when committing.
429 warning_factory = output_api.PresubmitNotifyResult
430 results.append(warning_factory(
[email protected]55f9f382012-07-31 11:02:18431 'You added one or more #includes of files that are temporarily\n'
432 'allowed but being removed. Can you avoid introducing the\n'
433 '#include? See relevant DEPS file(s) for details and contacts.',
434 warning_descriptions))
435 return results
436
437
[email protected]fbcafe5a2012-08-08 15:31:22438def _CheckFilePermissions(input_api, output_api):
439 """Check that all files have their permissions properly set."""
440 args = [sys.executable, 'tools/checkperms/checkperms.py', '--root',
441 input_api.change.RepositoryRoot()]
442 for f in input_api.AffectedFiles():
443 args += ['--file', f.LocalPath()]
444 errors = []
445 (errors, stderrdata) = subprocess.Popen(args).communicate()
446
447 results = []
448 if errors:
[email protected]c8278b32012-10-30 20:35:49449 results.append(output_api.PresubmitError('checkperms.py failed.',
[email protected]fbcafe5a2012-08-08 15:31:22450 errors))
451 return results
452
453
[email protected]c8278b32012-10-30 20:35:49454def _CheckNoAuraWindowPropertyHInHeaders(input_api, output_api):
455 """Makes sure we don't include ui/aura/window_property.h
456 in header files.
457 """
458 pattern = input_api.re.compile(r'^#include\s*"ui/aura/window_property.h"')
459 errors = []
460 for f in input_api.AffectedFiles():
461 if not f.LocalPath().endswith('.h'):
462 continue
463 for line_num, line in f.ChangedContents():
464 if pattern.match(line):
465 errors.append(' %s:%d' % (f.LocalPath(), line_num))
466
467 results = []
468 if errors:
469 results.append(output_api.PresubmitError(
470 'Header files should not include ui/aura/window_property.h', errors))
471 return results
472
473
[email protected]cf9b78f2012-11-14 11:40:28474def _CheckIncludeOrderForScope(scope, input_api, file_path, changed_linenums):
475 """Checks that the lines in scope occur in the right order.
476
477 1. C system files in alphabetical order
478 2. C++ system files in alphabetical order
479 3. Project's .h files
480 """
481
482 c_system_include_pattern = input_api.re.compile(r'\s*#include <.*\.h>')
483 cpp_system_include_pattern = input_api.re.compile(r'\s*#include <.*>')
484 custom_include_pattern = input_api.re.compile(r'\s*#include ".*')
485
486 C_SYSTEM_INCLUDES, CPP_SYSTEM_INCLUDES, CUSTOM_INCLUDES = range(3)
487
488 state = C_SYSTEM_INCLUDES
489
490 previous_line = ''
[email protected]728b9bb2012-11-14 20:38:57491 previous_line_num = 0
[email protected]cf9b78f2012-11-14 11:40:28492 problem_linenums = []
493 for line_num, line in scope:
494 if c_system_include_pattern.match(line):
495 if state != C_SYSTEM_INCLUDES:
[email protected]728b9bb2012-11-14 20:38:57496 problem_linenums.append((line_num, previous_line_num))
[email protected]cf9b78f2012-11-14 11:40:28497 elif previous_line and previous_line > line:
[email protected]728b9bb2012-11-14 20:38:57498 problem_linenums.append((line_num, previous_line_num))
[email protected]cf9b78f2012-11-14 11:40:28499 elif cpp_system_include_pattern.match(line):
500 if state == C_SYSTEM_INCLUDES:
501 state = CPP_SYSTEM_INCLUDES
502 elif state == CUSTOM_INCLUDES:
[email protected]728b9bb2012-11-14 20:38:57503 problem_linenums.append((line_num, previous_line_num))
[email protected]cf9b78f2012-11-14 11:40:28504 elif previous_line and previous_line > line:
[email protected]728b9bb2012-11-14 20:38:57505 problem_linenums.append((line_num, previous_line_num))
[email protected]cf9b78f2012-11-14 11:40:28506 elif custom_include_pattern.match(line):
507 if state != CUSTOM_INCLUDES:
508 state = CUSTOM_INCLUDES
509 elif previous_line and previous_line > line:
[email protected]728b9bb2012-11-14 20:38:57510 problem_linenums.append((line_num, previous_line_num))
[email protected]cf9b78f2012-11-14 11:40:28511 else:
512 problem_linenums.append(line_num)
513 previous_line = line
[email protected]728b9bb2012-11-14 20:38:57514 previous_line_num = line_num
[email protected]cf9b78f2012-11-14 11:40:28515
516 warnings = []
[email protected]728b9bb2012-11-14 20:38:57517 for (line_num, previous_line_num) in problem_linenums:
518 if line_num in changed_linenums or previous_line_num in changed_linenums:
[email protected]cf9b78f2012-11-14 11:40:28519 warnings.append(' %s:%d' % (file_path, line_num))
520 return warnings
521
522
[email protected]ac294a12012-12-06 16:38:43523def _CheckIncludeOrderInFile(input_api, f, changed_linenums):
[email protected]cf9b78f2012-11-14 11:40:28524 """Checks the #include order for the given file f."""
525
[email protected]2299dcf2012-11-15 19:56:24526 system_include_pattern = input_api.re.compile(r'\s*#include \<.*')
[email protected]962f117e2012-11-22 18:11:56527 # Exclude #include <.../...> includes from the check; e.g., <sys/...> includes
528 # often need to appear in a specific order.
529 excluded_include_pattern = input_api.re.compile(r'\s*#include \<.*/.*')
[email protected]2299dcf2012-11-15 19:56:24530 custom_include_pattern = input_api.re.compile(r'\s*#include "(?P<FILE>.*)"')
[email protected]0e5c1852012-12-18 20:17:11531 if_pattern = input_api.re.compile(
532 r'\s*#\s*(if|elif|else|endif|define|undef).*')
533 # Some files need specialized order of includes; exclude such files from this
534 # check.
535 uncheckable_includes_pattern = input_api.re.compile(
536 r'\s*#include '
537 '("ipc/.*macros\.h"|<windows\.h>|".*gl.*autogen.h")\s*')
[email protected]cf9b78f2012-11-14 11:40:28538
539 contents = f.NewContents()
540 warnings = []
541 line_num = 0
542
[email protected]ac294a12012-12-06 16:38:43543 # Handle the special first include. If the first include file is
544 # some/path/file.h, the corresponding including file can be some/path/file.cc,
545 # some/other/path/file.cc, some/path/file_platform.cc, some/path/file-suffix.h
546 # etc. It's also possible that no special first include exists.
547 for line in contents:
548 line_num += 1
549 if system_include_pattern.match(line):
550 # No special first include -> process the line again along with normal
551 # includes.
552 line_num -= 1
553 break
554 match = custom_include_pattern.match(line)
555 if match:
556 match_dict = match.groupdict()
557 header_basename = input_api.os_path.basename(
558 match_dict['FILE']).replace('.h', '')
559 if header_basename not in input_api.os_path.basename(f.LocalPath()):
[email protected]2299dcf2012-11-15 19:56:24560 # No special first include -> process the line again along with normal
561 # includes.
562 line_num -= 1
[email protected]ac294a12012-12-06 16:38:43563 break
[email protected]cf9b78f2012-11-14 11:40:28564
565 # Split into scopes: Each region between #if and #endif is its own scope.
566 scopes = []
567 current_scope = []
568 for line in contents[line_num:]:
569 line_num += 1
[email protected]0e5c1852012-12-18 20:17:11570 if uncheckable_includes_pattern.match(line):
571 return []
[email protected]2309b0fa02012-11-16 12:18:27572 if if_pattern.match(line):
[email protected]cf9b78f2012-11-14 11:40:28573 scopes.append(current_scope)
574 current_scope = []
[email protected]962f117e2012-11-22 18:11:56575 elif ((system_include_pattern.match(line) or
576 custom_include_pattern.match(line)) and
577 not excluded_include_pattern.match(line)):
[email protected]cf9b78f2012-11-14 11:40:28578 current_scope.append((line_num, line))
579 scopes.append(current_scope)
580
581 for scope in scopes:
582 warnings.extend(_CheckIncludeOrderForScope(scope, input_api, f.LocalPath(),
583 changed_linenums))
584 return warnings
585
586
587def _CheckIncludeOrder(input_api, output_api):
588 """Checks that the #include order is correct.
589
590 1. The corresponding header for source files.
591 2. C system files in alphabetical order
592 3. C++ system files in alphabetical order
593 4. Project's .h files in alphabetical order
594
[email protected]ac294a12012-12-06 16:38:43595 Each region separated by #if, #elif, #else, #endif, #define and #undef follows
596 these rules separately.
[email protected]cf9b78f2012-11-14 11:40:28597 """
598
599 warnings = []
600 for f in input_api.AffectedFiles():
[email protected]ac294a12012-12-06 16:38:43601 if f.LocalPath().endswith(('.cc', '.h')):
602 changed_linenums = set(line_num for line_num, _ in f.ChangedContents())
603 warnings.extend(_CheckIncludeOrderInFile(input_api, f, changed_linenums))
[email protected]cf9b78f2012-11-14 11:40:28604
605 results = []
606 if warnings:
[email protected]2fdd1f362013-01-16 03:56:03607 if not input_api.is_committing:
608 results.append(output_api.PresubmitPromptWarning(_INCLUDE_ORDER_WARNING,
609 warnings))
610 else:
[email protected]120cf540d2012-12-10 17:55:53611 # We don't warn on commit, to avoid stopping commits going through CQ.
612 results.append(output_api.PresubmitNotifyResult(_INCLUDE_ORDER_WARNING,
613 warnings))
[email protected]cf9b78f2012-11-14 11:40:28614 return results
615
616
[email protected]70ca77752012-11-20 03:45:03617def _CheckForVersionControlConflictsInFile(input_api, f):
618 pattern = input_api.re.compile('^(?:<<<<<<<|>>>>>>>) |^=======$')
619 errors = []
620 for line_num, line in f.ChangedContents():
621 if pattern.match(line):
622 errors.append(' %s:%d %s' % (f.LocalPath(), line_num, line))
623 return errors
624
625
626def _CheckForVersionControlConflicts(input_api, output_api):
627 """Usually this is not intentional and will cause a compile failure."""
628 errors = []
629 for f in input_api.AffectedFiles():
630 errors.extend(_CheckForVersionControlConflictsInFile(input_api, f))
631
632 results = []
633 if errors:
634 results.append(output_api.PresubmitError(
635 'Version control conflict markers found, please resolve.', errors))
636 return results
637
638
[email protected]06e6d0ff2012-12-11 01:36:44639def _CheckHardcodedGoogleHostsInLowerLayers(input_api, output_api):
640 def FilterFile(affected_file):
641 """Filter function for use with input_api.AffectedSourceFiles,
642 below. This filters out everything except non-test files from
643 top-level directories that generally speaking should not hard-code
644 service URLs (e.g. src/android_webview/, src/content/ and others).
645 """
646 return input_api.FilterSourceFile(
647 affected_file,
[email protected]78bb39d62012-12-11 15:11:56648 white_list=(r'^(android_webview|base|content|net)[\\\/].*', ),
[email protected]06e6d0ff2012-12-11 01:36:44649 black_list=(_EXCLUDED_PATHS +
650 _TEST_CODE_EXCLUDED_PATHS +
651 input_api.DEFAULT_BLACK_LIST))
652
653 pattern = input_api.re.compile('"[^"]*google\.com[^"]*"')
654 problems = [] # items are (filename, line_number, line)
655 for f in input_api.AffectedSourceFiles(FilterFile):
656 for line_num, line in f.ChangedContents():
657 if pattern.search(line):
658 problems.append((f.LocalPath(), line_num, line))
659
660 if problems:
[email protected]2fdd1f362013-01-16 03:56:03661 if not input_api.is_committing:
662 warning_factory = output_api.PresubmitPromptWarning
663 else:
[email protected]06e6d0ff2012-12-11 01:36:44664 # We don't want to block use of the CQ when there is a warning
665 # of this kind, so we only show a message when committing.
666 warning_factory = output_api.PresubmitNotifyResult
667 return [warning_factory(
668 'Most layers below src/chrome/ should not hardcode service URLs.\n'
669 'Are you sure this is correct? (Contact: [email protected])',
670 [' %s:%d: %s' % (
671 problem[0], problem[1], problem[2]) for problem in problems])]
[email protected]2fdd1f362013-01-16 03:56:03672 else:
673 return []
[email protected]06e6d0ff2012-12-11 01:36:44674
675
[email protected]d2530012013-01-25 16:39:27676def _CheckNoAbbreviationInPngFileName(input_api, output_api):
677 """Makes sure there are no abbreviations in the name of PNG files.
678 """
[email protected]4053a48e2013-01-25 21:43:04679 pattern = input_api.re.compile(r'.*_[a-z]_.*\.png$|.*_[a-z]\.png$')
[email protected]d2530012013-01-25 16:39:27680 errors = []
681 for f in input_api.AffectedFiles(include_deletes=False):
682 if pattern.match(f.LocalPath()):
683 errors.append(' %s' % f.LocalPath())
684
685 results = []
686 if errors:
687 results.append(output_api.PresubmitError(
688 'The name of PNG files should not have abbreviations. \n'
689 'Use _hover.png, _center.png, instead of _h.png, _c.png.\n'
690 'Contact [email protected] if you have questions.', errors))
691 return results
692
693
[email protected]22c9bd72011-03-27 16:47:39694def _CommonChecks(input_api, output_api):
695 """Checks common to both upload and commit."""
696 results = []
697 results.extend(input_api.canned_checks.PanProjectChecks(
698 input_api, output_api, excluded_paths=_EXCLUDED_PATHS))
[email protected]66daa702011-05-28 14:41:46699 results.extend(_CheckAuthorizedAuthor(input_api, output_api))
[email protected]55459852011-08-10 15:17:19700 results.extend(
701 _CheckNoProductionCodeUsingTestOnlyFunctions(input_api, output_api))
[email protected]10689ca2011-09-02 02:31:54702 results.extend(_CheckNoIOStreamInHeaders(input_api, output_api))
[email protected]72df4e782012-06-21 16:28:18703 results.extend(_CheckNoUNIT_TESTInSourceFiles(input_api, output_api))
[email protected]8ea5d4b2011-09-13 21:49:22704 results.extend(_CheckNoNewWStrings(input_api, output_api))
[email protected]2a8ac9c2011-10-19 17:20:44705 results.extend(_CheckNoDEPSGIT(input_api, output_api))
[email protected]127f18ec2012-06-16 05:05:59706 results.extend(_CheckNoBannedFunctions(input_api, output_api))
[email protected]6c063c62012-07-11 19:11:06707 results.extend(_CheckNoPragmaOnce(input_api, output_api))
[email protected]e7479052012-09-19 00:26:12708 results.extend(_CheckNoTrinaryTrueFalse(input_api, output_api))
[email protected]55f9f382012-07-31 11:02:18709 results.extend(_CheckUnwantedDependencies(input_api, output_api))
[email protected]fbcafe5a2012-08-08 15:31:22710 results.extend(_CheckFilePermissions(input_api, output_api))
[email protected]c8278b32012-10-30 20:35:49711 results.extend(_CheckNoAuraWindowPropertyHInHeaders(input_api, output_api))
[email protected]2309b0fa02012-11-16 12:18:27712 results.extend(_CheckIncludeOrder(input_api, output_api))
[email protected]70ca77752012-11-20 03:45:03713 results.extend(_CheckForVersionControlConflicts(input_api, output_api))
[email protected]b8079ae4a2012-12-05 19:56:49714 results.extend(_CheckPatchFiles(input_api, output_api))
[email protected]06e6d0ff2012-12-11 01:36:44715 results.extend(_CheckHardcodedGoogleHostsInLowerLayers(input_api, output_api))
[email protected]d2530012013-01-25 16:39:27716 results.extend(_CheckNoAbbreviationInPngFileName(input_api, output_api))
[email protected]2299dcf2012-11-15 19:56:24717
718 if any('PRESUBMIT.py' == f.LocalPath() for f in input_api.AffectedFiles()):
719 results.extend(input_api.canned_checks.RunUnitTestsInDirectory(
720 input_api, output_api,
721 input_api.PresubmitLocalPath(),
[email protected]6be63382013-01-21 15:42:38722 whitelist=[r'^PRESUBMIT_test\.py$']))
[email protected]22c9bd72011-03-27 16:47:39723 return results
[email protected]1f7b4172010-01-28 01:17:34724
[email protected]b337cb5b2011-01-23 21:24:05725
726def _CheckSubversionConfig(input_api, output_api):
727 """Verifies the subversion config file is correctly setup.
728
729 Checks that autoprops are enabled, returns an error otherwise.
730 """
731 join = input_api.os_path.join
732 if input_api.platform == 'win32':
733 appdata = input_api.environ.get('APPDATA', '')
734 if not appdata:
735 return [output_api.PresubmitError('%APPDATA% is not configured.')]
736 path = join(appdata, 'Subversion', 'config')
737 else:
738 home = input_api.environ.get('HOME', '')
739 if not home:
740 return [output_api.PresubmitError('$HOME is not configured.')]
741 path = join(home, '.subversion', 'config')
742
743 error_msg = (
744 'Please look at http://dev.chromium.org/developers/coding-style to\n'
745 'configure your subversion configuration file. This enables automatic\n'
[email protected]c6a3c10b2011-01-24 16:14:20746 'properties to simplify the project maintenance.\n'
747 'Pro-tip: just download and install\n'
748 'http://src.chromium.org/viewvc/chrome/trunk/tools/build/slave/config\n')
[email protected]b337cb5b2011-01-23 21:24:05749
750 try:
751 lines = open(path, 'r').read().splitlines()
752 # Make sure auto-props is enabled and check for 2 Chromium standard
753 # auto-prop.
754 if (not '*.cc = svn:eol-style=LF' in lines or
755 not '*.pdf = svn:mime-type=application/pdf' in lines or
756 not 'enable-auto-props = yes' in lines):
757 return [
[email protected]79ed7e62011-02-21 21:08:53758 output_api.PresubmitNotifyResult(
[email protected]b337cb5b2011-01-23 21:24:05759 'It looks like you have not configured your subversion config '
[email protected]b5359c02011-02-01 20:29:56760 'file or it is not up-to-date.\n' + error_msg)
[email protected]b337cb5b2011-01-23 21:24:05761 ]
762 except (OSError, IOError):
763 return [
[email protected]79ed7e62011-02-21 21:08:53764 output_api.PresubmitNotifyResult(
[email protected]b337cb5b2011-01-23 21:24:05765 'Can\'t find your subversion config file.\n' + error_msg)
766 ]
767 return []
768
769
[email protected]66daa702011-05-28 14:41:46770def _CheckAuthorizedAuthor(input_api, output_api):
771 """For non-googler/chromites committers, verify the author's email address is
772 in AUTHORS.
773 """
[email protected]9bb9cb82011-06-13 20:43:01774 # TODO(maruel): Add it to input_api?
775 import fnmatch
776
[email protected]66daa702011-05-28 14:41:46777 author = input_api.change.author_email
[email protected]9bb9cb82011-06-13 20:43:01778 if not author:
779 input_api.logging.info('No author, skipping AUTHOR check')
[email protected]66daa702011-05-28 14:41:46780 return []
[email protected]c99663292011-05-31 19:46:08781 authors_path = input_api.os_path.join(
[email protected]66daa702011-05-28 14:41:46782 input_api.PresubmitLocalPath(), 'AUTHORS')
783 valid_authors = (
784 input_api.re.match(r'[^#]+\s+\<(.+?)\>\s*$', line)
785 for line in open(authors_path))
[email protected]ac54b132011-06-06 18:11:18786 valid_authors = [item.group(1).lower() for item in valid_authors if item]
[email protected]d8b50be2011-06-15 14:19:44787 if not any(fnmatch.fnmatch(author.lower(), valid) for valid in valid_authors):
[email protected]5861efb2013-01-07 18:33:23788 input_api.logging.info('Valid authors are %s', ', '.join(valid_authors))
[email protected]66daa702011-05-28 14:41:46789 return [output_api.PresubmitPromptWarning(
790 ('%s is not in AUTHORS file. If you are a new contributor, please visit'
791 '\n'
792 'http://www.chromium.org/developers/contributing-code and read the '
793 '"Legal" section\n'
794 'If you are a chromite, verify the contributor signed the CLA.') %
795 author)]
796 return []
797
798
[email protected]b8079ae4a2012-12-05 19:56:49799def _CheckPatchFiles(input_api, output_api):
800 problems = [f.LocalPath() for f in input_api.AffectedFiles()
801 if f.LocalPath().endswith(('.orig', '.rej'))]
802 if problems:
803 return [output_api.PresubmitError(
804 "Don't commit .rej and .orig files.", problems)]
[email protected]2fdd1f362013-01-16 03:56:03805 else:
806 return []
[email protected]b8079ae4a2012-12-05 19:56:49807
808
[email protected]1f7b4172010-01-28 01:17:34809def CheckChangeOnUpload(input_api, output_api):
810 results = []
811 results.extend(_CommonChecks(input_api, output_api))
[email protected]fe5f57c52009-06-05 14:25:54812 return results
[email protected]ca8d1982009-02-19 16:33:12813
814
815def CheckChangeOnCommit(input_api, output_api):
[email protected]fe5f57c52009-06-05 14:25:54816 results = []
[email protected]1f7b4172010-01-28 01:17:34817 results.extend(_CommonChecks(input_api, output_api))
[email protected]dd805fe2009-10-01 08:11:51818 # TODO(thestig) temporarily disabled, doesn't work in third_party/
819 #results.extend(input_api.canned_checks.CheckSvnModifiedDirectories(
820 # input_api, output_api, sources))
[email protected]fe5f57c52009-06-05 14:25:54821 # Make sure the tree is 'open'.
[email protected]806e98e2010-03-19 17:49:27822 results.extend(input_api.canned_checks.CheckTreeIsOpen(
[email protected]7f238152009-08-12 19:00:34823 input_api,
824 output_api,
[email protected]2fdd1f362013-01-16 03:56:03825 json_url='http://chromium-status.appspot.com/current?format=json'))
[email protected]806e98e2010-03-19 17:49:27826 results.extend(input_api.canned_checks.CheckRietveldTryJobExecution(input_api,
[email protected]2fdd1f362013-01-16 03:56:03827 output_api, 'http://codereview.chromium.org',
[email protected]c1ba4c52012-03-09 14:23:28828 ('win_rel', 'linux_rel', 'mac_rel, win:compile'),
829 '[email protected]'))
[email protected]806e98e2010-03-19 17:49:27830
[email protected]3e4eb112011-01-18 03:29:54831 results.extend(input_api.canned_checks.CheckChangeHasBugField(
832 input_api, output_api))
[email protected]c4b47562011-12-05 23:39:41833 results.extend(input_api.canned_checks.CheckChangeHasDescription(
834 input_api, output_api))
[email protected]b337cb5b2011-01-23 21:24:05835 results.extend(_CheckSubversionConfig(input_api, output_api))
[email protected]fe5f57c52009-06-05 14:25:54836 return results
[email protected]ca8d1982009-02-19 16:33:12837
838
[email protected]5efb2a822011-09-27 23:06:13839def GetPreferredTrySlaves(project, change):
[email protected]4ce995ea2012-06-27 02:13:10840 files = change.LocalPaths()
841
[email protected]751b05f2013-01-10 23:12:17842 if not files or all(re.search(r'[\\/]OWNERS$', f) for f in files):
[email protected]3019c902012-06-29 00:09:03843 return []
844
[email protected]d668899a2012-09-06 18:16:59845 if all(re.search('\.(m|mm)$|(^|[/_])mac[/_.]', f) for f in files):
[email protected]641f2e3e2012-09-03 11:16:24846 return ['mac_rel', 'mac_asan']
[email protected]d668899a2012-09-06 18:16:59847 if all(re.search('(^|[/_])win[/_.]', f) for f in files):
[email protected]4ce995ea2012-06-27 02:13:10848 return ['win_rel']
[email protected]d668899a2012-09-06 18:16:59849 if all(re.search('(^|[/_])android[/_.]', f) for f in files):
[email protected]3e2f0402012-11-02 16:28:01850 return ['android_dbg', 'android_clang_dbg']
[email protected]356aa542012-09-19 23:31:29851 if all(re.search('^native_client_sdk', f) for f in files):
852 return ['linux_nacl_sdk', 'win_nacl_sdk', 'mac_nacl_sdk']
[email protected]de142152012-10-03 23:02:45853 if all(re.search('[/_]ios[/_.]', f) for f in files):
854 return ['ios_rel_device', 'ios_dbg_simulator']
[email protected]4ce995ea2012-06-27 02:13:10855
[email protected]3e2f0402012-11-02 16:28:01856 trybots = [
857 'android_clang_dbg',
858 'android_dbg',
859 'ios_dbg_simulator',
860 'ios_rel_device',
861 'linux_asan',
[email protected]95c989162012-11-29 05:58:25862 'linux_aura',
[email protected]3e2f0402012-11-02 16:28:01863 'linux_chromeos',
864 'linux_clang:compile',
865 'linux_rel',
866 'mac_asan',
867 'mac_rel',
[email protected]aa85c8b2013-01-11 04:20:28868 'win7_aura',
[email protected]3e2f0402012-11-02 16:28:01869 'win_rel',
870 ]
[email protected]911753b2012-08-02 12:11:54871
872 # Match things like path/aura/file.cc and path/file_aura.cc.
[email protected]95c989162012-11-29 05:58:25873 # Same for chromeos.
874 if any(re.search('[/_](aura|chromeos)', f) for f in files):
[email protected]3e2f0402012-11-02 16:28:01875 trybots += ['linux_chromeos_clang:compile', 'linux_chromeos_asan']
[email protected]4ce995ea2012-06-27 02:13:10876
[email protected]4ce995ea2012-06-27 02:13:10877 return trybots