GoogleGit

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