GoogleGit

blob: 0ce83a6874d3ebda049b4ca97e800b0c9288074f [file] [log] [blame]
  1. # Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. # Use of this source code is governed by a BSD-style license that can be
  3. # found in the LICENSE file.
  4. """Top-level presubmit script for Chromium.
  5. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
  6. for more details about the presubmit API built into depot_tools.
  7. """
  8. _EXCLUDED_PATHS = (
  9. r"^breakpad[\\\/].*",
  10. r"^native_client_sdk[\\\/]src[\\\/]build_tools[\\\/]make_rules.py",
  11. r"^native_client_sdk[\\\/]src[\\\/]build_tools[\\\/]make_simple.py",
  12. r"^native_client_sdk[\\\/]src[\\\/]tools[\\\/].*.mk",
  13. r"^net[\\\/]tools[\\\/]spdyshark[\\\/].*",
  14. r"^skia[\\\/].*",
  15. r"^v8[\\\/].*",
  16. r".*MakeFile$",
  17. r".+_autogen\.h$",
  18. r".+[\\\/]pnacl_shim\.c$",
  19. r"^gpu[\\\/]config[\\\/].*_list_json\.cc$",
  20. r"^chrome[\\\/]browser[\\\/]resources[\\\/]pdf[\\\/]index.js"
  21. )
  22. # The NetscapePlugIn library is excluded from pan-project as it will soon
  23. # be deleted together with the rest of the NPAPI and it's not worthwhile to
  24. # update the coding style until then.
  25. _TESTRUNNER_PATHS = (
  26. r"^content[\\\/]shell[\\\/]tools[\\\/]plugin[\\\/].*",
  27. )
  28. # Fragment of a regular expression that matches C++ and Objective-C++
  29. # implementation files.
  30. _IMPLEMENTATION_EXTENSIONS = r'\.(cc|cpp|cxx|mm)$'
  31. # Regular expression that matches code only used for test binaries
  32. # (best effort).
  33. _TEST_CODE_EXCLUDED_PATHS = (
  34. r'.*[\\\/](fake_|test_|mock_).+%s' % _IMPLEMENTATION_EXTENSIONS,
  35. r'.+_test_(base|support|util)%s' % _IMPLEMENTATION_EXTENSIONS,
  36. r'.+_(api|browser|kif|perf|pixel|unit|ui)?test(_[a-z]+)?%s' %
  37. _IMPLEMENTATION_EXTENSIONS,
  38. r'.+profile_sync_service_harness%s' % _IMPLEMENTATION_EXTENSIONS,
  39. r'.*[\\\/](test|tool(s)?)[\\\/].*',
  40. # content_shell is used for running layout tests.
  41. r'content[\\\/]shell[\\\/].*',
  42. # At request of folks maintaining this folder.
  43. r'chrome[\\\/]browser[\\\/]automation[\\\/].*',
  44. # Non-production example code.
  45. r'mojo[\\\/]examples[\\\/].*',
  46. # Launcher for running iOS tests on the simulator.
  47. r'testing[\\\/]iossim[\\\/]iossim\.mm$',
  48. )
  49. _TEST_ONLY_WARNING = (
  50. 'You might be calling functions intended only for testing from\n'
  51. 'production code. It is OK to ignore this warning if you know what\n'
  52. 'you are doing, as the heuristics used to detect the situation are\n'
  53. 'not perfect. The commit queue will not block on this warning.')
  54. _INCLUDE_ORDER_WARNING = (
  55. 'Your #include order seems to be broken. Remember to use the right '
  56. 'collation (LC_COLLATE=C) and check https://google-styleguide.googlecode'
  57. '.com/svn/trunk/cppguide.html#Names_and_Order_of_Includes')
  58. _BANNED_OBJC_FUNCTIONS = (
  59. (
  60. 'addTrackingRect:',
  61. (
  62. 'The use of -[NSView addTrackingRect:owner:userData:assumeInside:] is'
  63. 'prohibited. Please use CrTrackingArea instead.',
  64. 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
  65. ),
  66. False,
  67. ),
  68. (
  69. r'/NSTrackingArea\W',
  70. (
  71. 'The use of NSTrackingAreas is prohibited. Please use CrTrackingArea',
  72. 'instead.',
  73. 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
  74. ),
  75. False,
  76. ),
  77. (
  78. 'convertPointFromBase:',
  79. (
  80. 'The use of -[NSView convertPointFromBase:] is almost certainly wrong.',
  81. 'Please use |convertPoint:(point) fromView:nil| instead.',
  82. 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
  83. ),
  84. True,
  85. ),
  86. (
  87. 'convertPointToBase:',
  88. (
  89. 'The use of -[NSView convertPointToBase:] is almost certainly wrong.',
  90. 'Please use |convertPoint:(point) toView:nil| instead.',
  91. 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
  92. ),
  93. True,
  94. ),
  95. (
  96. 'convertRectFromBase:',
  97. (
  98. 'The use of -[NSView convertRectFromBase:] is almost certainly wrong.',
  99. 'Please use |convertRect:(point) fromView:nil| instead.',
  100. 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
  101. ),
  102. True,
  103. ),
  104. (
  105. 'convertRectToBase:',
  106. (
  107. 'The use of -[NSView convertRectToBase:] is almost certainly wrong.',
  108. 'Please use |convertRect:(point) toView:nil| instead.',
  109. 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
  110. ),
  111. True,
  112. ),
  113. (
  114. 'convertSizeFromBase:',
  115. (
  116. 'The use of -[NSView convertSizeFromBase:] is almost certainly wrong.',
  117. 'Please use |convertSize:(point) fromView:nil| instead.',
  118. 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
  119. ),
  120. True,
  121. ),
  122. (
  123. 'convertSizeToBase:',
  124. (
  125. 'The use of -[NSView convertSizeToBase:] is almost certainly wrong.',
  126. 'Please use |convertSize:(point) toView:nil| instead.',
  127. 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
  128. ),
  129. True,
  130. ),
  131. )
  132. _BANNED_CPP_FUNCTIONS = (
  133. # Make sure that gtest's FRIEND_TEST() macro is not used; the
  134. # FRIEND_TEST_ALL_PREFIXES() macro from base/gtest_prod_util.h should be
  135. # used instead since that allows for FLAKY_ and DISABLED_ prefixes.
  136. (
  137. 'FRIEND_TEST(',
  138. (
  139. 'Chromium code should not use gtest\'s FRIEND_TEST() macro. Include',
  140. 'base/gtest_prod_util.h and use FRIEND_TEST_ALL_PREFIXES() instead.',
  141. ),
  142. False,
  143. (),
  144. ),
  145. (
  146. 'ScopedAllowIO',
  147. (
  148. 'New code should not use ScopedAllowIO. Post a task to the blocking',
  149. 'pool or the FILE thread instead.',
  150. ),
  151. True,
  152. (
  153. r"^base[\\\/]process[\\\/]process_metrics_linux\.cc$",
  154. r"^chrome[\\\/]browser[\\\/]chromeos[\\\/]boot_times_recorder\.cc$",
  155. r"^chrome[\\\/]browser[\\\/]chromeos[\\\/]"
  156. "customization_document_browsertest\.cc$",
  157. r"^components[\\\/]crash[\\\/]app[\\\/]breakpad_mac\.mm$",
  158. r"^content[\\\/]shell[\\\/]browser[\\\/]shell_browser_main\.cc$",
  159. r"^content[\\\/]shell[\\\/]browser[\\\/]shell_message_filter\.cc$",
  160. r"^mojo[\\\/]edk[\\\/]embedder[\\\/]" +
  161. r"simple_platform_shared_buffer_posix\.cc$",
  162. r"^net[\\\/]disk_cache[\\\/]cache_util\.cc$",
  163. r"^net[\\\/]url_request[\\\/]test_url_fetcher_factory\.cc$",
  164. r"^ui[\\\/]ozone[\\\/]platform[\\\/]drm[\\\/]host[\\\/]"
  165. "drm_native_display_delegate\.cc$",
  166. ),
  167. ),
  168. (
  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. ),
  205. (
  206. r'/HANDLE_EINTR\(.*close',
  207. (
  208. 'HANDLE_EINTR(close) is invalid. If close fails with EINTR, the file',
  209. 'descriptor will be closed, and it is incorrect to retry the close.',
  210. 'Either call close directly and ignore its return value, or wrap close',
  211. 'in IGNORE_EINTR to use its return value. See http://crbug.com/269623'
  212. ),
  213. True,
  214. (),
  215. ),
  216. (
  217. r'/IGNORE_EINTR\((?!.*close)',
  218. (
  219. 'IGNORE_EINTR is only valid when wrapping close. To wrap other system',
  220. 'calls, use HANDLE_EINTR. See http://crbug.com/269623',
  221. ),
  222. True,
  223. (
  224. # Files that #define IGNORE_EINTR.
  225. r'^base[\\\/]posix[\\\/]eintr_wrapper\.h$',
  226. r'^ppapi[\\\/]tests[\\\/]test_broker\.cc$',
  227. ),
  228. ),
  229. (
  230. r'/v8::Extension\(',
  231. (
  232. 'Do not introduce new v8::Extensions into the code base, use',
  233. 'gin::Wrappable instead. See http://crbug.com/334679',
  234. ),
  235. True,
  236. (
  237. r'extensions[\\\/]renderer[\\\/]safe_builtins\.*',
  238. ),
  239. ),
  240. )
  241. _IPC_ENUM_TRAITS_DEPRECATED = (
  242. 'You are using IPC_ENUM_TRAITS() in your code. It has been deprecated.\n'
  243. 'See http://www.chromium.org/Home/chromium-security/education/security-tips-for-ipc')
  244. _VALID_OS_MACROS = (
  245. # Please keep sorted.
  246. 'OS_ANDROID',
  247. 'OS_ANDROID_HOST',
  248. 'OS_BSD',
  249. 'OS_CAT', # For testing.
  250. 'OS_CHROMEOS',
  251. 'OS_FREEBSD',
  252. 'OS_IOS',
  253. 'OS_LINUX',
  254. 'OS_MACOSX',
  255. 'OS_NACL',
  256. 'OS_NACL_NONSFI',
  257. 'OS_NACL_SFI',
  258. 'OS_OPENBSD',
  259. 'OS_POSIX',
  260. 'OS_QNX',
  261. 'OS_SOLARIS',
  262. 'OS_WIN',
  263. )
  264. def _CheckNoProductionCodeUsingTestOnlyFunctions(input_api, output_api):
  265. """Attempts to prevent use of functions intended only for testing in
  266. non-testing code. For now this is just a best-effort implementation
  267. that ignores header files and may have some false positives. A
  268. better implementation would probably need a proper C++ parser.
  269. """
  270. # We only scan .cc files and the like, as the declaration of
  271. # for-testing functions in header files are hard to distinguish from
  272. # calls to such functions without a proper C++ parser.
  273. file_inclusion_pattern = r'.+%s' % _IMPLEMENTATION_EXTENSIONS
  274. base_function_pattern = r'[ :]test::[^\s]+|ForTest(ing)?|for_test(ing)?'
  275. inclusion_pattern = input_api.re.compile(r'(%s)\s*\(' % base_function_pattern)
  276. comment_pattern = input_api.re.compile(r'//.*(%s)' % base_function_pattern)
  277. exclusion_pattern = input_api.re.compile(
  278. r'::[A-Za-z0-9_]+(%s)|(%s)[^;]+\{' % (
  279. base_function_pattern, base_function_pattern))
  280. def FilterFile(affected_file):
  281. black_list = (_EXCLUDED_PATHS +
  282. _TEST_CODE_EXCLUDED_PATHS +
  283. input_api.DEFAULT_BLACK_LIST)
  284. return input_api.FilterSourceFile(
  285. affected_file,
  286. white_list=(file_inclusion_pattern, ),
  287. black_list=black_list)
  288. problems = []
  289. for f in input_api.AffectedSourceFiles(FilterFile):
  290. local_path = f.LocalPath()
  291. for line_number, line in f.ChangedContents():
  292. if (inclusion_pattern.search(line) and
  293. not comment_pattern.search(line) and
  294. not exclusion_pattern.search(line)):
  295. problems.append(
  296. '%s:%d\n %s' % (local_path, line_number, line.strip()))
  297. if problems:
  298. return [output_api.PresubmitPromptOrNotify(_TEST_ONLY_WARNING, problems)]
  299. else:
  300. return []
  301. def _CheckNoIOStreamInHeaders(input_api, output_api):
  302. """Checks to make sure no .h files include <iostream>."""
  303. files = []
  304. pattern = input_api.re.compile(r'^#include\s*<iostream>',
  305. input_api.re.MULTILINE)
  306. for f in input_api.AffectedSourceFiles(input_api.FilterSourceFile):
  307. if not f.LocalPath().endswith('.h'):
  308. continue
  309. contents = input_api.ReadFile(f)
  310. if pattern.search(contents):
  311. files.append(f)
  312. if len(files):
  313. return [ output_api.PresubmitError(
  314. 'Do not #include <iostream> in header files, since it inserts static '
  315. 'initialization into every file including the header. Instead, '
  316. '#include <ostream>. See http://crbug.com/94794',
  317. files) ]
  318. return []
  319. def _CheckNoUNIT_TESTInSourceFiles(input_api, output_api):
  320. """Checks to make sure no source files use UNIT_TEST"""
  321. problems = []
  322. for f in input_api.AffectedFiles():
  323. if (not f.LocalPath().endswith(('.cc', '.mm'))):
  324. continue
  325. for line_num, line in f.ChangedContents():
  326. if 'UNIT_TEST ' in line or line.endswith('UNIT_TEST'):
  327. problems.append(' %s:%d' % (f.LocalPath(), line_num))
  328. if not problems:
  329. return []
  330. return [output_api.PresubmitPromptWarning('UNIT_TEST is only for headers.\n' +
  331. '\n'.join(problems))]
  332. def _FindHistogramNameInLine(histogram_name, line):
  333. """Tries to find a histogram name or prefix in a line."""
  334. if not "affected-histogram" in line:
  335. return histogram_name in line
  336. # A histogram_suffixes tag type has an affected-histogram name as a prefix of
  337. # the histogram_name.
  338. if not '"' in line:
  339. return False
  340. histogram_prefix = line.split('\"')[1]
  341. return histogram_prefix in histogram_name
  342. def _CheckUmaHistogramChanges(input_api, output_api):
  343. """Check that UMA histogram names in touched lines can still be found in other
  344. lines of the patch or in histograms.xml. Note that this check would not catch
  345. the reverse: changes in histograms.xml not matched in the code itself."""
  346. touched_histograms = []
  347. histograms_xml_modifications = []
  348. pattern = input_api.re.compile('UMA_HISTOGRAM.*\("(.*)"')
  349. for f in input_api.AffectedFiles():
  350. # If histograms.xml itself is modified, keep the modified lines for later.
  351. if f.LocalPath().endswith(('histograms.xml')):
  352. histograms_xml_modifications = f.ChangedContents()
  353. continue
  354. if not f.LocalPath().endswith(('cc', 'mm', 'cpp')):
  355. continue
  356. for line_num, line in f.ChangedContents():
  357. found = pattern.search(line)
  358. if found:
  359. touched_histograms.append([found.group(1), f, line_num])
  360. # Search for the touched histogram names in the local modifications to
  361. # histograms.xml, and, if not found, on the base histograms.xml file.
  362. unmatched_histograms = []
  363. for histogram_info in touched_histograms:
  364. histogram_name_found = False
  365. for line_num, line in histograms_xml_modifications:
  366. histogram_name_found = _FindHistogramNameInLine(histogram_info[0], line)
  367. if histogram_name_found:
  368. break
  369. if not histogram_name_found:
  370. unmatched_histograms.append(histogram_info)
  371. histograms_xml_path = 'tools/metrics/histograms/histograms.xml'
  372. problems = []
  373. if unmatched_histograms:
  374. with open(histograms_xml_path) as histograms_xml:
  375. for histogram_name, f, line_num in unmatched_histograms:
  376. histograms_xml.seek(0)
  377. histogram_name_found = False
  378. for line in histograms_xml:
  379. histogram_name_found = _FindHistogramNameInLine(histogram_name, line)
  380. if histogram_name_found:
  381. break
  382. if not histogram_name_found:
  383. problems.append(' [%s:%d] %s' %
  384. (f.LocalPath(), line_num, histogram_name))
  385. if not problems:
  386. return []
  387. return [output_api.PresubmitPromptWarning('Some UMA_HISTOGRAM lines have '
  388. 'been modified and the associated histogram name has no match in either '
  389. '%s or the modifications of it:' % (histograms_xml_path), problems)]
  390. def _CheckNoNewWStrings(input_api, output_api):
  391. """Checks to make sure we don't introduce use of wstrings."""
  392. problems = []
  393. for f in input_api.AffectedFiles():
  394. if (not f.LocalPath().endswith(('.cc', '.h')) or
  395. f.LocalPath().endswith(('test.cc', '_win.cc', '_win.h')) or
  396. '/win/' in f.LocalPath()):
  397. continue
  398. allowWString = False
  399. for line_num, line in f.ChangedContents():
  400. if 'presubmit: allow wstring' in line:
  401. allowWString = True
  402. elif not allowWString and 'wstring' in line:
  403. problems.append(' %s:%d' % (f.LocalPath(), line_num))
  404. allowWString = False
  405. else:
  406. allowWString = False
  407. if not problems:
  408. return []
  409. return [output_api.PresubmitPromptWarning('New code should not use wstrings.'
  410. ' If you are calling a cross-platform API that accepts a wstring, '
  411. 'fix the API.\n' +
  412. '\n'.join(problems))]
  413. def _CheckNoDEPSGIT(input_api, output_api):
  414. """Make sure .DEPS.git is never modified manually."""
  415. if any(f.LocalPath().endswith('.DEPS.git') for f in
  416. input_api.AffectedFiles()):
  417. return [output_api.PresubmitError(
  418. 'Never commit changes to .DEPS.git. This file is maintained by an\n'
  419. 'automated system based on what\'s in DEPS and your changes will be\n'
  420. 'overwritten.\n'
  421. 'See https://sites.google.com/a/chromium.org/dev/developers/how-tos/get-the-code#Rolling_DEPS\n'
  422. 'for more information')]
  423. return []
  424. def _CheckValidHostsInDEPS(input_api, output_api):
  425. """Checks that DEPS file deps are from allowed_hosts."""
  426. # Run only if DEPS file has been modified to annoy fewer bystanders.
  427. if all(f.LocalPath() != 'DEPS' for f in input_api.AffectedFiles()):
  428. return []
  429. # Outsource work to gclient verify
  430. try:
  431. input_api.subprocess.check_output(['gclient', 'verify'])
  432. return []
  433. except input_api.subprocess.CalledProcessError, error:
  434. return [output_api.PresubmitError(
  435. 'DEPS file must have only git dependencies.',
  436. long_text=error.output)]
  437. def _CheckNoBannedFunctions(input_api, output_api):
  438. """Make sure that banned functions are not used."""
  439. warnings = []
  440. errors = []
  441. file_filter = lambda f: f.LocalPath().endswith(('.mm', '.m', '.h'))
  442. for f in input_api.AffectedFiles(file_filter=file_filter):
  443. for line_num, line in f.ChangedContents():
  444. for func_name, message, error in _BANNED_OBJC_FUNCTIONS:
  445. matched = False
  446. if func_name[0:1] == '/':
  447. regex = func_name[1:]
  448. if input_api.re.search(regex, line):
  449. matched = True
  450. elif func_name in line:
  451. matched = True
  452. if matched:
  453. problems = warnings;
  454. if error:
  455. problems = errors;
  456. problems.append(' %s:%d:' % (f.LocalPath(), line_num))
  457. for message_line in message:
  458. problems.append(' %s' % message_line)
  459. file_filter = lambda f: f.LocalPath().endswith(('.cc', '.mm', '.h'))
  460. for f in input_api.AffectedFiles(file_filter=file_filter):
  461. for line_num, line in f.ChangedContents():
  462. for func_name, message, error, excluded_paths in _BANNED_CPP_FUNCTIONS:
  463. def IsBlacklisted(affected_file, blacklist):
  464. local_path = affected_file.LocalPath()
  465. for item in blacklist:
  466. if input_api.re.match(item, local_path):
  467. return True
  468. return False
  469. if IsBlacklisted(f, excluded_paths):
  470. continue
  471. matched = False
  472. if func_name[0:1] == '/':
  473. regex = func_name[1:]
  474. if input_api.re.search(regex, line):
  475. matched = True
  476. elif func_name in line:
  477. matched = True
  478. if matched:
  479. problems = warnings;
  480. if error:
  481. problems = errors;
  482. problems.append(' %s:%d:' % (f.LocalPath(), line_num))
  483. for message_line in message:
  484. problems.append(' %s' % message_line)
  485. result = []
  486. if (warnings):
  487. result.append(output_api.PresubmitPromptWarning(
  488. 'Banned functions were used.\n' + '\n'.join(warnings)))
  489. if (errors):
  490. result.append(output_api.PresubmitError(
  491. 'Banned functions were used.\n' + '\n'.join(errors)))
  492. return result
  493. def _CheckNoPragmaOnce(input_api, output_api):
  494. """Make sure that banned functions are not used."""
  495. files = []
  496. pattern = input_api.re.compile(r'^#pragma\s+once',
  497. input_api.re.MULTILINE)
  498. for f in input_api.AffectedSourceFiles(input_api.FilterSourceFile):
  499. if not f.LocalPath().endswith('.h'):
  500. continue
  501. contents = input_api.ReadFile(f)
  502. if pattern.search(contents):
  503. files.append(f)
  504. if files:
  505. return [output_api.PresubmitError(
  506. 'Do not use #pragma once in header files.\n'
  507. 'See http://www.chromium.org/developers/coding-style#TOC-File-headers',
  508. files)]
  509. return []
  510. def _CheckNoTrinaryTrueFalse(input_api, output_api):
  511. """Checks to make sure we don't introduce use of foo ? true : false."""
  512. problems = []
  513. pattern = input_api.re.compile(r'\?\s*(true|false)\s*:\s*(true|false)')
  514. for f in input_api.AffectedFiles():
  515. if not f.LocalPath().endswith(('.cc', '.h', '.inl', '.m', '.mm')):
  516. continue
  517. for line_num, line in f.ChangedContents():
  518. if pattern.match(line):
  519. problems.append(' %s:%d' % (f.LocalPath(), line_num))
  520. if not problems:
  521. return []
  522. return [output_api.PresubmitPromptWarning(
  523. 'Please consider avoiding the "? true : false" pattern if possible.\n' +
  524. '\n'.join(problems))]
  525. def _CheckUnwantedDependencies(input_api, output_api):
  526. """Runs checkdeps on #include statements added in this
  527. change. Breaking - rules is an error, breaking ! rules is a
  528. warning.
  529. """
  530. import sys
  531. # We need to wait until we have an input_api object and use this
  532. # roundabout construct to import checkdeps because this file is
  533. # eval-ed and thus doesn't have __file__.
  534. original_sys_path = sys.path
  535. try:
  536. sys.path = sys.path + [input_api.os_path.join(
  537. input_api.PresubmitLocalPath(), 'buildtools', 'checkdeps')]
  538. import checkdeps
  539. from cpp_checker import CppChecker
  540. from rules import Rule
  541. finally:
  542. # Restore sys.path to what it was before.
  543. sys.path = original_sys_path
  544. added_includes = []
  545. for f in input_api.AffectedFiles():
  546. if not CppChecker.IsCppFile(f.LocalPath()):
  547. continue
  548. changed_lines = [line for line_num, line in f.ChangedContents()]
  549. added_includes.append([f.LocalPath(), changed_lines])
  550. deps_checker = checkdeps.DepsChecker(input_api.PresubmitLocalPath())
  551. error_descriptions = []
  552. warning_descriptions = []
  553. for path, rule_type, rule_description in deps_checker.CheckAddedCppIncludes(
  554. added_includes):
  555. description_with_path = '%s\n %s' % (path, rule_description)
  556. if rule_type == Rule.DISALLOW:
  557. error_descriptions.append(description_with_path)
  558. else:
  559. warning_descriptions.append(description_with_path)
  560. results = []
  561. if error_descriptions:
  562. results.append(output_api.PresubmitError(
  563. 'You added one or more #includes that violate checkdeps rules.',
  564. error_descriptions))
  565. if warning_descriptions:
  566. results.append(output_api.PresubmitPromptOrNotify(
  567. 'You added one or more #includes of files that are temporarily\n'
  568. 'allowed but being removed. Can you avoid introducing the\n'
  569. '#include? See relevant DEPS file(s) for details and contacts.',
  570. warning_descriptions))
  571. return results
  572. def _CheckFilePermissions(input_api, output_api):
  573. """Check that all files have their permissions properly set."""
  574. if input_api.platform == 'win32':
  575. return []
  576. args = [input_api.python_executable, 'tools/checkperms/checkperms.py',
  577. '--root', input_api.change.RepositoryRoot()]
  578. for f in input_api.AffectedFiles():
  579. args += ['--file', f.LocalPath()]
  580. checkperms = input_api.subprocess.Popen(args,
  581. stdout=input_api.subprocess.PIPE)
  582. errors = checkperms.communicate()[0].strip()
  583. if errors:
  584. return [output_api.PresubmitError('checkperms.py failed.',
  585. errors.splitlines())]
  586. return []
  587. def _CheckNoAuraWindowPropertyHInHeaders(input_api, output_api):
  588. """Makes sure we don't include ui/aura/window_property.h
  589. in header files.
  590. """
  591. pattern = input_api.re.compile(r'^#include\s*"ui/aura/window_property.h"')
  592. errors = []
  593. for f in input_api.AffectedFiles():
  594. if not f.LocalPath().endswith('.h'):
  595. continue
  596. for line_num, line in f.ChangedContents():
  597. if pattern.match(line):
  598. errors.append(' %s:%d' % (f.LocalPath(), line_num))
  599. results = []
  600. if errors:
  601. results.append(output_api.PresubmitError(
  602. 'Header files should not include ui/aura/window_property.h', errors))
  603. return results
  604. def _CheckIncludeOrderForScope(scope, input_api, file_path, changed_linenums):
  605. """Checks that the lines in scope occur in the right order.
  606. 1. C system files in alphabetical order
  607. 2. C++ system files in alphabetical order
  608. 3. Project's .h files
  609. """
  610. c_system_include_pattern = input_api.re.compile(r'\s*#include <.*\.h>')
  611. cpp_system_include_pattern = input_api.re.compile(r'\s*#include <.*>')
  612. custom_include_pattern = input_api.re.compile(r'\s*#include ".*')
  613. C_SYSTEM_INCLUDES, CPP_SYSTEM_INCLUDES, CUSTOM_INCLUDES = range(3)
  614. state = C_SYSTEM_INCLUDES
  615. previous_line = ''
  616. previous_line_num = 0
  617. problem_linenums = []
  618. for line_num, line in scope:
  619. if c_system_include_pattern.match(line):
  620. if state != C_SYSTEM_INCLUDES:
  621. problem_linenums.append((line_num, previous_line_num))
  622. elif previous_line and previous_line > line:
  623. problem_linenums.append((line_num, previous_line_num))
  624. elif cpp_system_include_pattern.match(line):
  625. if state == C_SYSTEM_INCLUDES:
  626. state = CPP_SYSTEM_INCLUDES
  627. elif state == CUSTOM_INCLUDES:
  628. problem_linenums.append((line_num, previous_line_num))
  629. elif previous_line and previous_line > line:
  630. problem_linenums.append((line_num, previous_line_num))
  631. elif custom_include_pattern.match(line):
  632. if state != CUSTOM_INCLUDES:
  633. state = CUSTOM_INCLUDES
  634. elif previous_line and previous_line > line:
  635. problem_linenums.append((line_num, previous_line_num))
  636. else:
  637. problem_linenums.append(line_num)
  638. previous_line = line
  639. previous_line_num = line_num
  640. warnings = []
  641. for (line_num, previous_line_num) in problem_linenums:
  642. if line_num in changed_linenums or previous_line_num in changed_linenums:
  643. warnings.append(' %s:%d' % (file_path, line_num))
  644. return warnings
  645. def _CheckIncludeOrderInFile(input_api, f, changed_linenums):
  646. """Checks the #include order for the given file f."""
  647. system_include_pattern = input_api.re.compile(r'\s*#include \<.*')
  648. # Exclude the following includes from the check:
  649. # 1) #include <.../...>, e.g., <sys/...> includes often need to appear in a
  650. # specific order.
  651. # 2) <atlbase.h>, "build/build_config.h"
  652. excluded_include_pattern = input_api.re.compile(
  653. r'\s*#include (\<.*/.*|\<atlbase\.h\>|"build/build_config.h")')
  654. custom_include_pattern = input_api.re.compile(r'\s*#include "(?P<FILE>.*)"')
  655. # Match the final or penultimate token if it is xxxtest so we can ignore it
  656. # when considering the special first include.
  657. test_file_tag_pattern = input_api.re.compile(
  658. r'_[a-z]+test(?=(_[a-zA-Z0-9]+)?\.)')
  659. if_pattern = input_api.re.compile(
  660. r'\s*#\s*(if|elif|else|endif|define|undef).*')
  661. # Some files need specialized order of includes; exclude such files from this
  662. # check.
  663. uncheckable_includes_pattern = input_api.re.compile(
  664. r'\s*#include '
  665. '("ipc/.*macros\.h"|<windows\.h>|".*gl.*autogen.h")\s*')
  666. contents = f.NewContents()
  667. warnings = []
  668. line_num = 0
  669. # Handle the special first include. If the first include file is
  670. # some/path/file.h, the corresponding including file can be some/path/file.cc,
  671. # some/other/path/file.cc, some/path/file_platform.cc, some/path/file-suffix.h
  672. # etc. It's also possible that no special first include exists.
  673. # If the included file is some/path/file_platform.h the including file could
  674. # also be some/path/file_xxxtest_platform.h.
  675. including_file_base_name = test_file_tag_pattern.sub(
  676. '', input_api.os_path.basename(f.LocalPath()))
  677. for line in contents:
  678. line_num += 1
  679. if system_include_pattern.match(line):
  680. # No special first include -> process the line again along with normal
  681. # includes.
  682. line_num -= 1
  683. break
  684. match = custom_include_pattern.match(line)
  685. if match:
  686. match_dict = match.groupdict()
  687. header_basename = test_file_tag_pattern.sub(
  688. '', input_api.os_path.basename(match_dict['FILE'])).replace('.h', '')
  689. if header_basename not in including_file_base_name:
  690. # No special first include -> process the line again along with normal
  691. # includes.
  692. line_num -= 1
  693. break
  694. # Split into scopes: Each region between #if and #endif is its own scope.
  695. scopes = []
  696. current_scope = []
  697. for line in contents[line_num:]:
  698. line_num += 1
  699. if uncheckable_includes_pattern.match(line):
  700. continue
  701. if if_pattern.match(line):
  702. scopes.append(current_scope)
  703. current_scope = []
  704. elif ((system_include_pattern.match(line) or
  705. custom_include_pattern.match(line)) and
  706. not excluded_include_pattern.match(line)):
  707. current_scope.append((line_num, line))
  708. scopes.append(current_scope)
  709. for scope in scopes:
  710. warnings.extend(_CheckIncludeOrderForScope(scope, input_api, f.LocalPath(),
  711. changed_linenums))
  712. return warnings
  713. def _CheckIncludeOrder(input_api, output_api):
  714. """Checks that the #include order is correct.
  715. 1. The corresponding header for source files.
  716. 2. C system files in alphabetical order
  717. 3. C++ system files in alphabetical order
  718. 4. Project's .h files in alphabetical order
  719. Each region separated by #if, #elif, #else, #endif, #define and #undef follows
  720. these rules separately.
  721. """
  722. def FileFilterIncludeOrder(affected_file):
  723. black_list = (_EXCLUDED_PATHS + input_api.DEFAULT_BLACK_LIST)
  724. return input_api.FilterSourceFile(affected_file, black_list=black_list)
  725. warnings = []
  726. for f in input_api.AffectedFiles(file_filter=FileFilterIncludeOrder):
  727. if f.LocalPath().endswith(('.cc', '.h')):
  728. changed_linenums = set(line_num for line_num, _ in f.ChangedContents())
  729. warnings.extend(_CheckIncludeOrderInFile(input_api, f, changed_linenums))
  730. results = []
  731. if warnings:
  732. results.append(output_api.PresubmitPromptOrNotify(_INCLUDE_ORDER_WARNING,
  733. warnings))
  734. return results
  735. def _CheckForVersionControlConflictsInFile(input_api, f):
  736. pattern = input_api.re.compile('^(?:<<<<<<<|>>>>>>>) |^=======$')
  737. errors = []
  738. for line_num, line in f.ChangedContents():
  739. if pattern.match(line):
  740. errors.append(' %s:%d %s' % (f.LocalPath(), line_num, line))
  741. return errors
  742. def _CheckForVersionControlConflicts(input_api, output_api):
  743. """Usually this is not intentional and will cause a compile failure."""
  744. errors = []
  745. for f in input_api.AffectedFiles():
  746. errors.extend(_CheckForVersionControlConflictsInFile(input_api, f))
  747. results = []
  748. if errors:
  749. results.append(output_api.PresubmitError(
  750. 'Version control conflict markers found, please resolve.', errors))
  751. return results
  752. def _CheckHardcodedGoogleHostsInLowerLayers(input_api, output_api):
  753. def FilterFile(affected_file):
  754. """Filter function for use with input_api.AffectedSourceFiles,
  755. below. This filters out everything except non-test files from
  756. top-level directories that generally speaking should not hard-code
  757. service URLs (e.g. src/android_webview/, src/content/ and others).
  758. """
  759. return input_api.FilterSourceFile(
  760. affected_file,
  761. white_list=(r'^(android_webview|base|content|net)[\\\/].*', ),
  762. black_list=(_EXCLUDED_PATHS +
  763. _TEST_CODE_EXCLUDED_PATHS +
  764. input_api.DEFAULT_BLACK_LIST))
  765. base_pattern = '"[^"]*google\.com[^"]*"'
  766. comment_pattern = input_api.re.compile('//.*%s' % base_pattern)
  767. pattern = input_api.re.compile(base_pattern)
  768. problems = [] # items are (filename, line_number, line)
  769. for f in input_api.AffectedSourceFiles(FilterFile):
  770. for line_num, line in f.ChangedContents():
  771. if not comment_pattern.search(line) and pattern.search(line):
  772. problems.append((f.LocalPath(), line_num, line))
  773. if problems:
  774. return [output_api.PresubmitPromptOrNotify(
  775. 'Most layers below src/chrome/ should not hardcode service URLs.\n'
  776. 'Are you sure this is correct?',
  777. [' %s:%d: %s' % (
  778. problem[0], problem[1], problem[2]) for problem in problems])]
  779. else:
  780. return []
  781. def _CheckNoAbbreviationInPngFileName(input_api, output_api):
  782. """Makes sure there are no abbreviations in the name of PNG files.
  783. The native_client_sdk directory is excluded because it has auto-generated PNG
  784. files for documentation.
  785. """
  786. errors = []
  787. white_list = (r'.*_[a-z]_.*\.png$|.*_[a-z]\.png$',)
  788. black_list = (r'^native_client_sdk[\\\/]',)
  789. file_filter = lambda f: input_api.FilterSourceFile(
  790. f, white_list=white_list, black_list=black_list)
  791. for f in input_api.AffectedFiles(include_deletes=False,
  792. file_filter=file_filter):
  793. errors.append(' %s' % f.LocalPath())
  794. results = []
  795. if errors:
  796. results.append(output_api.PresubmitError(
  797. 'The name of PNG files should not have abbreviations. \n'
  798. 'Use _hover.png, _center.png, instead of _h.png, _c.png.\n'
  799. 'Contact oshima@chromium.org if you have questions.', errors))
  800. return results
  801. def _FilesToCheckForIncomingDeps(re, changed_lines):
  802. """Helper method for _CheckAddedDepsHaveTargetApprovals. Returns
  803. a set of DEPS entries that we should look up.
  804. For a directory (rather than a specific filename) we fake a path to
  805. a specific filename by adding /DEPS. This is chosen as a file that
  806. will seldom or never be subject to per-file include_rules.
  807. """
  808. # We ignore deps entries on auto-generated directories.
  809. AUTO_GENERATED_DIRS = ['grit', 'jni']
  810. # This pattern grabs the path without basename in the first
  811. # parentheses, and the basename (if present) in the second. It
  812. # relies on the simple heuristic that if there is a basename it will
  813. # be a header file ending in ".h".
  814. pattern = re.compile(
  815. r"""['"]\+([^'"]+?)(/[a-zA-Z0-9_]+\.h)?['"].*""")
  816. results = set()
  817. for changed_line in changed_lines:
  818. m = pattern.match(changed_line)
  819. if m:
  820. path = m.group(1)
  821. if path.split('/')[0] not in AUTO_GENERATED_DIRS:
  822. if m.group(2):
  823. results.add('%s%s' % (path, m.group(2)))
  824. else:
  825. results.add('%s/DEPS' % path)
  826. return results
  827. def _CheckAddedDepsHaveTargetApprovals(input_api, output_api):
  828. """When a dependency prefixed with + is added to a DEPS file, we
  829. want to make sure that the change is reviewed by an OWNER of the
  830. target file or directory, to avoid layering violations from being
  831. introduced. This check verifies that this happens.
  832. """
  833. changed_lines = set()
  834. for f in input_api.AffectedFiles():
  835. filename = input_api.os_path.basename(f.LocalPath())
  836. if filename == 'DEPS':
  837. changed_lines |= set(line.strip()
  838. for line_num, line
  839. in f.ChangedContents())
  840. if not changed_lines:
  841. return []
  842. virtual_depended_on_files = _FilesToCheckForIncomingDeps(input_api.re,
  843. changed_lines)
  844. if not virtual_depended_on_files:
  845. return []
  846. if input_api.is_committing:
  847. if input_api.tbr:
  848. return [output_api.PresubmitNotifyResult(
  849. '--tbr was specified, skipping OWNERS check for DEPS additions')]
  850. if not input_api.change.issue:
  851. return [output_api.PresubmitError(
  852. "DEPS approval by OWNERS check failed: this change has "
  853. "no Rietveld issue number, so we can't check it for approvals.")]
  854. output = output_api.PresubmitError
  855. else:
  856. output = output_api.PresubmitNotifyResult
  857. owners_db = input_api.owners_db
  858. owner_email, reviewers = input_api.canned_checks._RietveldOwnerAndReviewers(
  859. input_api,
  860. owners_db.email_regexp,
  861. approval_needed=input_api.is_committing)
  862. owner_email = owner_email or input_api.change.author_email
  863. reviewers_plus_owner = set(reviewers)
  864. if owner_email:
  865. reviewers_plus_owner.add(owner_email)
  866. missing_files = owners_db.files_not_covered_by(virtual_depended_on_files,
  867. reviewers_plus_owner)
  868. # We strip the /DEPS part that was added by
  869. # _FilesToCheckForIncomingDeps to fake a path to a file in a
  870. # directory.
  871. def StripDeps(path):
  872. start_deps = path.rfind('/DEPS')
  873. if start_deps != -1:
  874. return path[:start_deps]
  875. else:
  876. return path
  877. unapproved_dependencies = ["'+%s'," % StripDeps(path)
  878. for path in missing_files]
  879. if unapproved_dependencies:
  880. output_list = [
  881. output('Missing LGTM from OWNERS of dependencies added to DEPS:\n %s' %
  882. '\n '.join(sorted(unapproved_dependencies)))]
  883. if not input_api.is_committing:
  884. suggested_owners = owners_db.reviewers_for(missing_files, owner_email)
  885. output_list.append(output(
  886. 'Suggested missing target path OWNERS:\n %s' %
  887. '\n '.join(suggested_owners or [])))
  888. return output_list
  889. return []
  890. def _CheckSpamLogging(input_api, output_api):
  891. file_inclusion_pattern = r'.+%s' % _IMPLEMENTATION_EXTENSIONS
  892. black_list = (_EXCLUDED_PATHS +
  893. _TEST_CODE_EXCLUDED_PATHS +
  894. input_api.DEFAULT_BLACK_LIST +
  895. (r"^base[\\\/]logging\.h$",
  896. r"^base[\\\/]logging\.cc$",
  897. r"^chrome[\\\/]app[\\\/]chrome_main_delegate\.cc$",
  898. r"^chrome[\\\/]browser[\\\/]chrome_browser_main\.cc$",
  899. r"^chrome[\\\/]browser[\\\/]ui[\\\/]startup[\\\/]"
  900. r"startup_browser_creator\.cc$",
  901. r"^chrome[\\\/]installer[\\\/]setup[\\\/].*",
  902. r"chrome[\\\/]browser[\\\/]diagnostics[\\\/]" +
  903. r"diagnostics_writer\.cc$",
  904. r"^chrome_elf[\\\/]dll_hash[\\\/]dll_hash_main\.cc$",
  905. r"^chromecast[\\\/]",
  906. r"^cloud_print[\\\/]",
  907. r"^content[\\\/]common[\\\/]gpu[\\\/]client[\\\/]"
  908. r"gl_helper_benchmark\.cc$",
  909. r"^courgette[\\\/]courgette_tool\.cc$",
  910. r"^extensions[\\\/]renderer[\\\/]logging_native_handler\.cc$",
  911. r"^ipc[\\\/]ipc_logging\.cc$",
  912. r"^native_client_sdk[\\\/]",
  913. r"^remoting[\\\/]base[\\\/]logging\.h$",
  914. r"^remoting[\\\/]host[\\\/].*",
  915. r"^sandbox[\\\/]linux[\\\/].*",
  916. r"^tools[\\\/]",
  917. r"^ui[\\\/]aura[\\\/]bench[\\\/]bench_main\.cc$",
  918. r"^storage[\\\/]browser[\\\/]fileapi[\\\/]" +
  919. r"dump_file_system.cc$",))
  920. source_file_filter = lambda x: input_api.FilterSourceFile(
  921. x, white_list=(file_inclusion_pattern,), black_list=black_list)
  922. log_info = []
  923. printf = []
  924. for f in input_api.AffectedSourceFiles(source_file_filter):
  925. contents = input_api.ReadFile(f, 'rb')
  926. if input_api.re.search(r"\bD?LOG\s*\(\s*INFO\s*\)", contents):
  927. log_info.append(f.LocalPath())
  928. elif input_api.re.search(r"\bD?LOG_IF\s*\(\s*INFO\s*,", contents):
  929. log_info.append(f.LocalPath())
  930. if input_api.re.search(r"\bprintf\(", contents):
  931. printf.append(f.LocalPath())
  932. elif input_api.re.search(r"\bfprintf\((stdout|stderr)", contents):
  933. printf.append(f.LocalPath())
  934. if log_info:
  935. return [output_api.PresubmitError(
  936. 'These files spam the console log with LOG(INFO):',
  937. items=log_info)]
  938. if printf:
  939. return [output_api.PresubmitError(
  940. 'These files spam the console log with printf/fprintf:',
  941. items=printf)]
  942. return []
  943. def _CheckForAnonymousVariables(input_api, output_api):
  944. """These types are all expected to hold locks while in scope and
  945. so should never be anonymous (which causes them to be immediately
  946. destroyed)."""
  947. they_who_must_be_named = [
  948. 'base::AutoLock',
  949. 'base::AutoReset',
  950. 'base::AutoUnlock',
  951. 'SkAutoAlphaRestore',
  952. 'SkAutoBitmapShaderInstall',
  953. 'SkAutoBlitterChoose',
  954. 'SkAutoBounderCommit',
  955. 'SkAutoCallProc',
  956. 'SkAutoCanvasRestore',
  957. 'SkAutoCommentBlock',
  958. 'SkAutoDescriptor',
  959. 'SkAutoDisableDirectionCheck',
  960. 'SkAutoDisableOvalCheck',
  961. 'SkAutoFree',
  962. 'SkAutoGlyphCache',
  963. 'SkAutoHDC',
  964. 'SkAutoLockColors',
  965. 'SkAutoLockPixels',
  966. 'SkAutoMalloc',
  967. 'SkAutoMaskFreeImage',
  968. 'SkAutoMutexAcquire',
  969. 'SkAutoPathBoundsUpdate',
  970. 'SkAutoPDFRelease',
  971. 'SkAutoRasterClipValidate',
  972. 'SkAutoRef',
  973. 'SkAutoTime',
  974. 'SkAutoTrace',
  975. 'SkAutoUnref',
  976. ]
  977. anonymous = r'(%s)\s*[({]' % '|'.join(they_who_must_be_named)
  978. # bad: base::AutoLock(lock.get());
  979. # not bad: base::AutoLock lock(lock.get());
  980. bad_pattern = input_api.re.compile(anonymous)
  981. # good: new base::AutoLock(lock.get())
  982. good_pattern = input_api.re.compile(r'\bnew\s*' + anonymous)
  983. errors = []
  984. for f in input_api.AffectedFiles():
  985. if not f.LocalPath().endswith(('.cc', '.h', '.inl', '.m', '.mm')):
  986. continue
  987. for linenum, line in f.ChangedContents():
  988. if bad_pattern.search(line) and not good_pattern.search(line):
  989. errors.append('%s:%d' % (f.LocalPath(), linenum))
  990. if errors:
  991. return [output_api.PresubmitError(
  992. 'These lines create anonymous variables that need to be named:',
  993. items=errors)]
  994. return []
  995. def _CheckCygwinShell(input_api, output_api):
  996. source_file_filter = lambda x: input_api.FilterSourceFile(
  997. x, white_list=(r'.+\.(gyp|gypi)$',))
  998. cygwin_shell = []
  999. for f in input_api.AffectedSourceFiles(source_file_filter):
  1000. for linenum, line in f.ChangedContents():
  1001. if 'msvs_cygwin_shell' in line:
  1002. cygwin_shell.append(f.LocalPath())
  1003. break
  1004. if cygwin_shell:
  1005. return [output_api.PresubmitError(
  1006. 'These files should not use msvs_cygwin_shell (the default is 0):',
  1007. items=cygwin_shell)]
  1008. return []
  1009. def _CheckUserActionUpdate(input_api, output_api):
  1010. """Checks if any new user action has been added."""
  1011. if any('actions.xml' == input_api.os_path.basename(f) for f in
  1012. input_api.LocalPaths()):
  1013. # If actions.xml is already included in the changelist, the PRESUBMIT
  1014. # for actions.xml will do a more complete presubmit check.
  1015. return []
  1016. file_filter = lambda f: f.LocalPath().endswith(('.cc', '.mm'))
  1017. action_re = r'[^a-zA-Z]UserMetricsAction\("([^"]*)'
  1018. current_actions = None
  1019. for f in input_api.AffectedFiles(file_filter=file_filter):
  1020. for line_num, line in f.ChangedContents():
  1021. match = input_api.re.search(action_re, line)
  1022. if match:
  1023. # Loads contents in tools/metrics/actions/actions.xml to memory. It's
  1024. # loaded only once.
  1025. if not current_actions:
  1026. with open('tools/metrics/actions/actions.xml') as actions_f:
  1027. current_actions = actions_f.read()
  1028. # Search for the matched user action name in |current_actions|.
  1029. for action_name in match.groups():
  1030. action = 'name="{0}"'.format(action_name)
  1031. if action not in current_actions:
  1032. return [output_api.PresubmitPromptWarning(
  1033. 'File %s line %d: %s is missing in '
  1034. 'tools/metrics/actions/actions.xml. Please run '
  1035. 'tools/metrics/actions/extract_actions.py to update.'
  1036. % (f.LocalPath(), line_num, action_name))]
  1037. return []
  1038. def _GetJSONParseError(input_api, filename, eat_comments=True):
  1039. try:
  1040. contents = input_api.ReadFile(filename)
  1041. if eat_comments:
  1042. json_comment_eater = input_api.os_path.join(
  1043. input_api.PresubmitLocalPath(),
  1044. 'tools', 'json_comment_eater', 'json_comment_eater.py')
  1045. process = input_api.subprocess.Popen(
  1046. [input_api.python_executable, json_comment_eater],
  1047. stdin=input_api.subprocess.PIPE,
  1048. stdout=input_api.subprocess.PIPE,
  1049. universal_newlines=True)
  1050. (contents, _) = process.communicate(input=contents)
  1051. input_api.json.loads(contents)
  1052. except ValueError as e:
  1053. return e
  1054. return None
  1055. def _GetIDLParseError(input_api, filename):
  1056. try:
  1057. contents = input_api.ReadFile(filename)
  1058. idl_schema = input_api.os_path.join(
  1059. input_api.PresubmitLocalPath(),
  1060. 'tools', 'json_schema_compiler', 'idl_schema.py')
  1061. process = input_api.subprocess.Popen(
  1062. [input_api.python_executable, idl_schema],
  1063. stdin=input_api.subprocess.PIPE,
  1064. stdout=input_api.subprocess.PIPE,
  1065. stderr=input_api.subprocess.PIPE,
  1066. universal_newlines=True)
  1067. (_, error) = process.communicate(input=contents)
  1068. return error or None
  1069. except ValueError as e:
  1070. return e
  1071. def _CheckParseErrors(input_api, output_api):
  1072. """Check that IDL and JSON files do not contain syntax errors."""
  1073. actions = {
  1074. '.idl': _GetIDLParseError,
  1075. '.json': _GetJSONParseError,
  1076. }
  1077. # These paths contain test data and other known invalid JSON files.
  1078. excluded_patterns = [
  1079. r'test[\\\/]data[\\\/]',
  1080. r'^components[\\\/]policy[\\\/]resources[\\\/]policy_templates\.json$',
  1081. ]
  1082. # Most JSON files are preprocessed and support comments, but these do not.
  1083. json_no_comments_patterns = [
  1084. r'^testing[\\\/]',
  1085. ]
  1086. # Only run IDL checker on files in these directories.
  1087. idl_included_patterns = [
  1088. r'^chrome[\\\/]common[\\\/]extensions[\\\/]api[\\\/]',
  1089. r'^extensions[\\\/]common[\\\/]api[\\\/]',
  1090. ]
  1091. def get_action(affected_file):
  1092. filename = affected_file.LocalPath()
  1093. return actions.get(input_api.os_path.splitext(filename)[1])
  1094. def MatchesFile(patterns, path):
  1095. for pattern in patterns:
  1096. if input_api.re.search(pattern, path):
  1097. return True
  1098. return False
  1099. def FilterFile(affected_file):
  1100. action = get_action(affected_file)
  1101. if not action:
  1102. return False
  1103. path = affected_file.LocalPath()
  1104. if MatchesFile(excluded_patterns, path):
  1105. return False
  1106. if (action == _GetIDLParseError and
  1107. not MatchesFile(idl_included_patterns, path)):
  1108. return False
  1109. return True
  1110. results = []
  1111. for affected_file in input_api.AffectedFiles(
  1112. file_filter=FilterFile, include_deletes=False):
  1113. action = get_action(affected_file)
  1114. kwargs = {}
  1115. if (action == _GetJSONParseError and
  1116. MatchesFile(json_no_comments_patterns, affected_file.LocalPath())):
  1117. kwargs['eat_comments'] = False
  1118. parse_error = action(input_api,
  1119. affected_file.AbsoluteLocalPath(),
  1120. **kwargs)
  1121. if parse_error:
  1122. results.append(output_api.PresubmitError('%s could not be parsed: %s' %
  1123. (affected_file.LocalPath(), parse_error)))
  1124. return results
  1125. def _CheckJavaStyle(input_api, output_api):
  1126. """Runs checkstyle on changed java files and returns errors if any exist."""
  1127. import sys
  1128. original_sys_path = sys.path
  1129. try:
  1130. sys.path = sys.path + [input_api.os_path.join(
  1131. input_api.PresubmitLocalPath(), 'tools', 'android', 'checkstyle')]
  1132. import checkstyle
  1133. finally:
  1134. # Restore sys.path to what it was before.
  1135. sys.path = original_sys_path
  1136. return checkstyle.RunCheckstyle(
  1137. input_api, output_api, 'tools/android/checkstyle/chromium-style-5.0.xml',
  1138. black_list=_EXCLUDED_PATHS + input_api.DEFAULT_BLACK_LIST)
  1139. def _CheckForCopyrightedCode(input_api, output_api):
  1140. """Verifies that newly added code doesn't contain copyrighted material
  1141. and is properly licensed under the standard Chromium license.
  1142. As there can be false positives, we maintain a whitelist file. This check
  1143. also verifies that the whitelist file is up to date.
  1144. """
  1145. import sys
  1146. original_sys_path = sys.path
  1147. try:
  1148. sys.path = sys.path + [input_api.os_path.join(
  1149. input_api.PresubmitLocalPath(), 'android_webview', 'tools')]
  1150. import copyright_scanner
  1151. finally:
  1152. # Restore sys.path to what it was before.
  1153. sys.path = original_sys_path
  1154. return copyright_scanner.ScanAtPresubmit(input_api, output_api)
  1155. def _CheckSingletonInHeaders(input_api, output_api):
  1156. """Checks to make sure no header files have |Singleton<|."""
  1157. def FileFilter(affected_file):
  1158. # It's ok for base/memory/singleton.h to have |Singleton<|.
  1159. black_list = (_EXCLUDED_PATHS +
  1160. input_api.DEFAULT_BLACK_LIST +
  1161. (r"^base[\\\/]memory[\\\/]singleton\.h$",))
  1162. return input_api.FilterSourceFile(affected_file, black_list=black_list)
  1163. pattern = input_api.re.compile(r'(?<!class\s)Singleton\s*<')
  1164. files = []
  1165. for f in input_api.AffectedSourceFiles(FileFilter):
  1166. if (f.LocalPath().endswith('.h') or f.LocalPath().endswith('.hxx') or
  1167. f.LocalPath().endswith('.hpp') or f.LocalPath().endswith('.inl')):
  1168. contents = input_api.ReadFile(f)
  1169. for line in contents.splitlines(False):
  1170. if (not input_api.re.match(r'//', line) and # Strip C++ comment.
  1171. pattern.search(line)):
  1172. files.append(f)
  1173. break
  1174. if files:
  1175. return [ output_api.PresubmitError(
  1176. 'Found Singleton<T> in the following header files.\n' +
  1177. 'Please move them to an appropriate source file so that the ' +
  1178. 'template gets instantiated in a single compilation unit.',
  1179. files) ]
  1180. return []
  1181. _DEPRECATED_CSS = [
  1182. # Values
  1183. ( "-webkit-box", "flex" ),
  1184. ( "-webkit-inline-box", "inline-flex" ),
  1185. ( "-webkit-flex", "flex" ),
  1186. ( "-webkit-inline-flex", "inline-flex" ),
  1187. ( "-webkit-min-content", "min-content" ),
  1188. ( "-webkit-max-content", "max-content" ),
  1189. # Properties
  1190. ( "-webkit-background-clip", "background-clip" ),
  1191. ( "-webkit-background-origin", "background-origin" ),
  1192. ( "-webkit-background-size", "background-size" ),
  1193. ( "-webkit-box-shadow", "box-shadow" ),
  1194. # Functions
  1195. ( "-webkit-gradient", "gradient" ),
  1196. ( "-webkit-repeating-gradient", "repeating-gradient" ),
  1197. ( "-webkit-linear-gradient", "linear-gradient" ),
  1198. ( "-webkit-repeating-linear-gradient", "repeating-linear-gradient" ),
  1199. ( "-webkit-radial-gradient", "radial-gradient" ),
  1200. ( "-webkit-repeating-radial-gradient", "repeating-radial-gradient" ),
  1201. ]
  1202. def _CheckNoDeprecatedCSS(input_api, output_api):
  1203. """ Make sure that we don't use deprecated CSS
  1204. properties, functions or values. Our external
  1205. documentation is ignored by the hooks as it
  1206. needs to be consumed by WebKit. """
  1207. results = []
  1208. file_inclusion_pattern = (r".+\.css$",)
  1209. black_list = (_EXCLUDED_PATHS +
  1210. _TEST_CODE_EXCLUDED_PATHS +
  1211. input_api.DEFAULT_BLACK_LIST +
  1212. (r"^chrome/common/extensions/docs",
  1213. r"^chrome/docs",
  1214. r"^native_client_sdk"))
  1215. file_filter = lambda f: input_api.FilterSourceFile(
  1216. f, white_list=file_inclusion_pattern, black_list=black_list)
  1217. for fpath in input_api.AffectedFiles(file_filter=file_filter):
  1218. for line_num, line in fpath.ChangedContents():
  1219. for (deprecated_value, value) in _DEPRECATED_CSS:
  1220. if deprecated_value in line:
  1221. results.append(output_api.PresubmitError(
  1222. "%s:%d: Use of deprecated CSS %s, use %s instead" %
  1223. (fpath.LocalPath(), line_num, deprecated_value, value)))
  1224. return results
  1225. _DEPRECATED_JS = [
  1226. ( "__lookupGetter__", "Object.getOwnPropertyDescriptor" ),
  1227. ( "__defineGetter__", "Object.defineProperty" ),
  1228. ( "__defineSetter__", "Object.defineProperty" ),
  1229. ]
  1230. def _CheckNoDeprecatedJS(input_api, output_api):
  1231. """Make sure that we don't use deprecated JS in Chrome code."""
  1232. results = []
  1233. file_inclusion_pattern = (r".+\.js$",) # TODO(dbeam): .html?
  1234. black_list = (_EXCLUDED_PATHS + _TEST_CODE_EXCLUDED_PATHS +
  1235. input_api.DEFAULT_BLACK_LIST)
  1236. file_filter = lambda f: input_api.FilterSourceFile(
  1237. f, white_list=file_inclusion_pattern, black_list=black_list)
  1238. for fpath in input_api.AffectedFiles(file_filter=file_filter):
  1239. for lnum, line in fpath.ChangedContents():
  1240. for (deprecated, replacement) in _DEPRECATED_JS:
  1241. if deprecated in line:
  1242. results.append(output_api.PresubmitError(
  1243. "%s:%d: Use of deprecated JS %s, use %s instead" %
  1244. (fpath.LocalPath(), lnum, deprecated, replacement)))
  1245. return results
  1246. def _CommonChecks(input_api, output_api):
  1247. """Checks common to both upload and commit."""
  1248. results = []
  1249. results.extend(input_api.canned_checks.PanProjectChecks(
  1250. input_api, output_api,
  1251. excluded_paths=_EXCLUDED_PATHS + _TESTRUNNER_PATHS))
  1252. results.extend(_CheckAuthorizedAuthor(input_api, output_api))
  1253. results.extend(
  1254. _CheckNoProductionCodeUsingTestOnlyFunctions(input_api, output_api))
  1255. results.extend(_CheckNoIOStreamInHeaders(input_api, output_api))
  1256. results.extend(_CheckNoUNIT_TESTInSourceFiles(input_api, output_api))
  1257. results.extend(_CheckNoNewWStrings(input_api, output_api))
  1258. results.extend(_CheckNoDEPSGIT(input_api, output_api))
  1259. results.extend(_CheckNoBannedFunctions(input_api, output_api))
  1260. results.extend(_CheckNoPragmaOnce(input_api, output_api))
  1261. results.extend(_CheckNoTrinaryTrueFalse(input_api, output_api))
  1262. results.extend(_CheckUnwantedDependencies(input_api, output_api))
  1263. results.extend(_CheckFilePermissions(input_api, output_api))
  1264. results.extend(_CheckNoAuraWindowPropertyHInHeaders(input_api, output_api))
  1265. results.extend(_CheckIncludeOrder(input_api, output_api))
  1266. results.extend(_CheckForVersionControlConflicts(input_api, output_api))
  1267. results.extend(_CheckPatchFiles(input_api, output_api))
  1268. results.extend(_CheckHardcodedGoogleHostsInLowerLayers(input_api, output_api))
  1269. results.extend(_CheckNoAbbreviationInPngFileName(input_api, output_api))
  1270. results.extend(_CheckForInvalidOSMacros(input_api, output_api))
  1271. results.extend(_CheckForInvalidIfDefinedMacros(input_api, output_api))
  1272. # TODO(danakj): Remove this when base/move.h is removed.
  1273. results.extend(_CheckForUsingSideEffectsOfPass(input_api, output_api))
  1274. results.extend(_CheckAddedDepsHaveTargetApprovals(input_api, output_api))
  1275. results.extend(
  1276. input_api.canned_checks.CheckChangeHasNoTabs(
  1277. input_api,
  1278. output_api,
  1279. source_file_filter=lambda x: x.LocalPath().endswith('.grd')))
  1280. results.extend(_CheckSpamLogging(input_api, output_api))
  1281. results.extend(_CheckForAnonymousVariables(input_api, output_api))
  1282. results.extend(_CheckCygwinShell(input_api, output_api))
  1283. results.extend(_CheckUserActionUpdate(input_api, output_api))
  1284. results.extend(_CheckNoDeprecatedCSS(input_api, output_api))
  1285. results.extend(_CheckNoDeprecatedJS(input_api, output_api))
  1286. results.extend(_CheckParseErrors(input_api, output_api))
  1287. results.extend(_CheckForIPCRules(input_api, output_api))
  1288. results.extend(_CheckForCopyrightedCode(input_api, output_api))
  1289. results.extend(_CheckForWindowsLineEndings(input_api, output_api))
  1290. results.extend(_CheckSingletonInHeaders(input_api, output_api))
  1291. if any('PRESUBMIT.py' == f.LocalPath() for f in input_api.AffectedFiles()):
  1292. results.extend(input_api.canned_checks.RunUnitTestsInDirectory(
  1293. input_api, output_api,
  1294. input_api.PresubmitLocalPath(),
  1295. whitelist=[r'^PRESUBMIT_test\.py$']))
  1296. return results
  1297. def _CheckAuthorizedAuthor(input_api, output_api):
  1298. """For non-googler/chromites committers, verify the author's email address is
  1299. in AUTHORS.
  1300. """
  1301. # TODO(maruel): Add it to input_api?
  1302. import fnmatch
  1303. author = input_api.change.author_email
  1304. if not author:
  1305. input_api.logging.info('No author, skipping AUTHOR check')
  1306. return []
  1307. authors_path = input_api.os_path.join(
  1308. input_api.PresubmitLocalPath(), 'AUTHORS')
  1309. valid_authors = (
  1310. input_api.re.match(r'[^#]+\s+\<(.+?)\>\s*$', line)
  1311. for line in open(authors_path))
  1312. valid_authors = [item.group(1).lower() for item in valid_authors if item]
  1313. if not any(fnmatch.fnmatch(author.lower(), valid) for valid in valid_authors):
  1314. input_api.logging.info('Valid authors are %s', ', '.join(valid_authors))
  1315. return [output_api.PresubmitPromptWarning(
  1316. ('%s is not in AUTHORS file. If you are a new contributor, please visit'
  1317. '\n'
  1318. 'http://www.chromium.org/developers/contributing-code and read the '
  1319. '"Legal" section\n'
  1320. 'If you are a chromite, verify the contributor signed the CLA.') %
  1321. author)]
  1322. return []
  1323. def _CheckPatchFiles(input_api, output_api):
  1324. problems = [f.LocalPath() for f in input_api.AffectedFiles()
  1325. if f.LocalPath().endswith(('.orig', '.rej'))]
  1326. if problems:
  1327. return [output_api.PresubmitError(
  1328. "Don't commit .rej and .orig files.", problems)]
  1329. else:
  1330. return []
  1331. def _DidYouMeanOSMacro(bad_macro):
  1332. try:
  1333. return {'A': 'OS_ANDROID',
  1334. 'B': 'OS_BSD',
  1335. 'C': 'OS_CHROMEOS',
  1336. 'F': 'OS_FREEBSD',
  1337. 'L': 'OS_LINUX',
  1338. 'M': 'OS_MACOSX',
  1339. 'N': 'OS_NACL',
  1340. 'O': 'OS_OPENBSD',
  1341. 'P': 'OS_POSIX',
  1342. 'S': 'OS_SOLARIS',
  1343. 'W': 'OS_WIN'}[bad_macro[3].upper()]
  1344. except KeyError:
  1345. return ''
  1346. def _CheckForInvalidOSMacrosInFile(input_api, f):
  1347. """Check for sensible looking, totally invalid OS macros."""
  1348. preprocessor_statement = input_api.re.compile(r'^\s*#')
  1349. os_macro = input_api.re.compile(r'defined\((OS_[^)]+)\)')
  1350. results = []
  1351. for lnum, line in f.ChangedContents():
  1352. if preprocessor_statement.search(line):
  1353. for match in os_macro.finditer(line):
  1354. if not match.group(1) in _VALID_OS_MACROS:
  1355. good = _DidYouMeanOSMacro(match.group(1))
  1356. did_you_mean = ' (did you mean %s?)' % good if good else ''
  1357. results.append(' %s:%d %s%s' % (f.LocalPath(),
  1358. lnum,
  1359. match.group(1),
  1360. did_you_mean))
  1361. return results
  1362. def _CheckForInvalidOSMacros(input_api, output_api):
  1363. """Check all affected files for invalid OS macros."""
  1364. bad_macros = []
  1365. for f in input_api.AffectedFiles():
  1366. if not f.LocalPath().endswith(('.py', '.js', '.html', '.css')):
  1367. bad_macros.extend(_CheckForInvalidOSMacrosInFile(input_api, f))
  1368. if not bad_macros:
  1369. return []
  1370. return [output_api.PresubmitError(
  1371. 'Possibly invalid OS macro[s] found. Please fix your code\n'
  1372. 'or add your macro to src/PRESUBMIT.py.', bad_macros)]
  1373. def _CheckForInvalidIfDefinedMacrosInFile(input_api, f):
  1374. """Check all affected files for invalid "if defined" macros."""
  1375. ALWAYS_DEFINED_MACROS = (
  1376. "TARGET_CPU_PPC",
  1377. "TARGET_CPU_PPC64",
  1378. "TARGET_CPU_68K",
  1379. "TARGET_CPU_X86",
  1380. "TARGET_CPU_ARM",
  1381. "TARGET_CPU_MIPS",
  1382. "TARGET_CPU_SPARC",
  1383. "TARGET_CPU_ALPHA",
  1384. "TARGET_IPHONE_SIMULATOR",
  1385. "TARGET_OS_EMBEDDED",
  1386. "TARGET_OS_IPHONE",
  1387. "TARGET_OS_MAC",
  1388. "TARGET_OS_UNIX",
  1389. "TARGET_OS_WIN32",
  1390. )
  1391. ifdef_macro = input_api.re.compile(r'^\s*#.*(?:ifdef\s|defined\()([^\s\)]+)')
  1392. results = []
  1393. for lnum, line in f.ChangedContents():
  1394. for match in ifdef_macro.finditer(line):
  1395. if match.group(1) in ALWAYS_DEFINED_MACROS:
  1396. always_defined = ' %s is always defined. ' % match.group(1)
  1397. did_you_mean = 'Did you mean \'#if %s\'?' % match.group(1)
  1398. results.append(' %s:%d %s\n\t%s' % (f.LocalPath(),
  1399. lnum,
  1400. always_defined,
  1401. did_you_mean))
  1402. return results
  1403. def _CheckForInvalidIfDefinedMacros(input_api, output_api):
  1404. """Check all affected files for invalid "if defined" macros."""
  1405. bad_macros = []
  1406. for f in input_api.AffectedFiles():
  1407. if f.LocalPath().endswith(('.h', '.c', '.cc', '.m', '.mm')):
  1408. bad_macros.extend(_CheckForInvalidIfDefinedMacrosInFile(input_api, f))
  1409. if not bad_macros:
  1410. return []
  1411. return [output_api.PresubmitError(
  1412. 'Found ifdef check on always-defined macro[s]. Please fix your code\n'
  1413. 'or check the list of ALWAYS_DEFINED_MACROS in src/PRESUBMIT.py.',
  1414. bad_macros)]
  1415. def _CheckForUsingSideEffectsOfPass(input_api, output_api):
  1416. """Check all affected files for using side effects of Pass."""
  1417. errors = []
  1418. for f in input_api.AffectedFiles():
  1419. if f.LocalPath().endswith(('.h', '.c', '.cc', '.m', '.mm')):
  1420. for lnum, line in f.ChangedContents():
  1421. # Disallow Foo(*my_scoped_thing.Pass()); See crbug.com/418297.
  1422. if input_api.re.search(r'\*[a-zA-Z0-9_]+\.Pass\(\)', line):
  1423. errors.append(output_api.PresubmitError(
  1424. ('%s:%d uses *foo.Pass() to delete the contents of scoped_ptr. ' +
  1425. 'See crbug.com/418297.') % (f.LocalPath(), lnum)))
  1426. return errors
  1427. def _CheckForIPCRules(input_api, output_api):
  1428. """Check for same IPC rules described in
  1429. http://www.chromium.org/Home/chromium-security/education/security-tips-for-ipc
  1430. """
  1431. base_pattern = r'IPC_ENUM_TRAITS\('
  1432. inclusion_pattern = input_api.re.compile(r'(%s)' % base_pattern)
  1433. comment_pattern = input_api.re.compile(r'//.*(%s)' % base_pattern)
  1434. problems = []
  1435. for f in input_api.AffectedSourceFiles(None):
  1436. local_path = f.LocalPath()
  1437. if not local_path.endswith('.h'):
  1438. continue
  1439. for line_number, line in f.ChangedContents():
  1440. if inclusion_pattern.search(line) and not comment_pattern.search(line):
  1441. problems.append(
  1442. '%s:%d\n %s' % (local_path, line_number, line.strip()))
  1443. if problems:
  1444. return [output_api.PresubmitPromptWarning(
  1445. _IPC_ENUM_TRAITS_DEPRECATED, problems)]
  1446. else:
  1447. return []
  1448. def _CheckForWindowsLineEndings(input_api, output_api):
  1449. """Check source code and known ascii text files for Windows style line
  1450. endings.
  1451. """
  1452. known_text_files = r'.*\.(txt|html|htm|mhtml|py|gyp|gypi|gn|isolate)$'
  1453. file_inclusion_pattern = (
  1454. known_text_files,
  1455. r'.+%s' % _IMPLEMENTATION_EXTENSIONS
  1456. )
  1457. filter = lambda f: input_api.FilterSourceFile(
  1458. f, white_list=file_inclusion_pattern, black_list=None)
  1459. files = [f.LocalPath() for f in
  1460. input_api.AffectedSourceFiles(filter)]
  1461. problems = []
  1462. for file in files:
  1463. fp = open(file, 'r')
  1464. for line in fp:
  1465. if line.endswith('\r\n'):
  1466. problems.append(file)
  1467. break
  1468. fp.close()
  1469. if problems:
  1470. return [output_api.PresubmitPromptWarning('Are you sure that you want '
  1471. 'these files to contain Windows style line endings?\n' +
  1472. '\n'.join(problems))]
  1473. return []
  1474. def CheckChangeOnUpload(input_api, output_api):
  1475. results = []
  1476. results.extend(_CommonChecks(input_api, output_api))
  1477. results.extend(_CheckValidHostsInDEPS(input_api, output_api))
  1478. results.extend(_CheckJavaStyle(input_api, output_api))
  1479. results.extend(
  1480. input_api.canned_checks.CheckGNFormatted(input_api, output_api))
  1481. results.extend(_CheckUmaHistogramChanges(input_api, output_api))
  1482. return results
  1483. def GetTryServerMasterForBot(bot):
  1484. """Returns the Try Server master for the given bot.
  1485. It tries to guess the master from the bot name, but may still fail
  1486. and return None. There is no longer a default master.
  1487. """
  1488. # Potentially ambiguous bot names are listed explicitly.
  1489. master_map = {
  1490. 'chromium_presubmit': 'tryserver.chromium.linux',
  1491. 'blink_presubmit': 'tryserver.chromium.linux',
  1492. 'tools_build_presubmit': 'tryserver.chromium.linux',
  1493. }
  1494. master = master_map.get(bot)
  1495. if not master:
  1496. if 'linux' in bot or 'android' in bot or 'presubmit' in bot:
  1497. master = 'tryserver.chromium.linux'
  1498. elif 'win' in bot:
  1499. master = 'tryserver.chromium.win'
  1500. elif 'mac' in bot or 'ios' in bot:
  1501. master = 'tryserver.chromium.mac'
  1502. return master
  1503. def GetDefaultTryConfigs(bots):
  1504. """Returns a list of ('bot', set(['tests']), filtered by [bots].
  1505. """
  1506. builders_and_tests = dict((bot, set(['defaulttests'])) for bot in bots)
  1507. # Build up the mapping from tryserver master to bot/test.
  1508. out = dict()
  1509. for bot, tests in builders_and_tests.iteritems():
  1510. out.setdefault(GetTryServerMasterForBot(bot), {})[bot] = tests
  1511. return out
  1512. def CheckChangeOnCommit(input_api, output_api):
  1513. results = []
  1514. results.extend(_CommonChecks(input_api, output_api))
  1515. # TODO(thestig) temporarily disabled, doesn't work in third_party/
  1516. #results.extend(input_api.canned_checks.CheckSvnModifiedDirectories(
  1517. # input_api, output_api, sources))
  1518. # Make sure the tree is 'open'.
  1519. results.extend(input_api.canned_checks.CheckTreeIsOpen(
  1520. input_api,
  1521. output_api,
  1522. json_url='http://chromium-status.appspot.com/current?format=json'))
  1523. results.extend(input_api.canned_checks.CheckChangeHasBugField(
  1524. input_api, output_api))
  1525. results.extend(input_api.canned_checks.CheckChangeHasDescription(
  1526. input_api, output_api))
  1527. return results
  1528. def GetPreferredTryMasters(project, change):
  1529. import re
  1530. files = change.LocalPaths()
  1531. import os
  1532. import json
  1533. with open(os.path.join(
  1534. change.RepositoryRoot(), 'testing', 'commit_queue', 'config.json')) as f:
  1535. cq_config = json.load(f)
  1536. cq_verifiers = cq_config.get('verifiers_no_patch', {})
  1537. cq_try_jobs = cq_verifiers.get('try_job_verifier', {})
  1538. builders = cq_try_jobs.get('launched', {})
  1539. for master, master_config in cq_try_jobs.get('triggered', {}).iteritems():
  1540. for triggered_bot in master_config:
  1541. builders.get(master, {}).pop(triggered_bot, None)
  1542. # Explicitly iterate over copies of dicts since we mutate them.
  1543. for master in builders.keys():
  1544. for builder in builders[master].keys():
  1545. # Do not trigger presubmit builders, since they're likely to fail
  1546. # (e.g. OWNERS checks before finished code review), and we're
  1547. # running local presubmit anyway.
  1548. if 'presubmit' in builder:
  1549. builders[master].pop(builder)
  1550. return builders