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.
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.
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
:
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
)
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())
54 return [output_api
.PresubmitError(
55 'These files use ASSERT instead of using DCHECK:',
58 return [output_api
.PresubmitError(
59 'These files use ASSERT_NOT_REACHED instead of using NOTREACHED:',
60 items
=notreached_files
)]
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
,
70 using_std_abs_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())
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
))
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
))
109 def CheckPassByValue(input_api
,
111 white_list
=CC_SOURCE_FILES
,
113 black_list
= tuple(black_list
or input_api
.DEFAULT_BLACK_LIST
)
114 source_file_filter
= lambda x
: input_api
.FilterSourceFile(x
,
120 # Well-defined simple classes containing only <= 4 ints, or <= 2 floats.
121 pass_by_value_types
= ['base::Time',
125 for f
in input_api
.AffectedSourceFiles(source_file_filter
):
126 contents
= input_api
.ReadFile(f
, 'rb')
128 r
'\bconst +' + '(?P<type>(%s))&' %
129 string
.join(pass_by_value_types
, '|'),
132 local_errors
.append(output_api
.PresubmitError(
133 '%s passes %s by const ref instead of by value.' %
134 (f
.LocalPath(), match
.group('type'))))
137 def CheckTodos(input_api
, output_api
):
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())
147 return [output_api
.PresubmitError(
148 'All TODO comments should be of the form TODO(name). ' +
149 'Use TODO instead of FIX' + 'ME',
153 def CheckDoubleAngles(input_api
, output_api
, white_list
=CC_SOURCE_FILES
,
157 source_file_filter
= lambda x
: input_api
.FilterSourceFile(x
,
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())
166 return [output_api
.PresubmitError('Use >> instead of > >:', items
=errors
)]
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
,
176 for f
in input_api
.AffectedSourceFiles(source_file_filter
):
177 for line_number
, line
in f
.ChangedContents():
179 # return scoped_ptr<T>(foo);
180 # bar = scoped_ptr<T>(foo);
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
)))
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
)))
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
)))
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):
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())
214 return [output_api.PresubmitError(
215 'Don\'t use #if '+'0; just delete the code.',
219 def FindNamespaceInBlock(pos, namespace, contents, whitelist=[]):
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)
233 return False # The namespace is not used at all.
235 open_brace = len(contents)
237 close_brace = len(contents)
239 quote = len(contents)
241 next = min(open_brace, min(close_brace, min(quote, name)))
243 if next == open_brace:
245 elif next == close_brace:
248 quote_count = 0 if quote_count else 1
249 elif next == name and not quote_count:
252 if re.match(w, contents[next:]):
260 # Checks for the use of cc:: within the cc namespace, which is usually
262 def CheckNamespace(input_api, output_api):
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)
273 if FindNamespaceInBlock(match.end(), 'cc', contents, whitelist=whitelist):
274 errors.append(f.LocalPath())
277 return [output_api.PresubmitError(
278 'Do not use cc:: inside of the cc namespace.',
282 def CheckForUseOfWrongClock(input_api,
284 white_list=CC_SOURCE_FILES,
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,
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:
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')')
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):
324 ' %s:%d\n %s' % (f.LocalPath(), line_number, line.strip()))
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))]
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.
344 source_file_filter = lambda x: input_api.FilterSourceFile(
345 x, white_list=CC_SOURCE_FILES, black_list=None)
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())
361 return [output_api.PresubmitError(
362 'These files use OVERRIDE instead of using override:',
363 items=override_files)]
365 return [output_api.PresubmitError(
366 'These files use FINAL instead of using final:',
371 def CheckChangeOnUpload(input_api, output_api):
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)
387 def GetPreferredTryMasters(project, change):
390 'linux_blink_rel': set(['defaulttests']),