blob: d160eac29fe46711234ef2b00de42235de081c01 [file] [log] [blame]
[email protected]69085bc52012-10-15 16:41:581# 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
5"""Top-level presubmit script for cc.
6
[email protected]94be7f702014-02-03 19:06:457See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
8for more details about the presubmit API built into depot_tools.
[email protected]69085bc52012-10-15 16:41:589"""
10
[email protected]1d993172012-10-18 18:15:0411import re
[email protected]7add2e0b2013-04-23 05:16:4212import string
[email protected]1d993172012-10-18 18:15:0413
tfarina26ef0f02015-02-02 14:50:2514CC_SOURCE_FILES=(r'^cc[\\/].*\.(cc|h)$',)
[email protected]1d993172012-10-18 18:15:0415
[email protected]cf824592013-04-09 05:46:0016def CheckChangeLintsClean(input_api, output_api):
[email protected]cf824592013-04-09 05:46:0017 source_filter = lambda x: input_api.FilterSourceFile(
18 x, white_list=CC_SOURCE_FILES, black_list=None)
[email protected]cf824592013-04-09 05:46:0019
tfarina2d649012015-02-26 12:58:2620 return input_api.canned_checks.CheckChangeLintsClean(
21 input_api, output_api, source_filter, lint_filters=[], verbose_level=1)
[email protected]cf824592013-04-09 05:46:0022
[email protected]1d993172012-10-18 18:15:0423def CheckAsserts(input_api, output_api, white_list=CC_SOURCE_FILES, black_list=None):
24 black_list = tuple(black_list or input_api.DEFAULT_BLACK_LIST)
25 source_file_filter = lambda x: input_api.FilterSourceFile(x, white_list, black_list)
26
27 assert_files = []
[email protected]1d993172012-10-18 18:15:0428
29 for f in input_api.AffectedSourceFiles(source_file_filter):
30 contents = input_api.ReadFile(f, 'rb')
31 # WebKit ASSERT() is not allowed.
[email protected]f4a4b0e2012-10-22 22:01:3732 if re.search(r"\bASSERT\(", contents):
[email protected]1d993172012-10-18 18:15:0433 assert_files.append(f.LocalPath())
[email protected]1d993172012-10-18 18:15:0434
35 if assert_files:
36 return [output_api.PresubmitError(
37 'These files use ASSERT instead of using DCHECK:',
38 items=assert_files)]
[email protected]1d993172012-10-18 18:15:0439 return []
40
[email protected]81d205442013-07-29 21:42:0341def CheckStdAbs(input_api, output_api,
42 white_list=CC_SOURCE_FILES, black_list=None):
43 black_list = tuple(black_list or input_api.DEFAULT_BLACK_LIST)
44 source_file_filter = lambda x: input_api.FilterSourceFile(x,
45 white_list,
46 black_list)
47
48 using_std_abs_files = []
49 found_fabs_files = []
50 missing_std_prefix_files = []
51
52 for f in input_api.AffectedSourceFiles(source_file_filter):
53 contents = input_api.ReadFile(f, 'rb')
54 if re.search(r"using std::f?abs;", contents):
55 using_std_abs_files.append(f.LocalPath())
56 if re.search(r"\bfabsf?\(", contents):
57 found_fabs_files.append(f.LocalPath());
[email protected]dbddc7462013-09-06 06:33:3158
59 no_std_prefix = r"(?<!std::)"
60 # Matches occurrences of abs/absf/fabs/fabsf without a "std::" prefix.
61 abs_without_prefix = r"%s(\babsf?\()" % no_std_prefix
62 fabs_without_prefix = r"%s(\bfabsf?\()" % no_std_prefix
63 # Skips matching any lines that have "// NOLINT".
64 no_nolint = r"(?![^\n]*//\s+NOLINT)"
65
66 expression = re.compile("(%s|%s)%s" %
67 (abs_without_prefix, fabs_without_prefix, no_nolint))
68 if expression.search(contents):
[email protected]81d205442013-07-29 21:42:0369 missing_std_prefix_files.append(f.LocalPath())
70
71 result = []
72 if using_std_abs_files:
73 result.append(output_api.PresubmitError(
74 'These files have "using std::abs" which is not permitted.',
75 items=using_std_abs_files))
76 if found_fabs_files:
77 result.append(output_api.PresubmitError(
78 'std::abs() should be used instead of std::fabs() for consistency.',
79 items=found_fabs_files))
80 if missing_std_prefix_files:
81 result.append(output_api.PresubmitError(
82 'These files use abs(), absf(), fabs(), or fabsf() without qualifying '
83 'the std namespace. Please use std::abs() in all places.',
84 items=missing_std_prefix_files))
85 return result
86
[email protected]7add2e0b2013-04-23 05:16:4287def CheckPassByValue(input_api,
88 output_api,
89 white_list=CC_SOURCE_FILES,
90 black_list=None):
91 black_list = tuple(black_list or input_api.DEFAULT_BLACK_LIST)
92 source_file_filter = lambda x: input_api.FilterSourceFile(x,
93 white_list,
94 black_list)
95
96 local_errors = []
97
kylechare68cc4a2017-04-05 18:01:0598 # Well-defined simple classes the same size as a primitive type.
[email protected]7add2e0b2013-04-23 05:16:4299 pass_by_value_types = ['base::Time',
100 'base::TimeTicks',
[email protected]7add2e0b2013-04-23 05:16:42101 ]
102
103 for f in input_api.AffectedSourceFiles(source_file_filter):
104 contents = input_api.ReadFile(f, 'rb')
105 match = re.search(
106 r'\bconst +' + '(?P<type>(%s))&' %
107 string.join(pass_by_value_types, '|'),
108 contents)
109 if match:
110 local_errors.append(output_api.PresubmitError(
111 '%s passes %s by const ref instead of by value.' %
112 (f.LocalPath(), match.group('type'))))
113 return local_errors
[email protected]d936f902013-01-06 05:08:07114
[email protected]6dc0b6f2013-06-26 20:21:59115def CheckTodos(input_api, output_api):
116 errors = []
117
118 source_file_filter = lambda x: x
119 for f in input_api.AffectedSourceFiles(source_file_filter):
120 contents = input_api.ReadFile(f, 'rb')
[email protected]932aff42013-06-27 12:59:27121 if ('FIX'+'ME') in contents:
[email protected]6dc0b6f2013-06-26 20:21:59122 errors.append(f.LocalPath())
123
124 if errors:
125 return [output_api.PresubmitError(
kylechare68cc4a2017-04-05 18:01:05126 'All TODO comments should be of the form TODO(name/bug). ' +
weiliangc941dbec2014-08-28 18:56:16127 'Use TODO instead of FIX' + 'ME',
[email protected]6dc0b6f2013-06-26 20:21:59128 items=errors)]
129 return []
130
danakj6496cba2014-10-16 01:31:08131def CheckDoubleAngles(input_api, output_api, white_list=CC_SOURCE_FILES,
132 black_list=None):
133 errors = []
134
135 source_file_filter = lambda x: input_api.FilterSourceFile(x,
136 white_list,
137 black_list)
138 for f in input_api.AffectedSourceFiles(source_file_filter):
139 contents = input_api.ReadFile(f, 'rb')
140 if ('> >') in contents:
141 errors.append(f.LocalPath())
142
143 if errors:
144 return [output_api.PresubmitError('Use >> instead of > >:', items=errors)]
145 return []
146
danakj60bc3bc2016-04-09 00:24:48147def CheckUniquePtr(input_api, output_api,
danakjf446a072014-09-27 21:55:48148 white_list=CC_SOURCE_FILES, black_list=None):
149 black_list = tuple(black_list or input_api.DEFAULT_BLACK_LIST)
150 source_file_filter = lambda x: input_api.FilterSourceFile(x,
151 white_list,
152 black_list)
153 errors = []
154 for f in input_api.AffectedSourceFiles(source_file_filter):
155 for line_number, line in f.ChangedContents():
156 # Disallow:
danakj60bc3bc2016-04-09 00:24:48157 # return std::unique_ptr<T>(foo);
158 # bar = std::unique_ptr<T>(foo);
danakjf446a072014-09-27 21:55:48159 # But allow:
danakj60bc3bc2016-04-09 00:24:48160 # return std::unique_ptr<T[]>(foo);
161 # bar = std::unique_ptr<T[]>(foo);
162 if re.search(r'(=|\breturn)\s*std::unique_ptr<.*?(?<!])>\([^)]+\)', line):
danakjf446a072014-09-27 21:55:48163 errors.append(output_api.PresubmitError(
danakj60bc3bc2016-04-09 00:24:48164 ('%s:%d uses explicit std::unique_ptr constructor. ' +
Jeremy Roman909d927b2017-08-27 18:34:09165 'Use std::make_unique<T>() instead.') %
ricea87fe14eb2016-09-02 04:27:07166 (f.LocalPath(), line_number)))
danakjf446a072014-09-27 21:55:48167 # Disallow:
danakj60bc3bc2016-04-09 00:24:48168 # std::unique_ptr<T>()
169 if re.search(r'\bstd::unique_ptr<.*?>\(\)', line):
danakjf446a072014-09-27 21:55:48170 errors.append(output_api.PresubmitError(
danakj60bc3bc2016-04-09 00:24:48171 '%s:%d uses std::unique_ptr<T>(). Use nullptr instead.' %
danakjf446a072014-09-27 21:55:48172 (f.LocalPath(), line_number)))
danakjf446a072014-09-27 21:55:48173 return errors
174
[email protected]e51444a2013-12-10 23:05:01175def FindUnquotedQuote(contents, pos):
176 match = re.search(r"(?<!\\)(?P<quote>\")", contents[pos:])
177 return -1 if not match else match.start("quote") + pos
178
[email protected]3f52c8932014-06-13 08:46:38179def FindUselessIfdefs(input_api, output_api):
180 errors = []
181 source_file_filter = lambda x: x
182 for f in input_api.AffectedSourceFiles(source_file_filter):
183 contents = input_api.ReadFile(f, 'rb')
184 if re.search(r'#if\s*0\s', contents):
185 errors.append(f.LocalPath())
186 if errors:
187 return [output_api.PresubmitError(
188 'Don\'t use #if '+'0; just delete the code.',
189 items=errors)]
190 return []
191
[email protected]e51444a2013-12-10 23:05:01192def FindNamespaceInBlock(pos, namespace, contents, whitelist=[]):
193 open_brace = -1
194 close_brace = -1
195 quote = -1
196 name = -1
197 brace_count = 1
198 quote_count = 0
199 while pos < len(contents) and brace_count > 0:
200 if open_brace < pos: open_brace = contents.find("{", pos)
201 if close_brace < pos: close_brace = contents.find("}", pos)
202 if quote < pos: quote = FindUnquotedQuote(contents, pos)
203 if name < pos: name = contents.find(("%s::" % namespace), pos)
204
205 if name < 0:
206 return False # The namespace is not used at all.
207 if open_brace < 0:
208 open_brace = len(contents)
209 if close_brace < 0:
210 close_brace = len(contents)
211 if quote < 0:
212 quote = len(contents)
213
214 next = min(open_brace, min(close_brace, min(quote, name)))
215
216 if next == open_brace:
217 brace_count += 1
218 elif next == close_brace:
219 brace_count -= 1
220 elif next == quote:
221 quote_count = 0 if quote_count else 1
222 elif next == name and not quote_count:
223 in_whitelist = False
224 for w in whitelist:
225 if re.match(w, contents[next:]):
226 in_whitelist = True
227 break
228 if not in_whitelist:
229 return True
230 pos = next + 1
231 return False
232
233# Checks for the use of cc:: within the cc namespace, which is usually
234# redundant.
235def CheckNamespace(input_api, output_api):
236 errors = []
237
238 source_file_filter = lambda x: x
239 for f in input_api.AffectedSourceFiles(source_file_filter):
240 contents = input_api.ReadFile(f, 'rb')
241 match = re.search(r'namespace\s*cc\s*{', contents)
242 if match:
vmpstra370ef52015-11-18 10:41:28243 whitelist = []
[email protected]e51444a2013-12-10 23:05:01244 if FindNamespaceInBlock(match.end(), 'cc', contents, whitelist=whitelist):
245 errors.append(f.LocalPath())
246
247 if errors:
248 return [output_api.PresubmitError(
249 'Do not use cc:: inside of the cc namespace.',
250 items=errors)]
251 return []
252
[email protected]d2f1d582014-05-01 08:43:53253def CheckForUseOfWrongClock(input_api,
254 output_api,
255 white_list=CC_SOURCE_FILES,
256 black_list=None):
257 """Make sure new lines of code don't use a clock susceptible to skew."""
258 black_list = tuple(black_list or input_api.DEFAULT_BLACK_LIST)
259 source_file_filter = lambda x: input_api.FilterSourceFile(x,
260 white_list,
261 black_list)
262 # Regular expression that should detect any explicit references to the
263 # base::Time type (or base::Clock/DefaultClock), whether in using decls,
264 # typedefs, or to call static methods.
265 base_time_type_pattern = r'(^|\W)base::(Time|Clock|DefaultClock)(\W|$)'
266
267 # Regular expression that should detect references to the base::Time class
268 # members, such as a call to base::Time::Now.
269 base_time_member_pattern = r'(^|\W)(Time|Clock|DefaultClock)::'
270
271 # Regular expression to detect "using base::Time" declarations. We want to
272 # prevent these from triggerring a warning. For example, it's perfectly
273 # reasonable for code to be written like this:
274 #
275 # using base::Time;
276 # ...
277 # int64 foo_us = foo_s * Time::kMicrosecondsPerSecond;
278 using_base_time_decl_pattern = r'^\s*using\s+(::)?base::Time\s*;'
279
280 # Regular expression to detect references to the kXXX constants in the
281 # base::Time class. We want to prevent these from triggerring a warning.
282 base_time_konstant_pattern = r'(^|\W)Time::k\w+'
283
284 problem_re = input_api.re.compile(
285 r'(' + base_time_type_pattern + r')|(' + base_time_member_pattern + r')')
286 exception_re = input_api.re.compile(
287 r'(' + using_base_time_decl_pattern + r')|(' +
288 base_time_konstant_pattern + r')')
289 problems = []
290 for f in input_api.AffectedSourceFiles(source_file_filter):
291 for line_number, line in f.ChangedContents():
292 if problem_re.search(line):
293 if not exception_re.search(line):
294 problems.append(
295 ' %s:%d\n %s' % (f.LocalPath(), line_number, line.strip()))
296
297 if problems:
298 return [output_api.PresubmitPromptOrNotify(
299 'You added one or more references to the base::Time class and/or one\n'
300 'of its member functions (or base::Clock/DefaultClock). In cc code,\n'
301 'it is most certainly incorrect! Instead use base::TimeTicks.\n\n'
302 '\n'.join(problems))]
303 else:
304 return []
[email protected]6dc0b6f2013-06-26 20:21:59305
Bo Liu67e76f02017-08-07 17:57:50306def CheckIpcUpdatedWithMojo(input_api, output_api):
307 """Make sure IPC is updated whenever Mojo serialization is updated"""
308 def match_ipc(affected_file):
309 match = re.match(r'.*_param_traits.*', affected_file.LocalPath())
310 return match is not None
311
312 def match_mojo(affected_file):
313 mojo_patterns = (r'.*_struct_traits.*', r'.*\.mojom$', r'.*\.typemap$')
314 matches = (re.match(pattern, affected_file.LocalPath())
315 for pattern in mojo_patterns)
316 return any(matches)
317
318 ipc_files = input_api.AffectedFiles(file_filter=match_ipc)
319 mojo_files = input_api.AffectedFiles(file_filter=match_mojo)
320 if mojo_files and not ipc_files:
321 return [output_api.PresubmitPromptOrNotify(
322 'Make sure to update IPC ParamTraits along with mojo types.\n\n'),]
323 return []
324
[email protected]1d993172012-10-18 18:15:04325def CheckChangeOnUpload(input_api, output_api):
326 results = []
327 results += CheckAsserts(input_api, output_api)
[email protected]81d205442013-07-29 21:42:03328 results += CheckStdAbs(input_api, output_api)
[email protected]7add2e0b2013-04-23 05:16:42329 results += CheckPassByValue(input_api, output_api)
[email protected]cf824592013-04-09 05:46:00330 results += CheckChangeLintsClean(input_api, output_api)
[email protected]6dc0b6f2013-06-26 20:21:59331 results += CheckTodos(input_api, output_api)
danakj6496cba2014-10-16 01:31:08332 results += CheckDoubleAngles(input_api, output_api)
danakj60bc3bc2016-04-09 00:24:48333 results += CheckUniquePtr(input_api, output_api)
[email protected]e51444a2013-12-10 23:05:01334 results += CheckNamespace(input_api, output_api)
[email protected]d2f1d582014-05-01 08:43:53335 results += CheckForUseOfWrongClock(input_api, output_api)
[email protected]3f52c8932014-06-13 08:46:38336 results += FindUselessIfdefs(input_api, output_api)
Bo Liu67e76f02017-08-07 17:57:50337 results += CheckIpcUpdatedWithMojo(input_api, output_api)
[email protected]1d993172012-10-18 18:15:04338 return results
339
mithrocf7887522015-05-21 07:26:32340def PostUploadHook(cl, change, output_api):
341 """git cl upload will call this hook after the issue is created/modified.
342
kbr43842632017-02-16 19:06:56343 This hook adds an extra try bot list to the CL description in order to run
Kenneth Russellfbedc5d2017-11-16 20:53:21344 Blink tests and additional GPU tests in addition to the CQ try bots.
mithrocf7887522015-05-21 07:26:32345 """
kbr43842632017-02-16 19:06:56346 return output_api.EnsureCQIncludeTrybotsAreAdded(
347 cl,
Kenneth Russellfbedc5d2017-11-16 20:53:21348 [
349 'master.tryserver.blink:linux_trusty_blink_rel',
350 'master.tryserver.chromium.android:android_optional_gpu_tests_rel',
351 ],
352 'Automatically added Blink and Android GPU trybots for CQ.')