blob: f861ab5ab6c8fcfa4ca78cc96103de38df1660e7 [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[/\\].*',
[email protected]7b054982013-11-27 00:44:4748 # Non-production example code.
49 r'mojo[/\\]examples[/\\].*',
[email protected]06e6d0ff2012-12-11 01:36:4450)
[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 (
[email protected]0b818f72013-10-22 00:11:03162 r"^components[\\\/]breakpad[\\\/]app[\\\/]breakpad_mac\.mm$",
[email protected]de7d61ff2013-08-20 11:30:41163 r"^content[\\\/]shell[\\\/]browser[\\\/]shell_browser_main\.cc$",
164 r"^content[\\\/]shell[\\\/]browser[\\\/]shell_message_filter\.cc$",
[email protected]398ad132013-04-02 15:11:01165 r"^net[\\\/]disk_cache[\\\/]cache_util\.cc$",
[email protected]7345da02012-11-27 14:31:49166 ),
[email protected]23e6cbc2012-06-16 18:51:20167 ),
[email protected]52657f62013-05-20 05:30:31168 (
169 'SkRefPtr',
170 (
171 'The use of SkRefPtr is prohibited. ',
172 'Please use skia::RefPtr instead.'
173 ),
174 True,
175 (),
176 ),
177 (
178 'SkAutoRef',
179 (
180 'The indirect use of SkRefPtr via SkAutoRef is prohibited. ',
181 'Please use skia::RefPtr instead.'
182 ),
183 True,
184 (),
185 ),
186 (
187 'SkAutoTUnref',
188 (
189 'The use of SkAutoTUnref is dangerous because it implicitly ',
190 'converts to a raw pointer. Please use skia::RefPtr instead.'
191 ),
192 True,
193 (),
194 ),
195 (
196 'SkAutoUnref',
197 (
198 'The indirect use of SkAutoTUnref through SkAutoUnref is dangerous ',
199 'because it implicitly converts to a raw pointer. ',
200 'Please use skia::RefPtr instead.'
201 ),
202 True,
203 (),
204 ),
[email protected]127f18ec2012-06-16 05:05:59205)
206
207
[email protected]b00342e7f2013-03-26 16:21:54208_VALID_OS_MACROS = (
209 # Please keep sorted.
210 'OS_ANDROID',
211 'OS_BSD',
212 'OS_CAT', # For testing.
213 'OS_CHROMEOS',
214 'OS_FREEBSD',
215 'OS_IOS',
216 'OS_LINUX',
217 'OS_MACOSX',
218 'OS_NACL',
219 'OS_OPENBSD',
220 'OS_POSIX',
221 'OS_SOLARIS',
[email protected]b00342e7f2013-03-26 16:21:54222 'OS_WIN',
223)
224
225
[email protected]55459852011-08-10 15:17:19226def _CheckNoProductionCodeUsingTestOnlyFunctions(input_api, output_api):
227 """Attempts to prevent use of functions intended only for testing in
228 non-testing code. For now this is just a best-effort implementation
229 that ignores header files and may have some false positives. A
230 better implementation would probably need a proper C++ parser.
231 """
232 # We only scan .cc files and the like, as the declaration of
233 # for-testing functions in header files are hard to distinguish from
234 # calls to such functions without a proper C++ parser.
[email protected]06e6d0ff2012-12-11 01:36:44235 file_inclusion_pattern = r'.+%s' % _IMPLEMENTATION_EXTENSIONS
[email protected]55459852011-08-10 15:17:19236
237 base_function_pattern = r'ForTest(ing)?|for_test(ing)?'
238 inclusion_pattern = input_api.re.compile(r'(%s)\s*\(' % base_function_pattern)
[email protected]de4f7d22013-05-23 14:27:46239 comment_pattern = input_api.re.compile(r'//.*%s' % base_function_pattern)
[email protected]55459852011-08-10 15:17:19240 exclusion_pattern = input_api.re.compile(
241 r'::[A-Za-z0-9_]+(%s)|(%s)[^;]+\{' % (
242 base_function_pattern, base_function_pattern))
243
244 def FilterFile(affected_file):
[email protected]06e6d0ff2012-12-11 01:36:44245 black_list = (_EXCLUDED_PATHS +
246 _TEST_CODE_EXCLUDED_PATHS +
247 input_api.DEFAULT_BLACK_LIST)
[email protected]55459852011-08-10 15:17:19248 return input_api.FilterSourceFile(
249 affected_file,
250 white_list=(file_inclusion_pattern, ),
251 black_list=black_list)
252
253 problems = []
254 for f in input_api.AffectedSourceFiles(FilterFile):
255 local_path = f.LocalPath()
[email protected]2fdd1f362013-01-16 03:56:03256 lines = input_api.ReadFile(f).splitlines()
257 line_number = 0
258 for line in lines:
259 if (inclusion_pattern.search(line) and
[email protected]de4f7d22013-05-23 14:27:46260 not comment_pattern.search(line) and
[email protected]2fdd1f362013-01-16 03:56:03261 not exclusion_pattern.search(line)):
[email protected]55459852011-08-10 15:17:19262 problems.append(
[email protected]2fdd1f362013-01-16 03:56:03263 '%s:%d\n %s' % (local_path, line_number, line.strip()))
264 line_number += 1
[email protected]55459852011-08-10 15:17:19265
266 if problems:
[email protected]f7051d52013-04-02 18:31:42267 return [output_api.PresubmitPromptOrNotify(_TEST_ONLY_WARNING, problems)]
[email protected]2fdd1f362013-01-16 03:56:03268 else:
269 return []
[email protected]55459852011-08-10 15:17:19270
271
[email protected]10689ca2011-09-02 02:31:54272def _CheckNoIOStreamInHeaders(input_api, output_api):
273 """Checks to make sure no .h files include <iostream>."""
274 files = []
275 pattern = input_api.re.compile(r'^#include\s*<iostream>',
276 input_api.re.MULTILINE)
277 for f in input_api.AffectedSourceFiles(input_api.FilterSourceFile):
278 if not f.LocalPath().endswith('.h'):
279 continue
280 contents = input_api.ReadFile(f)
281 if pattern.search(contents):
282 files.append(f)
283
284 if len(files):
285 return [ output_api.PresubmitError(
[email protected]6c063c62012-07-11 19:11:06286 'Do not #include <iostream> in header files, since it inserts static '
287 'initialization into every file including the header. Instead, '
[email protected]10689ca2011-09-02 02:31:54288 '#include <ostream>. See http://crbug.com/94794',
289 files) ]
290 return []
291
292
[email protected]72df4e782012-06-21 16:28:18293def _CheckNoUNIT_TESTInSourceFiles(input_api, output_api):
294 """Checks to make sure no source files use UNIT_TEST"""
295 problems = []
296 for f in input_api.AffectedFiles():
297 if (not f.LocalPath().endswith(('.cc', '.mm'))):
298 continue
299
300 for line_num, line in f.ChangedContents():
[email protected]549f86a2013-11-19 13:00:04301 if 'UNIT_TEST ' in line or line.endswith('UNIT_TEST'):
[email protected]72df4e782012-06-21 16:28:18302 problems.append(' %s:%d' % (f.LocalPath(), line_num))
303
304 if not problems:
305 return []
306 return [output_api.PresubmitPromptWarning('UNIT_TEST is only for headers.\n' +
307 '\n'.join(problems))]
308
309
[email protected]8ea5d4b2011-09-13 21:49:22310def _CheckNoNewWStrings(input_api, output_api):
311 """Checks to make sure we don't introduce use of wstrings."""
[email protected]55463aa62011-10-12 00:48:27312 problems = []
[email protected]8ea5d4b2011-09-13 21:49:22313 for f in input_api.AffectedFiles():
[email protected]b5c24292011-11-28 14:38:20314 if (not f.LocalPath().endswith(('.cc', '.h')) or
[email protected]24be83c2013-08-29 23:01:23315 f.LocalPath().endswith(('test.cc', '_win.cc', '_win.h'))):
[email protected]b5c24292011-11-28 14:38:20316 continue
[email protected]8ea5d4b2011-09-13 21:49:22317
[email protected]a11dbe9b2012-08-07 01:32:58318 allowWString = False
[email protected]b5c24292011-11-28 14:38:20319 for line_num, line in f.ChangedContents():
[email protected]a11dbe9b2012-08-07 01:32:58320 if 'presubmit: allow wstring' in line:
321 allowWString = True
322 elif not allowWString and 'wstring' in line:
[email protected]55463aa62011-10-12 00:48:27323 problems.append(' %s:%d' % (f.LocalPath(), line_num))
[email protected]a11dbe9b2012-08-07 01:32:58324 allowWString = False
325 else:
326 allowWString = False
[email protected]8ea5d4b2011-09-13 21:49:22327
[email protected]55463aa62011-10-12 00:48:27328 if not problems:
329 return []
330 return [output_api.PresubmitPromptWarning('New code should not use wstrings.'
[email protected]a11dbe9b2012-08-07 01:32:58331 ' If you are calling a cross-platform API that accepts a wstring, '
332 'fix the API.\n' +
[email protected]55463aa62011-10-12 00:48:27333 '\n'.join(problems))]
[email protected]8ea5d4b2011-09-13 21:49:22334
335
[email protected]2a8ac9c2011-10-19 17:20:44336def _CheckNoDEPSGIT(input_api, output_api):
337 """Make sure .DEPS.git is never modified manually."""
338 if any(f.LocalPath().endswith('.DEPS.git') for f in
339 input_api.AffectedFiles()):
340 return [output_api.PresubmitError(
341 'Never commit changes to .DEPS.git. This file is maintained by an\n'
342 'automated system based on what\'s in DEPS and your changes will be\n'
343 'overwritten.\n'
344 'See http://code.google.com/p/chromium/wiki/UsingNewGit#Rolling_DEPS\n'
345 'for more information')]
346 return []
347
348
[email protected]127f18ec2012-06-16 05:05:59349def _CheckNoBannedFunctions(input_api, output_api):
350 """Make sure that banned functions are not used."""
351 warnings = []
352 errors = []
353
354 file_filter = lambda f: f.LocalPath().endswith(('.mm', '.m', '.h'))
355 for f in input_api.AffectedFiles(file_filter=file_filter):
356 for line_num, line in f.ChangedContents():
357 for func_name, message, error in _BANNED_OBJC_FUNCTIONS:
358 if func_name in line:
359 problems = warnings;
360 if error:
361 problems = errors;
362 problems.append(' %s:%d:' % (f.LocalPath(), line_num))
363 for message_line in message:
364 problems.append(' %s' % message_line)
365
366 file_filter = lambda f: f.LocalPath().endswith(('.cc', '.mm', '.h'))
367 for f in input_api.AffectedFiles(file_filter=file_filter):
368 for line_num, line in f.ChangedContents():
[email protected]7345da02012-11-27 14:31:49369 for func_name, message, error, excluded_paths in _BANNED_CPP_FUNCTIONS:
370 def IsBlacklisted(affected_file, blacklist):
371 local_path = affected_file.LocalPath()
372 for item in blacklist:
373 if input_api.re.match(item, local_path):
374 return True
375 return False
376 if IsBlacklisted(f, excluded_paths):
377 continue
[email protected]127f18ec2012-06-16 05:05:59378 if func_name in line:
379 problems = warnings;
380 if error:
381 problems = errors;
382 problems.append(' %s:%d:' % (f.LocalPath(), line_num))
383 for message_line in message:
384 problems.append(' %s' % message_line)
385
386 result = []
387 if (warnings):
388 result.append(output_api.PresubmitPromptWarning(
389 'Banned functions were used.\n' + '\n'.join(warnings)))
390 if (errors):
391 result.append(output_api.PresubmitError(
392 'Banned functions were used.\n' + '\n'.join(errors)))
393 return result
394
395
[email protected]6c063c62012-07-11 19:11:06396def _CheckNoPragmaOnce(input_api, output_api):
397 """Make sure that banned functions are not used."""
398 files = []
399 pattern = input_api.re.compile(r'^#pragma\s+once',
400 input_api.re.MULTILINE)
401 for f in input_api.AffectedSourceFiles(input_api.FilterSourceFile):
402 if not f.LocalPath().endswith('.h'):
403 continue
404 contents = input_api.ReadFile(f)
405 if pattern.search(contents):
406 files.append(f)
407
408 if files:
409 return [output_api.PresubmitError(
410 'Do not use #pragma once in header files.\n'
411 'See http://www.chromium.org/developers/coding-style#TOC-File-headers',
412 files)]
413 return []
414
[email protected]127f18ec2012-06-16 05:05:59415
[email protected]e7479052012-09-19 00:26:12416def _CheckNoTrinaryTrueFalse(input_api, output_api):
417 """Checks to make sure we don't introduce use of foo ? true : false."""
418 problems = []
419 pattern = input_api.re.compile(r'\?\s*(true|false)\s*:\s*(true|false)')
420 for f in input_api.AffectedFiles():
421 if not f.LocalPath().endswith(('.cc', '.h', '.inl', '.m', '.mm')):
422 continue
423
424 for line_num, line in f.ChangedContents():
425 if pattern.match(line):
426 problems.append(' %s:%d' % (f.LocalPath(), line_num))
427
428 if not problems:
429 return []
430 return [output_api.PresubmitPromptWarning(
431 'Please consider avoiding the "? true : false" pattern if possible.\n' +
432 '\n'.join(problems))]
433
434
[email protected]55f9f382012-07-31 11:02:18435def _CheckUnwantedDependencies(input_api, output_api):
436 """Runs checkdeps on #include statements added in this
437 change. Breaking - rules is an error, breaking ! rules is a
438 warning.
439 """
440 # We need to wait until we have an input_api object and use this
441 # roundabout construct to import checkdeps because this file is
442 # eval-ed and thus doesn't have __file__.
443 original_sys_path = sys.path
444 try:
445 sys.path = sys.path + [input_api.os_path.join(
446 input_api.PresubmitLocalPath(), 'tools', 'checkdeps')]
447 import checkdeps
448 from cpp_checker import CppChecker
449 from rules import Rule
450 finally:
451 # Restore sys.path to what it was before.
452 sys.path = original_sys_path
453
454 added_includes = []
455 for f in input_api.AffectedFiles():
456 if not CppChecker.IsCppFile(f.LocalPath()):
457 continue
458
459 changed_lines = [line for line_num, line in f.ChangedContents()]
460 added_includes.append([f.LocalPath(), changed_lines])
461
[email protected]26385172013-05-09 23:11:35462 deps_checker = checkdeps.DepsChecker(input_api.PresubmitLocalPath())
[email protected]55f9f382012-07-31 11:02:18463
464 error_descriptions = []
465 warning_descriptions = []
466 for path, rule_type, rule_description in deps_checker.CheckAddedCppIncludes(
467 added_includes):
468 description_with_path = '%s\n %s' % (path, rule_description)
469 if rule_type == Rule.DISALLOW:
470 error_descriptions.append(description_with_path)
471 else:
472 warning_descriptions.append(description_with_path)
473
474 results = []
475 if error_descriptions:
476 results.append(output_api.PresubmitError(
477 'You added one or more #includes that violate checkdeps rules.',
478 error_descriptions))
479 if warning_descriptions:
[email protected]f7051d52013-04-02 18:31:42480 results.append(output_api.PresubmitPromptOrNotify(
[email protected]55f9f382012-07-31 11:02:18481 'You added one or more #includes of files that are temporarily\n'
482 'allowed but being removed. Can you avoid introducing the\n'
483 '#include? See relevant DEPS file(s) for details and contacts.',
484 warning_descriptions))
485 return results
486
487
[email protected]fbcafe5a2012-08-08 15:31:22488def _CheckFilePermissions(input_api, output_api):
489 """Check that all files have their permissions properly set."""
490 args = [sys.executable, 'tools/checkperms/checkperms.py', '--root',
491 input_api.change.RepositoryRoot()]
492 for f in input_api.AffectedFiles():
493 args += ['--file', f.LocalPath()]
494 errors = []
495 (errors, stderrdata) = subprocess.Popen(args).communicate()
496
497 results = []
498 if errors:
[email protected]c8278b32012-10-30 20:35:49499 results.append(output_api.PresubmitError('checkperms.py failed.',
[email protected]fbcafe5a2012-08-08 15:31:22500 errors))
501 return results
502
503
[email protected]c8278b32012-10-30 20:35:49504def _CheckNoAuraWindowPropertyHInHeaders(input_api, output_api):
505 """Makes sure we don't include ui/aura/window_property.h
506 in header files.
507 """
508 pattern = input_api.re.compile(r'^#include\s*"ui/aura/window_property.h"')
509 errors = []
510 for f in input_api.AffectedFiles():
511 if not f.LocalPath().endswith('.h'):
512 continue
513 for line_num, line in f.ChangedContents():
514 if pattern.match(line):
515 errors.append(' %s:%d' % (f.LocalPath(), line_num))
516
517 results = []
518 if errors:
519 results.append(output_api.PresubmitError(
520 'Header files should not include ui/aura/window_property.h', errors))
521 return results
522
523
[email protected]cf9b78f2012-11-14 11:40:28524def _CheckIncludeOrderForScope(scope, input_api, file_path, changed_linenums):
525 """Checks that the lines in scope occur in the right order.
526
527 1. C system files in alphabetical order
528 2. C++ system files in alphabetical order
529 3. Project's .h files
530 """
531
532 c_system_include_pattern = input_api.re.compile(r'\s*#include <.*\.h>')
533 cpp_system_include_pattern = input_api.re.compile(r'\s*#include <.*>')
534 custom_include_pattern = input_api.re.compile(r'\s*#include ".*')
535
536 C_SYSTEM_INCLUDES, CPP_SYSTEM_INCLUDES, CUSTOM_INCLUDES = range(3)
537
538 state = C_SYSTEM_INCLUDES
539
540 previous_line = ''
[email protected]728b9bb2012-11-14 20:38:57541 previous_line_num = 0
[email protected]cf9b78f2012-11-14 11:40:28542 problem_linenums = []
543 for line_num, line in scope:
544 if c_system_include_pattern.match(line):
545 if state != C_SYSTEM_INCLUDES:
[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 previous_line and previous_line > line:
[email protected]728b9bb2012-11-14 20:38:57548 problem_linenums.append((line_num, previous_line_num))
[email protected]cf9b78f2012-11-14 11:40:28549 elif cpp_system_include_pattern.match(line):
550 if state == C_SYSTEM_INCLUDES:
551 state = CPP_SYSTEM_INCLUDES
552 elif state == CUSTOM_INCLUDES:
[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 previous_line and previous_line > line:
[email protected]728b9bb2012-11-14 20:38:57555 problem_linenums.append((line_num, previous_line_num))
[email protected]cf9b78f2012-11-14 11:40:28556 elif custom_include_pattern.match(line):
557 if state != CUSTOM_INCLUDES:
558 state = CUSTOM_INCLUDES
559 elif previous_line and previous_line > line:
[email protected]728b9bb2012-11-14 20:38:57560 problem_linenums.append((line_num, previous_line_num))
[email protected]cf9b78f2012-11-14 11:40:28561 else:
562 problem_linenums.append(line_num)
563 previous_line = line
[email protected]728b9bb2012-11-14 20:38:57564 previous_line_num = line_num
[email protected]cf9b78f2012-11-14 11:40:28565
566 warnings = []
[email protected]728b9bb2012-11-14 20:38:57567 for (line_num, previous_line_num) in problem_linenums:
568 if line_num in changed_linenums or previous_line_num in changed_linenums:
[email protected]cf9b78f2012-11-14 11:40:28569 warnings.append(' %s:%d' % (file_path, line_num))
570 return warnings
571
572
[email protected]ac294a12012-12-06 16:38:43573def _CheckIncludeOrderInFile(input_api, f, changed_linenums):
[email protected]cf9b78f2012-11-14 11:40:28574 """Checks the #include order for the given file f."""
575
[email protected]2299dcf2012-11-15 19:56:24576 system_include_pattern = input_api.re.compile(r'\s*#include \<.*')
[email protected]23093b62013-09-20 12:16:30577 # Exclude the following includes from the check:
578 # 1) #include <.../...>, e.g., <sys/...> includes often need to appear in a
579 # specific order.
580 # 2) <atlbase.h>, "build/build_config.h"
581 excluded_include_pattern = input_api.re.compile(
582 r'\s*#include (\<.*/.*|\<atlbase\.h\>|"build/build_config.h")')
[email protected]2299dcf2012-11-15 19:56:24583 custom_include_pattern = input_api.re.compile(r'\s*#include "(?P<FILE>.*)"')
[email protected]3e83618c2013-10-09 22:32:33584 # Match the final or penultimate token if it is xxxtest so we can ignore it
585 # when considering the special first include.
586 test_file_tag_pattern = input_api.re.compile(
587 r'_[a-z]+test(?=(_[a-zA-Z0-9]+)?\.)')
[email protected]0e5c1852012-12-18 20:17:11588 if_pattern = input_api.re.compile(
589 r'\s*#\s*(if|elif|else|endif|define|undef).*')
590 # Some files need specialized order of includes; exclude such files from this
591 # check.
592 uncheckable_includes_pattern = input_api.re.compile(
593 r'\s*#include '
594 '("ipc/.*macros\.h"|<windows\.h>|".*gl.*autogen.h")\s*')
[email protected]cf9b78f2012-11-14 11:40:28595
596 contents = f.NewContents()
597 warnings = []
598 line_num = 0
599
[email protected]ac294a12012-12-06 16:38:43600 # Handle the special first include. If the first include file is
601 # some/path/file.h, the corresponding including file can be some/path/file.cc,
602 # some/other/path/file.cc, some/path/file_platform.cc, some/path/file-suffix.h
603 # etc. It's also possible that no special first include exists.
[email protected]3e83618c2013-10-09 22:32:33604 # If the included file is some/path/file_platform.h the including file could
605 # also be some/path/file_xxxtest_platform.h.
606 including_file_base_name = test_file_tag_pattern.sub(
607 '', input_api.os_path.basename(f.LocalPath()))
608
[email protected]ac294a12012-12-06 16:38:43609 for line in contents:
610 line_num += 1
611 if system_include_pattern.match(line):
612 # No special first include -> process the line again along with normal
613 # includes.
614 line_num -= 1
615 break
616 match = custom_include_pattern.match(line)
617 if match:
618 match_dict = match.groupdict()
[email protected]3e83618c2013-10-09 22:32:33619 header_basename = test_file_tag_pattern.sub(
620 '', input_api.os_path.basename(match_dict['FILE'])).replace('.h', '')
621
622 if header_basename not in including_file_base_name:
[email protected]2299dcf2012-11-15 19:56:24623 # No special first include -> process the line again along with normal
624 # includes.
625 line_num -= 1
[email protected]ac294a12012-12-06 16:38:43626 break
[email protected]cf9b78f2012-11-14 11:40:28627
628 # Split into scopes: Each region between #if and #endif is its own scope.
629 scopes = []
630 current_scope = []
631 for line in contents[line_num:]:
632 line_num += 1
[email protected]0e5c1852012-12-18 20:17:11633 if uncheckable_includes_pattern.match(line):
634 return []
[email protected]2309b0fa02012-11-16 12:18:27635 if if_pattern.match(line):
[email protected]cf9b78f2012-11-14 11:40:28636 scopes.append(current_scope)
637 current_scope = []
[email protected]962f117e2012-11-22 18:11:56638 elif ((system_include_pattern.match(line) or
639 custom_include_pattern.match(line)) and
640 not excluded_include_pattern.match(line)):
[email protected]cf9b78f2012-11-14 11:40:28641 current_scope.append((line_num, line))
642 scopes.append(current_scope)
643
644 for scope in scopes:
645 warnings.extend(_CheckIncludeOrderForScope(scope, input_api, f.LocalPath(),
646 changed_linenums))
647 return warnings
648
649
650def _CheckIncludeOrder(input_api, output_api):
651 """Checks that the #include order is correct.
652
653 1. The corresponding header for source files.
654 2. C system files in alphabetical order
655 3. C++ system files in alphabetical order
656 4. Project's .h files in alphabetical order
657
[email protected]ac294a12012-12-06 16:38:43658 Each region separated by #if, #elif, #else, #endif, #define and #undef follows
659 these rules separately.
[email protected]cf9b78f2012-11-14 11:40:28660 """
661
662 warnings = []
663 for f in input_api.AffectedFiles():
[email protected]ac294a12012-12-06 16:38:43664 if f.LocalPath().endswith(('.cc', '.h')):
665 changed_linenums = set(line_num for line_num, _ in f.ChangedContents())
666 warnings.extend(_CheckIncludeOrderInFile(input_api, f, changed_linenums))
[email protected]cf9b78f2012-11-14 11:40:28667
668 results = []
669 if warnings:
[email protected]f7051d52013-04-02 18:31:42670 results.append(output_api.PresubmitPromptOrNotify(_INCLUDE_ORDER_WARNING,
[email protected]120cf540d2012-12-10 17:55:53671 warnings))
[email protected]cf9b78f2012-11-14 11:40:28672 return results
673
674
[email protected]70ca77752012-11-20 03:45:03675def _CheckForVersionControlConflictsInFile(input_api, f):
676 pattern = input_api.re.compile('^(?:<<<<<<<|>>>>>>>) |^=======$')
677 errors = []
678 for line_num, line in f.ChangedContents():
679 if pattern.match(line):
680 errors.append(' %s:%d %s' % (f.LocalPath(), line_num, line))
681 return errors
682
683
684def _CheckForVersionControlConflicts(input_api, output_api):
685 """Usually this is not intentional and will cause a compile failure."""
686 errors = []
687 for f in input_api.AffectedFiles():
688 errors.extend(_CheckForVersionControlConflictsInFile(input_api, f))
689
690 results = []
691 if errors:
692 results.append(output_api.PresubmitError(
693 'Version control conflict markers found, please resolve.', errors))
694 return results
695
696
[email protected]06e6d0ff2012-12-11 01:36:44697def _CheckHardcodedGoogleHostsInLowerLayers(input_api, output_api):
698 def FilterFile(affected_file):
699 """Filter function for use with input_api.AffectedSourceFiles,
700 below. This filters out everything except non-test files from
701 top-level directories that generally speaking should not hard-code
702 service URLs (e.g. src/android_webview/, src/content/ and others).
703 """
704 return input_api.FilterSourceFile(
705 affected_file,
[email protected]78bb39d62012-12-11 15:11:56706 white_list=(r'^(android_webview|base|content|net)[\\\/].*', ),
[email protected]06e6d0ff2012-12-11 01:36:44707 black_list=(_EXCLUDED_PATHS +
708 _TEST_CODE_EXCLUDED_PATHS +
709 input_api.DEFAULT_BLACK_LIST))
710
[email protected]de4f7d22013-05-23 14:27:46711 base_pattern = '"[^"]*google\.com[^"]*"'
712 comment_pattern = input_api.re.compile('//.*%s' % base_pattern)
713 pattern = input_api.re.compile(base_pattern)
[email protected]06e6d0ff2012-12-11 01:36:44714 problems = [] # items are (filename, line_number, line)
715 for f in input_api.AffectedSourceFiles(FilterFile):
716 for line_num, line in f.ChangedContents():
[email protected]de4f7d22013-05-23 14:27:46717 if not comment_pattern.search(line) and pattern.search(line):
[email protected]06e6d0ff2012-12-11 01:36:44718 problems.append((f.LocalPath(), line_num, line))
719
720 if problems:
[email protected]f7051d52013-04-02 18:31:42721 return [output_api.PresubmitPromptOrNotify(
[email protected]06e6d0ff2012-12-11 01:36:44722 'Most layers below src/chrome/ should not hardcode service URLs.\n'
723 'Are you sure this is correct? (Contact: [email protected])',
724 [' %s:%d: %s' % (
725 problem[0], problem[1], problem[2]) for problem in problems])]
[email protected]2fdd1f362013-01-16 03:56:03726 else:
727 return []
[email protected]06e6d0ff2012-12-11 01:36:44728
729
[email protected]d2530012013-01-25 16:39:27730def _CheckNoAbbreviationInPngFileName(input_api, output_api):
731 """Makes sure there are no abbreviations in the name of PNG files.
732 """
[email protected]4053a48e2013-01-25 21:43:04733 pattern = input_api.re.compile(r'.*_[a-z]_.*\.png$|.*_[a-z]\.png$')
[email protected]d2530012013-01-25 16:39:27734 errors = []
735 for f in input_api.AffectedFiles(include_deletes=False):
736 if pattern.match(f.LocalPath()):
737 errors.append(' %s' % f.LocalPath())
738
739 results = []
740 if errors:
741 results.append(output_api.PresubmitError(
742 'The name of PNG files should not have abbreviations. \n'
743 'Use _hover.png, _center.png, instead of _h.png, _c.png.\n'
744 'Contact [email protected] if you have questions.', errors))
745 return results
746
747
[email protected]f32e2d1e2013-07-26 21:39:08748def _DepsFilesToCheck(re, changed_lines):
749 """Helper method for _CheckAddedDepsHaveTargetApprovals. Returns
750 a set of DEPS entries that we should look up."""
[email protected]2b438d62013-11-14 17:54:14751 # We ignore deps entries on auto-generated directories.
752 AUTO_GENERATED_DIRS = ['grit', 'jni']
[email protected]f32e2d1e2013-07-26 21:39:08753
754 # This pattern grabs the path without basename in the first
755 # parentheses, and the basename (if present) in the second. It
756 # relies on the simple heuristic that if there is a basename it will
757 # be a header file ending in ".h".
758 pattern = re.compile(
759 r"""['"]\+([^'"]+?)(/[a-zA-Z0-9_]+\.h)?['"].*""")
[email protected]2b438d62013-11-14 17:54:14760 results = set()
[email protected]f32e2d1e2013-07-26 21:39:08761 for changed_line in changed_lines:
762 m = pattern.match(changed_line)
763 if m:
764 path = m.group(1)
[email protected]2b438d62013-11-14 17:54:14765 if path.split('/')[0] not in AUTO_GENERATED_DIRS:
[email protected]f32e2d1e2013-07-26 21:39:08766 results.add('%s/DEPS' % m.group(1))
767 return results
768
769
[email protected]e871964c2013-05-13 14:14:55770def _CheckAddedDepsHaveTargetApprovals(input_api, output_api):
771 """When a dependency prefixed with + is added to a DEPS file, we
772 want to make sure that the change is reviewed by an OWNER of the
773 target file or directory, to avoid layering violations from being
774 introduced. This check verifies that this happens.
775 """
776 changed_lines = set()
777 for f in input_api.AffectedFiles():
778 filename = input_api.os_path.basename(f.LocalPath())
779 if filename == 'DEPS':
780 changed_lines |= set(line.strip()
781 for line_num, line
782 in f.ChangedContents())
783 if not changed_lines:
784 return []
785
[email protected]f32e2d1e2013-07-26 21:39:08786 virtual_depended_on_files = _DepsFilesToCheck(input_api.re, changed_lines)
[email protected]e871964c2013-05-13 14:14:55787 if not virtual_depended_on_files:
788 return []
789
790 if input_api.is_committing:
791 if input_api.tbr:
792 return [output_api.PresubmitNotifyResult(
793 '--tbr was specified, skipping OWNERS check for DEPS additions')]
794 if not input_api.change.issue:
795 return [output_api.PresubmitError(
796 "DEPS approval by OWNERS check failed: this change has "
797 "no Rietveld issue number, so we can't check it for approvals.")]
798 output = output_api.PresubmitError
799 else:
800 output = output_api.PresubmitNotifyResult
801
802 owners_db = input_api.owners_db
803 owner_email, reviewers = input_api.canned_checks._RietveldOwnerAndReviewers(
804 input_api,
805 owners_db.email_regexp,
806 approval_needed=input_api.is_committing)
807
808 owner_email = owner_email or input_api.change.author_email
809
[email protected]de4f7d22013-05-23 14:27:46810 reviewers_plus_owner = set(reviewers)
[email protected]e71c6082013-05-22 02:28:51811 if owner_email:
[email protected]de4f7d22013-05-23 14:27:46812 reviewers_plus_owner.add(owner_email)
[email protected]e871964c2013-05-13 14:14:55813 missing_files = owners_db.files_not_covered_by(virtual_depended_on_files,
814 reviewers_plus_owner)
815 unapproved_dependencies = ["'+%s'," % path[:-len('/DEPS')]
816 for path in missing_files]
817
818 if unapproved_dependencies:
819 output_list = [
820 output('Missing LGTM from OWNERS of directories added to DEPS:\n %s' %
821 '\n '.join(sorted(unapproved_dependencies)))]
822 if not input_api.is_committing:
823 suggested_owners = owners_db.reviewers_for(missing_files, owner_email)
824 output_list.append(output(
825 'Suggested missing target path OWNERS:\n %s' %
826 '\n '.join(suggested_owners or [])))
827 return output_list
828
829 return []
830
831
[email protected]85218562013-11-22 07:41:40832def _CheckSpamLogging(input_api, output_api):
833 file_inclusion_pattern = r'.+%s' % _IMPLEMENTATION_EXTENSIONS
834 black_list = (_EXCLUDED_PATHS +
835 _TEST_CODE_EXCLUDED_PATHS +
836 input_api.DEFAULT_BLACK_LIST +
[email protected]6f742dd02013-11-26 23:19:50837 (r"^base[\\\/]logging\.h$",
[email protected]cdbdced2013-11-27 21:35:50838 r"^remoting[\\\/]base[\\\/]logging\.h$",
839 r"^sandbox[\\\/]linux[\\\/].*",))
[email protected]85218562013-11-22 07:41:40840 source_file_filter = lambda x: input_api.FilterSourceFile(
841 x, white_list=(file_inclusion_pattern,), black_list=black_list)
842
843 log_info = []
844 printf = []
845
846 for f in input_api.AffectedSourceFiles(source_file_filter):
847 contents = input_api.ReadFile(f, 'rb')
848 if re.search(r"\bD?LOG\s*\(\s*INFO\s*\)", contents):
849 log_info.append(f.LocalPath())
[email protected]85210652013-11-28 05:50:13850 if re.search(r"\bD?LOG_IF\s*\(\s*INFO\s*,", contents):
851 log_info.append(f.LocalPath())
[email protected]cdbdced2013-11-27 21:35:50852 if re.search(r"\bf?printf\((stdout|stderr)", contents):
[email protected]85218562013-11-22 07:41:40853 printf.append(f.LocalPath())
854
855 if log_info:
856 return [output_api.PresubmitError(
857 'These files spam the console log with LOG(INFO):',
858 items=log_info)]
859 if printf:
860 return [output_api.PresubmitError(
861 'These files spam the console log with printf/fprintf:',
862 items=printf)]
863 return []
864
865
[email protected]5fe0f8742013-11-29 01:04:59866def _CheckCygwinShell(input_api, output_api):
867 source_file_filter = lambda x: input_api.FilterSourceFile(
868 x, white_list=(r'.+\.(gyp|gypi)$',))
869 cygwin_shell = []
870
871 for f in input_api.AffectedSourceFiles(source_file_filter):
872 for linenum, line in f.ChangedContents():
873 if 'msvs_cygwin_shell' in line:
874 cygwin_shell.append(f.LocalPath())
875 break
876
877 if cygwin_shell:
878 return [output_api.PresubmitError(
879 'These files should not use msvs_cygwin_shell (the default is 0):',
880 items=cygwin_shell)]
881 return []
882
[email protected]85218562013-11-22 07:41:40883
[email protected]22c9bd72011-03-27 16:47:39884def _CommonChecks(input_api, output_api):
885 """Checks common to both upload and commit."""
886 results = []
887 results.extend(input_api.canned_checks.PanProjectChecks(
888 input_api, output_api, excluded_paths=_EXCLUDED_PATHS))
[email protected]66daa702011-05-28 14:41:46889 results.extend(_CheckAuthorizedAuthor(input_api, output_api))
[email protected]55459852011-08-10 15:17:19890 results.extend(
891 _CheckNoProductionCodeUsingTestOnlyFunctions(input_api, output_api))
[email protected]10689ca2011-09-02 02:31:54892 results.extend(_CheckNoIOStreamInHeaders(input_api, output_api))
[email protected]72df4e782012-06-21 16:28:18893 results.extend(_CheckNoUNIT_TESTInSourceFiles(input_api, output_api))
[email protected]8ea5d4b2011-09-13 21:49:22894 results.extend(_CheckNoNewWStrings(input_api, output_api))
[email protected]2a8ac9c2011-10-19 17:20:44895 results.extend(_CheckNoDEPSGIT(input_api, output_api))
[email protected]127f18ec2012-06-16 05:05:59896 results.extend(_CheckNoBannedFunctions(input_api, output_api))
[email protected]6c063c62012-07-11 19:11:06897 results.extend(_CheckNoPragmaOnce(input_api, output_api))
[email protected]e7479052012-09-19 00:26:12898 results.extend(_CheckNoTrinaryTrueFalse(input_api, output_api))
[email protected]55f9f382012-07-31 11:02:18899 results.extend(_CheckUnwantedDependencies(input_api, output_api))
[email protected]fbcafe5a2012-08-08 15:31:22900 results.extend(_CheckFilePermissions(input_api, output_api))
[email protected]c8278b32012-10-30 20:35:49901 results.extend(_CheckNoAuraWindowPropertyHInHeaders(input_api, output_api))
[email protected]2309b0fa02012-11-16 12:18:27902 results.extend(_CheckIncludeOrder(input_api, output_api))
[email protected]70ca77752012-11-20 03:45:03903 results.extend(_CheckForVersionControlConflicts(input_api, output_api))
[email protected]b8079ae4a2012-12-05 19:56:49904 results.extend(_CheckPatchFiles(input_api, output_api))
[email protected]06e6d0ff2012-12-11 01:36:44905 results.extend(_CheckHardcodedGoogleHostsInLowerLayers(input_api, output_api))
[email protected]d2530012013-01-25 16:39:27906 results.extend(_CheckNoAbbreviationInPngFileName(input_api, output_api))
[email protected]b00342e7f2013-03-26 16:21:54907 results.extend(_CheckForInvalidOSMacros(input_api, output_api))
[email protected]e871964c2013-05-13 14:14:55908 results.extend(_CheckAddedDepsHaveTargetApprovals(input_api, output_api))
[email protected]9f919cc2013-07-31 03:04:04909 results.extend(
910 input_api.canned_checks.CheckChangeHasNoTabs(
911 input_api,
912 output_api,
913 source_file_filter=lambda x: x.LocalPath().endswith('.grd')))
[email protected]85218562013-11-22 07:41:40914 results.extend(_CheckSpamLogging(input_api, output_api))
[email protected]5fe0f8742013-11-29 01:04:59915 results.extend(_CheckCygwinShell(input_api, output_api))
[email protected]2299dcf2012-11-15 19:56:24916
917 if any('PRESUBMIT.py' == f.LocalPath() for f in input_api.AffectedFiles()):
918 results.extend(input_api.canned_checks.RunUnitTestsInDirectory(
919 input_api, output_api,
920 input_api.PresubmitLocalPath(),
[email protected]6be63382013-01-21 15:42:38921 whitelist=[r'^PRESUBMIT_test\.py$']))
[email protected]22c9bd72011-03-27 16:47:39922 return results
[email protected]1f7b4172010-01-28 01:17:34923
[email protected]b337cb5b2011-01-23 21:24:05924
925def _CheckSubversionConfig(input_api, output_api):
926 """Verifies the subversion config file is correctly setup.
927
928 Checks that autoprops are enabled, returns an error otherwise.
929 """
930 join = input_api.os_path.join
931 if input_api.platform == 'win32':
932 appdata = input_api.environ.get('APPDATA', '')
933 if not appdata:
934 return [output_api.PresubmitError('%APPDATA% is not configured.')]
935 path = join(appdata, 'Subversion', 'config')
936 else:
937 home = input_api.environ.get('HOME', '')
938 if not home:
939 return [output_api.PresubmitError('$HOME is not configured.')]
940 path = join(home, '.subversion', 'config')
941
942 error_msg = (
943 'Please look at http://dev.chromium.org/developers/coding-style to\n'
944 'configure your subversion configuration file. This enables automatic\n'
[email protected]c6a3c10b2011-01-24 16:14:20945 'properties to simplify the project maintenance.\n'
946 'Pro-tip: just download and install\n'
947 'http://src.chromium.org/viewvc/chrome/trunk/tools/build/slave/config\n')
[email protected]b337cb5b2011-01-23 21:24:05948
949 try:
950 lines = open(path, 'r').read().splitlines()
951 # Make sure auto-props is enabled and check for 2 Chromium standard
952 # auto-prop.
953 if (not '*.cc = svn:eol-style=LF' in lines or
954 not '*.pdf = svn:mime-type=application/pdf' in lines or
955 not 'enable-auto-props = yes' in lines):
956 return [
[email protected]79ed7e62011-02-21 21:08:53957 output_api.PresubmitNotifyResult(
[email protected]b337cb5b2011-01-23 21:24:05958 'It looks like you have not configured your subversion config '
[email protected]b5359c02011-02-01 20:29:56959 'file or it is not up-to-date.\n' + error_msg)
[email protected]b337cb5b2011-01-23 21:24:05960 ]
961 except (OSError, IOError):
962 return [
[email protected]79ed7e62011-02-21 21:08:53963 output_api.PresubmitNotifyResult(
[email protected]b337cb5b2011-01-23 21:24:05964 'Can\'t find your subversion config file.\n' + error_msg)
965 ]
966 return []
967
968
[email protected]66daa702011-05-28 14:41:46969def _CheckAuthorizedAuthor(input_api, output_api):
970 """For non-googler/chromites committers, verify the author's email address is
971 in AUTHORS.
972 """
[email protected]9bb9cb82011-06-13 20:43:01973 # TODO(maruel): Add it to input_api?
974 import fnmatch
975
[email protected]66daa702011-05-28 14:41:46976 author = input_api.change.author_email
[email protected]9bb9cb82011-06-13 20:43:01977 if not author:
978 input_api.logging.info('No author, skipping AUTHOR check')
[email protected]66daa702011-05-28 14:41:46979 return []
[email protected]c99663292011-05-31 19:46:08980 authors_path = input_api.os_path.join(
[email protected]66daa702011-05-28 14:41:46981 input_api.PresubmitLocalPath(), 'AUTHORS')
982 valid_authors = (
983 input_api.re.match(r'[^#]+\s+\<(.+?)\>\s*$', line)
984 for line in open(authors_path))
[email protected]ac54b132011-06-06 18:11:18985 valid_authors = [item.group(1).lower() for item in valid_authors if item]
[email protected]d8b50be2011-06-15 14:19:44986 if not any(fnmatch.fnmatch(author.lower(), valid) for valid in valid_authors):
[email protected]5861efb2013-01-07 18:33:23987 input_api.logging.info('Valid authors are %s', ', '.join(valid_authors))
[email protected]66daa702011-05-28 14:41:46988 return [output_api.PresubmitPromptWarning(
989 ('%s is not in AUTHORS file. If you are a new contributor, please visit'
990 '\n'
991 'http://www.chromium.org/developers/contributing-code and read the '
992 '"Legal" section\n'
993 'If you are a chromite, verify the contributor signed the CLA.') %
994 author)]
995 return []
996
997
[email protected]b8079ae4a2012-12-05 19:56:49998def _CheckPatchFiles(input_api, output_api):
999 problems = [f.LocalPath() for f in input_api.AffectedFiles()
1000 if f.LocalPath().endswith(('.orig', '.rej'))]
1001 if problems:
1002 return [output_api.PresubmitError(
1003 "Don't commit .rej and .orig files.", problems)]
[email protected]2fdd1f362013-01-16 03:56:031004 else:
1005 return []
[email protected]b8079ae4a2012-12-05 19:56:491006
1007
[email protected]b00342e7f2013-03-26 16:21:541008def _DidYouMeanOSMacro(bad_macro):
1009 try:
1010 return {'A': 'OS_ANDROID',
1011 'B': 'OS_BSD',
1012 'C': 'OS_CHROMEOS',
1013 'F': 'OS_FREEBSD',
1014 'L': 'OS_LINUX',
1015 'M': 'OS_MACOSX',
1016 'N': 'OS_NACL',
1017 'O': 'OS_OPENBSD',
1018 'P': 'OS_POSIX',
1019 'S': 'OS_SOLARIS',
1020 'W': 'OS_WIN'}[bad_macro[3].upper()]
1021 except KeyError:
1022 return ''
1023
1024
1025def _CheckForInvalidOSMacrosInFile(input_api, f):
1026 """Check for sensible looking, totally invalid OS macros."""
1027 preprocessor_statement = input_api.re.compile(r'^\s*#')
1028 os_macro = input_api.re.compile(r'defined\((OS_[^)]+)\)')
1029 results = []
1030 for lnum, line in f.ChangedContents():
1031 if preprocessor_statement.search(line):
1032 for match in os_macro.finditer(line):
1033 if not match.group(1) in _VALID_OS_MACROS:
1034 good = _DidYouMeanOSMacro(match.group(1))
1035 did_you_mean = ' (did you mean %s?)' % good if good else ''
1036 results.append(' %s:%d %s%s' % (f.LocalPath(),
1037 lnum,
1038 match.group(1),
1039 did_you_mean))
1040 return results
1041
1042
1043def _CheckForInvalidOSMacros(input_api, output_api):
1044 """Check all affected files for invalid OS macros."""
1045 bad_macros = []
1046 for f in input_api.AffectedFiles():
1047 if not f.LocalPath().endswith(('.py', '.js', '.html', '.css')):
1048 bad_macros.extend(_CheckForInvalidOSMacrosInFile(input_api, f))
1049
1050 if not bad_macros:
1051 return []
1052
1053 return [output_api.PresubmitError(
1054 'Possibly invalid OS macro[s] found. Please fix your code\n'
1055 'or add your macro to src/PRESUBMIT.py.', bad_macros)]
1056
1057
[email protected]1f7b4172010-01-28 01:17:341058def CheckChangeOnUpload(input_api, output_api):
1059 results = []
1060 results.extend(_CommonChecks(input_api, output_api))
[email protected]fe5f57c52009-06-05 14:25:541061 return results
[email protected]ca8d1982009-02-19 16:33:121062
1063
1064def CheckChangeOnCommit(input_api, output_api):
[email protected]fe5f57c52009-06-05 14:25:541065 results = []
[email protected]1f7b4172010-01-28 01:17:341066 results.extend(_CommonChecks(input_api, output_api))
[email protected]dd805fe2009-10-01 08:11:511067 # TODO(thestig) temporarily disabled, doesn't work in third_party/
1068 #results.extend(input_api.canned_checks.CheckSvnModifiedDirectories(
1069 # input_api, output_api, sources))
[email protected]fe5f57c52009-06-05 14:25:541070 # Make sure the tree is 'open'.
[email protected]806e98e2010-03-19 17:49:271071 results.extend(input_api.canned_checks.CheckTreeIsOpen(
[email protected]7f238152009-08-12 19:00:341072 input_api,
1073 output_api,
[email protected]2fdd1f362013-01-16 03:56:031074 json_url='http://chromium-status.appspot.com/current?format=json'))
[email protected]806e98e2010-03-19 17:49:271075 results.extend(input_api.canned_checks.CheckRietveldTryJobExecution(input_api,
[email protected]2fdd1f362013-01-16 03:56:031076 output_api, 'http://codereview.chromium.org',
[email protected]c1ba4c52012-03-09 14:23:281077 ('win_rel', 'linux_rel', 'mac_rel, win:compile'),
1078 '[email protected]'))
[email protected]806e98e2010-03-19 17:49:271079
[email protected]3e4eb112011-01-18 03:29:541080 results.extend(input_api.canned_checks.CheckChangeHasBugField(
1081 input_api, output_api))
[email protected]c4b47562011-12-05 23:39:411082 results.extend(input_api.canned_checks.CheckChangeHasDescription(
1083 input_api, output_api))
[email protected]b337cb5b2011-01-23 21:24:051084 results.extend(_CheckSubversionConfig(input_api, output_api))
[email protected]fe5f57c52009-06-05 14:25:541085 return results
[email protected]ca8d1982009-02-19 16:33:121086
1087
[email protected]5efb2a822011-09-27 23:06:131088def GetPreferredTrySlaves(project, change):
[email protected]4ce995ea2012-06-27 02:13:101089 files = change.LocalPaths()
1090
[email protected]751b05f2013-01-10 23:12:171091 if not files or all(re.search(r'[\\/]OWNERS$', f) for f in files):
[email protected]3019c902012-06-29 00:09:031092 return []
1093
[email protected]d668899a2012-09-06 18:16:591094 if all(re.search('\.(m|mm)$|(^|[/_])mac[/_.]', f) for f in files):
[email protected]49da83c2013-11-07 14:08:501095 return ['mac_rel', 'mac:compile']
[email protected]d668899a2012-09-06 18:16:591096 if all(re.search('(^|[/_])win[/_.]', f) for f in files):
[email protected]c42e885c2013-11-12 17:01:381097 return ['win_rel', 'win:compile']
[email protected]d668899a2012-09-06 18:16:591098 if all(re.search('(^|[/_])android[/_.]', f) for f in files):
[email protected]49da83c2013-11-07 14:08:501099 return ['android_aosp', 'android_dbg', 'android_clang_dbg']
[email protected]356aa542012-09-19 23:31:291100 if all(re.search('^native_client_sdk', f) for f in files):
[email protected]49da83c2013-11-07 14:08:501101 return ['linux_nacl_sdk', 'win_nacl_sdk', 'mac_nacl_sdk']
[email protected]de142152012-10-03 23:02:451102 if all(re.search('[/_]ios[/_.]', f) for f in files):
[email protected]49da83c2013-11-07 14:08:501103 return ['ios_rel_device', 'ios_dbg_simulator']
[email protected]4ce995ea2012-06-27 02:13:101104
[email protected]49da83c2013-11-07 14:08:501105 trybots = [
[email protected]3e2f0402012-11-02 16:28:011106 'android_clang_dbg',
1107 'android_dbg',
1108 'ios_dbg_simulator',
1109 'ios_rel_device',
1110 'linux_asan',
[email protected]95c989162012-11-29 05:58:251111 'linux_aura',
[email protected]3e2f0402012-11-02 16:28:011112 'linux_chromeos',
[email protected]49da83c2013-11-07 14:08:501113 'linux_clang:compile',
[email protected]3e2f0402012-11-02 16:28:011114 'linux_rel',
[email protected]3e2f0402012-11-02 16:28:011115 'mac_rel',
[email protected]49da83c2013-11-07 14:08:501116 'mac:compile',
[email protected]3e2f0402012-11-02 16:28:011117 'win_rel',
[email protected]49da83c2013-11-07 14:08:501118 'win:compile',
1119 'win_x64_rel:base_unittests',
1120 ]
[email protected]911753b2012-08-02 12:11:541121
1122 # Match things like path/aura/file.cc and path/file_aura.cc.
[email protected]95c989162012-11-29 05:58:251123 # Same for chromeos.
1124 if any(re.search('[/_](aura|chromeos)', f) for f in files):
[email protected]49da83c2013-11-07 14:08:501125 trybots += ['linux_chromeos_clang:compile', 'linux_chromeos_asan']
[email protected]4ce995ea2012-06-27 02:13:101126
[email protected]e8df48f2013-09-30 20:07:541127 # If there are gyp changes to base, build, or chromeos, run a full cros build
1128 # in addition to the shorter linux_chromeos build. Changes to high level gyp
1129 # files have a much higher chance of breaking the cros build, which is
1130 # differnt from the linux_chromeos build that most chrome developers test
1131 # with.
1132 if any(re.search('^(base|build|chromeos).*\.gypi?$', f) for f in files):
[email protected]49da83c2013-11-07 14:08:501133 trybots += ['cros_x86']
[email protected]e8df48f2013-09-30 20:07:541134
[email protected]d95948ef2013-07-02 10:51:001135 # The AOSP bot doesn't build the chrome/ layer, so ignore any changes to it
1136 # unless they're .gyp(i) files as changes to those files can break the gyp
1137 # step on that bot.
1138 if (not all(re.search('^chrome', f) for f in files) or
1139 any(re.search('\.gypi?$', f) for f in files)):
[email protected]49da83c2013-11-07 14:08:501140 trybots += ['android_aosp']
[email protected]d95948ef2013-07-02 10:51:001141
[email protected]4ce995ea2012-06-27 02:13:101142 return trybots