blob: c26129430db20605f4eccdce5abd5037a6c427c5 [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 = []
28 notreached_files = []
29
30 for f in input_api.AffectedSourceFiles(source_file_filter):
31 contents = input_api.ReadFile(f, 'rb')
32 # WebKit ASSERT() is not allowed.
[email protected]f4a4b0e2012-10-22 22:01:3733 if re.search(r"\bASSERT\(", contents):
[email protected]1d993172012-10-18 18:15:0434 assert_files.append(f.LocalPath())
35 # WebKit ASSERT_NOT_REACHED() is not allowed.
36 if re.search(r"ASSERT_NOT_REACHED\(", contents):
37 notreached_files.append(f.LocalPath())
38
39 if assert_files:
40 return [output_api.PresubmitError(
41 'These files use ASSERT instead of using DCHECK:',
42 items=assert_files)]
43 if notreached_files:
44 return [output_api.PresubmitError(
45 'These files use ASSERT_NOT_REACHED instead of using NOTREACHED:',
46 items=notreached_files)]
47 return []
48
[email protected]81d205442013-07-29 21:42:0349def CheckStdAbs(input_api, output_api,
50 white_list=CC_SOURCE_FILES, black_list=None):
51 black_list = tuple(black_list or input_api.DEFAULT_BLACK_LIST)
52 source_file_filter = lambda x: input_api.FilterSourceFile(x,
53 white_list,
54 black_list)
55
56 using_std_abs_files = []
57 found_fabs_files = []
58 missing_std_prefix_files = []
59
60 for f in input_api.AffectedSourceFiles(source_file_filter):
61 contents = input_api.ReadFile(f, 'rb')
62 if re.search(r"using std::f?abs;", contents):
63 using_std_abs_files.append(f.LocalPath())
64 if re.search(r"\bfabsf?\(", contents):
65 found_fabs_files.append(f.LocalPath());
[email protected]dbddc7462013-09-06 06:33:3166
67 no_std_prefix = r"(?<!std::)"
68 # Matches occurrences of abs/absf/fabs/fabsf without a "std::" prefix.
69 abs_without_prefix = r"%s(\babsf?\()" % no_std_prefix
70 fabs_without_prefix = r"%s(\bfabsf?\()" % no_std_prefix
71 # Skips matching any lines that have "// NOLINT".
72 no_nolint = r"(?![^\n]*//\s+NOLINT)"
73
74 expression = re.compile("(%s|%s)%s" %
75 (abs_without_prefix, fabs_without_prefix, no_nolint))
76 if expression.search(contents):
[email protected]81d205442013-07-29 21:42:0377 missing_std_prefix_files.append(f.LocalPath())
78
79 result = []
80 if using_std_abs_files:
81 result.append(output_api.PresubmitError(
82 'These files have "using std::abs" which is not permitted.',
83 items=using_std_abs_files))
84 if found_fabs_files:
85 result.append(output_api.PresubmitError(
86 'std::abs() should be used instead of std::fabs() for consistency.',
87 items=found_fabs_files))
88 if missing_std_prefix_files:
89 result.append(output_api.PresubmitError(
90 'These files use abs(), absf(), fabs(), or fabsf() without qualifying '
91 'the std namespace. Please use std::abs() in all places.',
92 items=missing_std_prefix_files))
93 return result
94
[email protected]7add2e0b2013-04-23 05:16:4295def CheckPassByValue(input_api,
96 output_api,
97 white_list=CC_SOURCE_FILES,
98 black_list=None):
99 black_list = tuple(black_list or input_api.DEFAULT_BLACK_LIST)
100 source_file_filter = lambda x: input_api.FilterSourceFile(x,
101 white_list,
102 black_list)
103
104 local_errors = []
105
106 # Well-defined simple classes containing only <= 4 ints, or <= 2 floats.
107 pass_by_value_types = ['base::Time',
108 'base::TimeTicks',
[email protected]7add2e0b2013-04-23 05:16:42109 ]
110
111 for f in input_api.AffectedSourceFiles(source_file_filter):
112 contents = input_api.ReadFile(f, 'rb')
113 match = re.search(
114 r'\bconst +' + '(?P<type>(%s))&' %
115 string.join(pass_by_value_types, '|'),
116 contents)
117 if match:
118 local_errors.append(output_api.PresubmitError(
119 '%s passes %s by const ref instead of by value.' %
120 (f.LocalPath(), match.group('type'))))
121 return local_errors
[email protected]d936f902013-01-06 05:08:07122
[email protected]6dc0b6f2013-06-26 20:21:59123def CheckTodos(input_api, output_api):
124 errors = []
125
126 source_file_filter = lambda x: x
127 for f in input_api.AffectedSourceFiles(source_file_filter):
128 contents = input_api.ReadFile(f, 'rb')
[email protected]932aff42013-06-27 12:59:27129 if ('FIX'+'ME') in contents:
[email protected]6dc0b6f2013-06-26 20:21:59130 errors.append(f.LocalPath())
131
132 if errors:
133 return [output_api.PresubmitError(
weiliangc941dbec2014-08-28 18:56:16134 'All TODO comments should be of the form TODO(name). ' +
135 'Use TODO instead of FIX' + 'ME',
[email protected]6dc0b6f2013-06-26 20:21:59136 items=errors)]
137 return []
138
danakj6496cba2014-10-16 01:31:08139def CheckDoubleAngles(input_api, output_api, white_list=CC_SOURCE_FILES,
140 black_list=None):
141 errors = []
142
143 source_file_filter = lambda x: input_api.FilterSourceFile(x,
144 white_list,
145 black_list)
146 for f in input_api.AffectedSourceFiles(source_file_filter):
147 contents = input_api.ReadFile(f, 'rb')
148 if ('> >') in contents:
149 errors.append(f.LocalPath())
150
151 if errors:
152 return [output_api.PresubmitError('Use >> instead of > >:', items=errors)]
153 return []
154
danakj60bc3bc2016-04-09 00:24:48155def CheckUniquePtr(input_api, output_api,
danakjf446a072014-09-27 21:55:48156 white_list=CC_SOURCE_FILES, black_list=None):
157 black_list = tuple(black_list or input_api.DEFAULT_BLACK_LIST)
158 source_file_filter = lambda x: input_api.FilterSourceFile(x,
159 white_list,
160 black_list)
161 errors = []
162 for f in input_api.AffectedSourceFiles(source_file_filter):
163 for line_number, line in f.ChangedContents():
164 # Disallow:
danakj60bc3bc2016-04-09 00:24:48165 # return std::unique_ptr<T>(foo);
166 # bar = std::unique_ptr<T>(foo);
danakjf446a072014-09-27 21:55:48167 # But allow:
danakj60bc3bc2016-04-09 00:24:48168 # return std::unique_ptr<T[]>(foo);
169 # bar = std::unique_ptr<T[]>(foo);
170 if re.search(r'(=|\breturn)\s*std::unique_ptr<.*?(?<!])>\([^)]+\)', line):
danakjf446a072014-09-27 21:55:48171 errors.append(output_api.PresubmitError(
danakj60bc3bc2016-04-09 00:24:48172 ('%s:%d uses explicit std::unique_ptr constructor. ' +
ricea87fe14eb2016-09-02 04:27:07173 'Use base::MakeUnique<T>() instead.') %
174 (f.LocalPath(), line_number)))
danakjf446a072014-09-27 21:55:48175 # Disallow:
danakj60bc3bc2016-04-09 00:24:48176 # std::unique_ptr<T>()
177 if re.search(r'\bstd::unique_ptr<.*?>\(\)', line):
danakjf446a072014-09-27 21:55:48178 errors.append(output_api.PresubmitError(
danakj60bc3bc2016-04-09 00:24:48179 '%s:%d uses std::unique_ptr<T>(). Use nullptr instead.' %
danakjf446a072014-09-27 21:55:48180 (f.LocalPath(), line_number)))
danakjf446a072014-09-27 21:55:48181 return errors
182
[email protected]e51444a2013-12-10 23:05:01183def FindUnquotedQuote(contents, pos):
184 match = re.search(r"(?<!\\)(?P<quote>\")", contents[pos:])
185 return -1 if not match else match.start("quote") + pos
186
[email protected]3f52c8932014-06-13 08:46:38187def FindUselessIfdefs(input_api, output_api):
188 errors = []
189 source_file_filter = lambda x: x
190 for f in input_api.AffectedSourceFiles(source_file_filter):
191 contents = input_api.ReadFile(f, 'rb')
192 if re.search(r'#if\s*0\s', contents):
193 errors.append(f.LocalPath())
194 if errors:
195 return [output_api.PresubmitError(
196 'Don\'t use #if '+'0; just delete the code.',
197 items=errors)]
198 return []
199
[email protected]e51444a2013-12-10 23:05:01200def FindNamespaceInBlock(pos, namespace, contents, whitelist=[]):
201 open_brace = -1
202 close_brace = -1
203 quote = -1
204 name = -1
205 brace_count = 1
206 quote_count = 0
207 while pos < len(contents) and brace_count > 0:
208 if open_brace < pos: open_brace = contents.find("{", pos)
209 if close_brace < pos: close_brace = contents.find("}", pos)
210 if quote < pos: quote = FindUnquotedQuote(contents, pos)
211 if name < pos: name = contents.find(("%s::" % namespace), pos)
212
213 if name < 0:
214 return False # The namespace is not used at all.
215 if open_brace < 0:
216 open_brace = len(contents)
217 if close_brace < 0:
218 close_brace = len(contents)
219 if quote < 0:
220 quote = len(contents)
221
222 next = min(open_brace, min(close_brace, min(quote, name)))
223
224 if next == open_brace:
225 brace_count += 1
226 elif next == close_brace:
227 brace_count -= 1
228 elif next == quote:
229 quote_count = 0 if quote_count else 1
230 elif next == name and not quote_count:
231 in_whitelist = False
232 for w in whitelist:
233 if re.match(w, contents[next:]):
234 in_whitelist = True
235 break
236 if not in_whitelist:
237 return True
238 pos = next + 1
239 return False
240
241# Checks for the use of cc:: within the cc namespace, which is usually
242# redundant.
243def CheckNamespace(input_api, output_api):
244 errors = []
245
246 source_file_filter = lambda x: x
247 for f in input_api.AffectedSourceFiles(source_file_filter):
248 contents = input_api.ReadFile(f, 'rb')
249 match = re.search(r'namespace\s*cc\s*{', contents)
250 if match:
vmpstra370ef52015-11-18 10:41:28251 whitelist = []
[email protected]e51444a2013-12-10 23:05:01252 if FindNamespaceInBlock(match.end(), 'cc', contents, whitelist=whitelist):
253 errors.append(f.LocalPath())
254
255 if errors:
256 return [output_api.PresubmitError(
257 'Do not use cc:: inside of the cc namespace.',
258 items=errors)]
259 return []
260
[email protected]d2f1d582014-05-01 08:43:53261def CheckForUseOfWrongClock(input_api,
262 output_api,
263 white_list=CC_SOURCE_FILES,
264 black_list=None):
265 """Make sure new lines of code don't use a clock susceptible to skew."""
266 black_list = tuple(black_list or input_api.DEFAULT_BLACK_LIST)
267 source_file_filter = lambda x: input_api.FilterSourceFile(x,
268 white_list,
269 black_list)
270 # Regular expression that should detect any explicit references to the
271 # base::Time type (or base::Clock/DefaultClock), whether in using decls,
272 # typedefs, or to call static methods.
273 base_time_type_pattern = r'(^|\W)base::(Time|Clock|DefaultClock)(\W|$)'
274
275 # Regular expression that should detect references to the base::Time class
276 # members, such as a call to base::Time::Now.
277 base_time_member_pattern = r'(^|\W)(Time|Clock|DefaultClock)::'
278
279 # Regular expression to detect "using base::Time" declarations. We want to
280 # prevent these from triggerring a warning. For example, it's perfectly
281 # reasonable for code to be written like this:
282 #
283 # using base::Time;
284 # ...
285 # int64 foo_us = foo_s * Time::kMicrosecondsPerSecond;
286 using_base_time_decl_pattern = r'^\s*using\s+(::)?base::Time\s*;'
287
288 # Regular expression to detect references to the kXXX constants in the
289 # base::Time class. We want to prevent these from triggerring a warning.
290 base_time_konstant_pattern = r'(^|\W)Time::k\w+'
291
292 problem_re = input_api.re.compile(
293 r'(' + base_time_type_pattern + r')|(' + base_time_member_pattern + r')')
294 exception_re = input_api.re.compile(
295 r'(' + using_base_time_decl_pattern + r')|(' +
296 base_time_konstant_pattern + r')')
297 problems = []
298 for f in input_api.AffectedSourceFiles(source_file_filter):
299 for line_number, line in f.ChangedContents():
300 if problem_re.search(line):
301 if not exception_re.search(line):
302 problems.append(
303 ' %s:%d\n %s' % (f.LocalPath(), line_number, line.strip()))
304
305 if problems:
306 return [output_api.PresubmitPromptOrNotify(
307 'You added one or more references to the base::Time class and/or one\n'
308 'of its member functions (or base::Clock/DefaultClock). In cc code,\n'
309 'it is most certainly incorrect! Instead use base::TimeTicks.\n\n'
310 '\n'.join(problems))]
311 else:
312 return []
[email protected]6dc0b6f2013-06-26 20:21:59313
[email protected]1d993172012-10-18 18:15:04314def CheckChangeOnUpload(input_api, output_api):
315 results = []
316 results += CheckAsserts(input_api, output_api)
[email protected]81d205442013-07-29 21:42:03317 results += CheckStdAbs(input_api, output_api)
[email protected]7add2e0b2013-04-23 05:16:42318 results += CheckPassByValue(input_api, output_api)
[email protected]cf824592013-04-09 05:46:00319 results += CheckChangeLintsClean(input_api, output_api)
[email protected]6dc0b6f2013-06-26 20:21:59320 results += CheckTodos(input_api, output_api)
danakj6496cba2014-10-16 01:31:08321 results += CheckDoubleAngles(input_api, output_api)
danakj60bc3bc2016-04-09 00:24:48322 results += CheckUniquePtr(input_api, output_api)
[email protected]e51444a2013-12-10 23:05:01323 results += CheckNamespace(input_api, output_api)
[email protected]d2f1d582014-05-01 08:43:53324 results += CheckForUseOfWrongClock(input_api, output_api)
[email protected]3f52c8932014-06-13 08:46:38325 results += FindUselessIfdefs(input_api, output_api)
[email protected]4f0fd022014-01-30 08:05:22326 results += input_api.canned_checks.CheckPatchFormatted(input_api, output_api)
[email protected]1d993172012-10-18 18:15:04327 return results
328
mithrocf7887522015-05-21 07:26:32329def PostUploadHook(cl, change, output_api):
330 """git cl upload will call this hook after the issue is created/modified.
331
332 This hook adds extra try bots list to the CL description in order to run
333 Blink tests in addition to CQ try bots.
334 """
335 rietveld_obj = cl.RpcServer()
336 issue = cl.issue
337 description = rietveld_obj.get_description(issue)
338 if re.search(r'^CQ_INCLUDE_TRYBOTS=.*', description, re.M | re.I):
339 return []
340
sunnypsb34b8622016-01-29 03:06:51341 bots = [
qyearsleyacb45c52016-07-27 16:51:27342 'master.tryserver.blink:linux_precise_blink_rel',
sunnypsb34b8622016-01-29 03:06:51343 ]
mithrocf7887522015-05-21 07:26:32344
345 results = []
346 new_description = description
sunnypsb34b8622016-01-29 03:06:51347 new_description += '\nCQ_INCLUDE_TRYBOTS=%s' % ';'.join(bots)
mithrocf7887522015-05-21 07:26:32348 results.append(output_api.PresubmitNotifyResult(
sunnypsb34b8622016-01-29 03:06:51349 'Automatically added Blink trybots to run Blink tests on CQ.'))
mithrocf7887522015-05-21 07:26:32350
351 if new_description != description:
352 rietveld_obj.update_description(issue, new_description)
353
354 return results