1 # Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file.
5 """Top-level presubmit script for Chromium.
7 See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
8 for more details about the presubmit API built into gcl.
19 r
"^native_client_sdk[\\\/]src[\\\/]build_tools[\\\/]make_rules.py",
20 r
"^native_client_sdk[\\\/]src[\\\/]build_tools[\\\/]make_simple.py",
21 r
"^native_client_sdk[\\\/]src[\\\/]tools[\\\/].*.mk",
22 r
"^net[\\\/]tools[\\\/]spdyshark[\\\/].*",
27 r
".+[\\\/]pnacl_shim\.c$",
30 # Fragment of a regular expression that matches file name suffixes
31 # used to indicate different platforms.
32 _PLATFORM_SPECIFIERS
= r
'(_(android|chromeos|gtk|mac|posix|win))?'
34 # Fragment of a regular expression that matches C++ and Objective-C++
35 # implementation files.
36 _IMPLEMENTATION_EXTENSIONS
= r
'\.(cc|cpp|cxx|mm)$'
38 # Regular expression that matches code only used for test binaries
40 _TEST_CODE_EXCLUDED_PATHS
= (
41 r
'.*[/\\](fake_|test_|mock_).+%s' % _IMPLEMENTATION_EXTENSIONS
,
42 r
'.+_test_(base|support|util)%s' % _IMPLEMENTATION_EXTENSIONS
,
43 r
'.+_(api|browser|perf|unit|ui)?test%s%s' % (_PLATFORM_SPECIFIERS
,
44 _IMPLEMENTATION_EXTENSIONS
),
45 r
'.+profile_sync_service_harness%s' % _IMPLEMENTATION_EXTENSIONS
,
46 r
'.*[/\\](test|tool(s)?)[/\\].*',
47 # At request of folks maintaining this folder.
48 r
'chrome[/\\]browser[/\\]automation[/\\].*',
51 _TEST_ONLY_WARNING
= (
52 'You might be calling functions intended only for testing from\n'
53 'production code. It is OK to ignore this warning if you know what\n'
54 'you are doing, as the heuristics used to detect the situation are\n'
55 'not perfect. The commit queue will not block on this warning.\n'
56 'Email joi@chromium.org if you have questions.')
59 _INCLUDE_ORDER_WARNING
= (
60 'Your #include order seems to be broken. Send mail to\n'
61 'marja@chromium.org if this is not the case.')
64 _BANNED_OBJC_FUNCTIONS
= (
68 'The use of -[NSView addTrackingRect:owner:userData:assumeInside:] is'
69 'prohibited. Please use CrTrackingArea instead.',
70 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
77 'The use of NSTrackingAreas is prohibited. Please use CrTrackingArea',
79 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
84 'convertPointFromBase:',
86 'The use of -[NSView convertPointFromBase:] is almost certainly wrong.',
87 'Please use |convertPoint:(point) fromView:nil| instead.',
88 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
93 'convertPointToBase:',
95 'The use of -[NSView convertPointToBase:] is almost certainly wrong.',
96 'Please use |convertPoint:(point) toView:nil| instead.',
97 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
102 'convertRectFromBase:',
104 'The use of -[NSView convertRectFromBase:] is almost certainly wrong.',
105 'Please use |convertRect:(point) fromView:nil| instead.',
106 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
111 'convertRectToBase:',
113 'The use of -[NSView convertRectToBase:] is almost certainly wrong.',
114 'Please use |convertRect:(point) toView:nil| instead.',
115 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
120 'convertSizeFromBase:',
122 'The use of -[NSView convertSizeFromBase:] is almost certainly wrong.',
123 'Please use |convertSize:(point) fromView:nil| instead.',
124 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
129 'convertSizeToBase:',
131 'The use of -[NSView convertSizeToBase:] is almost certainly wrong.',
132 'Please use |convertSize:(point) toView:nil| instead.',
133 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
140 _BANNED_CPP_FUNCTIONS
= (
141 # Make sure that gtest's FRIEND_TEST() macro is not used; the
142 # FRIEND_TEST_ALL_PREFIXES() macro from base/gtest_prod_util.h should be
143 # used instead since that allows for FLAKY_ and DISABLED_ prefixes.
147 'Chromium code should not use gtest\'s FRIEND_TEST() macro. Include',
148 'base/gtest_prod_util.h and use FRIEND_TEST_ALL_PREFIXES() instead.',
156 'New code should not use ScopedAllowIO. Post a task to the blocking',
157 'pool or the FILE thread instead.',
161 r
"^content[\\\/]shell[\\\/]shell_browser_main\.cc$",
162 r
"^net[\\\/]disk_cache[\\\/]cache_util\.cc$",
169 # Please keep sorted.
172 'OS_CAT', # For testing.
186 def _CheckNoProductionCodeUsingTestOnlyFunctions(input_api
, output_api
):
187 """Attempts to prevent use of functions intended only for testing in
188 non-testing code. For now this is just a best-effort implementation
189 that ignores header files and may have some false positives. A
190 better implementation would probably need a proper C++ parser.
192 # We only scan .cc files and the like, as the declaration of
193 # for-testing functions in header files are hard to distinguish from
194 # calls to such functions without a proper C++ parser.
195 file_inclusion_pattern
= r
'.+%s' % _IMPLEMENTATION_EXTENSIONS
197 base_function_pattern
= r
'ForTest(ing)?|for_test(ing)?'
198 inclusion_pattern
= input_api
.re
.compile(r
'(%s)\s*\(' % base_function_pattern
)
199 exclusion_pattern
= input_api
.re
.compile(
200 r
'::[A-Za-z0-9_]+(%s)|(%s)[^;]+\{' % (
201 base_function_pattern
, base_function_pattern
))
203 def FilterFile(affected_file
):
204 black_list
= (_EXCLUDED_PATHS
+
205 _TEST_CODE_EXCLUDED_PATHS
+
206 input_api
.DEFAULT_BLACK_LIST
)
207 return input_api
.FilterSourceFile(
209 white_list
=(file_inclusion_pattern
, ),
210 black_list
=black_list
)
213 for f
in input_api
.AffectedSourceFiles(FilterFile
):
214 local_path
= f
.LocalPath()
215 lines
= input_api
.ReadFile(f
).splitlines()
218 if (inclusion_pattern
.search(line
) and
219 not exclusion_pattern
.search(line
)):
221 '%s:%d\n %s' % (local_path
, line_number
, line
.strip()))
225 return [output_api
.PresubmitPromptOrNotify(_TEST_ONLY_WARNING
, problems
)]
230 def _CheckNoIOStreamInHeaders(input_api
, output_api
):
231 """Checks to make sure no .h files include <iostream>."""
233 pattern
= input_api
.re
.compile(r
'^#include\s*<iostream>',
234 input_api
.re
.MULTILINE
)
235 for f
in input_api
.AffectedSourceFiles(input_api
.FilterSourceFile
):
236 if not f
.LocalPath().endswith('.h'):
238 contents
= input_api
.ReadFile(f
)
239 if pattern
.search(contents
):
243 return [ output_api
.PresubmitError(
244 'Do not #include <iostream> in header files, since it inserts static '
245 'initialization into every file including the header. Instead, '
246 '#include <ostream>. See http://crbug.com/94794',
251 def _CheckNoUNIT_TESTInSourceFiles(input_api
, output_api
):
252 """Checks to make sure no source files use UNIT_TEST"""
254 for f
in input_api
.AffectedFiles():
255 if (not f
.LocalPath().endswith(('.cc', '.mm'))):
258 for line_num
, line
in f
.ChangedContents():
259 if 'UNIT_TEST' in line
:
260 problems
.append(' %s:%d' % (f
.LocalPath(), line_num
))
264 return [output_api
.PresubmitPromptWarning('UNIT_TEST is only for headers.\n' +
265 '\n'.join(problems
))]
268 def _CheckNoNewWStrings(input_api
, output_api
):
269 """Checks to make sure we don't introduce use of wstrings."""
271 for f
in input_api
.AffectedFiles():
272 if (not f
.LocalPath().endswith(('.cc', '.h')) or
273 f
.LocalPath().endswith('test.cc')):
277 for line_num
, line
in f
.ChangedContents():
278 if 'presubmit: allow wstring' in line
:
280 elif not allowWString
and 'wstring' in line
:
281 problems
.append(' %s:%d' % (f
.LocalPath(), line_num
))
288 return [output_api
.PresubmitPromptWarning('New code should not use wstrings.'
289 ' If you are calling a cross-platform API that accepts a wstring, '
291 '\n'.join(problems
))]
294 def _CheckNoDEPSGIT(input_api
, output_api
):
295 """Make sure .DEPS.git is never modified manually."""
296 if any(f
.LocalPath().endswith('.DEPS.git') for f
in
297 input_api
.AffectedFiles()):
298 return [output_api
.PresubmitError(
299 'Never commit changes to .DEPS.git. This file is maintained by an\n'
300 'automated system based on what\'s in DEPS and your changes will be\n'
302 'See http://code.google.com/p/chromium/wiki/UsingNewGit#Rolling_DEPS\n'
303 'for more information')]
307 def _CheckNoBannedFunctions(input_api
, output_api
):
308 """Make sure that banned functions are not used."""
312 file_filter
= lambda f
: f
.LocalPath().endswith(('.mm', '.m', '.h'))
313 for f
in input_api
.AffectedFiles(file_filter
=file_filter
):
314 for line_num
, line
in f
.ChangedContents():
315 for func_name
, message
, error
in _BANNED_OBJC_FUNCTIONS
:
316 if func_name
in line
:
320 problems
.append(' %s:%d:' % (f
.LocalPath(), line_num
))
321 for message_line
in message
:
322 problems
.append(' %s' % message_line
)
324 file_filter
= lambda f
: f
.LocalPath().endswith(('.cc', '.mm', '.h'))
325 for f
in input_api
.AffectedFiles(file_filter
=file_filter
):
326 for line_num
, line
in f
.ChangedContents():
327 for func_name
, message
, error
, excluded_paths
in _BANNED_CPP_FUNCTIONS
:
328 def IsBlacklisted(affected_file
, blacklist
):
329 local_path
= affected_file
.LocalPath()
330 for item
in blacklist
:
331 if input_api
.re
.match(item
, local_path
):
334 if IsBlacklisted(f
, excluded_paths
):
336 if func_name
in line
:
340 problems
.append(' %s:%d:' % (f
.LocalPath(), line_num
))
341 for message_line
in message
:
342 problems
.append(' %s' % message_line
)
346 result
.append(output_api
.PresubmitPromptWarning(
347 'Banned functions were used.\n' + '\n'.join(warnings
)))
349 result
.append(output_api
.PresubmitError(
350 'Banned functions were used.\n' + '\n'.join(errors
)))
354 def _CheckNoPragmaOnce(input_api
, output_api
):
355 """Make sure that banned functions are not used."""
357 pattern
= input_api
.re
.compile(r
'^#pragma\s+once',
358 input_api
.re
.MULTILINE
)
359 for f
in input_api
.AffectedSourceFiles(input_api
.FilterSourceFile
):
360 if not f
.LocalPath().endswith('.h'):
362 contents
= input_api
.ReadFile(f
)
363 if pattern
.search(contents
):
367 return [output_api
.PresubmitError(
368 'Do not use #pragma once in header files.\n'
369 'See http://www.chromium.org/developers/coding-style#TOC-File-headers',
374 def _CheckNoTrinaryTrueFalse(input_api
, output_api
):
375 """Checks to make sure we don't introduce use of foo ? true : false."""
377 pattern
= input_api
.re
.compile(r
'\?\s*(true|false)\s*:\s*(true|false)')
378 for f
in input_api
.AffectedFiles():
379 if not f
.LocalPath().endswith(('.cc', '.h', '.inl', '.m', '.mm')):
382 for line_num
, line
in f
.ChangedContents():
383 if pattern
.match(line
):
384 problems
.append(' %s:%d' % (f
.LocalPath(), line_num
))
388 return [output_api
.PresubmitPromptWarning(
389 'Please consider avoiding the "? true : false" pattern if possible.\n' +
390 '\n'.join(problems
))]
393 def _CheckUnwantedDependencies(input_api
, output_api
):
394 """Runs checkdeps on #include statements added in this
395 change. Breaking - rules is an error, breaking ! rules is a
398 # We need to wait until we have an input_api object and use this
399 # roundabout construct to import checkdeps because this file is
400 # eval-ed and thus doesn't have __file__.
401 original_sys_path
= sys
.path
403 sys
.path
= sys
.path
+ [input_api
.os_path
.join(
404 input_api
.PresubmitLocalPath(), 'tools', 'checkdeps')]
406 from cpp_checker
import CppChecker
407 from rules
import Rule
409 # Restore sys.path to what it was before.
410 sys
.path
= original_sys_path
413 for f
in input_api
.AffectedFiles():
414 if not CppChecker
.IsCppFile(f
.LocalPath()):
417 changed_lines
= [line
for line_num
, line
in f
.ChangedContents()]
418 added_includes
.append([f
.LocalPath(), changed_lines
])
420 deps_checker
= checkdeps
.DepsChecker()
422 error_descriptions
= []
423 warning_descriptions
= []
424 for path
, rule_type
, rule_description
in deps_checker
.CheckAddedCppIncludes(
426 description_with_path
= '%s\n %s' % (path
, rule_description
)
427 if rule_type
== Rule
.DISALLOW
:
428 error_descriptions
.append(description_with_path
)
430 warning_descriptions
.append(description_with_path
)
433 if error_descriptions
:
434 results
.append(output_api
.PresubmitError(
435 'You added one or more #includes that violate checkdeps rules.',
437 if warning_descriptions
:
438 results
.append(output_api
.PresubmitPromptOrNotify(
439 'You added one or more #includes of files that are temporarily\n'
440 'allowed but being removed. Can you avoid introducing the\n'
441 '#include? See relevant DEPS file(s) for details and contacts.',
442 warning_descriptions
))
446 def _CheckFilePermissions(input_api
, output_api
):
447 """Check that all files have their permissions properly set."""
448 args
= [sys
.executable
, 'tools/checkperms/checkperms.py', '--root',
449 input_api
.change
.RepositoryRoot()]
450 for f
in input_api
.AffectedFiles():
451 args
+= ['--file', f
.LocalPath()]
453 (errors
, stderrdata
) = subprocess
.Popen(args
).communicate()
457 results
.append(output_api
.PresubmitError('checkperms.py failed.',
462 def _CheckNoAuraWindowPropertyHInHeaders(input_api
, output_api
):
463 """Makes sure we don't include ui/aura/window_property.h
466 pattern
= input_api
.re
.compile(r
'^#include\s*"ui/aura/window_property.h"')
468 for f
in input_api
.AffectedFiles():
469 if not f
.LocalPath().endswith('.h'):
471 for line_num
, line
in f
.ChangedContents():
472 if pattern
.match(line
):
473 errors
.append(' %s:%d' % (f
.LocalPath(), line_num
))
477 results
.append(output_api
.PresubmitError(
478 'Header files should not include ui/aura/window_property.h', errors
))
482 def _CheckIncludeOrderForScope(scope
, input_api
, file_path
, changed_linenums
):
483 """Checks that the lines in scope occur in the right order.
485 1. C system files in alphabetical order
486 2. C++ system files in alphabetical order
487 3. Project's .h files
490 c_system_include_pattern
= input_api
.re
.compile(r
'\s*#include <.*\.h>')
491 cpp_system_include_pattern
= input_api
.re
.compile(r
'\s*#include <.*>')
492 custom_include_pattern
= input_api
.re
.compile(r
'\s*#include ".*')
494 C_SYSTEM_INCLUDES
, CPP_SYSTEM_INCLUDES
, CUSTOM_INCLUDES
= range(3)
496 state
= C_SYSTEM_INCLUDES
499 previous_line_num
= 0
500 problem_linenums
= []
501 for line_num
, line
in scope
:
502 if c_system_include_pattern
.match(line
):
503 if state
!= C_SYSTEM_INCLUDES
:
504 problem_linenums
.append((line_num
, previous_line_num
))
505 elif previous_line
and previous_line
> line
:
506 problem_linenums
.append((line_num
, previous_line_num
))
507 elif cpp_system_include_pattern
.match(line
):
508 if state
== C_SYSTEM_INCLUDES
:
509 state
= CPP_SYSTEM_INCLUDES
510 elif state
== CUSTOM_INCLUDES
:
511 problem_linenums
.append((line_num
, previous_line_num
))
512 elif previous_line
and previous_line
> line
:
513 problem_linenums
.append((line_num
, previous_line_num
))
514 elif custom_include_pattern
.match(line
):
515 if state
!= CUSTOM_INCLUDES
:
516 state
= CUSTOM_INCLUDES
517 elif previous_line
and previous_line
> line
:
518 problem_linenums
.append((line_num
, previous_line_num
))
520 problem_linenums
.append(line_num
)
522 previous_line_num
= line_num
525 for (line_num
, previous_line_num
) in problem_linenums
:
526 if line_num
in changed_linenums
or previous_line_num
in changed_linenums
:
527 warnings
.append(' %s:%d' % (file_path
, line_num
))
531 def _CheckIncludeOrderInFile(input_api
, f
, changed_linenums
):
532 """Checks the #include order for the given file f."""
534 system_include_pattern
= input_api
.re
.compile(r
'\s*#include \<.*')
535 # Exclude #include <.../...> includes from the check; e.g., <sys/...> includes
536 # often need to appear in a specific order.
537 excluded_include_pattern
= input_api
.re
.compile(r
'\s*#include \<.*/.*')
538 custom_include_pattern
= input_api
.re
.compile(r
'\s*#include "(?P<FILE>.*)"')
539 if_pattern
= input_api
.re
.compile(
540 r
'\s*#\s*(if|elif|else|endif|define|undef).*')
541 # Some files need specialized order of includes; exclude such files from this
543 uncheckable_includes_pattern
= input_api
.re
.compile(
545 '("ipc/.*macros\.h"|<windows\.h>|".*gl.*autogen.h")\s*')
547 contents
= f
.NewContents()
551 # Handle the special first include. If the first include file is
552 # some/path/file.h, the corresponding including file can be some/path/file.cc,
553 # some/other/path/file.cc, some/path/file_platform.cc, some/path/file-suffix.h
554 # etc. It's also possible that no special first include exists.
555 for line
in contents
:
557 if system_include_pattern
.match(line
):
558 # No special first include -> process the line again along with normal
562 match
= custom_include_pattern
.match(line
)
564 match_dict
= match
.groupdict()
565 header_basename
= input_api
.os_path
.basename(
566 match_dict
['FILE']).replace('.h', '')
567 if header_basename
not in input_api
.os_path
.basename(f
.LocalPath()):
568 # No special first include -> process the line again along with normal
573 # Split into scopes: Each region between #if and #endif is its own scope.
576 for line
in contents
[line_num
:]:
578 if uncheckable_includes_pattern
.match(line
):
580 if if_pattern
.match(line
):
581 scopes
.append(current_scope
)
583 elif ((system_include_pattern
.match(line
) or
584 custom_include_pattern
.match(line
)) and
585 not excluded_include_pattern
.match(line
)):
586 current_scope
.append((line_num
, line
))
587 scopes
.append(current_scope
)
590 warnings
.extend(_CheckIncludeOrderForScope(scope
, input_api
, f
.LocalPath(),
595 def _CheckIncludeOrder(input_api
, output_api
):
596 """Checks that the #include order is correct.
598 1. The corresponding header for source files.
599 2. C system files in alphabetical order
600 3. C++ system files in alphabetical order
601 4. Project's .h files in alphabetical order
603 Each region separated by #if, #elif, #else, #endif, #define and #undef follows
604 these rules separately.
608 for f
in input_api
.AffectedFiles():
609 if f
.LocalPath().endswith(('.cc', '.h')):
610 changed_linenums
= set(line_num
for line_num
, _
in f
.ChangedContents())
611 warnings
.extend(_CheckIncludeOrderInFile(input_api
, f
, changed_linenums
))
615 results
.append(output_api
.PresubmitPromptOrNotify(_INCLUDE_ORDER_WARNING
,
620 def _CheckForVersionControlConflictsInFile(input_api
, f
):
621 pattern
= input_api
.re
.compile('^(?:<<<<<<<|>>>>>>>) |^=======$')
623 for line_num
, line
in f
.ChangedContents():
624 if pattern
.match(line
):
625 errors
.append(' %s:%d %s' % (f
.LocalPath(), line_num
, line
))
629 def _CheckForVersionControlConflicts(input_api
, output_api
):
630 """Usually this is not intentional and will cause a compile failure."""
632 for f
in input_api
.AffectedFiles():
633 errors
.extend(_CheckForVersionControlConflictsInFile(input_api
, f
))
637 results
.append(output_api
.PresubmitError(
638 'Version control conflict markers found, please resolve.', errors
))
642 def _CheckHardcodedGoogleHostsInLowerLayers(input_api
, output_api
):
643 def FilterFile(affected_file
):
644 """Filter function for use with input_api.AffectedSourceFiles,
645 below. This filters out everything except non-test files from
646 top-level directories that generally speaking should not hard-code
647 service URLs (e.g. src/android_webview/, src/content/ and others).
649 return input_api
.FilterSourceFile(
651 white_list
=(r
'^(android_webview|base|content|net)[\\\/].*', ),
652 black_list
=(_EXCLUDED_PATHS
+
653 _TEST_CODE_EXCLUDED_PATHS
+
654 input_api
.DEFAULT_BLACK_LIST
))
656 pattern
= input_api
.re
.compile('"[^"]*google\.com[^"]*"')
657 problems
= [] # items are (filename, line_number, line)
658 for f
in input_api
.AffectedSourceFiles(FilterFile
):
659 for line_num
, line
in f
.ChangedContents():
660 if pattern
.search(line
):
661 problems
.append((f
.LocalPath(), line_num
, line
))
664 return [output_api
.PresubmitPromptOrNotify(
665 'Most layers below src/chrome/ should not hardcode service URLs.\n'
666 'Are you sure this is correct? (Contact: joi@chromium.org)',
668 problem
[0], problem
[1], problem
[2]) for problem
in problems
])]
673 def _CheckNoAbbreviationInPngFileName(input_api
, output_api
):
674 """Makes sure there are no abbreviations in the name of PNG files.
676 pattern
= input_api
.re
.compile(r
'.*_[a-z]_.*\.png$|.*_[a-z]\.png$')
678 for f
in input_api
.AffectedFiles(include_deletes
=False):
679 if pattern
.match(f
.LocalPath()):
680 errors
.append(' %s' % f
.LocalPath())
684 results
.append(output_api
.PresubmitError(
685 'The name of PNG files should not have abbreviations. \n'
686 'Use _hover.png, _center.png, instead of _h.png, _c.png.\n'
687 'Contact oshima@chromium.org if you have questions.', errors
))
691 def _CommonChecks(input_api
, output_api
):
692 """Checks common to both upload and commit."""
694 results
.extend(input_api
.canned_checks
.PanProjectChecks(
695 input_api
, output_api
, excluded_paths
=_EXCLUDED_PATHS
))
696 results
.extend(_CheckAuthorizedAuthor(input_api
, output_api
))
698 _CheckNoProductionCodeUsingTestOnlyFunctions(input_api
, output_api
))
699 results
.extend(_CheckNoIOStreamInHeaders(input_api
, output_api
))
700 results
.extend(_CheckNoUNIT_TESTInSourceFiles(input_api
, output_api
))
701 results
.extend(_CheckNoNewWStrings(input_api
, output_api
))
702 results
.extend(_CheckNoDEPSGIT(input_api
, output_api
))
703 results
.extend(_CheckNoBannedFunctions(input_api
, output_api
))
704 results
.extend(_CheckNoPragmaOnce(input_api
, output_api
))
705 results
.extend(_CheckNoTrinaryTrueFalse(input_api
, output_api
))
706 results
.extend(_CheckUnwantedDependencies(input_api
, output_api
))
707 results
.extend(_CheckFilePermissions(input_api
, output_api
))
708 results
.extend(_CheckNoAuraWindowPropertyHInHeaders(input_api
, output_api
))
709 results
.extend(_CheckIncludeOrder(input_api
, output_api
))
710 results
.extend(_CheckForVersionControlConflicts(input_api
, output_api
))
711 results
.extend(_CheckPatchFiles(input_api
, output_api
))
712 results
.extend(_CheckHardcodedGoogleHostsInLowerLayers(input_api
, output_api
))
713 results
.extend(_CheckNoAbbreviationInPngFileName(input_api
, output_api
))
714 results
.extend(_CheckForInvalidOSMacros(input_api
, output_api
))
716 if any('PRESUBMIT.py' == f
.LocalPath() for f
in input_api
.AffectedFiles()):
717 results
.extend(input_api
.canned_checks
.RunUnitTestsInDirectory(
718 input_api
, output_api
,
719 input_api
.PresubmitLocalPath(),
720 whitelist
=[r
'^PRESUBMIT_test\.py$']))
724 def _CheckSubversionConfig(input_api
, output_api
):
725 """Verifies the subversion config file is correctly setup.
727 Checks that autoprops are enabled, returns an error otherwise.
729 join
= input_api
.os_path
.join
730 if input_api
.platform
== 'win32':
731 appdata
= input_api
.environ
.get('APPDATA', '')
733 return [output_api
.PresubmitError('%APPDATA% is not configured.')]
734 path
= join(appdata
, 'Subversion', 'config')
736 home
= input_api
.environ
.get('HOME', '')
738 return [output_api
.PresubmitError('$HOME is not configured.')]
739 path
= join(home
, '.subversion', 'config')
742 'Please look at http://dev.chromium.org/developers/coding-style to\n'
743 'configure your subversion configuration file. This enables automatic\n'
744 'properties to simplify the project maintenance.\n'
745 'Pro-tip: just download and install\n'
746 'http://src.chromium.org/viewvc/chrome/trunk/tools/build/slave/config\n')
749 lines
= open(path
, 'r').read().splitlines()
750 # Make sure auto-props is enabled and check for 2 Chromium standard
752 if (not '*.cc = svn:eol-style=LF' in lines
or
753 not '*.pdf = svn:mime-type=application/pdf' in lines
or
754 not 'enable-auto-props = yes' in lines
):
756 output_api
.PresubmitNotifyResult(
757 'It looks like you have not configured your subversion config '
758 'file or it is not up-to-date.\n' + error_msg
)
760 except (OSError, IOError):
762 output_api
.PresubmitNotifyResult(
763 'Can\'t find your subversion config file.\n' + error_msg
)
768 def _CheckAuthorizedAuthor(input_api
, output_api
):
769 """For non-googler/chromites committers, verify the author's email address is
772 # TODO(maruel): Add it to input_api?
775 author
= input_api
.change
.author_email
777 input_api
.logging
.info('No author, skipping AUTHOR check')
779 authors_path
= input_api
.os_path
.join(
780 input_api
.PresubmitLocalPath(), 'AUTHORS')
782 input_api
.re
.match(r
'[^#]+\s+\<(.+?)\>\s*$', line
)
783 for line
in open(authors_path
))
784 valid_authors
= [item
.group(1).lower() for item
in valid_authors
if item
]
785 if not any(fnmatch
.fnmatch(author
.lower(), valid
) for valid
in valid_authors
):
786 input_api
.logging
.info('Valid authors are %s', ', '.join(valid_authors
))
787 return [output_api
.PresubmitPromptWarning(
788 ('%s is not in AUTHORS file. If you are a new contributor, please visit'
790 'http://www.chromium.org/developers/contributing-code and read the '
792 'If you are a chromite, verify the contributor signed the CLA.') %
797 def _CheckPatchFiles(input_api
, output_api
):
798 problems
= [f
.LocalPath() for f
in input_api
.AffectedFiles()
799 if f
.LocalPath().endswith(('.orig', '.rej'))]
801 return [output_api
.PresubmitError(
802 "Don't commit .rej and .orig files.", problems
)]
807 def _DidYouMeanOSMacro(bad_macro
):
809 return {'A': 'OS_ANDROID',
819 'W': 'OS_WIN'}[bad_macro
[3].upper()]
824 def _CheckForInvalidOSMacrosInFile(input_api
, f
):
825 """Check for sensible looking, totally invalid OS macros."""
826 preprocessor_statement
= input_api
.re
.compile(r
'^\s*#')
827 os_macro
= input_api
.re
.compile(r
'defined\((OS_[^)]+)\)')
829 for lnum
, line
in f
.ChangedContents():
830 if preprocessor_statement
.search(line
):
831 for match
in os_macro
.finditer(line
):
832 if not match
.group(1) in _VALID_OS_MACROS
:
833 good
= _DidYouMeanOSMacro(match
.group(1))
834 did_you_mean
= ' (did you mean %s?)' % good
if good
else ''
835 results
.append(' %s:%d %s%s' % (f
.LocalPath(),
842 def _CheckForInvalidOSMacros(input_api
, output_api
):
843 """Check all affected files for invalid OS macros."""
845 for f
in input_api
.AffectedFiles():
846 if not f
.LocalPath().endswith(('.py', '.js', '.html', '.css')):
847 bad_macros
.extend(_CheckForInvalidOSMacrosInFile(input_api
, f
))
852 return [output_api
.PresubmitError(
853 'Possibly invalid OS macro[s] found. Please fix your code\n'
854 'or add your macro to src/PRESUBMIT.py.', bad_macros
)]
857 def CheckChangeOnUpload(input_api
, output_api
):
859 results
.extend(_CommonChecks(input_api
, output_api
))
863 def CheckChangeOnCommit(input_api
, output_api
):
865 results
.extend(_CommonChecks(input_api
, output_api
))
866 # TODO(thestig) temporarily disabled, doesn't work in third_party/
867 #results.extend(input_api.canned_checks.CheckSvnModifiedDirectories(
868 # input_api, output_api, sources))
869 # Make sure the tree is 'open'.
870 results
.extend(input_api
.canned_checks
.CheckTreeIsOpen(
873 json_url
='http://chromium-status.appspot.com/current?format=json'))
874 results
.extend(input_api
.canned_checks
.CheckRietveldTryJobExecution(input_api
,
875 output_api
, 'http://codereview.chromium.org',
876 ('win_rel', 'linux_rel', 'mac_rel, win:compile'),
877 'tryserver@chromium.org'))
879 results
.extend(input_api
.canned_checks
.CheckChangeHasBugField(
880 input_api
, output_api
))
881 results
.extend(input_api
.canned_checks
.CheckChangeHasDescription(
882 input_api
, output_api
))
883 results
.extend(_CheckSubversionConfig(input_api
, output_api
))
887 def GetPreferredTrySlaves(project
, change
):
888 files
= change
.LocalPaths()
890 if not files
or all(re
.search(r
'[\\/]OWNERS$', f
) for f
in files
):
893 if all(re
.search('\.(m|mm)$|(^|[/_])mac[/_.]', f
) for f
in files
):
894 return ['mac_rel', 'mac_asan', 'mac:compile']
895 if all(re
.search('(^|[/_])win[/_.]', f
) for f
in files
):
896 return ['win_rel', 'win7_aura', 'win:compile']
897 if all(re
.search('(^|[/_])android[/_.]', f
) for f
in files
):
898 return ['android_dbg', 'android_clang_dbg']
899 if all(re
.search('^native_client_sdk', f
) for f
in files
):
900 return ['linux_nacl_sdk', 'win_nacl_sdk', 'mac_nacl_sdk']
901 if all(re
.search('[/_]ios[/_.]', f
) for f
in files
):
902 return ['ios_rel_device', 'ios_dbg_simulator']
912 'linux_clang:compile',
922 # Match things like path/aura/file.cc and path/file_aura.cc.
924 if any(re
.search('[/_](aura|chromeos)', f
) for f
in files
):
925 trybots
+= ['linux_chromeos_clang:compile', 'linux_chromeos_asan']