blob: f381684bfbc991e110a1087f2e9b750cb255e530 [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
14CC_SOURCE_FILES=(r'^cc/.*\.(cc|h)$',)
15
[email protected]cf824592013-04-09 05:46:0016def CheckChangeLintsClean(input_api, output_api):
[email protected]16f5cf02013-04-17 15:47:2917 input_api.cpplint._cpplint_state.ResetErrorCounts() # reset global state
[email protected]cf824592013-04-09 05:46:0018 source_filter = lambda x: input_api.FilterSourceFile(
19 x, white_list=CC_SOURCE_FILES, black_list=None)
20 files = [f.AbsoluteLocalPath() for f in
21 input_api.AffectedSourceFiles(source_filter)]
22 level = 1 # strict, but just warn
23
24 for file_name in files:
[email protected]16f5cf02013-04-17 15:47:2925 input_api.cpplint.ProcessFile(file_name, level)
[email protected]cf824592013-04-09 05:46:0026
[email protected]16f5cf02013-04-17 15:47:2927 if not input_api.cpplint._cpplint_state.error_count:
[email protected]cf824592013-04-09 05:46:0028 return []
29
30 return [output_api.PresubmitPromptWarning(
31 'Changelist failed cpplint.py check.')]
32
[email protected]1d993172012-10-18 18:15:0433def CheckAsserts(input_api, output_api, white_list=CC_SOURCE_FILES, black_list=None):
34 black_list = tuple(black_list or input_api.DEFAULT_BLACK_LIST)
35 source_file_filter = lambda x: input_api.FilterSourceFile(x, white_list, black_list)
36
37 assert_files = []
38 notreached_files = []
39
40 for f in input_api.AffectedSourceFiles(source_file_filter):
41 contents = input_api.ReadFile(f, 'rb')
42 # WebKit ASSERT() is not allowed.
[email protected]f4a4b0e2012-10-22 22:01:3743 if re.search(r"\bASSERT\(", contents):
[email protected]1d993172012-10-18 18:15:0444 assert_files.append(f.LocalPath())
45 # WebKit ASSERT_NOT_REACHED() is not allowed.
46 if re.search(r"ASSERT_NOT_REACHED\(", contents):
47 notreached_files.append(f.LocalPath())
48
49 if assert_files:
50 return [output_api.PresubmitError(
51 'These files use ASSERT instead of using DCHECK:',
52 items=assert_files)]
53 if notreached_files:
54 return [output_api.PresubmitError(
55 'These files use ASSERT_NOT_REACHED instead of using NOTREACHED:',
56 items=notreached_files)]
57 return []
58
[email protected]81d205442013-07-29 21:42:0359def CheckStdAbs(input_api, output_api,
60 white_list=CC_SOURCE_FILES, black_list=None):
61 black_list = tuple(black_list or input_api.DEFAULT_BLACK_LIST)
62 source_file_filter = lambda x: input_api.FilterSourceFile(x,
63 white_list,
64 black_list)
65
66 using_std_abs_files = []
67 found_fabs_files = []
68 missing_std_prefix_files = []
69
70 for f in input_api.AffectedSourceFiles(source_file_filter):
71 contents = input_api.ReadFile(f, 'rb')
72 if re.search(r"using std::f?abs;", contents):
73 using_std_abs_files.append(f.LocalPath())
74 if re.search(r"\bfabsf?\(", contents):
75 found_fabs_files.append(f.LocalPath());
[email protected]dbddc7462013-09-06 06:33:3176
77 no_std_prefix = r"(?<!std::)"
78 # Matches occurrences of abs/absf/fabs/fabsf without a "std::" prefix.
79 abs_without_prefix = r"%s(\babsf?\()" % no_std_prefix
80 fabs_without_prefix = r"%s(\bfabsf?\()" % no_std_prefix
81 # Skips matching any lines that have "// NOLINT".
82 no_nolint = r"(?![^\n]*//\s+NOLINT)"
83
84 expression = re.compile("(%s|%s)%s" %
85 (abs_without_prefix, fabs_without_prefix, no_nolint))
86 if expression.search(contents):
[email protected]81d205442013-07-29 21:42:0387 missing_std_prefix_files.append(f.LocalPath())
88
89 result = []
90 if using_std_abs_files:
91 result.append(output_api.PresubmitError(
92 'These files have "using std::abs" which is not permitted.',
93 items=using_std_abs_files))
94 if found_fabs_files:
95 result.append(output_api.PresubmitError(
96 'std::abs() should be used instead of std::fabs() for consistency.',
97 items=found_fabs_files))
98 if missing_std_prefix_files:
99 result.append(output_api.PresubmitError(
100 'These files use abs(), absf(), fabs(), or fabsf() without qualifying '
101 'the std namespace. Please use std::abs() in all places.',
102 items=missing_std_prefix_files))
103 return result
104
[email protected]7add2e0b2013-04-23 05:16:42105def CheckPassByValue(input_api,
106 output_api,
107 white_list=CC_SOURCE_FILES,
108 black_list=None):
109 black_list = tuple(black_list or input_api.DEFAULT_BLACK_LIST)
110 source_file_filter = lambda x: input_api.FilterSourceFile(x,
111 white_list,
112 black_list)
113
114 local_errors = []
115
116 # Well-defined simple classes containing only <= 4 ints, or <= 2 floats.
117 pass_by_value_types = ['base::Time',
118 'base::TimeTicks',
[email protected]7add2e0b2013-04-23 05:16:42119 ]
120
121 for f in input_api.AffectedSourceFiles(source_file_filter):
122 contents = input_api.ReadFile(f, 'rb')
123 match = re.search(
124 r'\bconst +' + '(?P<type>(%s))&' %
125 string.join(pass_by_value_types, '|'),
126 contents)
127 if match:
128 local_errors.append(output_api.PresubmitError(
129 '%s passes %s by const ref instead of by value.' %
130 (f.LocalPath(), match.group('type'))))
131 return local_errors
[email protected]d936f902013-01-06 05:08:07132
[email protected]6dc0b6f2013-06-26 20:21:59133def CheckTodos(input_api, output_api):
134 errors = []
135
136 source_file_filter = lambda x: x
137 for f in input_api.AffectedSourceFiles(source_file_filter):
138 contents = input_api.ReadFile(f, 'rb')
[email protected]932aff42013-06-27 12:59:27139 if ('FIX'+'ME') in contents:
[email protected]6dc0b6f2013-06-26 20:21:59140 errors.append(f.LocalPath())
141
142 if errors:
143 return [output_api.PresubmitError(
weiliangc941dbec2014-08-28 18:56:16144 'All TODO comments should be of the form TODO(name). ' +
145 'Use TODO instead of FIX' + 'ME',
[email protected]6dc0b6f2013-06-26 20:21:59146 items=errors)]
147 return []
148
danakjf446a072014-09-27 21:55:48149def CheckScopedPtr(input_api, output_api,
150 white_list=CC_SOURCE_FILES, black_list=None):
151 black_list = tuple(black_list or input_api.DEFAULT_BLACK_LIST)
152 source_file_filter = lambda x: input_api.FilterSourceFile(x,
153 white_list,
154 black_list)
155 errors = []
156 for f in input_api.AffectedSourceFiles(source_file_filter):
157 for line_number, line in f.ChangedContents():
158 # Disallow:
159 # return scoped_ptr<T>(foo);
160 # bar = scoped_ptr<T>(foo);
161 # But allow:
162 # return scoped_ptr<T[]>(foo);
163 # bar = scoped_ptr<T[]>(foo);
164 if re.search(r'(=|\breturn)\s*scoped_ptr<.*?(?<!])>\([^)]+\)', line):
165 errors.append(output_api.PresubmitError(
166 ('%s:%d uses explicit scoped_ptr constructor. ' +
167 'Use make_scoped_ptr() instead.') % (f.LocalPath(), line_number)))
168 # Disallow:
169 # return scoped_ptr<T>();
170 # bar = scoped_ptr<T>();
171 if re.search(r'(=|\breturn)\s*scoped_ptr<.*?>\(\)', line):
172 errors.append(output_api.PresubmitError(
173 '%s:%d uses scoped_ptr<T>(). Use nullptr instead.' %
174 (f.LocalPath(), line_number)))
175 # Disallow:
176 # foo.PassAs<T>();
177 if re.search(r'\bPassAs<.*?>\(\)', line):
178 errors.append(output_api.PresubmitError(
179 '%s:%d uses PassAs<T>(). Use Pass() instead.' %
180 (f.LocalPath(), line_number)))
181 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:
251 whitelist = [
252 r"cc::remove_if\b",
253 ]
254 if FindNamespaceInBlock(match.end(), 'cc', contents, whitelist=whitelist):
255 errors.append(f.LocalPath())
256
257 if errors:
258 return [output_api.PresubmitError(
259 'Do not use cc:: inside of the cc namespace.',
260 items=errors)]
261 return []
262
[email protected]d2f1d582014-05-01 08:43:53263def CheckForUseOfWrongClock(input_api,
264 output_api,
265 white_list=CC_SOURCE_FILES,
266 black_list=None):
267 """Make sure new lines of code don't use a clock susceptible to skew."""
268 black_list = tuple(black_list or input_api.DEFAULT_BLACK_LIST)
269 source_file_filter = lambda x: input_api.FilterSourceFile(x,
270 white_list,
271 black_list)
272 # Regular expression that should detect any explicit references to the
273 # base::Time type (or base::Clock/DefaultClock), whether in using decls,
274 # typedefs, or to call static methods.
275 base_time_type_pattern = r'(^|\W)base::(Time|Clock|DefaultClock)(\W|$)'
276
277 # Regular expression that should detect references to the base::Time class
278 # members, such as a call to base::Time::Now.
279 base_time_member_pattern = r'(^|\W)(Time|Clock|DefaultClock)::'
280
281 # Regular expression to detect "using base::Time" declarations. We want to
282 # prevent these from triggerring a warning. For example, it's perfectly
283 # reasonable for code to be written like this:
284 #
285 # using base::Time;
286 # ...
287 # int64 foo_us = foo_s * Time::kMicrosecondsPerSecond;
288 using_base_time_decl_pattern = r'^\s*using\s+(::)?base::Time\s*;'
289
290 # Regular expression to detect references to the kXXX constants in the
291 # base::Time class. We want to prevent these from triggerring a warning.
292 base_time_konstant_pattern = r'(^|\W)Time::k\w+'
293
294 problem_re = input_api.re.compile(
295 r'(' + base_time_type_pattern + r')|(' + base_time_member_pattern + r')')
296 exception_re = input_api.re.compile(
297 r'(' + using_base_time_decl_pattern + r')|(' +
298 base_time_konstant_pattern + r')')
299 problems = []
300 for f in input_api.AffectedSourceFiles(source_file_filter):
301 for line_number, line in f.ChangedContents():
302 if problem_re.search(line):
303 if not exception_re.search(line):
304 problems.append(
305 ' %s:%d\n %s' % (f.LocalPath(), line_number, line.strip()))
306
307 if problems:
308 return [output_api.PresubmitPromptOrNotify(
309 'You added one or more references to the base::Time class and/or one\n'
310 'of its member functions (or base::Clock/DefaultClock). In cc code,\n'
311 'it is most certainly incorrect! Instead use base::TimeTicks.\n\n'
312 '\n'.join(problems))]
313 else:
314 return []
[email protected]6dc0b6f2013-06-26 20:21:59315
[email protected]1d993172012-10-18 18:15:04316def CheckChangeOnUpload(input_api, output_api):
317 results = []
318 results += CheckAsserts(input_api, output_api)
[email protected]81d205442013-07-29 21:42:03319 results += CheckStdAbs(input_api, output_api)
[email protected]7add2e0b2013-04-23 05:16:42320 results += CheckPassByValue(input_api, output_api)
[email protected]cf824592013-04-09 05:46:00321 results += CheckChangeLintsClean(input_api, output_api)
[email protected]6dc0b6f2013-06-26 20:21:59322 results += CheckTodos(input_api, output_api)
danakjf446a072014-09-27 21:55:48323 results += CheckScopedPtr(input_api, output_api)
[email protected]e51444a2013-12-10 23:05:01324 results += CheckNamespace(input_api, output_api)
[email protected]d2f1d582014-05-01 08:43:53325 results += CheckForUseOfWrongClock(input_api, output_api)
[email protected]3f52c8932014-06-13 08:46:38326 results += FindUselessIfdefs(input_api, output_api)
[email protected]4f0fd022014-01-30 08:05:22327 results += input_api.canned_checks.CheckPatchFormatted(input_api, output_api)
[email protected]1d993172012-10-18 18:15:04328 return results
329
[email protected]634c8a6f2014-03-11 17:22:59330def GetPreferredTryMasters(project, change):
331 return {
[email protected]0bb112362014-07-26 04:38:32332 'tryserver.blink': {
[email protected]0094fa12014-03-13 03:18:28333 'linux_blink_rel': set(['defaulttests']),
[email protected]ed5040942014-03-18 03:16:29334 },
335 'tryserver.chromium.gpu': {
[email protected]634c8a6f2014-03-11 17:22:59336 'linux_gpu': set(['defaulttests']),
337 'mac_gpu': set(['defaulttests']),
[email protected]634c8a6f2014-03-11 17:22:59338 'win_gpu': set(['defaulttests']),
339 },
340 }