PRESUBMIT.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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 cc.
  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. import re
  9. USE_PYTHON3 = True
  10. CC_SOURCE_FILES=(r'^cc[\\/].*\.(cc|h)$',)
  11. def CheckChangeLintsClean(input_api, output_api):
  12. allowlist = CC_SOURCE_FILES
  13. denylist = None
  14. source_filter = lambda x: input_api.FilterSourceFile(x, allowlist, denylist)
  15. return input_api.canned_checks.CheckChangeLintsClean(
  16. input_api, output_api, source_filter, lint_filters=[], verbose_level=1)
  17. def CheckAsserts(input_api, output_api, allowlist=CC_SOURCE_FILES,
  18. denylist=None):
  19. denylist = tuple(denylist or input_api.DEFAULT_FILES_TO_SKIP)
  20. source_file_filter = lambda x: input_api.FilterSourceFile(x, allowlist,
  21. denylist)
  22. assert_files = []
  23. for f in input_api.AffectedSourceFiles(source_file_filter):
  24. contents = input_api.ReadFile(f, 'rb')
  25. # WebKit ASSERT() is not allowed.
  26. if re.search(r"\bASSERT\(", contents):
  27. assert_files.append(f.LocalPath())
  28. if assert_files:
  29. return [output_api.PresubmitError(
  30. 'These files use ASSERT instead of using DCHECK:',
  31. items=assert_files)]
  32. return []
  33. def CheckStdAbs(input_api, output_api,
  34. allowlist=CC_SOURCE_FILES, denylist=None):
  35. denylist = tuple(denylist or input_api.DEFAULT_FILES_TO_SKIP)
  36. source_file_filter = lambda x: input_api.FilterSourceFile(x,
  37. allowlist,
  38. denylist)
  39. using_std_abs_files = []
  40. found_fabs_files = []
  41. missing_std_prefix_files = []
  42. for f in input_api.AffectedSourceFiles(source_file_filter):
  43. contents = input_api.ReadFile(f, 'rb')
  44. if re.search(r"using std::f?abs;", contents):
  45. using_std_abs_files.append(f.LocalPath())
  46. if re.search(r"\bfabsf?\(", contents):
  47. found_fabs_files.append(f.LocalPath());
  48. no_std_prefix = r"(?<!std::)"
  49. # Matches occurrences of abs/absf/fabs/fabsf without a "std::" prefix.
  50. abs_without_prefix = r"%s(\babsf?\()" % no_std_prefix
  51. fabs_without_prefix = r"%s(\bfabsf?\()" % no_std_prefix
  52. # Skips matching any lines that have "// NOLINT".
  53. no_nolint = r"(?![^\n]*//\s+NOLINT)"
  54. expression = re.compile("(%s|%s)%s" %
  55. (abs_without_prefix, fabs_without_prefix, no_nolint))
  56. if expression.search(contents):
  57. missing_std_prefix_files.append(f.LocalPath())
  58. result = []
  59. if using_std_abs_files:
  60. result.append(output_api.PresubmitError(
  61. 'These files have "using std::abs" which is not permitted.',
  62. items=using_std_abs_files))
  63. if found_fabs_files:
  64. result.append(output_api.PresubmitError(
  65. 'std::abs() should be used instead of std::fabs() for consistency.',
  66. items=found_fabs_files))
  67. if missing_std_prefix_files:
  68. result.append(output_api.PresubmitError(
  69. 'These files use abs(), absf(), fabs(), or fabsf() without qualifying '
  70. 'the std namespace. Please use std::abs() in all places.',
  71. items=missing_std_prefix_files))
  72. return result
  73. def CheckPassByValue(input_api,
  74. output_api,
  75. allowlist=CC_SOURCE_FILES,
  76. denylist=None):
  77. denylist = tuple(denylist or input_api.DEFAULT_FILES_TO_SKIP)
  78. source_file_filter = lambda x: input_api.FilterSourceFile(x,
  79. allowlist,
  80. denylist)
  81. local_errors = []
  82. # Well-defined simple classes the same size as a primitive type.
  83. pass_by_value_types = ['base::Time',
  84. 'base::TimeTicks',
  85. ]
  86. for f in input_api.AffectedSourceFiles(source_file_filter):
  87. contents = input_api.ReadFile(f, 'rb')
  88. sep = '|'
  89. match = re.search(
  90. r'\bconst +' + '(?P<type>(%s))&' % sep.join(pass_by_value_types),
  91. contents)
  92. if match:
  93. local_errors.append(output_api.PresubmitError(
  94. '%s passes %s by const ref instead of by value.' %
  95. (f.LocalPath(), match.group('type'))))
  96. return local_errors
  97. def CheckTodos(input_api, output_api):
  98. errors = []
  99. source_file_filter = lambda x: x
  100. for f in input_api.AffectedSourceFiles(source_file_filter):
  101. contents = input_api.ReadFile(f, 'rb')
  102. if ('FIX'+'ME') in contents:
  103. errors.append(f.LocalPath())
  104. if errors:
  105. return [output_api.PresubmitError(
  106. 'All TODO comments should be of the form TODO(name/bug). ' +
  107. 'Use TODO instead of FIX' + 'ME',
  108. items=errors)]
  109. return []
  110. def CheckDoubleAngles(input_api, output_api, allowlist=CC_SOURCE_FILES,
  111. denylist=None):
  112. errors = []
  113. source_file_filter = lambda x: input_api.FilterSourceFile(x,
  114. allowlist,
  115. denylist)
  116. for f in input_api.AffectedSourceFiles(source_file_filter):
  117. contents = input_api.ReadFile(f, 'rb')
  118. if ('> >') in contents:
  119. errors.append(f.LocalPath())
  120. if errors:
  121. return [output_api.PresubmitError('Use >> instead of > >:', items=errors)]
  122. return []
  123. def FindUnquotedQuote(contents, pos):
  124. match = re.search(r"(?<!\\)(?P<quote>\")", contents[pos:])
  125. return -1 if not match else match.start("quote") + pos
  126. def FindUselessIfdefs(input_api, output_api):
  127. errors = []
  128. source_file_filter = lambda x: x
  129. for f in input_api.AffectedSourceFiles(source_file_filter):
  130. contents = input_api.ReadFile(f, 'rb')
  131. if re.search(r'#if\s*0\s', contents):
  132. errors.append(f.LocalPath())
  133. if errors:
  134. return [output_api.PresubmitError(
  135. 'Don\'t use #if '+'0; just delete the code.',
  136. items=errors)]
  137. return []
  138. def FindNamespaceInBlock(pos, namespace, contents, allowlist=[]):
  139. open_brace = -1
  140. close_brace = -1
  141. quote = -1
  142. name = -1
  143. brace_count = 1
  144. quote_count = 0
  145. while pos < len(contents) and brace_count > 0:
  146. if open_brace < pos: open_brace = contents.find("{", pos)
  147. if close_brace < pos: close_brace = contents.find("}", pos)
  148. if quote < pos: quote = FindUnquotedQuote(contents, pos)
  149. if name < pos: name = contents.find(("%s::" % namespace), pos)
  150. if name < 0:
  151. return False # The namespace is not used at all.
  152. if open_brace < 0:
  153. open_brace = len(contents)
  154. if close_brace < 0:
  155. close_brace = len(contents)
  156. if quote < 0:
  157. quote = len(contents)
  158. next = min(open_brace, min(close_brace, min(quote, name)))
  159. if next == open_brace:
  160. brace_count += 1
  161. elif next == close_brace:
  162. brace_count -= 1
  163. elif next == quote:
  164. quote_count = 0 if quote_count else 1
  165. elif next == name and not quote_count:
  166. in_allowlist = False
  167. for w in allowlist:
  168. if re.match(w, contents[next:]):
  169. in_allowlist = True
  170. break
  171. if not in_allowlist:
  172. return True
  173. pos = next + 1
  174. return False
  175. # Checks for the use of cc:: within the cc namespace, which is usually
  176. # redundant.
  177. def CheckNamespace(input_api, output_api):
  178. errors = []
  179. source_file_filter = lambda x: x
  180. for f in input_api.AffectedSourceFiles(source_file_filter):
  181. contents = input_api.ReadFile(f, 'rb')
  182. match = re.search(r'namespace\s*cc\s*{', contents)
  183. if match:
  184. allowlist = []
  185. if FindNamespaceInBlock(match.end(), 'cc', contents, allowlist=allowlist):
  186. errors.append(f.LocalPath())
  187. if errors:
  188. return [output_api.PresubmitError(
  189. 'Do not use cc:: inside of the cc namespace.',
  190. items=errors)]
  191. return []
  192. def CheckForUseOfWrongClock(input_api,
  193. output_api,
  194. allowlist=CC_SOURCE_FILES,
  195. denylist=None):
  196. """Make sure new lines of code don't use a clock susceptible to skew."""
  197. denylist = tuple(denylist or input_api.DEFAULT_FILES_TO_SKIP)
  198. source_file_filter = lambda x: input_api.FilterSourceFile(x,
  199. allowlist,
  200. denylist)
  201. # Regular expression that should detect any explicit references to the
  202. # base::Time type (or base::Clock/DefaultClock), whether in using decls,
  203. # typedefs, or to call static methods.
  204. base_time_type_pattern = r'(^|\W)base::(Time|Clock|DefaultClock)(\W|$)'
  205. # Regular expression that should detect references to the base::Time class
  206. # members, such as a call to base::Time::Now.
  207. base_time_member_pattern = r'(^|\W)(Time|Clock|DefaultClock)::'
  208. # Regular expression to detect "using base::Time" declarations. We want to
  209. # prevent these from triggerring a warning. For example, it's perfectly
  210. # reasonable for code to be written like this:
  211. #
  212. # using base::Time;
  213. # ...
  214. # int64 foo_us = foo_s * Time::kMicrosecondsPerSecond;
  215. using_base_time_decl_pattern = r'^\s*using\s+(::)?base::Time\s*;'
  216. # Regular expression to detect references to the kXXX constants in the
  217. # base::Time class. We want to prevent these from triggerring a warning.
  218. base_time_konstant_pattern = r'(^|\W)Time::k\w+'
  219. problem_re = input_api.re.compile(
  220. r'(' + base_time_type_pattern + r')|(' + base_time_member_pattern + r')')
  221. exception_re = input_api.re.compile(
  222. r'(' + using_base_time_decl_pattern + r')|(' +
  223. base_time_konstant_pattern + r')')
  224. problems = []
  225. for f in input_api.AffectedSourceFiles(source_file_filter):
  226. for line_number, line in f.ChangedContents():
  227. if problem_re.search(line):
  228. if not exception_re.search(line):
  229. problems.append(
  230. ' %s:%d\n %s' % (f.LocalPath(), line_number, line.strip()))
  231. if problems:
  232. return [output_api.PresubmitPromptOrNotify(
  233. 'You added one or more references to the base::Time class and/or one\n'
  234. 'of its member functions (or base::Clock/DefaultClock). In cc code,\n'
  235. 'it is most certainly incorrect! Instead use base::TimeTicks.\n\n'
  236. '\n'.join(problems))]
  237. else:
  238. return []
  239. def CheckChangeOnUpload(input_api, output_api):
  240. results = []
  241. results += CheckAsserts(input_api, output_api)
  242. results += CheckStdAbs(input_api, output_api)
  243. results += CheckPassByValue(input_api, output_api)
  244. results += CheckChangeLintsClean(input_api, output_api)
  245. results += CheckTodos(input_api, output_api)
  246. results += CheckDoubleAngles(input_api, output_api)
  247. results += CheckNamespace(input_api, output_api)
  248. results += CheckForUseOfWrongClock(input_api, output_api)
  249. results += FindUselessIfdefs(input_api, output_api)
  250. return results