PageRenderTime 41ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/cc/PRESUBMIT.py

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