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 for file_name
in files
:
25 input_api
.cpplint
.ProcessFile(file_name
, level
)
27 if not input_api
.cpplint
._cpplint
_state
.error_count
:
30 return [output_api
.PresubmitPromptWarning(
31 'Changelist failed cpplint.py check.')]
33 def 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
)
40 for f
in input_api
.AffectedSourceFiles(source_file_filter
):
41 contents
= input_api
.ReadFile(f
, 'rb')
42 # WebKit ASSERT() is not allowed.
43 if re
.search(r
"\bASSERT\(", contents
):
44 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())
50 return [output_api
.PresubmitError(
51 'These files use ASSERT instead of using DCHECK:',
54 return [output_api
.PresubmitError(
55 'These files use ASSERT_NOT_REACHED instead of using NOTREACHED:',
56 items
=notreached_files
)]
59 def 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
,
66 using_std_abs_files
= []
68 missing_std_prefix_files
= []
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());
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)"
84 expression
= re
.compile("(%s|%s)%s" %
85 (abs_without_prefix
, fabs_without_prefix
, no_nolint
))
86 if expression
.search(contents
):
87 missing_std_prefix_files
.append(f
.LocalPath())
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
))
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
))
105 def CheckPassByValue(input_api
,
107 white_list
=CC_SOURCE_FILES
,
109 black_list
= tuple(black_list
or input_api
.DEFAULT_BLACK_LIST
)
110 source_file_filter
= lambda x
: input_api
.FilterSourceFile(x
,
116 # Well-defined simple classes containing only <= 4 ints, or <= 2 floats.
117 pass_by_value_types
= ['base::Time',
121 for f
in input_api
.AffectedSourceFiles(source_file_filter
):
122 contents
= input_api
.ReadFile(f
, 'rb')
124 r
'\bconst +' + '(?P<type>(%s))&' %
125 string
.join(pass_by_value_types
, '|'),
128 local_errors
.append(output_api
.PresubmitError(
129 '%s passes %s by const ref instead of by value.' %
130 (f
.LocalPath(), match
.group('type'))))
133 def CheckTodos(input_api
, output_api
):
136 source_file_filter
= lambda x
: x
137 for f
in input_api
.AffectedSourceFiles(source_file_filter
):
138 contents
= input_api
.ReadFile(f
, 'rb')
139 if ('FIX'+'ME') in contents
:
140 errors
.append(f
.LocalPath())
143 return [output_api
.PresubmitError(
144 'All TODO comments should be of the form TODO(name). ' +
145 'Use TODO instead of FIX' + 'ME',
149 def CheckDoubleAngles(input_api
, output_api
, white_list
=CC_SOURCE_FILES
,
153 source_file_filter
= lambda x
: input_api
.FilterSourceFile(x
,
156 for f
in input_api
.AffectedSourceFiles(source_file_filter
):
157 contents
= input_api
.ReadFile(f
, 'rb')
158 if ('> >') in contents
:
159 errors
.append(f
.LocalPath())
162 return [output_api
.PresubmitError('Use >> instead of > >:', items
=errors
)]
165 def CheckScopedPtr(input_api
, output_api
,
166 white_list
=CC_SOURCE_FILES
, black_list
=None):
167 black_list
= tuple(black_list
or input_api
.DEFAULT_BLACK_LIST
)
168 source_file_filter
= lambda x
: input_api
.FilterSourceFile(x
,
172 for f
in input_api
.AffectedSourceFiles(source_file_filter
):
173 for line_number
, line
in f
.ChangedContents():
175 # return scoped_ptr<T>(foo);
176 # bar = scoped_ptr<T>(foo);
178 # return scoped_ptr<T[]>(foo);
179 # bar = scoped_ptr<T[]>(foo);
180 if re
.search(r
'(=|\breturn)\s*scoped_ptr<.*?(?<!])>\([^)]+\)', line
):
181 errors
.append(output_api
.PresubmitError(
182 ('%s:%d uses explicit scoped_ptr constructor. ' +
183 'Use make_scoped_ptr() instead.') % (f
.LocalPath(), line_number
)))
186 if re
.search(r
'\bscoped_ptr<.*?>\(\)', line
):
187 errors
.append(output_api
.PresubmitError(
188 '%s:%d uses scoped_ptr<T>(). Use nullptr instead.' %
189 (f
.LocalPath(), line_number
)))
192 def FindUnquotedQuote(contents
, pos
):
193 match
= re
.search(r
"(?<!\\)(?P<quote>\")", contents[pos:])
194 return -1 if not match else match.start("quote
") + pos
196 def FindUselessIfdefs(input_api, output_api):
198 source_file_filter = lambda x: x
199 for f in input_api.AffectedSourceFiles(source_file_filter):
200 contents = input_api.ReadFile(f, 'rb')
201 if re.search(r'#if\s*0\s', contents):
202 errors.append(f.LocalPath())
204 return [output_api.PresubmitError(
205 'Don\'t use #if '+'0; just delete the code.',
209 def FindNamespaceInBlock(pos, namespace, contents, whitelist=[]):
216 while pos < len(contents) and brace_count > 0:
217 if open_brace < pos: open_brace = contents.find("{", pos)
218 if close_brace < pos: close_brace = contents.find("}", pos)
219 if quote < pos: quote = FindUnquotedQuote(contents, pos)
220 if name < pos: name = contents.find(("%s::" % namespace), pos)
223 return False # The namespace is not used at all.
225 open_brace = len(contents)
227 close_brace = len(contents)
229 quote = len(contents)
231 next = min(open_brace, min(close_brace, min(quote, name)))
233 if next == open_brace:
235 elif next == close_brace:
238 quote_count = 0 if quote_count else 1
239 elif next == name and not quote_count:
242 if re.match(w, contents[next:]):
250 # Checks for the use of cc:: within the cc namespace, which is usually
252 def CheckNamespace(input_api, output_api):
255 source_file_filter = lambda x: x
256 for f in input_api.AffectedSourceFiles(source_file_filter):
257 contents = input_api.ReadFile(f, 'rb')
258 match = re.search(r'namespace\s*cc\s*{', contents)
263 if FindNamespaceInBlock(match.end(), 'cc', contents, whitelist=whitelist):
264 errors.append(f.LocalPath())
267 return [output_api.PresubmitError(
268 'Do not use cc:: inside of the cc namespace.',
272 def CheckForUseOfWrongClock(input_api,
274 white_list=CC_SOURCE_FILES,
276 """Make sure new lines of code don't use a clock susceptible to skew."""
277 black_list = tuple(black_list or input_api.DEFAULT_BLACK_LIST)
278 source_file_filter = lambda x: input_api.FilterSourceFile(x,
281 # Regular expression that should detect any explicit references to the
282 # base::Time type (or base::Clock/DefaultClock), whether in using decls,
283 # typedefs, or to call static methods.
284 base_time_type_pattern = r'(^|\W)base::(Time|Clock|DefaultClock)(\W|$)'
286 # Regular expression that should detect references to the base::Time class
287 # members, such as a call to base::Time::Now.
288 base_time_member_pattern = r'(^|\W)(Time|Clock|DefaultClock)::'
290 # Regular expression to detect "using base
::Time
" declarations. We want to
291 # prevent these from triggerring a warning. For example, it's perfectly
292 # reasonable for code to be written like this:
296 # int64 foo_us = foo_s * Time::kMicrosecondsPerSecond;
297 using_base_time_decl_pattern = r'^\s*using\s+(::)?base::Time\s*;'
299 # Regular expression to detect references to the kXXX constants in the
300 # base::Time class. We want to prevent these from triggerring a warning.
301 base_time_konstant_pattern = r'(^|\W)Time::k\w+'
303 problem_re = input_api.re.compile(
304 r'(' + base_time_type_pattern + r')|(' + base_time_member_pattern + r')')
305 exception_re = input_api.re.compile(
306 r'(' + using_base_time_decl_pattern + r')|(' +
307 base_time_konstant_pattern + r')')
309 for f in input_api.AffectedSourceFiles(source_file_filter):
310 for line_number, line in f.ChangedContents():
311 if problem_re.search(line):
312 if not exception_re.search(line):
314 ' %s:%d\n %s' % (f.LocalPath(), line_number, line.strip()))
317 return [output_api.PresubmitPromptOrNotify(
318 'You added one or more references to the base::Time class and/or one\n'
319 'of its member functions (or base::Clock/DefaultClock). In cc code,\n'
320 'it is most certainly incorrect! Instead use base::TimeTicks.\n\n'
321 '\n'.join(problems))]
325 def CheckChangeOnUpload(input_api, output_api):
327 results += CheckAsserts(input_api, output_api)
328 results += CheckStdAbs(input_api, output_api)
329 results += CheckPassByValue(input_api, output_api)
330 results += CheckChangeLintsClean(input_api, output_api)
331 results += CheckTodos(input_api, output_api)
332 results += CheckDoubleAngles(input_api, output_api)
333 results += CheckScopedPtr(input_api, output_api)
334 results += CheckNamespace(input_api, output_api)
335 results += CheckForUseOfWrongClock(input_api, output_api)
336 results += FindUselessIfdefs(input_api, output_api)
337 results += input_api.canned_checks.CheckPatchFormatted(input_api, output_api)
340 def GetPreferredTryMasters(project, change):
343 'linux_blink_rel': set(['defaulttests']),