blob: 9ad9cd189ee1497b596361ffc109a29ef4176fed [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]8886ffcb2013-02-12 04:56:2821 r"^native_client_sdk[\\\/]src[\\\/]tools[\\\/].*.mk",
[email protected]a18130a2012-01-03 17:52:0822 r"^net[\\\/]tools[\\\/]spdyshark[\\\/].*",
[email protected]3e4eb112011-01-18 03:29:5423 r"^skia[\\\/].*",
24 r"^v8[\\\/].*",
25 r".*MakeFile$",
[email protected]1084ccc2012-03-14 03:22:5326 r".+_autogen\.h$",
[email protected]ce145c02012-09-06 09:49:3427 r".+[\\\/]pnacl_shim\.c$",
[email protected]e07b6ac72013-08-20 00:30:4228 r"^gpu[\\\/]config[\\\/].*_list_json\.cc$",
[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 C++ and Objective-C++
32# implementation files.
33_IMPLEMENTATION_EXTENSIONS = r'\.(cc|cpp|cxx|mm)$'
34
35# Regular expression that matches code only used for test binaries
36# (best effort).
37_TEST_CODE_EXCLUDED_PATHS = (
38 r'.*[/\\](fake_|test_|mock_).+%s' % _IMPLEMENTATION_EXTENSIONS,
39 r'.+_test_(base|support|util)%s' % _IMPLEMENTATION_EXTENSIONS,
[email protected]11e06082013-04-26 19:09:0340 r'.+_(api|browser|perf|pixel|unit|ui)?test(_[a-z]+)?%s' %
[email protected]e2d7e6f2013-04-23 12:57:1241 _IMPLEMENTATION_EXTENSIONS,
[email protected]06e6d0ff2012-12-11 01:36:4442 r'.+profile_sync_service_harness%s' % _IMPLEMENTATION_EXTENSIONS,
43 r'.*[/\\](test|tool(s)?)[/\\].*',
[email protected]ef070cc2013-05-03 11:53:0544 # content_shell is used for running layout tests.
45 r'content[/\\]shell[/\\].*',
[email protected]06e6d0ff2012-12-11 01:36:4446 # At request of folks maintaining this folder.
47 r'chrome[/\\]browser[/\\]automation[/\\].*',
48)
[email protected]ca8d1982009-02-19 16:33:1249
[email protected]eea609a2011-11-18 13:10:1250_TEST_ONLY_WARNING = (
51 'You might be calling functions intended only for testing from\n'
52 'production code. It is OK to ignore this warning if you know what\n'
53 'you are doing, as the heuristics used to detect the situation are\n'
54 'not perfect. The commit queue will not block on this warning.\n'
55 'Email [email protected] if you have questions.')
56
57
[email protected]cf9b78f2012-11-14 11:40:2858_INCLUDE_ORDER_WARNING = (
59 'Your #include order seems to be broken. Send mail to\n'
60 '[email protected] if this is not the case.')
61
62
[email protected]127f18ec2012-06-16 05:05:5963_BANNED_OBJC_FUNCTIONS = (
64 (
65 'addTrackingRect:',
[email protected]23e6cbc2012-06-16 18:51:2066 (
67 'The use of -[NSView addTrackingRect:owner:userData:assumeInside:] is'
[email protected]127f18ec2012-06-16 05:05:5968 'prohibited. Please use CrTrackingArea instead.',
69 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
70 ),
71 False,
72 ),
73 (
74 'NSTrackingArea',
[email protected]23e6cbc2012-06-16 18:51:2075 (
76 'The use of NSTrackingAreas is prohibited. Please use CrTrackingArea',
[email protected]127f18ec2012-06-16 05:05:5977 'instead.',
78 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
79 ),
80 False,
81 ),
82 (
83 'convertPointFromBase:',
[email protected]23e6cbc2012-06-16 18:51:2084 (
85 'The use of -[NSView convertPointFromBase:] is almost certainly wrong.',
[email protected]127f18ec2012-06-16 05:05:5986 'Please use |convertPoint:(point) fromView:nil| instead.',
87 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
88 ),
89 True,
90 ),
91 (
92 'convertPointToBase:',
[email protected]23e6cbc2012-06-16 18:51:2093 (
94 'The use of -[NSView convertPointToBase:] is almost certainly wrong.',
[email protected]127f18ec2012-06-16 05:05:5995 'Please use |convertPoint:(point) toView:nil| instead.',
96 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
97 ),
98 True,
99 ),
100 (
101 'convertRectFromBase:',
[email protected]23e6cbc2012-06-16 18:51:20102 (
103 'The use of -[NSView convertRectFromBase:] is almost certainly wrong.',
[email protected]127f18ec2012-06-16 05:05:59104 'Please use |convertRect:(point) fromView:nil| instead.',
105 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
106 ),
107 True,
108 ),
109 (
110 'convertRectToBase:',
[email protected]23e6cbc2012-06-16 18:51:20111 (
112 'The use of -[NSView convertRectToBase:] is almost certainly wrong.',
[email protected]127f18ec2012-06-16 05:05:59113 'Please use |convertRect:(point) toView:nil| instead.',
114 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
115 ),
116 True,
117 ),
118 (
119 'convertSizeFromBase:',
[email protected]23e6cbc2012-06-16 18:51:20120 (
121 'The use of -[NSView convertSizeFromBase:] is almost certainly wrong.',
[email protected]127f18ec2012-06-16 05:05:59122 'Please use |convertSize:(point) fromView:nil| instead.',
123 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
124 ),
125 True,
126 ),
127 (
128 'convertSizeToBase:',
[email protected]23e6cbc2012-06-16 18:51:20129 (
130 'The use of -[NSView convertSizeToBase:] is almost certainly wrong.',
[email protected]127f18ec2012-06-16 05:05:59131 'Please use |convertSize:(point) toView:nil| instead.',
132 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
133 ),
134 True,
135 ),
136)
137
138
139_BANNED_CPP_FUNCTIONS = (
[email protected]23e6cbc2012-06-16 18:51:20140 # Make sure that gtest's FRIEND_TEST() macro is not used; the
141 # FRIEND_TEST_ALL_PREFIXES() macro from base/gtest_prod_util.h should be
[email protected]e00ccc92012-11-01 17:32:30142 # used instead since that allows for FLAKY_ and DISABLED_ prefixes.
[email protected]23e6cbc2012-06-16 18:51:20143 (
144 'FRIEND_TEST(',
145 (
[email protected]e3c945502012-06-26 20:01:49146 'Chromium code should not use gtest\'s FRIEND_TEST() macro. Include',
[email protected]23e6cbc2012-06-16 18:51:20147 'base/gtest_prod_util.h and use FRIEND_TEST_ALL_PREFIXES() instead.',
148 ),
149 False,
[email protected]7345da02012-11-27 14:31:49150 (),
[email protected]23e6cbc2012-06-16 18:51:20151 ),
152 (
153 'ScopedAllowIO',
154 (
[email protected]e3c945502012-06-26 20:01:49155 'New code should not use ScopedAllowIO. Post a task to the blocking',
156 'pool or the FILE thread instead.',
[email protected]23e6cbc2012-06-16 18:51:20157 ),
[email protected]e3c945502012-06-26 20:01:49158 True,
[email protected]7345da02012-11-27 14:31:49159 (
[email protected]0b818f72013-10-22 00:11:03160 r"^components[\\\/]breakpad[\\\/]app[\\\/]breakpad_mac\.mm$",
[email protected]de7d61ff2013-08-20 11:30:41161 r"^content[\\\/]shell[\\\/]browser[\\\/]shell_browser_main\.cc$",
162 r"^content[\\\/]shell[\\\/]browser[\\\/]shell_message_filter\.cc$",
[email protected]398ad132013-04-02 15:11:01163 r"^net[\\\/]disk_cache[\\\/]cache_util\.cc$",
[email protected]7345da02012-11-27 14:31:49164 ),
[email protected]23e6cbc2012-06-16 18:51:20165 ),
[email protected]52657f62013-05-20 05:30:31166 (
167 'SkRefPtr',
168 (
169 'The use of SkRefPtr is prohibited. ',
170 'Please use skia::RefPtr instead.'
171 ),
172 True,
173 (),
174 ),
175 (
176 'SkAutoRef',
177 (
178 'The indirect use of SkRefPtr via SkAutoRef is prohibited. ',
179 'Please use skia::RefPtr instead.'
180 ),
181 True,
182 (),
183 ),
184 (
185 'SkAutoTUnref',
186 (
187 'The use of SkAutoTUnref is dangerous because it implicitly ',
188 'converts to a raw pointer. Please use skia::RefPtr instead.'
189 ),
190 True,
191 (),
192 ),
193 (
194 'SkAutoUnref',
195 (
196 'The indirect use of SkAutoTUnref through SkAutoUnref is dangerous ',
197 'because it implicitly converts to a raw pointer. ',
198 'Please use skia::RefPtr instead.'
199 ),
200 True,
201 (),
202 ),
[email protected]127f18ec2012-06-16 05:05:59203)
204
205
[email protected]b00342e7f2013-03-26 16:21:54206_VALID_OS_MACROS = (
207 # Please keep sorted.
208 'OS_ANDROID',
209 'OS_BSD',
210 'OS_CAT', # For testing.
211 'OS_CHROMEOS',
212 'OS_FREEBSD',
213 'OS_IOS',
214 'OS_LINUX',
215 'OS_MACOSX',
216 'OS_NACL',
217 'OS_OPENBSD',
218 'OS_POSIX',
219 'OS_SOLARIS',
[email protected]b00342e7f2013-03-26 16:21:54220 'OS_WIN',
221)
222
223
[email protected]55459852011-08-10 15:17:19224def _CheckNoProductionCodeUsingTestOnlyFunctions(input_api, output_api):
225 """Attempts to prevent use of functions intended only for testing in
226 non-testing code. For now this is just a best-effort implementation
227 that ignores header files and may have some false positives. A
228 better implementation would probably need a proper C++ parser.
229 """
230 # We only scan .cc files and the like, as the declaration of
231 # for-testing functions in header files are hard to distinguish from
232 # calls to such functions without a proper C++ parser.
[email protected]06e6d0ff2012-12-11 01:36:44233 file_inclusion_pattern = r'.+%s' % _IMPLEMENTATION_EXTENSIONS
[email protected]55459852011-08-10 15:17:19234
235 base_function_pattern = r'ForTest(ing)?|for_test(ing)?'
236 inclusion_pattern = input_api.re.compile(r'(%s)\s*\(' % base_function_pattern)
[email protected]de4f7d22013-05-23 14:27:46237 comment_pattern = input_api.re.compile(r'//.*%s' % base_function_pattern)
[email protected]55459852011-08-10 15:17:19238 exclusion_pattern = input_api.re.compile(
239 r'::[A-Za-z0-9_]+(%s)|(%s)[^;]+\{' % (
240 base_function_pattern, base_function_pattern))
241
242 def FilterFile(affected_file):
[email protected]06e6d0ff2012-12-11 01:36:44243 black_list = (_EXCLUDED_PATHS +
244 _TEST_CODE_EXCLUDED_PATHS +
245 input_api.DEFAULT_BLACK_LIST)
[email protected]55459852011-08-10 15:17:19246 return input_api.FilterSourceFile(
247 affected_file,
248 white_list=(file_inclusion_pattern, ),
249 black_list=black_list)
250
251 problems = []
252 for f in input_api.AffectedSourceFiles(FilterFile):
253 local_path = f.LocalPath()
[email protected]2fdd1f362013-01-16 03:56:03254 lines = input_api.ReadFile(f).splitlines()
255 line_number = 0
256 for line in lines:
257 if (inclusion_pattern.search(line) and
[email protected]de4f7d22013-05-23 14:27:46258 not comment_pattern.search(line) and
[email protected]2fdd1f362013-01-16 03:56:03259 not exclusion_pattern.search(line)):
[email protected]55459852011-08-10 15:17:19260 problems.append(
[email protected]2fdd1f362013-01-16 03:56:03261 '%s:%d\n %s' % (local_path, line_number, line.strip()))
262 line_number += 1
[email protected]55459852011-08-10 15:17:19263
264 if problems:
[email protected]f7051d52013-04-02 18:31:42265 return [output_api.PresubmitPromptOrNotify(_TEST_ONLY_WARNING, problems)]
[email protected]2fdd1f362013-01-16 03:56:03266 else:
267 return []
[email protected]55459852011-08-10 15:17:19268
269
[email protected]10689ca2011-09-02 02:31:54270def _CheckNoIOStreamInHeaders(input_api, output_api):
271 """Checks to make sure no .h files include <iostream>."""
272 files = []
273 pattern = input_api.re.compile(r'^#include\s*<iostream>',
274 input_api.re.MULTILINE)
275 for f in input_api.AffectedSourceFiles(input_api.FilterSourceFile):
276 if not f.LocalPath().endswith('.h'):
277 continue
278 contents = input_api.ReadFile(f)
279 if pattern.search(contents):
280 files.append(f)
281
282 if len(files):
283 return [ output_api.PresubmitError(
[email protected]6c063c62012-07-11 19:11:06284 'Do not #include <iostream> in header files, since it inserts static '
285 'initialization into every file including the header. Instead, '
[email protected]10689ca2011-09-02 02:31:54286 '#include <ostream>. See http://crbug.com/94794',
287 files) ]
288 return []
289
290
[email protected]72df4e782012-06-21 16:28:18291def _CheckNoUNIT_TESTInSourceFiles(input_api, output_api):
292 """Checks to make sure no source files use UNIT_TEST"""
293 problems = []
294 for f in input_api.AffectedFiles():
295 if (not f.LocalPath().endswith(('.cc', '.mm'))):
296 continue
297
298 for line_num, line in f.ChangedContents():
[email protected]549f86a2013-11-19 13:00:04299 if 'UNIT_TEST ' in line or line.endswith('UNIT_TEST'):
[email protected]72df4e782012-06-21 16:28:18300 problems.append(' %s:%d' % (f.LocalPath(), line_num))
301
302 if not problems:
303 return []
304 return [output_api.PresubmitPromptWarning('UNIT_TEST is only for headers.\n' +
305 '\n'.join(problems))]
306
307
[email protected]8ea5d4b2011-09-13 21:49:22308def _CheckNoNewWStrings(input_api, output_api):
309 """Checks to make sure we don't introduce use of wstrings."""
[email protected]55463aa62011-10-12 00:48:27310 problems = []
[email protected]8ea5d4b2011-09-13 21:49:22311 for f in input_api.AffectedFiles():
[email protected]b5c24292011-11-28 14:38:20312 if (not f.LocalPath().endswith(('.cc', '.h')) or
[email protected]24be83c2013-08-29 23:01:23313 f.LocalPath().endswith(('test.cc', '_win.cc', '_win.h'))):
[email protected]b5c24292011-11-28 14:38:20314 continue
[email protected]8ea5d4b2011-09-13 21:49:22315
[email protected]a11dbe9b2012-08-07 01:32:58316 allowWString = False
[email protected]b5c24292011-11-28 14:38:20317 for line_num, line in f.ChangedContents():
[email protected]a11dbe9b2012-08-07 01:32:58318 if 'presubmit: allow wstring' in line:
319 allowWString = True
320 elif not allowWString and 'wstring' in line:
[email protected]55463aa62011-10-12 00:48:27321 problems.append(' %s:%d' % (f.LocalPath(), line_num))
[email protected]a11dbe9b2012-08-07 01:32:58322 allowWString = False
323 else:
324 allowWString = False
[email protected]8ea5d4b2011-09-13 21:49:22325
[email protected]55463aa62011-10-12 00:48:27326 if not problems:
327 return []
328 return [output_api.PresubmitPromptWarning('New code should not use wstrings.'
[email protected]a11dbe9b2012-08-07 01:32:58329 ' If you are calling a cross-platform API that accepts a wstring, '
330 'fix the API.\n' +
[email protected]55463aa62011-10-12 00:48:27331 '\n'.join(problems))]
[email protected]8ea5d4b2011-09-13 21:49:22332
333
[email protected]2a8ac9c2011-10-19 17:20:44334def _CheckNoDEPSGIT(input_api, output_api):
335 """Make sure .DEPS.git is never modified manually."""
336 if any(f.LocalPath().endswith('.DEPS.git') for f in
337 input_api.AffectedFiles()):
338 return [output_api.PresubmitError(
339 'Never commit changes to .DEPS.git. This file is maintained by an\n'
340 'automated system based on what\'s in DEPS and your changes will be\n'
341 'overwritten.\n'
342 'See http://code.google.com/p/chromium/wiki/UsingNewGit#Rolling_DEPS\n'
343 'for more information')]
344 return []
345
346
[email protected]127f18ec2012-06-16 05:05:59347def _CheckNoBannedFunctions(input_api, output_api):
348 """Make sure that banned functions are not used."""
349 warnings = []
350 errors = []
351
352 file_filter = lambda f: f.LocalPath().endswith(('.mm', '.m', '.h'))
353 for f in input_api.AffectedFiles(file_filter=file_filter):
354 for line_num, line in f.ChangedContents():
355 for func_name, message, error in _BANNED_OBJC_FUNCTIONS:
356 if func_name in line:
357 problems = warnings;
358 if error:
359 problems = errors;
360 problems.append(' %s:%d:' % (f.LocalPath(), line_num))
361 for message_line in message:
362 problems.append(' %s' % message_line)
363
364 file_filter = lambda f: f.LocalPath().endswith(('.cc', '.mm', '.h'))
365 for f in input_api.AffectedFiles(file_filter=file_filter):
366 for line_num, line in f.ChangedContents():
[email protected]7345da02012-11-27 14:31:49367 for func_name, message, error, excluded_paths in _BANNED_CPP_FUNCTIONS:
368 def IsBlacklisted(affected_file, blacklist):
369 local_path = affected_file.LocalPath()
370 for item in blacklist:
371 if input_api.re.match(item, local_path):
372 return True
373 return False
374 if IsBlacklisted(f, excluded_paths):
375 continue
[email protected]127f18ec2012-06-16 05:05:59376 if func_name in line:
377 problems = warnings;
378 if error:
379 problems = errors;
380 problems.append(' %s:%d:' % (f.LocalPath(), line_num))
381 for message_line in message:
382 problems.append(' %s' % message_line)
383
384 result = []
385 if (warnings):
386 result.append(output_api.PresubmitPromptWarning(
387 'Banned functions were used.\n' + '\n'.join(warnings)))
388 if (errors):
389 result.append(output_api.PresubmitError(
390 'Banned functions were used.\n' + '\n'.join(errors)))
391 return result
392
393
[email protected]6c063c62012-07-11 19:11:06394def _CheckNoPragmaOnce(input_api, output_api):
395 """Make sure that banned functions are not used."""
396 files = []
397 pattern = input_api.re.compile(r'^#pragma\s+once',
398 input_api.re.MULTILINE)
399 for f in input_api.AffectedSourceFiles(input_api.FilterSourceFile):
400 if not f.LocalPath().endswith('.h'):
401 continue
402 contents = input_api.ReadFile(f)
403 if pattern.search(contents):
404 files.append(f)
405
406 if files:
407 return [output_api.PresubmitError(
408 'Do not use #pragma once in header files.\n'
409 'See http://www.chromium.org/developers/coding-style#TOC-File-headers',
410 files)]
411 return []
412
[email protected]127f18ec2012-06-16 05:05:59413
[email protected]e7479052012-09-19 00:26:12414def _CheckNoTrinaryTrueFalse(input_api, output_api):
415 """Checks to make sure we don't introduce use of foo ? true : false."""
416 problems = []
417 pattern = input_api.re.compile(r'\?\s*(true|false)\s*:\s*(true|false)')
418 for f in input_api.AffectedFiles():
419 if not f.LocalPath().endswith(('.cc', '.h', '.inl', '.m', '.mm')):
420 continue
421
422 for line_num, line in f.ChangedContents():
423 if pattern.match(line):
424 problems.append(' %s:%d' % (f.LocalPath(), line_num))
425
426 if not problems:
427 return []
428 return [output_api.PresubmitPromptWarning(
429 'Please consider avoiding the "? true : false" pattern if possible.\n' +
430 '\n'.join(problems))]
431
432
[email protected]55f9f382012-07-31 11:02:18433def _CheckUnwantedDependencies(input_api, output_api):
434 """Runs checkdeps on #include statements added in this
435 change. Breaking - rules is an error, breaking ! rules is a
436 warning.
437 """
438 # We need to wait until we have an input_api object and use this
439 # roundabout construct to import checkdeps because this file is
440 # eval-ed and thus doesn't have __file__.
441 original_sys_path = sys.path
442 try:
443 sys.path = sys.path + [input_api.os_path.join(
444 input_api.PresubmitLocalPath(), 'tools', 'checkdeps')]
445 import checkdeps
446 from cpp_checker import CppChecker
447 from rules import Rule
448 finally:
449 # Restore sys.path to what it was before.
450 sys.path = original_sys_path
451
452 added_includes = []
453 for f in input_api.AffectedFiles():
454 if not CppChecker.IsCppFile(f.LocalPath()):
455 continue
456
457 changed_lines = [line for line_num, line in f.ChangedContents()]
458 added_includes.append([f.LocalPath(), changed_lines])
459
[email protected]26385172013-05-09 23:11:35460 deps_checker = checkdeps.DepsChecker(input_api.PresubmitLocalPath())
[email protected]55f9f382012-07-31 11:02:18461
462 error_descriptions = []
463 warning_descriptions = []
464 for path, rule_type, rule_description in deps_checker.CheckAddedCppIncludes(
465 added_includes):
466 description_with_path = '%s\n %s' % (path, rule_description)
467 if rule_type == Rule.DISALLOW:
468 error_descriptions.append(description_with_path)
469 else:
470 warning_descriptions.append(description_with_path)
471
472 results = []
473 if error_descriptions:
474 results.append(output_api.PresubmitError(
475 'You added one or more #includes that violate checkdeps rules.',
476 error_descriptions))
477 if warning_descriptions:
[email protected]f7051d52013-04-02 18:31:42478 results.append(output_api.PresubmitPromptOrNotify(
[email protected]55f9f382012-07-31 11:02:18479 'You added one or more #includes of files that are temporarily\n'
480 'allowed but being removed. Can you avoid introducing the\n'
481 '#include? See relevant DEPS file(s) for details and contacts.',
482 warning_descriptions))
483 return results
484
485
[email protected]fbcafe5a2012-08-08 15:31:22486def _CheckFilePermissions(input_api, output_api):
487 """Check that all files have their permissions properly set."""
488 args = [sys.executable, 'tools/checkperms/checkperms.py', '--root',
489 input_api.change.RepositoryRoot()]
490 for f in input_api.AffectedFiles():
491 args += ['--file', f.LocalPath()]
492 errors = []
493 (errors, stderrdata) = subprocess.Popen(args).communicate()
494
495 results = []
496 if errors:
[email protected]c8278b32012-10-30 20:35:49497 results.append(output_api.PresubmitError('checkperms.py failed.',
[email protected]fbcafe5a2012-08-08 15:31:22498 errors))
499 return results
500
501
[email protected]c8278b32012-10-30 20:35:49502def _CheckNoAuraWindowPropertyHInHeaders(input_api, output_api):
503 """Makes sure we don't include ui/aura/window_property.h
504 in header files.
505 """
506 pattern = input_api.re.compile(r'^#include\s*"ui/aura/window_property.h"')
507 errors = []
508 for f in input_api.AffectedFiles():
509 if not f.LocalPath().endswith('.h'):
510 continue
511 for line_num, line in f.ChangedContents():
512 if pattern.match(line):
513 errors.append(' %s:%d' % (f.LocalPath(), line_num))
514
515 results = []
516 if errors:
517 results.append(output_api.PresubmitError(
518 'Header files should not include ui/aura/window_property.h', errors))
519 return results
520
521
[email protected]cf9b78f2012-11-14 11:40:28522def _CheckIncludeOrderForScope(scope, input_api, file_path, changed_linenums):
523 """Checks that the lines in scope occur in the right order.
524
525 1. C system files in alphabetical order
526 2. C++ system files in alphabetical order
527 3. Project's .h files
528 """
529
530 c_system_include_pattern = input_api.re.compile(r'\s*#include <.*\.h>')
531 cpp_system_include_pattern = input_api.re.compile(r'\s*#include <.*>')
532 custom_include_pattern = input_api.re.compile(r'\s*#include ".*')
533
534 C_SYSTEM_INCLUDES, CPP_SYSTEM_INCLUDES, CUSTOM_INCLUDES = range(3)
535
536 state = C_SYSTEM_INCLUDES
537
538 previous_line = ''
[email protected]728b9bb2012-11-14 20:38:57539 previous_line_num = 0
[email protected]cf9b78f2012-11-14 11:40:28540 problem_linenums = []
541 for line_num, line in scope:
542 if c_system_include_pattern.match(line):
543 if state != C_SYSTEM_INCLUDES:
[email protected]728b9bb2012-11-14 20:38:57544 problem_linenums.append((line_num, previous_line_num))
[email protected]cf9b78f2012-11-14 11:40:28545 elif previous_line and previous_line > line:
[email protected]728b9bb2012-11-14 20:38:57546 problem_linenums.append((line_num, previous_line_num))
[email protected]cf9b78f2012-11-14 11:40:28547 elif cpp_system_include_pattern.match(line):
548 if state == C_SYSTEM_INCLUDES:
549 state = CPP_SYSTEM_INCLUDES
550 elif state == CUSTOM_INCLUDES:
[email protected]728b9bb2012-11-14 20:38:57551 problem_linenums.append((line_num, previous_line_num))
[email protected]cf9b78f2012-11-14 11:40:28552 elif previous_line and previous_line > line:
[email protected]728b9bb2012-11-14 20:38:57553 problem_linenums.append((line_num, previous_line_num))
[email protected]cf9b78f2012-11-14 11:40:28554 elif custom_include_pattern.match(line):
555 if state != CUSTOM_INCLUDES:
556 state = CUSTOM_INCLUDES
557 elif previous_line and previous_line > line:
[email protected]728b9bb2012-11-14 20:38:57558 problem_linenums.append((line_num, previous_line_num))
[email protected]cf9b78f2012-11-14 11:40:28559 else:
560 problem_linenums.append(line_num)
561 previous_line = line
[email protected]728b9bb2012-11-14 20:38:57562 previous_line_num = line_num
[email protected]cf9b78f2012-11-14 11:40:28563
564 warnings = []
[email protected]728b9bb2012-11-14 20:38:57565 for (line_num, previous_line_num) in problem_linenums:
566 if line_num in changed_linenums or previous_line_num in changed_linenums:
[email protected]cf9b78f2012-11-14 11:40:28567 warnings.append(' %s:%d' % (file_path, line_num))
568 return warnings
569
570
[email protected]ac294a12012-12-06 16:38:43571def _CheckIncludeOrderInFile(input_api, f, changed_linenums):
[email protected]cf9b78f2012-11-14 11:40:28572 """Checks the #include order for the given file f."""
573
[email protected]2299dcf2012-11-15 19:56:24574 system_include_pattern = input_api.re.compile(r'\s*#include \<.*')
[email protected]23093b62013-09-20 12:16:30575 # Exclude the following includes from the check:
576 # 1) #include <.../...>, e.g., <sys/...> includes often need to appear in a
577 # specific order.
578 # 2) <atlbase.h>, "build/build_config.h"
579 excluded_include_pattern = input_api.re.compile(
580 r'\s*#include (\<.*/.*|\<atlbase\.h\>|"build/build_config.h")')
[email protected]2299dcf2012-11-15 19:56:24581 custom_include_pattern = input_api.re.compile(r'\s*#include "(?P<FILE>.*)"')
[email protected]3e83618c2013-10-09 22:32:33582 # Match the final or penultimate token if it is xxxtest so we can ignore it
583 # when considering the special first include.
584 test_file_tag_pattern = input_api.re.compile(
585 r'_[a-z]+test(?=(_[a-zA-Z0-9]+)?\.)')
[email protected]0e5c1852012-12-18 20:17:11586 if_pattern = input_api.re.compile(
587 r'\s*#\s*(if|elif|else|endif|define|undef).*')
588 # Some files need specialized order of includes; exclude such files from this
589 # check.
590 uncheckable_includes_pattern = input_api.re.compile(
591 r'\s*#include '
592 '("ipc/.*macros\.h"|<windows\.h>|".*gl.*autogen.h")\s*')
[email protected]cf9b78f2012-11-14 11:40:28593
594 contents = f.NewContents()
595 warnings = []
596 line_num = 0
597
[email protected]ac294a12012-12-06 16:38:43598 # Handle the special first include. If the first include file is
599 # some/path/file.h, the corresponding including file can be some/path/file.cc,
600 # some/other/path/file.cc, some/path/file_platform.cc, some/path/file-suffix.h
601 # etc. It's also possible that no special first include exists.
[email protected]3e83618c2013-10-09 22:32:33602 # If the included file is some/path/file_platform.h the including file could
603 # also be some/path/file_xxxtest_platform.h.
604 including_file_base_name = test_file_tag_pattern.sub(
605 '', input_api.os_path.basename(f.LocalPath()))
606
[email protected]ac294a12012-12-06 16:38:43607 for line in contents:
608 line_num += 1
609 if system_include_pattern.match(line):
610 # No special first include -> process the line again along with normal
611 # includes.
612 line_num -= 1
613 break
614 match = custom_include_pattern.match(line)
615 if match:
616 match_dict = match.groupdict()
[email protected]3e83618c2013-10-09 22:32:33617 header_basename = test_file_tag_pattern.sub(
618 '', input_api.os_path.basename(match_dict['FILE'])).replace('.h', '')
619
620 if header_basename not in including_file_base_name:
[email protected]2299dcf2012-11-15 19:56:24621 # No special first include -> process the line again along with normal
622 # includes.
623 line_num -= 1
[email protected]ac294a12012-12-06 16:38:43624 break
[email protected]cf9b78f2012-11-14 11:40:28625
626 # Split into scopes: Each region between #if and #endif is its own scope.
627 scopes = []
628 current_scope = []
629 for line in contents[line_num:]:
630 line_num += 1
[email protected]0e5c1852012-12-18 20:17:11631 if uncheckable_includes_pattern.match(line):
632 return []
[email protected]2309b0fa02012-11-16 12:18:27633 if if_pattern.match(line):
[email protected]cf9b78f2012-11-14 11:40:28634 scopes.append(current_scope)
635 current_scope = []
[email protected]962f117e2012-11-22 18:11:56636 elif ((system_include_pattern.match(line) or
637 custom_include_pattern.match(line)) and
638 not excluded_include_pattern.match(line)):
[email protected]cf9b78f2012-11-14 11:40:28639 current_scope.append((line_num, line))
640 scopes.append(current_scope)
641
642 for scope in scopes:
643 warnings.extend(_CheckIncludeOrderForScope(scope, input_api, f.LocalPath(),
644 changed_linenums))
645 return warnings
646
647
648def _CheckIncludeOrder(input_api, output_api):
649 """Checks that the #include order is correct.
650
651 1. The corresponding header for source files.
652 2. C system files in alphabetical order
653 3. C++ system files in alphabetical order
654 4. Project's .h files in alphabetical order
655
[email protected]ac294a12012-12-06 16:38:43656 Each region separated by #if, #elif, #else, #endif, #define and #undef follows
657 these rules separately.
[email protected]cf9b78f2012-11-14 11:40:28658 """
659
660 warnings = []
661 for f in input_api.AffectedFiles():
[email protected]ac294a12012-12-06 16:38:43662 if f.LocalPath().endswith(('.cc', '.h')):
663 changed_linenums = set(line_num for line_num, _ in f.ChangedContents())
664 warnings.extend(_CheckIncludeOrderInFile(input_api, f, changed_linenums))
[email protected]cf9b78f2012-11-14 11:40:28665
666 results = []
667 if warnings:
[email protected]f7051d52013-04-02 18:31:42668 results.append(output_api.PresubmitPromptOrNotify(_INCLUDE_ORDER_WARNING,
[email protected]120cf540d2012-12-10 17:55:53669 warnings))
[email protected]cf9b78f2012-11-14 11:40:28670 return results
671
672
[email protected]70ca77752012-11-20 03:45:03673def _CheckForVersionControlConflictsInFile(input_api, f):
674 pattern = input_api.re.compile('^(?:<<<<<<<|>>>>>>>) |^=======$')
675 errors = []
676 for line_num, line in f.ChangedContents():
677 if pattern.match(line):
678 errors.append(' %s:%d %s' % (f.LocalPath(), line_num, line))
679 return errors
680
681
682def _CheckForVersionControlConflicts(input_api, output_api):
683 """Usually this is not intentional and will cause a compile failure."""
684 errors = []
685 for f in input_api.AffectedFiles():
686 errors.extend(_CheckForVersionControlConflictsInFile(input_api, f))
687
688 results = []
689 if errors:
690 results.append(output_api.PresubmitError(
691 'Version control conflict markers found, please resolve.', errors))
692 return results
693
694
[email protected]06e6d0ff2012-12-11 01:36:44695def _CheckHardcodedGoogleHostsInLowerLayers(input_api, output_api):
696 def FilterFile(affected_file):
697 """Filter function for use with input_api.AffectedSourceFiles,
698 below. This filters out everything except non-test files from
699 top-level directories that generally speaking should not hard-code
700 service URLs (e.g. src/android_webview/, src/content/ and others).
701 """
702 return input_api.FilterSourceFile(
703 affected_file,
[email protected]78bb39d62012-12-11 15:11:56704 white_list=(r'^(android_webview|base|content|net)[\\\/].*', ),
[email protected]06e6d0ff2012-12-11 01:36:44705 black_list=(_EXCLUDED_PATHS +
706 _TEST_CODE_EXCLUDED_PATHS +
707 input_api.DEFAULT_BLACK_LIST))
708
[email protected]de4f7d22013-05-23 14:27:46709 base_pattern = '"[^"]*google\.com[^"]*"'
710 comment_pattern = input_api.re.compile('//.*%s' % base_pattern)
711 pattern = input_api.re.compile(base_pattern)
[email protected]06e6d0ff2012-12-11 01:36:44712 problems = [] # items are (filename, line_number, line)
713 for f in input_api.AffectedSourceFiles(FilterFile):
714 for line_num, line in f.ChangedContents():
[email protected]de4f7d22013-05-23 14:27:46715 if not comment_pattern.search(line) and pattern.search(line):
[email protected]06e6d0ff2012-12-11 01:36:44716 problems.append((f.LocalPath(), line_num, line))
717
718 if problems:
[email protected]f7051d52013-04-02 18:31:42719 return [output_api.PresubmitPromptOrNotify(
[email protected]06e6d0ff2012-12-11 01:36:44720 'Most layers below src/chrome/ should not hardcode service URLs.\n'
721 'Are you sure this is correct? (Contact: [email protected])',
722 [' %s:%d: %s' % (
723 problem[0], problem[1], problem[2]) for problem in problems])]
[email protected]2fdd1f362013-01-16 03:56:03724 else:
725 return []
[email protected]06e6d0ff2012-12-11 01:36:44726
727
[email protected]d2530012013-01-25 16:39:27728def _CheckNoAbbreviationInPngFileName(input_api, output_api):
729 """Makes sure there are no abbreviations in the name of PNG files.
730 """
[email protected]4053a48e2013-01-25 21:43:04731 pattern = input_api.re.compile(r'.*_[a-z]_.*\.png$|.*_[a-z]\.png$')
[email protected]d2530012013-01-25 16:39:27732 errors = []
733 for f in input_api.AffectedFiles(include_deletes=False):
734 if pattern.match(f.LocalPath()):
735 errors.append(' %s' % f.LocalPath())
736
737 results = []
738 if errors:
739 results.append(output_api.PresubmitError(
740 'The name of PNG files should not have abbreviations. \n'
741 'Use _hover.png, _center.png, instead of _h.png, _c.png.\n'
742 'Contact [email protected] if you have questions.', errors))
743 return results
744
745
[email protected]f32e2d1e2013-07-26 21:39:08746def _DepsFilesToCheck(re, changed_lines):
747 """Helper method for _CheckAddedDepsHaveTargetApprovals. Returns
748 a set of DEPS entries that we should look up."""
[email protected]2b438d62013-11-14 17:54:14749 # We ignore deps entries on auto-generated directories.
750 AUTO_GENERATED_DIRS = ['grit', 'jni']
[email protected]f32e2d1e2013-07-26 21:39:08751
752 # This pattern grabs the path without basename in the first
753 # parentheses, and the basename (if present) in the second. It
754 # relies on the simple heuristic that if there is a basename it will
755 # be a header file ending in ".h".
756 pattern = re.compile(
757 r"""['"]\+([^'"]+?)(/[a-zA-Z0-9_]+\.h)?['"].*""")
[email protected]2b438d62013-11-14 17:54:14758 results = set()
[email protected]f32e2d1e2013-07-26 21:39:08759 for changed_line in changed_lines:
760 m = pattern.match(changed_line)
761 if m:
762 path = m.group(1)
[email protected]2b438d62013-11-14 17:54:14763 if path.split('/')[0] not in AUTO_GENERATED_DIRS:
[email protected]f32e2d1e2013-07-26 21:39:08764 results.add('%s/DEPS' % m.group(1))
765 return results
766
767
[email protected]e871964c2013-05-13 14:14:55768def _CheckAddedDepsHaveTargetApprovals(input_api, output_api):
769 """When a dependency prefixed with + is added to a DEPS file, we
770 want to make sure that the change is reviewed by an OWNER of the
771 target file or directory, to avoid layering violations from being
772 introduced. This check verifies that this happens.
773 """
774 changed_lines = set()
775 for f in input_api.AffectedFiles():
776 filename = input_api.os_path.basename(f.LocalPath())
777 if filename == 'DEPS':
778 changed_lines |= set(line.strip()
779 for line_num, line
780 in f.ChangedContents())
781 if not changed_lines:
782 return []
783
[email protected]f32e2d1e2013-07-26 21:39:08784 virtual_depended_on_files = _DepsFilesToCheck(input_api.re, changed_lines)
[email protected]e871964c2013-05-13 14:14:55785 if not virtual_depended_on_files:
786 return []
787
788 if input_api.is_committing:
789 if input_api.tbr:
790 return [output_api.PresubmitNotifyResult(
791 '--tbr was specified, skipping OWNERS check for DEPS additions')]
792 if not input_api.change.issue:
793 return [output_api.PresubmitError(
794 "DEPS approval by OWNERS check failed: this change has "
795 "no Rietveld issue number, so we can't check it for approvals.")]
796 output = output_api.PresubmitError
797 else:
798 output = output_api.PresubmitNotifyResult
799
800 owners_db = input_api.owners_db
801 owner_email, reviewers = input_api.canned_checks._RietveldOwnerAndReviewers(
802 input_api,
803 owners_db.email_regexp,
804 approval_needed=input_api.is_committing)
805
806 owner_email = owner_email or input_api.change.author_email
807
[email protected]de4f7d22013-05-23 14:27:46808 reviewers_plus_owner = set(reviewers)
[email protected]e71c6082013-05-22 02:28:51809 if owner_email:
[email protected]de4f7d22013-05-23 14:27:46810 reviewers_plus_owner.add(owner_email)
[email protected]e871964c2013-05-13 14:14:55811 missing_files = owners_db.files_not_covered_by(virtual_depended_on_files,
812 reviewers_plus_owner)
813 unapproved_dependencies = ["'+%s'," % path[:-len('/DEPS')]
814 for path in missing_files]
815
816 if unapproved_dependencies:
817 output_list = [
818 output('Missing LGTM from OWNERS of directories added to DEPS:\n %s' %
819 '\n '.join(sorted(unapproved_dependencies)))]
820 if not input_api.is_committing:
821 suggested_owners = owners_db.reviewers_for(missing_files, owner_email)
822 output_list.append(output(
823 'Suggested missing target path OWNERS:\n %s' %
824 '\n '.join(suggested_owners or [])))
825 return output_list
826
827 return []
828
829
[email protected]85218562013-11-22 07:41:40830def _CheckSpamLogging(input_api, output_api):
831 file_inclusion_pattern = r'.+%s' % _IMPLEMENTATION_EXTENSIONS
832 black_list = (_EXCLUDED_PATHS +
833 _TEST_CODE_EXCLUDED_PATHS +
834 input_api.DEFAULT_BLACK_LIST +
[email protected]6f742dd02013-11-26 23:19:50835 (r"^base[\\\/]logging\.h$",
836 r"^remoting[\\\/]base[\\\/]logging\.h$",))
[email protected]85218562013-11-22 07:41:40837 source_file_filter = lambda x: input_api.FilterSourceFile(
838 x, white_list=(file_inclusion_pattern,), black_list=black_list)
839
840 log_info = []
841 printf = []
842
843 for f in input_api.AffectedSourceFiles(source_file_filter):
844 contents = input_api.ReadFile(f, 'rb')
845 if re.search(r"\bD?LOG\s*\(\s*INFO\s*\)", contents):
846 log_info.append(f.LocalPath())
847 if re.search(r"\bf?printf\(", contents):
848 printf.append(f.LocalPath())
849
850 if log_info:
851 return [output_api.PresubmitError(
852 'These files spam the console log with LOG(INFO):',
853 items=log_info)]
854 if printf:
855 return [output_api.PresubmitError(
856 'These files spam the console log with printf/fprintf:',
857 items=printf)]
858 return []
859
860
861
[email protected]22c9bd72011-03-27 16:47:39862def _CommonChecks(input_api, output_api):
863 """Checks common to both upload and commit."""
864 results = []
865 results.extend(input_api.canned_checks.PanProjectChecks(
866 input_api, output_api, excluded_paths=_EXCLUDED_PATHS))
[email protected]66daa702011-05-28 14:41:46867 results.extend(_CheckAuthorizedAuthor(input_api, output_api))
[email protected]55459852011-08-10 15:17:19868 results.extend(
869 _CheckNoProductionCodeUsingTestOnlyFunctions(input_api, output_api))
[email protected]10689ca2011-09-02 02:31:54870 results.extend(_CheckNoIOStreamInHeaders(input_api, output_api))
[email protected]72df4e782012-06-21 16:28:18871 results.extend(_CheckNoUNIT_TESTInSourceFiles(input_api, output_api))
[email protected]8ea5d4b2011-09-13 21:49:22872 results.extend(_CheckNoNewWStrings(input_api, output_api))
[email protected]2a8ac9c2011-10-19 17:20:44873 results.extend(_CheckNoDEPSGIT(input_api, output_api))
[email protected]127f18ec2012-06-16 05:05:59874 results.extend(_CheckNoBannedFunctions(input_api, output_api))
[email protected]6c063c62012-07-11 19:11:06875 results.extend(_CheckNoPragmaOnce(input_api, output_api))
[email protected]e7479052012-09-19 00:26:12876 results.extend(_CheckNoTrinaryTrueFalse(input_api, output_api))
[email protected]55f9f382012-07-31 11:02:18877 results.extend(_CheckUnwantedDependencies(input_api, output_api))
[email protected]fbcafe5a2012-08-08 15:31:22878 results.extend(_CheckFilePermissions(input_api, output_api))
[email protected]c8278b32012-10-30 20:35:49879 results.extend(_CheckNoAuraWindowPropertyHInHeaders(input_api, output_api))
[email protected]2309b0fa02012-11-16 12:18:27880 results.extend(_CheckIncludeOrder(input_api, output_api))
[email protected]70ca77752012-11-20 03:45:03881 results.extend(_CheckForVersionControlConflicts(input_api, output_api))
[email protected]b8079ae4a2012-12-05 19:56:49882 results.extend(_CheckPatchFiles(input_api, output_api))
[email protected]06e6d0ff2012-12-11 01:36:44883 results.extend(_CheckHardcodedGoogleHostsInLowerLayers(input_api, output_api))
[email protected]d2530012013-01-25 16:39:27884 results.extend(_CheckNoAbbreviationInPngFileName(input_api, output_api))
[email protected]b00342e7f2013-03-26 16:21:54885 results.extend(_CheckForInvalidOSMacros(input_api, output_api))
[email protected]e871964c2013-05-13 14:14:55886 results.extend(_CheckAddedDepsHaveTargetApprovals(input_api, output_api))
[email protected]9f919cc2013-07-31 03:04:04887 results.extend(
888 input_api.canned_checks.CheckChangeHasNoTabs(
889 input_api,
890 output_api,
891 source_file_filter=lambda x: x.LocalPath().endswith('.grd')))
[email protected]85218562013-11-22 07:41:40892 results.extend(_CheckSpamLogging(input_api, output_api))
[email protected]2299dcf2012-11-15 19:56:24893
894 if any('PRESUBMIT.py' == f.LocalPath() for f in input_api.AffectedFiles()):
895 results.extend(input_api.canned_checks.RunUnitTestsInDirectory(
896 input_api, output_api,
897 input_api.PresubmitLocalPath(),
[email protected]6be63382013-01-21 15:42:38898 whitelist=[r'^PRESUBMIT_test\.py$']))
[email protected]22c9bd72011-03-27 16:47:39899 return results
[email protected]1f7b4172010-01-28 01:17:34900
[email protected]b337cb5b2011-01-23 21:24:05901
902def _CheckSubversionConfig(input_api, output_api):
903 """Verifies the subversion config file is correctly setup.
904
905 Checks that autoprops are enabled, returns an error otherwise.
906 """
907 join = input_api.os_path.join
908 if input_api.platform == 'win32':
909 appdata = input_api.environ.get('APPDATA', '')
910 if not appdata:
911 return [output_api.PresubmitError('%APPDATA% is not configured.')]
912 path = join(appdata, 'Subversion', 'config')
913 else:
914 home = input_api.environ.get('HOME', '')
915 if not home:
916 return [output_api.PresubmitError('$HOME is not configured.')]
917 path = join(home, '.subversion', 'config')
918
919 error_msg = (
920 'Please look at http://dev.chromium.org/developers/coding-style to\n'
921 'configure your subversion configuration file. This enables automatic\n'
[email protected]c6a3c10b2011-01-24 16:14:20922 'properties to simplify the project maintenance.\n'
923 'Pro-tip: just download and install\n'
924 'http://src.chromium.org/viewvc/chrome/trunk/tools/build/slave/config\n')
[email protected]b337cb5b2011-01-23 21:24:05925
926 try:
927 lines = open(path, 'r').read().splitlines()
928 # Make sure auto-props is enabled and check for 2 Chromium standard
929 # auto-prop.
930 if (not '*.cc = svn:eol-style=LF' in lines or
931 not '*.pdf = svn:mime-type=application/pdf' in lines or
932 not 'enable-auto-props = yes' in lines):
933 return [
[email protected]79ed7e62011-02-21 21:08:53934 output_api.PresubmitNotifyResult(
[email protected]b337cb5b2011-01-23 21:24:05935 'It looks like you have not configured your subversion config '
[email protected]b5359c02011-02-01 20:29:56936 'file or it is not up-to-date.\n' + error_msg)
[email protected]b337cb5b2011-01-23 21:24:05937 ]
938 except (OSError, IOError):
939 return [
[email protected]79ed7e62011-02-21 21:08:53940 output_api.PresubmitNotifyResult(
[email protected]b337cb5b2011-01-23 21:24:05941 'Can\'t find your subversion config file.\n' + error_msg)
942 ]
943 return []
944
945
[email protected]66daa702011-05-28 14:41:46946def _CheckAuthorizedAuthor(input_api, output_api):
947 """For non-googler/chromites committers, verify the author's email address is
948 in AUTHORS.
949 """
[email protected]9bb9cb82011-06-13 20:43:01950 # TODO(maruel): Add it to input_api?
951 import fnmatch
952
[email protected]66daa702011-05-28 14:41:46953 author = input_api.change.author_email
[email protected]9bb9cb82011-06-13 20:43:01954 if not author:
955 input_api.logging.info('No author, skipping AUTHOR check')
[email protected]66daa702011-05-28 14:41:46956 return []
[email protected]c99663292011-05-31 19:46:08957 authors_path = input_api.os_path.join(
[email protected]66daa702011-05-28 14:41:46958 input_api.PresubmitLocalPath(), 'AUTHORS')
959 valid_authors = (
960 input_api.re.match(r'[^#]+\s+\<(.+?)\>\s*$', line)
961 for line in open(authors_path))
[email protected]ac54b132011-06-06 18:11:18962 valid_authors = [item.group(1).lower() for item in valid_authors if item]
[email protected]d8b50be2011-06-15 14:19:44963 if not any(fnmatch.fnmatch(author.lower(), valid) for valid in valid_authors):
[email protected]5861efb2013-01-07 18:33:23964 input_api.logging.info('Valid authors are %s', ', '.join(valid_authors))
[email protected]66daa702011-05-28 14:41:46965 return [output_api.PresubmitPromptWarning(
966 ('%s is not in AUTHORS file. If you are a new contributor, please visit'
967 '\n'
968 'http://www.chromium.org/developers/contributing-code and read the '
969 '"Legal" section\n'
970 'If you are a chromite, verify the contributor signed the CLA.') %
971 author)]
972 return []
973
974
[email protected]b8079ae4a2012-12-05 19:56:49975def _CheckPatchFiles(input_api, output_api):
976 problems = [f.LocalPath() for f in input_api.AffectedFiles()
977 if f.LocalPath().endswith(('.orig', '.rej'))]
978 if problems:
979 return [output_api.PresubmitError(
980 "Don't commit .rej and .orig files.", problems)]
[email protected]2fdd1f362013-01-16 03:56:03981 else:
982 return []
[email protected]b8079ae4a2012-12-05 19:56:49983
984
[email protected]b00342e7f2013-03-26 16:21:54985def _DidYouMeanOSMacro(bad_macro):
986 try:
987 return {'A': 'OS_ANDROID',
988 'B': 'OS_BSD',
989 'C': 'OS_CHROMEOS',
990 'F': 'OS_FREEBSD',
991 'L': 'OS_LINUX',
992 'M': 'OS_MACOSX',
993 'N': 'OS_NACL',
994 'O': 'OS_OPENBSD',
995 'P': 'OS_POSIX',
996 'S': 'OS_SOLARIS',
997 'W': 'OS_WIN'}[bad_macro[3].upper()]
998 except KeyError:
999 return ''
1000
1001
1002def _CheckForInvalidOSMacrosInFile(input_api, f):
1003 """Check for sensible looking, totally invalid OS macros."""
1004 preprocessor_statement = input_api.re.compile(r'^\s*#')
1005 os_macro = input_api.re.compile(r'defined\((OS_[^)]+)\)')
1006 results = []
1007 for lnum, line in f.ChangedContents():
1008 if preprocessor_statement.search(line):
1009 for match in os_macro.finditer(line):
1010 if not match.group(1) in _VALID_OS_MACROS:
1011 good = _DidYouMeanOSMacro(match.group(1))
1012 did_you_mean = ' (did you mean %s?)' % good if good else ''
1013 results.append(' %s:%d %s%s' % (f.LocalPath(),
1014 lnum,
1015 match.group(1),
1016 did_you_mean))
1017 return results
1018
1019
1020def _CheckForInvalidOSMacros(input_api, output_api):
1021 """Check all affected files for invalid OS macros."""
1022 bad_macros = []
1023 for f in input_api.AffectedFiles():
1024 if not f.LocalPath().endswith(('.py', '.js', '.html', '.css')):
1025 bad_macros.extend(_CheckForInvalidOSMacrosInFile(input_api, f))
1026
1027 if not bad_macros:
1028 return []
1029
1030 return [output_api.PresubmitError(
1031 'Possibly invalid OS macro[s] found. Please fix your code\n'
1032 'or add your macro to src/PRESUBMIT.py.', bad_macros)]
1033
1034
[email protected]1f7b4172010-01-28 01:17:341035def CheckChangeOnUpload(input_api, output_api):
1036 results = []
1037 results.extend(_CommonChecks(input_api, output_api))
[email protected]fe5f57c52009-06-05 14:25:541038 return results
[email protected]ca8d1982009-02-19 16:33:121039
1040
1041def CheckChangeOnCommit(input_api, output_api):
[email protected]fe5f57c52009-06-05 14:25:541042 results = []
[email protected]1f7b4172010-01-28 01:17:341043 results.extend(_CommonChecks(input_api, output_api))
[email protected]dd805fe2009-10-01 08:11:511044 # TODO(thestig) temporarily disabled, doesn't work in third_party/
1045 #results.extend(input_api.canned_checks.CheckSvnModifiedDirectories(
1046 # input_api, output_api, sources))
[email protected]fe5f57c52009-06-05 14:25:541047 # Make sure the tree is 'open'.
[email protected]806e98e2010-03-19 17:49:271048 results.extend(input_api.canned_checks.CheckTreeIsOpen(
[email protected]7f238152009-08-12 19:00:341049 input_api,
1050 output_api,
[email protected]2fdd1f362013-01-16 03:56:031051 json_url='http://chromium-status.appspot.com/current?format=json'))
[email protected]806e98e2010-03-19 17:49:271052 results.extend(input_api.canned_checks.CheckRietveldTryJobExecution(input_api,
[email protected]2fdd1f362013-01-16 03:56:031053 output_api, 'http://codereview.chromium.org',
[email protected]c1ba4c52012-03-09 14:23:281054 ('win_rel', 'linux_rel', 'mac_rel, win:compile'),
1055 '[email protected]'))
[email protected]806e98e2010-03-19 17:49:271056
[email protected]3e4eb112011-01-18 03:29:541057 results.extend(input_api.canned_checks.CheckChangeHasBugField(
1058 input_api, output_api))
[email protected]c4b47562011-12-05 23:39:411059 results.extend(input_api.canned_checks.CheckChangeHasDescription(
1060 input_api, output_api))
[email protected]b337cb5b2011-01-23 21:24:051061 results.extend(_CheckSubversionConfig(input_api, output_api))
[email protected]fe5f57c52009-06-05 14:25:541062 return results
[email protected]ca8d1982009-02-19 16:33:121063
1064
[email protected]5efb2a822011-09-27 23:06:131065def GetPreferredTrySlaves(project, change):
[email protected]4ce995ea2012-06-27 02:13:101066 files = change.LocalPaths()
1067
[email protected]751b05f2013-01-10 23:12:171068 if not files or all(re.search(r'[\\/]OWNERS$', f) for f in files):
[email protected]3019c902012-06-29 00:09:031069 return []
1070
[email protected]d668899a2012-09-06 18:16:591071 if all(re.search('\.(m|mm)$|(^|[/_])mac[/_.]', f) for f in files):
[email protected]49da83c2013-11-07 14:08:501072 return ['mac_rel', 'mac:compile']
[email protected]d668899a2012-09-06 18:16:591073 if all(re.search('(^|[/_])win[/_.]', f) for f in files):
[email protected]c42e885c2013-11-12 17:01:381074 return ['win_rel', 'win:compile']
[email protected]d668899a2012-09-06 18:16:591075 if all(re.search('(^|[/_])android[/_.]', f) for f in files):
[email protected]49da83c2013-11-07 14:08:501076 return ['android_aosp', 'android_dbg', 'android_clang_dbg']
[email protected]356aa542012-09-19 23:31:291077 if all(re.search('^native_client_sdk', f) for f in files):
[email protected]49da83c2013-11-07 14:08:501078 return ['linux_nacl_sdk', 'win_nacl_sdk', 'mac_nacl_sdk']
[email protected]de142152012-10-03 23:02:451079 if all(re.search('[/_]ios[/_.]', f) for f in files):
[email protected]49da83c2013-11-07 14:08:501080 return ['ios_rel_device', 'ios_dbg_simulator']
[email protected]4ce995ea2012-06-27 02:13:101081
[email protected]49da83c2013-11-07 14:08:501082 trybots = [
[email protected]3e2f0402012-11-02 16:28:011083 'android_clang_dbg',
1084 'android_dbg',
1085 'ios_dbg_simulator',
1086 'ios_rel_device',
1087 'linux_asan',
[email protected]95c989162012-11-29 05:58:251088 'linux_aura',
[email protected]3e2f0402012-11-02 16:28:011089 'linux_chromeos',
[email protected]49da83c2013-11-07 14:08:501090 'linux_clang:compile',
[email protected]3e2f0402012-11-02 16:28:011091 'linux_rel',
[email protected]3e2f0402012-11-02 16:28:011092 'mac_rel',
[email protected]49da83c2013-11-07 14:08:501093 'mac:compile',
[email protected]3e2f0402012-11-02 16:28:011094 'win_rel',
[email protected]49da83c2013-11-07 14:08:501095 'win:compile',
1096 'win_x64_rel:base_unittests',
1097 ]
[email protected]911753b2012-08-02 12:11:541098
1099 # Match things like path/aura/file.cc and path/file_aura.cc.
[email protected]95c989162012-11-29 05:58:251100 # Same for chromeos.
1101 if any(re.search('[/_](aura|chromeos)', f) for f in files):
[email protected]49da83c2013-11-07 14:08:501102 trybots += ['linux_chromeos_clang:compile', 'linux_chromeos_asan']
[email protected]4ce995ea2012-06-27 02:13:101103
[email protected]e8df48f2013-09-30 20:07:541104 # If there are gyp changes to base, build, or chromeos, run a full cros build
1105 # in addition to the shorter linux_chromeos build. Changes to high level gyp
1106 # files have a much higher chance of breaking the cros build, which is
1107 # differnt from the linux_chromeos build that most chrome developers test
1108 # with.
1109 if any(re.search('^(base|build|chromeos).*\.gypi?$', f) for f in files):
[email protected]49da83c2013-11-07 14:08:501110 trybots += ['cros_x86']
[email protected]e8df48f2013-09-30 20:07:541111
[email protected]d95948ef2013-07-02 10:51:001112 # The AOSP bot doesn't build the chrome/ layer, so ignore any changes to it
1113 # unless they're .gyp(i) files as changes to those files can break the gyp
1114 # step on that bot.
1115 if (not all(re.search('^chrome', f) for f in files) or
1116 any(re.search('\.gypi?$', f) for f in files)):
[email protected]49da83c2013-11-07 14:08:501117 trybots += ['android_aosp']
[email protected]d95948ef2013-07-02 10:51:001118
[email protected]4ce995ea2012-06-27 02:13:101119 return trybots