Roll src/third_party/skia 33e6466:43b8b36
[chromium-blink-merge.git] / cc / PRESUBMIT.py
blob1aa48f3501ad2d186b20b626ae2de8013bb40423
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.
5 """Top-level presubmit script for cc.
7 See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
8 for more details about the presubmit API built into depot_tools.
9 """
11 import re
12 import string
14 CC_SOURCE_FILES=(r'^cc/.*\.(cc|h)$',)
16 def CheckChangeLintsClean(input_api, output_api):
17 input_api.cpplint._cpplint_state.ResetErrorCounts() # reset global state
18 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
24 # TODO(danakj): Temporary, while the OVERRIDE and FINAL fixup is in progress.
25 # crbug.com/422353
26 input_api.cpplint._SetFilters('-readability/inheritance')
28 for file_name in files:
29 input_api.cpplint.ProcessFile(file_name, level)
31 if not input_api.cpplint._cpplint_state.error_count:
32 return []
34 return [output_api.PresubmitPromptWarning(
35 'Changelist failed cpplint.py check.')]
37 def CheckAsserts(input_api, output_api, white_list=CC_SOURCE_FILES, black_list=None):
38 black_list = tuple(black_list or input_api.DEFAULT_BLACK_LIST)
39 source_file_filter = lambda x: input_api.FilterSourceFile(x, white_list, black_list)
41 assert_files = []
42 notreached_files = []
44 for f in input_api.AffectedSourceFiles(source_file_filter):
45 contents = input_api.ReadFile(f, 'rb')
46 # WebKit ASSERT() is not allowed.
47 if re.search(r"\bASSERT\(", contents):
48 assert_files.append(f.LocalPath())
49 # WebKit ASSERT_NOT_REACHED() is not allowed.
50 if re.search(r"ASSERT_NOT_REACHED\(", contents):
51 notreached_files.append(f.LocalPath())
53 if assert_files:
54 return [output_api.PresubmitError(
55 'These files use ASSERT instead of using DCHECK:',
56 items=assert_files)]
57 if notreached_files:
58 return [output_api.PresubmitError(
59 'These files use ASSERT_NOT_REACHED instead of using NOTREACHED:',
60 items=notreached_files)]
61 return []
63 def CheckStdAbs(input_api, output_api,
64 white_list=CC_SOURCE_FILES, black_list=None):
65 black_list = tuple(black_list or input_api.DEFAULT_BLACK_LIST)
66 source_file_filter = lambda x: input_api.FilterSourceFile(x,
67 white_list,
68 black_list)
70 using_std_abs_files = []
71 found_fabs_files = []
72 missing_std_prefix_files = []
74 for f in input_api.AffectedSourceFiles(source_file_filter):
75 contents = input_api.ReadFile(f, 'rb')
76 if re.search(r"using std::f?abs;", contents):
77 using_std_abs_files.append(f.LocalPath())
78 if re.search(r"\bfabsf?\(", contents):
79 found_fabs_files.append(f.LocalPath());
81 no_std_prefix = r"(?<!std::)"
82 # Matches occurrences of abs/absf/fabs/fabsf without a "std::" prefix.
83 abs_without_prefix = r"%s(\babsf?\()" % no_std_prefix
84 fabs_without_prefix = r"%s(\bfabsf?\()" % no_std_prefix
85 # Skips matching any lines that have "// NOLINT".
86 no_nolint = r"(?![^\n]*//\s+NOLINT)"
88 expression = re.compile("(%s|%s)%s" %
89 (abs_without_prefix, fabs_without_prefix, no_nolint))
90 if expression.search(contents):
91 missing_std_prefix_files.append(f.LocalPath())
93 result = []
94 if using_std_abs_files:
95 result.append(output_api.PresubmitError(
96 'These files have "using std::abs" which is not permitted.',
97 items=using_std_abs_files))
98 if found_fabs_files:
99 result.append(output_api.PresubmitError(
100 'std::abs() should be used instead of std::fabs() for consistency.',
101 items=found_fabs_files))
102 if missing_std_prefix_files:
103 result.append(output_api.PresubmitError(
104 'These files use abs(), absf(), fabs(), or fabsf() without qualifying '
105 'the std namespace. Please use std::abs() in all places.',
106 items=missing_std_prefix_files))
107 return result
109 def CheckPassByValue(input_api,
110 output_api,
111 white_list=CC_SOURCE_FILES,
112 black_list=None):
113 black_list = tuple(black_list or input_api.DEFAULT_BLACK_LIST)
114 source_file_filter = lambda x: input_api.FilterSourceFile(x,
115 white_list,
116 black_list)
118 local_errors = []
120 # Well-defined simple classes containing only <= 4 ints, or <= 2 floats.
121 pass_by_value_types = ['base::Time',
122 'base::TimeTicks',
125 for f in input_api.AffectedSourceFiles(source_file_filter):
126 contents = input_api.ReadFile(f, 'rb')
127 match = re.search(
128 r'\bconst +' + '(?P<type>(%s))&' %
129 string.join(pass_by_value_types, '|'),
130 contents)
131 if match:
132 local_errors.append(output_api.PresubmitError(
133 '%s passes %s by const ref instead of by value.' %
134 (f.LocalPath(), match.group('type'))))
135 return local_errors
137 def CheckTodos(input_api, output_api):
138 errors = []
140 source_file_filter = lambda x: x
141 for f in input_api.AffectedSourceFiles(source_file_filter):
142 contents = input_api.ReadFile(f, 'rb')
143 if ('FIX'+'ME') in contents:
144 errors.append(f.LocalPath())
146 if errors:
147 return [output_api.PresubmitError(
148 'All TODO comments should be of the form TODO(name). ' +
149 'Use TODO instead of FIX' + 'ME',
150 items=errors)]
151 return []
153 def CheckDoubleAngles(input_api, output_api, white_list=CC_SOURCE_FILES,
154 black_list=None):
155 errors = []
157 source_file_filter = lambda x: input_api.FilterSourceFile(x,
158 white_list,
159 black_list)
160 for f in input_api.AffectedSourceFiles(source_file_filter):
161 contents = input_api.ReadFile(f, 'rb')
162 if ('> >') in contents:
163 errors.append(f.LocalPath())
165 if errors:
166 return [output_api.PresubmitError('Use >> instead of > >:', items=errors)]
167 return []
169 def CheckScopedPtr(input_api, output_api,
170 white_list=CC_SOURCE_FILES, black_list=None):
171 black_list = tuple(black_list or input_api.DEFAULT_BLACK_LIST)
172 source_file_filter = lambda x: input_api.FilterSourceFile(x,
173 white_list,
174 black_list)
175 errors = []
176 for f in input_api.AffectedSourceFiles(source_file_filter):
177 for line_number, line in f.ChangedContents():
178 # Disallow:
179 # return scoped_ptr<T>(foo);
180 # bar = scoped_ptr<T>(foo);
181 # But allow:
182 # return scoped_ptr<T[]>(foo);
183 # bar = scoped_ptr<T[]>(foo);
184 if re.search(r'(=|\breturn)\s*scoped_ptr<.*?(?<!])>\([^)]+\)', line):
185 errors.append(output_api.PresubmitError(
186 ('%s:%d uses explicit scoped_ptr constructor. ' +
187 'Use make_scoped_ptr() instead.') % (f.LocalPath(), line_number)))
188 # Disallow:
189 # scoped_ptr<T>()
190 if re.search(r'\bscoped_ptr<.*?>\(\)', line):
191 errors.append(output_api.PresubmitError(
192 '%s:%d uses scoped_ptr<T>(). Use nullptr instead.' %
193 (f.LocalPath(), line_number)))
194 # Disallow:
195 # foo.PassAs<T>();
196 if re.search(r'\bPassAs<.*?>\(\)', line):
197 errors.append(output_api.PresubmitError(
198 '%s:%d uses PassAs<T>(). Use Pass() instead.' %
199 (f.LocalPath(), line_number)))
200 return errors
202 def FindUnquotedQuote(contents, pos):
203 match = re.search(r"(?<!\\)(?P<quote>\")", contents[pos:])
204 return -1 if not match else match.start("quote") + pos
206 def FindUselessIfdefs(input_api, output_api):
207 errors = []
208 source_file_filter = lambda x: x
209 for f in input_api.AffectedSourceFiles(source_file_filter):
210 contents = input_api.ReadFile(f, 'rb')
211 if re.search(r'#if\s*0\s', contents):
212 errors.append(f.LocalPath())
213 if errors:
214 return [output_api.PresubmitError(
215 'Don\'t use #if '+'0; just delete the code.',
216 items=errors)]
217 return []
219 def FindNamespaceInBlock(pos, namespace, contents, whitelist=[]):
220 open_brace = -1
221 close_brace = -1
222 quote = -1
223 name = -1
224 brace_count = 1
225 quote_count = 0
226 while pos < len(contents) and brace_count > 0:
227 if open_brace < pos: open_brace = contents.find("{", pos)
228 if close_brace < pos: close_brace = contents.find("}", pos)
229 if quote < pos: quote = FindUnquotedQuote(contents, pos)
230 if name < pos: name = contents.find(("%s::" % namespace), pos)
232 if name < 0:
233 return False # The namespace is not used at all.
234 if open_brace < 0:
235 open_brace = len(contents)
236 if close_brace < 0:
237 close_brace = len(contents)
238 if quote < 0:
239 quote = len(contents)
241 next = min(open_brace, min(close_brace, min(quote, name)))
243 if next == open_brace:
244 brace_count += 1
245 elif next == close_brace:
246 brace_count -= 1
247 elif next == quote:
248 quote_count = 0 if quote_count else 1
249 elif next == name and not quote_count:
250 in_whitelist = False
251 for w in whitelist:
252 if re.match(w, contents[next:]):
253 in_whitelist = True
254 break
255 if not in_whitelist:
256 return True
257 pos = next + 1
258 return False
260 # Checks for the use of cc:: within the cc namespace, which is usually
261 # redundant.
262 def CheckNamespace(input_api, output_api):
263 errors = []
265 source_file_filter = lambda x: x
266 for f in input_api.AffectedSourceFiles(source_file_filter):
267 contents = input_api.ReadFile(f, 'rb')
268 match = re.search(r'namespace\s*cc\s*{', contents)
269 if match:
270 whitelist = [
271 r"cc::remove_if\b",
273 if FindNamespaceInBlock(match.end(), 'cc', contents, whitelist=whitelist):
274 errors.append(f.LocalPath())
276 if errors:
277 return [output_api.PresubmitError(
278 'Do not use cc:: inside of the cc namespace.',
279 items=errors)]
280 return []
282 def CheckForUseOfWrongClock(input_api,
283 output_api,
284 white_list=CC_SOURCE_FILES,
285 black_list=None):
286 """Make sure new lines of code don't use a clock susceptible to skew."""
287 black_list = tuple(black_list or input_api.DEFAULT_BLACK_LIST)
288 source_file_filter = lambda x: input_api.FilterSourceFile(x,
289 white_list,
290 black_list)
291 # Regular expression that should detect any explicit references to the
292 # base::Time type (or base::Clock/DefaultClock), whether in using decls,
293 # typedefs, or to call static methods.
294 base_time_type_pattern = r'(^|\W)base::(Time|Clock|DefaultClock)(\W|$)'
296 # Regular expression that should detect references to the base::Time class
297 # members, such as a call to base::Time::Now.
298 base_time_member_pattern = r'(^|\W)(Time|Clock|DefaultClock)::'
300 # Regular expression to detect "using base::Time" declarations. We want to
301 # prevent these from triggerring a warning. For example, it's perfectly
302 # reasonable for code to be written like this:
304 # using base::Time;
305 # ...
306 # int64 foo_us = foo_s * Time::kMicrosecondsPerSecond;
307 using_base_time_decl_pattern = r'^\s*using\s+(::)?base::Time\s*;'
309 # Regular expression to detect references to the kXXX constants in the
310 # base::Time class. We want to prevent these from triggerring a warning.
311 base_time_konstant_pattern = r'(^|\W)Time::k\w+'
313 problem_re = input_api.re.compile(
314 r'(' + base_time_type_pattern + r')|(' + base_time_member_pattern + r')')
315 exception_re = input_api.re.compile(
316 r'(' + using_base_time_decl_pattern + r')|(' +
317 base_time_konstant_pattern + r')')
318 problems = []
319 for f in input_api.AffectedSourceFiles(source_file_filter):
320 for line_number, line in f.ChangedContents():
321 if problem_re.search(line):
322 if not exception_re.search(line):
323 problems.append(
324 ' %s:%d\n %s' % (f.LocalPath(), line_number, line.strip()))
326 if problems:
327 return [output_api.PresubmitPromptOrNotify(
328 'You added one or more references to the base::Time class and/or one\n'
329 'of its member functions (or base::Clock/DefaultClock). In cc code,\n'
330 'it is most certainly incorrect! Instead use base::TimeTicks.\n\n'
331 '\n'.join(problems))]
332 else:
333 return []
335 def CheckOverrideFinal(input_api, output_api,
336 whitelist=CC_SOURCE_FILES, blacklist=None):
337 """Make sure new lines of code don't use the OVERRIDE or FINAL macros."""
339 # TODO(mostynb): remove this check once the macros are removed
340 # from base/compiler_specific.h.
342 errors = []
344 source_file_filter = lambda x: input_api.FilterSourceFile(
345 x, white_list=CC_SOURCE_FILES, black_list=None)
347 override_files = []
348 final_files = []
350 for f in input_api.AffectedSourceFiles(source_file_filter):
351 contents = input_api.ReadFile(f, 'rb')
353 # "override" and "final" should be used instead of OVERRIDE/FINAL now.
354 if re.search(r"\bOVERRIDE\b", contents):
355 override_files.append(f.LocalPath())
357 if re.search(r"\bFINAL\b", contents):
358 final_files.append(f.LocalPath())
360 if override_files:
361 return [output_api.PresubmitError(
362 'These files use OVERRIDE instead of using override:',
363 items=override_files)]
364 if final_files:
365 return [output_api.PresubmitError(
366 'These files use FINAL instead of using final:',
367 items=final_files)]
369 return []
371 def CheckChangeOnUpload(input_api, output_api):
372 results = []
373 results += CheckAsserts(input_api, output_api)
374 results += CheckStdAbs(input_api, output_api)
375 results += CheckPassByValue(input_api, output_api)
376 results += CheckChangeLintsClean(input_api, output_api)
377 results += CheckTodos(input_api, output_api)
378 results += CheckDoubleAngles(input_api, output_api)
379 results += CheckScopedPtr(input_api, output_api)
380 results += CheckNamespace(input_api, output_api)
381 results += CheckForUseOfWrongClock(input_api, output_api)
382 results += FindUselessIfdefs(input_api, output_api)
383 results += CheckOverrideFinal(input_api, output_api)
384 results += input_api.canned_checks.CheckPatchFormatted(input_api, output_api)
385 return results
387 def GetPreferredTryMasters(project, change):
388 return {
389 'tryserver.blink': {
390 'linux_blink_rel': set(['defaulttests']),