You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1212 lines
47 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. # Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
  2. #
  3. # Use of this source code is governed by a BSD-style license
  4. # that can be found in the LICENSE file in the root of the source
  5. # tree. An additional intellectual property rights grant can be found
  6. # in the file PATENTS. All contributing project authors may
  7. # be found in the AUTHORS file in the root of the source tree.
  8. import json
  9. import os
  10. import re
  11. import sys
  12. from collections import defaultdict
  13. from contextlib import contextmanager
  14. # Files and directories that are *skipped* by cpplint in the presubmit script.
  15. CPPLINT_BLACKLIST = [
  16. 'api/video_codecs/video_decoder.h',
  17. 'common_types.cc',
  18. 'common_types.h',
  19. 'examples/objc',
  20. 'media/base/stream_params.h',
  21. 'media/base/video_common.h',
  22. 'media/sctp/sctp_transport.cc',
  23. 'modules/audio_coding',
  24. 'modules/audio_device',
  25. 'modules/audio_processing',
  26. 'modules/desktop_capture',
  27. 'modules/include/module_common_types.h',
  28. 'modules/utility',
  29. 'modules/video_capture',
  30. 'p2p/base/pseudo_tcp.cc',
  31. 'p2p/base/pseudo_tcp.h',
  32. 'rtc_base',
  33. 'sdk/android/src/jni',
  34. 'sdk/objc',
  35. 'system_wrappers',
  36. 'test',
  37. 'tools_webrtc',
  38. 'voice_engine',
  39. ]
  40. # These filters will always be removed, even if the caller specifies a filter
  41. # set, as they are problematic or broken in some way.
  42. #
  43. # Justifications for each filter:
  44. # - build/c++11 : Rvalue ref checks are unreliable (false positives),
  45. # include file and feature blacklists are
  46. # google3-specific.
  47. # - whitespace/operators: Same as above (doesn't seem sufficient to eliminate
  48. # all move-related errors).
  49. BLACKLIST_LINT_FILTERS = [
  50. '-build/c++11',
  51. '-whitespace/operators',
  52. ]
  53. # List of directories of "supported" native APIs. That means changes to headers
  54. # will be done in a compatible way following this scheme:
  55. # 1. Non-breaking changes are made.
  56. # 2. The old APIs as marked as deprecated (with comments).
  57. # 3. Deprecation is announced to discuss-webrtc@googlegroups.com and
  58. # webrtc-users@google.com (internal list).
  59. # 4. (later) The deprecated APIs are removed.
  60. NATIVE_API_DIRS = (
  61. 'api', # All subdirectories of api/ are included as well.
  62. 'media/base',
  63. 'media/engine',
  64. 'modules/audio_device/include',
  65. 'pc',
  66. )
  67. # These directories should not be used but are maintained only to avoid breaking
  68. # some legacy downstream code.
  69. LEGACY_API_DIRS = (
  70. 'common_audio/include',
  71. 'modules/audio_coding/include',
  72. 'modules/audio_processing/include',
  73. 'modules/congestion_controller/include',
  74. 'modules/include',
  75. 'modules/remote_bitrate_estimator/include',
  76. 'modules/rtp_rtcp/include',
  77. 'modules/rtp_rtcp/source',
  78. 'modules/utility/include',
  79. 'modules/video_coding/codecs/h264/include',
  80. 'modules/video_coding/codecs/vp8/include',
  81. 'modules/video_coding/codecs/vp9/include',
  82. 'modules/video_coding/include',
  83. 'rtc_base',
  84. 'system_wrappers/include',
  85. )
  86. # NOTE: The set of directories in API_DIRS should be the same as those
  87. # listed in the table in native-api.md.
  88. API_DIRS = NATIVE_API_DIRS[:] + LEGACY_API_DIRS[:]
  89. # TARGET_RE matches a GN target, and extracts the target name and the contents.
  90. TARGET_RE = re.compile(r'(?P<indent>\s*)\w+\("(?P<target_name>\w+)"\) {'
  91. r'(?P<target_contents>.*?)'
  92. r'(?P=indent)}',
  93. re.MULTILINE | re.DOTALL)
  94. # SOURCES_RE matches a block of sources inside a GN target.
  95. SOURCES_RE = re.compile(r'sources \+?= \[(?P<sources>.*?)\]',
  96. re.MULTILINE | re.DOTALL)
  97. # FILE_PATH_RE matchies a file path.
  98. FILE_PATH_RE = re.compile(r'"(?P<file_path>(\w|\/)+)(?P<extension>\.\w+)"')
  99. def FindSrcDirPath(starting_dir):
  100. """Returns the abs path to the src/ dir of the project."""
  101. src_dir = starting_dir
  102. while os.path.basename(src_dir) != 'src':
  103. src_dir = os.path.normpath(os.path.join(src_dir, os.pardir))
  104. return src_dir
  105. @contextmanager
  106. def _AddToPath(*paths):
  107. original_sys_path = sys.path
  108. sys.path.extend(paths)
  109. try:
  110. yield
  111. finally:
  112. # Restore sys.path to what it was before.
  113. sys.path = original_sys_path
  114. def VerifyNativeApiHeadersListIsValid(input_api, output_api):
  115. """Ensures the list of native API header directories is up to date."""
  116. non_existing_paths = []
  117. native_api_full_paths = [
  118. input_api.os_path.join(input_api.PresubmitLocalPath(),
  119. *path.split('/')) for path in API_DIRS]
  120. for path in native_api_full_paths:
  121. if not os.path.isdir(path):
  122. non_existing_paths.append(path)
  123. if non_existing_paths:
  124. return [output_api.PresubmitError(
  125. 'Directories to native API headers have changed which has made the '
  126. 'list in PRESUBMIT.py outdated.\nPlease update it to the current '
  127. 'location of our native APIs.',
  128. non_existing_paths)]
  129. return []
  130. API_CHANGE_MSG = """
  131. You seem to be changing native API header files. Please make sure that you:
  132. 1. Make compatible changes that don't break existing clients. Usually
  133. this is done by keeping the existing method signatures unchanged.
  134. 2. Mark the old stuff as deprecated (see RTC_DEPRECATED macro).
  135. 3. Create a timeline and plan for when the deprecated stuff will be
  136. removed. (The amount of time we give users to change their code
  137. should be informed by how much work it is for them. If they just
  138. need to replace one name with another or something equally
  139. simple, 1-2 weeks might be good; if they need to do serious work,
  140. up to 3 months may be called for.)
  141. 4. Update/inform existing downstream code owners to stop using the
  142. deprecated stuff. (Send announcements to
  143. discuss-webrtc@googlegroups.com and webrtc-users@google.com.)
  144. 5. Remove the deprecated stuff, once the agreed-upon amount of time
  145. has passed.
  146. Related files:
  147. """
  148. def CheckNativeApiHeaderChanges(input_api, output_api):
  149. """Checks to remind proper changing of native APIs."""
  150. files = []
  151. source_file_filter = lambda x: input_api.FilterSourceFile(
  152. x, white_list=[r'.+\.(gn|gni|h)$'])
  153. for f in input_api.AffectedSourceFiles(source_file_filter):
  154. for path in API_DIRS:
  155. dn = os.path.dirname(f.LocalPath())
  156. if path == 'api':
  157. # Special case: Subdirectories included.
  158. if dn == 'api' or dn.startswith('api/'):
  159. files.append(f.LocalPath())
  160. else:
  161. # Normal case: Subdirectories not included.
  162. if dn == path:
  163. files.append(f.LocalPath())
  164. if files:
  165. return [output_api.PresubmitNotifyResult(API_CHANGE_MSG, files)]
  166. return []
  167. def CheckNoIOStreamInHeaders(input_api, output_api,
  168. source_file_filter):
  169. """Checks to make sure no .h files include <iostream>."""
  170. files = []
  171. pattern = input_api.re.compile(r'^#include\s*<iostream>',
  172. input_api.re.MULTILINE)
  173. file_filter = lambda x: (input_api.FilterSourceFile(x)
  174. and source_file_filter(x))
  175. for f in input_api.AffectedSourceFiles(file_filter):
  176. if not f.LocalPath().endswith('.h'):
  177. continue
  178. contents = input_api.ReadFile(f)
  179. if pattern.search(contents):
  180. files.append(f)
  181. if len(files):
  182. return [output_api.PresubmitError(
  183. 'Do not #include <iostream> in header files, since it inserts static ' +
  184. 'initialization into every file including the header. Instead, ' +
  185. '#include <ostream>. See http://crbug.com/94794',
  186. files)]
  187. return []
  188. def CheckNoPragmaOnce(input_api, output_api,
  189. source_file_filter):
  190. """Make sure that banned functions are not used."""
  191. files = []
  192. pattern = input_api.re.compile(r'^#pragma\s+once',
  193. input_api.re.MULTILINE)
  194. file_filter = lambda x: (input_api.FilterSourceFile(x)
  195. and source_file_filter(x))
  196. for f in input_api.AffectedSourceFiles(file_filter):
  197. if not f.LocalPath().endswith('.h'):
  198. continue
  199. contents = input_api.ReadFile(f)
  200. if pattern.search(contents):
  201. files.append(f)
  202. if files:
  203. return [output_api.PresubmitError(
  204. 'Do not use #pragma once in header files.\n'
  205. 'See http://www.chromium.org/developers/coding-style#TOC-File-headers',
  206. files)]
  207. return []
  208. def CheckNoFRIEND_TEST(input_api, output_api, # pylint: disable=invalid-name
  209. source_file_filter):
  210. """Make sure that gtest's FRIEND_TEST() macro is not used, the
  211. FRIEND_TEST_ALL_PREFIXES() macro from testsupport/gtest_prod_util.h should be
  212. used instead since that allows for FLAKY_, FAILS_ and DISABLED_ prefixes."""
  213. problems = []
  214. file_filter = lambda f: (f.LocalPath().endswith(('.cc', '.h'))
  215. and source_file_filter(f))
  216. for f in input_api.AffectedFiles(file_filter=file_filter):
  217. for line_num, line in f.ChangedContents():
  218. if 'FRIEND_TEST(' in line:
  219. problems.append(' %s:%d' % (f.LocalPath(), line_num))
  220. if not problems:
  221. return []
  222. return [output_api.PresubmitPromptWarning('WebRTC\'s code should not use '
  223. 'gtest\'s FRIEND_TEST() macro. Include testsupport/gtest_prod_util.h and '
  224. 'use FRIEND_TEST_ALL_PREFIXES() instead.\n' + '\n'.join(problems))]
  225. def IsLintBlacklisted(blacklist_paths, file_path):
  226. """ Checks if a file is blacklisted for lint check."""
  227. for path in blacklist_paths:
  228. if file_path == path or os.path.dirname(file_path).startswith(path):
  229. return True
  230. return False
  231. def CheckApprovedFilesLintClean(input_api, output_api,
  232. source_file_filter=None):
  233. """Checks that all new or non-blacklisted .cc and .h files pass cpplint.py.
  234. This check is based on CheckChangeLintsClean in
  235. depot_tools/presubmit_canned_checks.py but has less filters and only checks
  236. added files."""
  237. result = []
  238. # Initialize cpplint.
  239. import cpplint
  240. # Access to a protected member _XX of a client class
  241. # pylint: disable=W0212
  242. cpplint._cpplint_state.ResetErrorCounts()
  243. lint_filters = cpplint._Filters()
  244. lint_filters.extend(BLACKLIST_LINT_FILTERS)
  245. cpplint._SetFilters(','.join(lint_filters))
  246. # Create a platform independent blacklist for cpplint.
  247. blacklist_paths = [input_api.os_path.join(*path.split('/'))
  248. for path in CPPLINT_BLACKLIST]
  249. # Use the strictest verbosity level for cpplint.py (level 1) which is the
  250. # default when running cpplint.py from command line. To make it possible to
  251. # work with not-yet-converted code, we're only applying it to new (or
  252. # moved/renamed) files and files not listed in CPPLINT_BLACKLIST.
  253. verbosity_level = 1
  254. files = []
  255. for f in input_api.AffectedSourceFiles(source_file_filter):
  256. # Note that moved/renamed files also count as added.
  257. if f.Action() == 'A' or not IsLintBlacklisted(blacklist_paths,
  258. f.LocalPath()):
  259. files.append(f.AbsoluteLocalPath())
  260. for file_name in files:
  261. cpplint.ProcessFile(file_name, verbosity_level)
  262. if cpplint._cpplint_state.error_count > 0:
  263. if input_api.is_committing:
  264. res_type = output_api.PresubmitError
  265. else:
  266. res_type = output_api.PresubmitPromptWarning
  267. result = [res_type('Changelist failed cpplint.py check.')]
  268. return result
  269. def CheckNoSourcesAbove(input_api, gn_files, output_api):
  270. # Disallow referencing source files with paths above the GN file location.
  271. source_pattern = input_api.re.compile(r' +sources \+?= \[(.*?)\]',
  272. re.MULTILINE | re.DOTALL)
  273. file_pattern = input_api.re.compile(r'"((\.\./.*?)|(//.*?))"')
  274. violating_gn_files = set()
  275. violating_source_entries = []
  276. for gn_file in gn_files:
  277. contents = input_api.ReadFile(gn_file)
  278. for source_block_match in source_pattern.finditer(contents):
  279. # Find all source list entries starting with ../ in the source block
  280. # (exclude overrides entries).
  281. for file_list_match in file_pattern.finditer(source_block_match.group(1)):
  282. source_file = file_list_match.group(1)
  283. if 'overrides/' not in source_file:
  284. violating_source_entries.append(source_file)
  285. violating_gn_files.add(gn_file)
  286. if violating_gn_files:
  287. return [output_api.PresubmitError(
  288. 'Referencing source files above the directory of the GN file is not '
  289. 'allowed. Please introduce new GN targets in the proper location '
  290. 'instead.\n'
  291. 'Invalid source entries:\n'
  292. '%s\n'
  293. 'Violating GN files:' % '\n'.join(violating_source_entries),
  294. items=violating_gn_files)]
  295. return []
  296. def CheckNoMixingSources(input_api, gn_files, output_api):
  297. """Disallow mixing C, C++ and Obj-C/Obj-C++ in the same target.
  298. See bugs.webrtc.org/7743 for more context.
  299. """
  300. def _MoreThanOneSourceUsed(*sources_lists):
  301. sources_used = 0
  302. for source_list in sources_lists:
  303. if len(source_list):
  304. sources_used += 1
  305. return sources_used > 1
  306. errors = defaultdict(lambda: [])
  307. for gn_file in gn_files:
  308. gn_file_content = input_api.ReadFile(gn_file)
  309. for target_match in TARGET_RE.finditer(gn_file_content):
  310. # list_of_sources is a list of tuples of the form
  311. # (c_files, cc_files, objc_files) that keeps track of all the sources
  312. # defined in a target. A GN target can have more that on definition of
  313. # sources (since it supports if/else statements).
  314. # E.g.:
  315. # rtc_static_library("foo") {
  316. # if (is_win) {
  317. # sources = [ "foo.cc" ]
  318. # } else {
  319. # sources = [ "foo.mm" ]
  320. # }
  321. # }
  322. # This is allowed and the presubmit check should support this case.
  323. list_of_sources = []
  324. c_files = []
  325. cc_files = []
  326. objc_files = []
  327. target_name = target_match.group('target_name')
  328. target_contents = target_match.group('target_contents')
  329. for sources_match in SOURCES_RE.finditer(target_contents):
  330. if '+=' not in sources_match.group(0):
  331. if c_files or cc_files or objc_files:
  332. list_of_sources.append((c_files, cc_files, objc_files))
  333. c_files = []
  334. cc_files = []
  335. objc_files = []
  336. for file_match in FILE_PATH_RE.finditer(sources_match.group(1)):
  337. file_path = file_match.group('file_path')
  338. extension = file_match.group('extension')
  339. if extension == '.c':
  340. c_files.append(file_path + extension)
  341. if extension == '.cc':
  342. cc_files.append(file_path + extension)
  343. if extension in ['.m', '.mm']:
  344. objc_files.append(file_path + extension)
  345. list_of_sources.append((c_files, cc_files, objc_files))
  346. for c_files_list, cc_files_list, objc_files_list in list_of_sources:
  347. if _MoreThanOneSourceUsed(c_files_list, cc_files_list, objc_files_list):
  348. all_sources = sorted(c_files_list + cc_files_list + objc_files_list)
  349. errors[gn_file.LocalPath()].append((target_name, all_sources))
  350. if errors:
  351. return [output_api.PresubmitError(
  352. 'GN targets cannot mix .c, .cc and .m (or .mm) source files.\n'
  353. 'Please create a separate target for each collection of sources.\n'
  354. 'Mixed sources: \n'
  355. '%s\n'
  356. 'Violating GN files:\n%s\n' % (json.dumps(errors, indent=2),
  357. '\n'.join(errors.keys())))]
  358. return []
  359. def CheckNoPackageBoundaryViolations(input_api, gn_files, output_api):
  360. cwd = input_api.PresubmitLocalPath()
  361. with _AddToPath(input_api.os_path.join(
  362. cwd, 'tools_webrtc', 'presubmit_checks_lib')):
  363. from check_package_boundaries import CheckPackageBoundaries
  364. build_files = [os.path.join(cwd, gn_file.LocalPath()) for gn_file in gn_files]
  365. errors = CheckPackageBoundaries(cwd, build_files)[:5]
  366. if errors:
  367. return [output_api.PresubmitError(
  368. 'There are package boundary violations in the following GN files:',
  369. long_text='\n\n'.join(str(err) for err in errors))]
  370. return []
  371. def _ReportFileAndLine(filename, line_num):
  372. """Default error formatter for _FindNewViolationsOfRule."""
  373. return '%s (line %s)' % (filename, line_num)
  374. def CheckNoWarningSuppressionFlagsAreAdded(gn_files, input_api, output_api,
  375. error_formatter=_ReportFileAndLine):
  376. """Make sure that warning suppression flags are not added wihtout a reason."""
  377. msg = ('Usage of //build/config/clang:extra_warnings is discouraged '
  378. 'in WebRTC.\n'
  379. 'If you are not adding this code (e.g. you are just moving '
  380. 'existing code) or you want to add an exception,\n'
  381. 'you can add a comment on the line that causes the problem:\n\n'
  382. '"-Wno-odr" # no-presubmit-check TODO(bugs.webrtc.org/BUG_ID)\n'
  383. '\n'
  384. 'Affected files:\n')
  385. errors = [] # 2-element tuples with (file, line number)
  386. clang_warn_re = input_api.re.compile(r'//build/config/clang:extra_warnings')
  387. no_presubmit_re = input_api.re.compile(
  388. r'# no-presubmit-check TODO\(bugs\.webrtc\.org/\d+\)')
  389. for f in gn_files:
  390. for line_num, line in f.ChangedContents():
  391. if clang_warn_re.search(line) and not no_presubmit_re.search(line):
  392. errors.append(error_formatter(f.LocalPath(), line_num))
  393. if errors:
  394. return [output_api.PresubmitError(msg, errors)]
  395. return []
  396. def CheckNoTestCaseUsageIsAdded(input_api, output_api, source_file_filter,
  397. error_formatter=_ReportFileAndLine):
  398. error_msg = ('Usage of legacy GoogleTest API detected!\nPlease use the '
  399. 'new API: https://github.com/google/googletest/blob/master/'
  400. 'googletest/docs/primer.md#beware-of-the-nomenclature.\n'
  401. 'Affected files:\n')
  402. errors = [] # 2-element tuples with (file, line number)
  403. test_case_re = input_api.re.compile(r'TEST_CASE')
  404. file_filter = lambda f: (source_file_filter(f)
  405. and f.LocalPath().endswith('.cc'))
  406. for f in input_api.AffectedSourceFiles(file_filter):
  407. for line_num, line in f.ChangedContents():
  408. if test_case_re.search(line):
  409. errors.append(error_formatter(f.LocalPath(), line_num))
  410. if errors:
  411. return [output_api.PresubmitError(error_msg, errors)]
  412. return []
  413. def CheckNoStreamUsageIsAdded(input_api, output_api,
  414. source_file_filter,
  415. error_formatter=_ReportFileAndLine):
  416. """Make sure that no more dependencies on stringstream are added."""
  417. error_msg = ('Usage of <sstream>, <istream> and <ostream> in WebRTC is '
  418. 'deprecated.\n'
  419. 'This includes the following types:\n'
  420. 'std::istringstream, std::ostringstream, std::wistringstream, '
  421. 'std::wostringstream,\n'
  422. 'std::wstringstream, std::ostream, std::wostream, std::istream,'
  423. 'std::wistream,\n'
  424. 'std::iostream, std::wiostream.\n'
  425. 'If you are not adding this code (e.g. you are just moving '
  426. 'existing code),\n'
  427. 'you can add a comment on the line that causes the problem:\n\n'
  428. '#include <sstream> // no-presubmit-check TODO(webrtc:8982)\n'
  429. 'std::ostream& F() { // no-presubmit-check TODO(webrtc:8982)\n'
  430. '\n'
  431. 'If you are adding new code, consider using '
  432. 'rtc::SimpleStringBuilder\n'
  433. '(in rtc_base/strings/string_builder.h).\n'
  434. 'Affected files:\n')
  435. errors = [] # 2-element tuples with (file, line number)
  436. include_re = input_api.re.compile(r'#include <(i|o|s)stream>')
  437. usage_re = input_api.re.compile(r'std::(w|i|o|io|wi|wo|wio)(string)*stream')
  438. no_presubmit_re = input_api.re.compile(
  439. r'// no-presubmit-check TODO\(webrtc:8982\)')
  440. file_filter = lambda x: (input_api.FilterSourceFile(x)
  441. and source_file_filter(x))
  442. def _IsException(file_path):
  443. is_test = any(file_path.endswith(x) for x in ['_test.cc', '_tests.cc',
  444. '_unittest.cc',
  445. '_unittests.cc'])
  446. return file_path.startswith('examples') or is_test
  447. for f in input_api.AffectedSourceFiles(file_filter):
  448. # Usage of stringstream is allowed under examples/ and in tests.
  449. if f.LocalPath() == 'PRESUBMIT.py' or _IsException(f.LocalPath()):
  450. continue
  451. for line_num, line in f.ChangedContents():
  452. if ((include_re.search(line) or usage_re.search(line))
  453. and not no_presubmit_re.search(line)):
  454. errors.append(error_formatter(f.LocalPath(), line_num))
  455. if errors:
  456. return [output_api.PresubmitError(error_msg, errors)]
  457. return []
  458. def CheckPublicDepsIsNotUsed(gn_files, input_api, output_api):
  459. """Checks that public_deps is not used without a good reason."""
  460. result = []
  461. no_presubmit_check_re = input_api.re.compile(
  462. r'# no-presubmit-check TODO\(webrtc:8603\)')
  463. error_msg = ('public_deps is not recommended in WebRTC BUILD.gn files '
  464. 'because it doesn\'t map well to downstream build systems.\n'
  465. 'Used in: %s (line %d).\n'
  466. 'If you are not adding this code (e.g. you are just moving '
  467. 'existing code) or you have a good reason, you can add a '
  468. 'comment on the line that causes the problem:\n\n'
  469. 'public_deps = [ # no-presubmit-check TODO(webrtc:8603)\n')
  470. for affected_file in gn_files:
  471. for (line_number, affected_line) in affected_file.ChangedContents():
  472. if ('public_deps' in affected_line
  473. and not no_presubmit_check_re.search(affected_line)):
  474. result.append(
  475. output_api.PresubmitError(error_msg % (affected_file.LocalPath(),
  476. line_number)))
  477. return result
  478. def CheckCheckIncludesIsNotUsed(gn_files, output_api):
  479. result = []
  480. error_msg = ('check_includes overrides are not allowed since it can cause '
  481. 'incorrect dependencies to form. It effectively means that your '
  482. 'module can include any .h file without depending on its '
  483. 'corresponding target. There are some exceptional cases when '
  484. 'this is allowed: if so, get approval from a .gn owner in the'
  485. 'root OWNERS file.\n'
  486. 'Used in: %s (line %d).')
  487. for affected_file in gn_files:
  488. for (line_number, affected_line) in affected_file.ChangedContents():
  489. if 'check_includes' in affected_line:
  490. result.append(
  491. output_api.PresubmitError(error_msg % (affected_file.LocalPath(),
  492. line_number)))
  493. return result
  494. def CheckGnChanges(input_api, output_api):
  495. file_filter = lambda x: (input_api.FilterSourceFile(
  496. x, white_list=(r'.+\.(gn|gni)$',),
  497. black_list=(r'.*/presubmit_checks_lib/testdata/.*',)))
  498. gn_files = []
  499. for f in input_api.AffectedSourceFiles(file_filter):
  500. gn_files.append(f)
  501. result = []
  502. if gn_files:
  503. result.extend(CheckNoSourcesAbove(input_api, gn_files, output_api))
  504. result.extend(CheckNoMixingSources(input_api, gn_files, output_api))
  505. result.extend(CheckNoPackageBoundaryViolations(input_api, gn_files,
  506. output_api))
  507. result.extend(CheckPublicDepsIsNotUsed(gn_files, input_api, output_api))
  508. result.extend(CheckCheckIncludesIsNotUsed(gn_files, output_api))
  509. result.extend(CheckNoWarningSuppressionFlagsAreAdded(gn_files, input_api,
  510. output_api))
  511. return result
  512. def CheckGnGen(input_api, output_api):
  513. """Runs `gn gen --check` with default args to detect mismatches between
  514. #includes and dependencies in the BUILD.gn files, as well as general build
  515. errors.
  516. """
  517. with _AddToPath(input_api.os_path.join(
  518. input_api.PresubmitLocalPath(), 'tools_webrtc', 'presubmit_checks_lib')):
  519. from build_helpers import RunGnCheck
  520. errors = RunGnCheck(FindSrcDirPath(input_api.PresubmitLocalPath()))[:5]
  521. if errors:
  522. return [output_api.PresubmitPromptWarning(
  523. 'Some #includes do not match the build dependency graph. Please run:\n'
  524. ' gn gen --check <out_dir>',
  525. long_text='\n\n'.join(errors))]
  526. return []
  527. def CheckUnwantedDependencies(input_api, output_api, source_file_filter):
  528. """Runs checkdeps on #include statements added in this
  529. change. Breaking - rules is an error, breaking ! rules is a
  530. warning.
  531. """
  532. # Copied from Chromium's src/PRESUBMIT.py.
  533. # We need to wait until we have an input_api object and use this
  534. # roundabout construct to import checkdeps because this file is
  535. # eval-ed and thus doesn't have __file__.
  536. src_path = FindSrcDirPath(input_api.PresubmitLocalPath())
  537. checkdeps_path = input_api.os_path.join(src_path, 'buildtools', 'checkdeps')
  538. if not os.path.exists(checkdeps_path):
  539. return [output_api.PresubmitError(
  540. 'Cannot find checkdeps at %s\nHave you run "gclient sync" to '
  541. 'download all the DEPS entries?' % checkdeps_path)]
  542. with _AddToPath(checkdeps_path):
  543. import checkdeps
  544. from cpp_checker import CppChecker
  545. from rules import Rule
  546. added_includes = []
  547. for f in input_api.AffectedFiles(file_filter=source_file_filter):
  548. if not CppChecker.IsCppFile(f.LocalPath()):
  549. continue
  550. changed_lines = [line for _, line in f.ChangedContents()]
  551. added_includes.append([f.LocalPath(), changed_lines])
  552. deps_checker = checkdeps.DepsChecker(input_api.PresubmitLocalPath())
  553. error_descriptions = []
  554. warning_descriptions = []
  555. for path, rule_type, rule_description in deps_checker.CheckAddedCppIncludes(
  556. added_includes):
  557. description_with_path = '%s\n %s' % (path, rule_description)
  558. if rule_type == Rule.DISALLOW:
  559. error_descriptions.append(description_with_path)
  560. else:
  561. warning_descriptions.append(description_with_path)
  562. results = []
  563. if error_descriptions:
  564. results.append(output_api.PresubmitError(
  565. 'You added one or more #includes that violate checkdeps rules.\n'
  566. 'Check that the DEPS files in these locations contain valid rules.\n'
  567. 'See https://cs.chromium.org/chromium/src/buildtools/checkdeps/ for '
  568. 'more details about checkdeps.',
  569. error_descriptions))
  570. if warning_descriptions:
  571. results.append(output_api.PresubmitPromptOrNotify(
  572. 'You added one or more #includes of files that are temporarily\n'
  573. 'allowed but being removed. Can you avoid introducing the\n'
  574. '#include? See relevant DEPS file(s) for details and contacts.\n'
  575. 'See https://cs.chromium.org/chromium/src/buildtools/checkdeps/ for '
  576. 'more details about checkdeps.',
  577. warning_descriptions))
  578. return results
  579. def CheckCommitMessageBugEntry(input_api, output_api):
  580. """Check that bug entries are well-formed in commit message."""
  581. bogus_bug_msg = (
  582. 'Bogus Bug entry: %s. Please specify the issue tracker prefix and the '
  583. 'issue number, separated by a colon, e.g. webrtc:123 or chromium:12345.')
  584. results = []
  585. for bug in input_api.change.BugsFromDescription():
  586. bug = bug.strip()
  587. if bug.lower() == 'none':
  588. continue
  589. if 'b/' not in bug and ':' not in bug:
  590. try:
  591. if int(bug) > 100000:
  592. # Rough indicator for current chromium bugs.
  593. prefix_guess = 'chromium'
  594. else:
  595. prefix_guess = 'webrtc'
  596. results.append('Bug entry requires issue tracker prefix, e.g. %s:%s' %
  597. (prefix_guess, bug))
  598. except ValueError:
  599. results.append(bogus_bug_msg % bug)
  600. elif not (re.match(r'\w+:\d+', bug) or re.match(r'b/\d+', bug)):
  601. results.append(bogus_bug_msg % bug)
  602. return [output_api.PresubmitError(r) for r in results]
  603. def CheckChangeHasBugField(input_api, output_api):
  604. """Requires that the changelist is associated with a bug.
  605. This check is stricter than the one in depot_tools/presubmit_canned_checks.py
  606. since it fails the presubmit if the bug field is missing or doesn't contain
  607. a bug reference.
  608. This supports both 'BUG=' and 'Bug:' since we are in the process of migrating
  609. to Gerrit and it encourages the usage of 'Bug:'.
  610. """
  611. if input_api.change.BugsFromDescription():
  612. return []
  613. else:
  614. return [output_api.PresubmitError(
  615. 'The "Bug: [bug number]" footer is mandatory. Please create a bug and '
  616. 'reference it using either of:\n'
  617. ' * https://bugs.webrtc.org - reference it using Bug: webrtc:XXXX\n'
  618. ' * https://crbug.com - reference it using Bug: chromium:XXXXXX')]
  619. def CheckJSONParseErrors(input_api, output_api, source_file_filter):
  620. """Check that JSON files do not contain syntax errors."""
  621. def FilterFile(affected_file):
  622. return (input_api.os_path.splitext(affected_file.LocalPath())[1] == '.json'
  623. and source_file_filter(affected_file))
  624. def GetJSONParseError(input_api, filename):
  625. try:
  626. contents = input_api.ReadFile(filename)
  627. input_api.json.loads(contents)
  628. except ValueError as e:
  629. return e
  630. return None
  631. results = []
  632. for affected_file in input_api.AffectedFiles(
  633. file_filter=FilterFile, include_deletes=False):
  634. parse_error = GetJSONParseError(input_api,
  635. affected_file.AbsoluteLocalPath())
  636. if parse_error:
  637. results.append(output_api.PresubmitError('%s could not be parsed: %s' %
  638. (affected_file.LocalPath(),
  639. parse_error)))
  640. return results
  641. def RunPythonTests(input_api, output_api):
  642. def Join(*args):
  643. return input_api.os_path.join(input_api.PresubmitLocalPath(), *args)
  644. test_directories = [
  645. input_api.PresubmitLocalPath(),
  646. Join('rtc_tools', 'py_event_log_analyzer'),
  647. Join('audio', 'test', 'unittests'),
  648. ] + [
  649. root for root, _, files in os.walk(Join('tools_webrtc'))
  650. if any(f.endswith('_test.py') for f in files)
  651. ]
  652. tests = []
  653. for directory in test_directories:
  654. tests.extend(
  655. input_api.canned_checks.GetUnitTestsInDirectory(
  656. input_api,
  657. output_api,
  658. directory,
  659. whitelist=[r'.+_test\.py$']))
  660. return input_api.RunTests(tests, parallel=True)
  661. def CheckUsageOfGoogleProtobufNamespace(input_api, output_api,
  662. source_file_filter):
  663. """Checks that the namespace google::protobuf has not been used."""
  664. files = []
  665. pattern = input_api.re.compile(r'google::protobuf')
  666. proto_utils_path = os.path.join('rtc_base', 'protobuf_utils.h')
  667. file_filter = lambda x: (input_api.FilterSourceFile(x)
  668. and source_file_filter(x))
  669. for f in input_api.AffectedSourceFiles(file_filter):
  670. if f.LocalPath() in [proto_utils_path, 'PRESUBMIT.py']:
  671. continue
  672. contents = input_api.ReadFile(f)
  673. if pattern.search(contents):
  674. files.append(f)
  675. if files:
  676. return [output_api.PresubmitError(
  677. 'Please avoid to use namespace `google::protobuf` directly.\n'
  678. 'Add a using directive in `%s` and include that header instead.'
  679. % proto_utils_path, files)]
  680. return []
  681. def _LicenseHeader(input_api):
  682. """Returns the license header regexp."""
  683. # Accept any year number from 2003 to the current year
  684. current_year = int(input_api.time.strftime('%Y'))
  685. allowed_years = (str(s) for s in reversed(xrange(2003, current_year + 1)))
  686. years_re = '(' + '|'.join(allowed_years) + ')'
  687. license_header = (
  688. r'.*? Copyright( \(c\))? %(year)s The WebRTC [Pp]roject [Aa]uthors\. '
  689. r'All [Rr]ights [Rr]eserved\.\n'
  690. r'.*?\n'
  691. r'.*? Use of this source code is governed by a BSD-style license\n'
  692. r'.*? that can be found in the LICENSE file in the root of the source\n'
  693. r'.*? tree\. An additional intellectual property rights grant can be '
  694. r'found\n'
  695. r'.*? in the file PATENTS\. All contributing project authors may\n'
  696. r'.*? be found in the AUTHORS file in the root of the source tree\.\n'
  697. ) % {
  698. 'year': years_re,
  699. }
  700. return license_header
  701. def CommonChecks(input_api, output_api):
  702. """Checks common to both upload and commit."""
  703. results = []
  704. # Filter out files that are in objc or ios dirs from being cpplint-ed since
  705. # they do not follow C++ lint rules.
  706. black_list = input_api.DEFAULT_BLACK_LIST + (
  707. r".*\bobjc[\\\/].*",
  708. r".*objc\.[hcm]+$",
  709. )
  710. source_file_filter = lambda x: input_api.FilterSourceFile(x, None, black_list)
  711. results.extend(CheckApprovedFilesLintClean(
  712. input_api, output_api, source_file_filter))
  713. results.extend(input_api.canned_checks.CheckLicense(
  714. input_api, output_api, _LicenseHeader(input_api)))
  715. results.extend(input_api.canned_checks.RunPylint(input_api, output_api,
  716. black_list=(r'^base[\\\/].*\.py$',
  717. r'^build[\\\/].*\.py$',
  718. r'^buildtools[\\\/].*\.py$',
  719. r'^infra[\\\/].*\.py$',
  720. r'^ios[\\\/].*\.py$',
  721. r'^out.*[\\\/].*\.py$',
  722. r'^testing[\\\/].*\.py$',
  723. r'^third_party[\\\/].*\.py$',
  724. r'^tools[\\\/].*\.py$',
  725. # TODO(phoglund): should arguably be checked.
  726. r'^tools_webrtc[\\\/]mb[\\\/].*\.py$',
  727. r'^xcodebuild.*[\\\/].*\.py$',),
  728. pylintrc='pylintrc'))
  729. # TODO(nisse): talk/ is no more, so make below checks simpler?
  730. # WebRTC can't use the presubmit_canned_checks.PanProjectChecks function since
  731. # we need to have different license checks in talk/ and webrtc/ directories.
  732. # Instead, hand-picked checks are included below.
  733. # .m and .mm files are ObjC files. For simplicity we will consider .h files in
  734. # ObjC subdirectories ObjC headers.
  735. objc_filter_list = (r'.+\.m$', r'.+\.mm$', r'.+objc\/.+\.h$')
  736. # Skip long-lines check for DEPS and GN files.
  737. build_file_filter_list = (r'.+\.gn$', r'.+\.gni$', 'DEPS')
  738. # Also we will skip most checks for third_party directory.
  739. third_party_filter_list = (r'^third_party[\\\/].+',)
  740. eighty_char_sources = lambda x: input_api.FilterSourceFile(x,
  741. black_list=build_file_filter_list + objc_filter_list +
  742. third_party_filter_list)
  743. hundred_char_sources = lambda x: input_api.FilterSourceFile(x,
  744. white_list=objc_filter_list)
  745. non_third_party_sources = lambda x: input_api.FilterSourceFile(x,
  746. black_list=third_party_filter_list)
  747. results.extend(input_api.canned_checks.CheckLongLines(
  748. input_api, output_api, maxlen=80, source_file_filter=eighty_char_sources))
  749. results.extend(input_api.canned_checks.CheckLongLines(
  750. input_api, output_api, maxlen=100,
  751. source_file_filter=hundred_char_sources))
  752. results.extend(input_api.canned_checks.CheckChangeHasNoTabs(
  753. input_api, output_api, source_file_filter=non_third_party_sources))
  754. results.extend(input_api.canned_checks.CheckChangeHasNoStrayWhitespace(
  755. input_api, output_api, source_file_filter=non_third_party_sources))
  756. results.extend(input_api.canned_checks.CheckAuthorizedAuthor(
  757. input_api, output_api, bot_whitelist=[
  758. 'chromium-webrtc-autoroll@webrtc-ci.iam.gserviceaccount.com'
  759. ]))
  760. results.extend(input_api.canned_checks.CheckChangeTodoHasOwner(
  761. input_api, output_api, source_file_filter=non_third_party_sources))
  762. results.extend(input_api.canned_checks.CheckPatchFormatted(
  763. input_api, output_api))
  764. results.extend(CheckNativeApiHeaderChanges(input_api, output_api))
  765. results.extend(CheckNoIOStreamInHeaders(
  766. input_api, output_api, source_file_filter=non_third_party_sources))
  767. results.extend(CheckNoPragmaOnce(
  768. input_api, output_api, source_file_filter=non_third_party_sources))
  769. results.extend(CheckNoFRIEND_TEST(
  770. input_api, output_api, source_file_filter=non_third_party_sources))
  771. results.extend(CheckGnChanges(input_api, output_api))
  772. results.extend(CheckUnwantedDependencies(
  773. input_api, output_api, source_file_filter=non_third_party_sources))
  774. results.extend(CheckJSONParseErrors(
  775. input_api, output_api, source_file_filter=non_third_party_sources))
  776. results.extend(RunPythonTests(input_api, output_api))
  777. results.extend(CheckUsageOfGoogleProtobufNamespace(
  778. input_api, output_api, source_file_filter=non_third_party_sources))
  779. results.extend(CheckOrphanHeaders(
  780. input_api, output_api, source_file_filter=non_third_party_sources))
  781. results.extend(CheckNewlineAtTheEndOfProtoFiles(
  782. input_api, output_api, source_file_filter=non_third_party_sources))
  783. results.extend(CheckNoStreamUsageIsAdded(
  784. input_api, output_api, non_third_party_sources))
  785. results.extend(CheckNoTestCaseUsageIsAdded(
  786. input_api, output_api, non_third_party_sources))
  787. results.extend(CheckAddedDepsHaveTargetApprovals(input_api, output_api))
  788. results.extend(CheckApiDepsFileIsUpToDate(input_api, output_api))
  789. results.extend(CheckAbslMemoryInclude(
  790. input_api, output_api, non_third_party_sources))
  791. results.extend(CheckBannedAbslMakeUnique(
  792. input_api, output_api, non_third_party_sources))
  793. return results
  794. def CheckApiDepsFileIsUpToDate(input_api, output_api):
  795. """Check that 'include_rules' in api/DEPS is up to date.
  796. The file api/DEPS must be kept up to date in order to avoid to avoid to
  797. include internal header from WebRTC's api/ headers.
  798. This check is focused on ensuring that 'include_rules' contains a deny
  799. rule for each root level directory. More focused allow rules can be
  800. added to 'specific_include_rules'.
  801. """
  802. results = []
  803. api_deps = os.path.join(input_api.PresubmitLocalPath(), 'api', 'DEPS')
  804. with open(api_deps) as f:
  805. deps_content = _ParseDeps(f.read())
  806. include_rules = deps_content.get('include_rules', [])
  807. dirs_to_skip = set(['api', 'docs'])
  808. # Only check top level directories affected by the current CL.
  809. dirs_to_check = set()
  810. for f in input_api.AffectedFiles():
  811. path_tokens = [t for t in f.LocalPath().split(os.sep) if t]
  812. if len(path_tokens) > 1:
  813. if (path_tokens[0] not in dirs_to_skip and
  814. os.path.isdir(os.path.join(input_api.PresubmitLocalPath(),
  815. path_tokens[0]))):
  816. dirs_to_check.add(path_tokens[0])
  817. missing_include_rules = set()
  818. for p in dirs_to_check:
  819. rule = '-%s' % p
  820. if rule not in include_rules:
  821. missing_include_rules.add(rule)
  822. if missing_include_rules:
  823. error_msg = [
  824. 'include_rules = [\n',
  825. ' ...\n',
  826. ]
  827. for r in sorted(missing_include_rules):
  828. error_msg.append(' "%s",\n' % str(r))
  829. error_msg.append(' ...\n')
  830. error_msg.append(']\n')
  831. results.append(output_api.PresubmitError(
  832. 'New root level directory detected! WebRTC api/ headers should '
  833. 'not #include headers from \n'
  834. 'the new directory, so please update "include_rules" in file\n'
  835. '"%s". Example:\n%s\n' % (api_deps, ''.join(error_msg))))
  836. return results
  837. def CheckBannedAbslMakeUnique(input_api, output_api, source_file_filter):
  838. file_filter = lambda f: (f.LocalPath().endswith(('.cc', '.h'))
  839. and source_file_filter(f))
  840. files = []
  841. for f in input_api.AffectedFiles(
  842. include_deletes=False, file_filter=file_filter):
  843. for _, line in f.ChangedContents():
  844. if 'absl::make_unique' in line:
  845. files.append(f)
  846. break
  847. if len(files):
  848. return [output_api.PresubmitError(
  849. 'Please use std::make_unique instead of absl::make_unique.\n'
  850. 'Affected files:',
  851. files)]
  852. return []
  853. def CheckAbslMemoryInclude(input_api, output_api, source_file_filter):
  854. pattern = input_api.re.compile(
  855. r'^#include\s*"absl/memory/memory.h"', input_api.re.MULTILINE)
  856. file_filter = lambda f: (f.LocalPath().endswith(('.cc', '.h'))
  857. and source_file_filter(f))
  858. files = []
  859. for f in input_api.AffectedFiles(
  860. include_deletes=False, file_filter=file_filter):
  861. contents = input_api.ReadFile(f)
  862. if pattern.search(contents):
  863. continue
  864. for _, line in f.ChangedContents():
  865. if 'absl::WrapUnique' in line:
  866. files.append(f)
  867. break
  868. if len(files):
  869. return [output_api.PresubmitError(
  870. 'Please include "absl/memory/memory.h" header for absl::WrapUnique.\n'
  871. 'This header may or may not be included transitively depending on the '
  872. 'C++ standard version.',
  873. files)]
  874. return []
  875. def CheckChangeOnUpload(input_api, output_api):
  876. results = []
  877. results.extend(CommonChecks(input_api, output_api))
  878. results.extend(CheckGnGen(input_api, output_api))
  879. results.extend(
  880. input_api.canned_checks.CheckGNFormatted(input_api, output_api))
  881. return results
  882. def CheckChangeOnCommit(input_api, output_api):
  883. results = []
  884. results.extend(CommonChecks(input_api, output_api))
  885. results.extend(VerifyNativeApiHeadersListIsValid(input_api, output_api))
  886. results.extend(input_api.canned_checks.CheckOwners(input_api, output_api))
  887. results.extend(input_api.canned_checks.CheckChangeWasUploaded(
  888. input_api, output_api))
  889. results.extend(input_api.canned_checks.CheckChangeHasDescription(
  890. input_api, output_api))
  891. results.extend(CheckChangeHasBugField(input_api, output_api))
  892. results.extend(CheckCommitMessageBugEntry(input_api, output_api))
  893. results.extend(input_api.canned_checks.CheckTreeIsOpen(
  894. input_api, output_api,
  895. json_url='http://webrtc-status.appspot.com/current?format=json'))
  896. return results
  897. def CheckOrphanHeaders(input_api, output_api, source_file_filter):
  898. # We need to wait until we have an input_api object and use this
  899. # roundabout construct to import prebubmit_checks_lib because this file is
  900. # eval-ed and thus doesn't have __file__.
  901. error_msg = """{} should be listed in {}."""
  902. results = []
  903. orphan_blacklist = [
  904. os.path.join('tools_webrtc', 'ios', 'SDK'),
  905. ]
  906. with _AddToPath(input_api.os_path.join(
  907. input_api.PresubmitLocalPath(), 'tools_webrtc', 'presubmit_checks_lib')):
  908. from check_orphan_headers import GetBuildGnPathFromFilePath
  909. from check_orphan_headers import IsHeaderInBuildGn
  910. file_filter = lambda x: input_api.FilterSourceFile(
  911. x, black_list=orphan_blacklist) and source_file_filter(x)
  912. for f in input_api.AffectedSourceFiles(file_filter):
  913. if f.LocalPath().endswith('.h'):
  914. file_path = os.path.abspath(f.LocalPath())
  915. root_dir = os.getcwd()
  916. gn_file_path = GetBuildGnPathFromFilePath(file_path, os.path.exists,
  917. root_dir)
  918. in_build_gn = IsHeaderInBuildGn(file_path, gn_file_path)
  919. if not in_build_gn:
  920. results.append(output_api.PresubmitError(error_msg.format(
  921. f.LocalPath(), os.path.relpath(gn_file_path))))
  922. return results
  923. def CheckNewlineAtTheEndOfProtoFiles(input_api, output_api, source_file_filter):
  924. """Checks that all .proto files are terminated with a newline."""
  925. error_msg = 'File {} must end with exactly one newline.'
  926. results = []
  927. file_filter = lambda x: input_api.FilterSourceFile(
  928. x, white_list=(r'.+\.proto$',)) and source_file_filter(x)
  929. for f in input_api.AffectedSourceFiles(file_filter):
  930. file_path = f.LocalPath()
  931. with open(file_path) as f:
  932. lines = f.readlines()
  933. if len(lines) > 0 and not lines[-1].endswith('\n'):
  934. results.append(output_api.PresubmitError(error_msg.format(file_path)))
  935. return results
  936. def _ExtractAddRulesFromParsedDeps(parsed_deps):
  937. """Extract the rules that add dependencies from a parsed DEPS file.
  938. Args:
  939. parsed_deps: the locals dictionary from evaluating the DEPS file."""
  940. add_rules = set()
  941. add_rules.update([
  942. rule[1:] for rule in parsed_deps.get('include_rules', [])
  943. if rule.startswith('+') or rule.startswith('!')
  944. ])
  945. for _, rules in parsed_deps.get('specific_include_rules',
  946. {}).iteritems():
  947. add_rules.update([
  948. rule[1:] for rule in rules
  949. if rule.startswith('+') or rule.startswith('!')
  950. ])
  951. return add_rules
  952. def _ParseDeps(contents):
  953. """Simple helper for parsing DEPS files."""
  954. # Stubs for handling special syntax in the root DEPS file.
  955. class VarImpl(object):
  956. def __init__(self, local_scope):
  957. self._local_scope = local_scope
  958. def Lookup(self, var_name):
  959. """Implements the Var syntax."""
  960. try:
  961. return self._local_scope['vars'][var_name]
  962. except KeyError:
  963. raise Exception('Var is not defined: %s' % var_name)
  964. local_scope = {}
  965. global_scope = {
  966. 'Var': VarImpl(local_scope).Lookup,
  967. }
  968. exec contents in global_scope, local_scope
  969. return local_scope
  970. def _CalculateAddedDeps(os_path, old_contents, new_contents):
  971. """Helper method for _CheckAddedDepsHaveTargetApprovals. Returns
  972. a set of DEPS entries that we should look up.
  973. For a directory (rather than a specific filename) we fake a path to
  974. a specific filename by adding /DEPS. This is chosen as a file that
  975. will seldom or never be subject to per-file include_rules.
  976. """
  977. # We ignore deps entries on auto-generated directories.
  978. auto_generated_dirs = ['grit', 'jni']
  979. old_deps = _ExtractAddRulesFromParsedDeps(_ParseDeps(old_contents))
  980. new_deps = _ExtractAddRulesFromParsedDeps(_ParseDeps(new_contents))
  981. added_deps = new_deps.difference(old_deps)
  982. results = set()
  983. for added_dep in added_deps:
  984. if added_dep.split('/')[0] in auto_generated_dirs:
  985. continue
  986. # Assume that a rule that ends in .h is a rule for a specific file.
  987. if added_dep.endswith('.h'):
  988. results.add(added_dep)
  989. else:
  990. results.add(os_path.join(added_dep, 'DEPS'))
  991. return results
  992. def CheckAddedDepsHaveTargetApprovals(input_api, output_api):
  993. """When a dependency prefixed with + is added to a DEPS file, we
  994. want to make sure that the change is reviewed by an OWNER of the
  995. target file or directory, to avoid layering violations from being
  996. introduced. This check verifies that this happens.
  997. """
  998. virtual_depended_on_files = set()
  999. file_filter = lambda f: not input_api.re.match(
  1000. r"^third_party[\\\/](WebKit|blink)[\\\/].*", f.LocalPath())
  1001. for f in input_api.AffectedFiles(include_deletes=False,
  1002. file_filter=file_filter):
  1003. filename = input_api.os_path.basename(f.LocalPath())
  1004. if filename == 'DEPS':
  1005. virtual_depended_on_files.update(_CalculateAddedDeps(
  1006. input_api.os_path,
  1007. '\n'.join(f.OldContents()),
  1008. '\n'.join(f.NewContents())))
  1009. if not virtual_depended_on_files:
  1010. return []
  1011. if input_api.is_committing:
  1012. if input_api.tbr:
  1013. return [output_api.PresubmitNotifyResult(
  1014. '--tbr was specified, skipping OWNERS check for DEPS additions')]
  1015. if input_api.dry_run:
  1016. return [output_api.PresubmitNotifyResult(
  1017. 'This is a dry run, skipping OWNERS check for DEPS additions')]
  1018. if not input_api.change.issue:
  1019. return [output_api.PresubmitError(
  1020. "DEPS approval by OWNERS check failed: this change has "
  1021. "no change number, so we can't check it for approvals.")]
  1022. output = output_api.PresubmitError
  1023. else:
  1024. output = output_api.PresubmitNotifyResult
  1025. owners_db = input_api.owners_db
  1026. owner_email, reviewers = (
  1027. input_api.canned_checks.GetCodereviewOwnerAndReviewers(
  1028. input_api,
  1029. owners_db.email_regexp,
  1030. approval_needed=input_api.is_committing))
  1031. owner_email = owner_email or input_api.change.author_email
  1032. reviewers_plus_owner = set(reviewers)
  1033. if owner_email:
  1034. reviewers_plus_owner.add(owner_email)
  1035. missing_files = owners_db.files_not_covered_by(virtual_depended_on_files,
  1036. reviewers_plus_owner)
  1037. # We strip the /DEPS part that was added by
  1038. # _FilesToCheckForIncomingDeps to fake a path to a file in a
  1039. # directory.
  1040. def StripDeps(path):
  1041. start_deps = path.rfind('/DEPS')
  1042. if start_deps != -1:
  1043. return path[:start_deps]
  1044. else:
  1045. return path
  1046. unapproved_dependencies = ["'+%s'," % StripDeps(path)
  1047. for path in missing_files]
  1048. if unapproved_dependencies:
  1049. output_list = [
  1050. output('You need LGTM from owners of depends-on paths in DEPS that were '
  1051. 'modified in this CL:\n %s' %
  1052. '\n '.join(sorted(unapproved_dependencies)))]
  1053. suggested_owners = owners_db.reviewers_for(missing_files, owner_email)
  1054. output_list.append(output(
  1055. 'Suggested missing target path OWNERS:\n %s' %
  1056. '\n '.join(suggested_owners or [])))
  1057. return output_list
  1058. return []