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 def FindUnquotedQuote(contents
, pos
):
197 match
= re
.search(r
"(?<!\\)(?P<quote>\")", contents[pos:])
198 return -1 if not match else match.start("quote
") + pos
200 def FindUselessIfdefs(input_api, output_api):
202 source_file_filter = lambda x: x
203 for f in input_api.AffectedSourceFiles(source_file_filter):
204 contents = input_api.ReadFile(f, 'rb')
205 if re.search(r'#if\s*0\s', contents):
206 errors.append(f.LocalPath())
208 return [output_api.PresubmitError(
209 'Don\'t use #if '+'0; just delete the code.',
213 def FindNamespaceInBlock(pos, namespace, contents, whitelist=[]):
220 while pos < len(contents) and brace_count > 0:
221 if open_brace < pos: open_brace = contents.find("{", pos)
222 if close_brace < pos: close_brace = contents.find("}", pos)
223 if quote < pos: quote = FindUnquotedQuote(contents, pos)
224 if name < pos: name = contents.find(("%s::" % namespace), pos)
227 return False # The namespace is not used at all.
229 open_brace = len(contents)
231 close_brace = len(contents)
233 quote = len(contents)
235 next = min(open_brace, min(close_brace, min(quote, name)))
237 if next == open_brace:
239 elif next == close_brace:
242 quote_count = 0 if quote_count else 1
243 elif next == name and not quote_count:
246 if re.match(w, contents[next:]):
254 # Checks for the use of cc:: within the cc namespace, which is usually
256 def CheckNamespace(input_api, output_api):
259 source_file_filter = lambda x: x
260 for f in input_api.AffectedSourceFiles(source_file_filter):
261 contents = input_api.ReadFile(f, 'rb')
262 match = re.search(r'namespace\s*cc\s*{', contents)
267 if FindNamespaceInBlock(match.end(), 'cc', contents, whitelist=whitelist):
268 errors.append(f.LocalPath())
271 return [output_api.PresubmitError(
272 'Do not use cc:: inside of the cc namespace.',
276 def CheckForUseOfWrongClock(input_api,
278 white_list=CC_SOURCE_FILES,
280 """Make sure new lines of code don't use a clock susceptible to skew."""
281 black_list = tuple(black_list or input_api.DEFAULT_BLACK_LIST)
282 source_file_filter = lambda x: input_api.FilterSourceFile(x,
285 # Regular expression that should detect any explicit references to the
286 # base::Time type (or base::Clock/DefaultClock), whether in using decls,
287 # typedefs, or to call static methods.
288 base_time_type_pattern = r'(^|\W)base::(Time|Clock|DefaultClock)(\W|$)'
290 # Regular expression that should detect references to the base::Time class
291 # members, such as a call to base::Time::Now.
292 base_time_member_pattern = r'(^|\W)(Time|Clock|DefaultClock)::'
294 # Regular expression to detect "using base
::Time
" declarations. We want to
295 # prevent these from triggerring a warning. For example, it's perfectly
296 # reasonable for code to be written like this:
300 # int64 foo_us = foo_s * Time::kMicrosecondsPerSecond;
301 using_base_time_decl_pattern = r'^\s*using\s+(::)?base::Time\s*;'
303 # Regular expression to detect references to the kXXX constants in the
304 # base::Time class. We want to prevent these from triggerring a warning.
305 base_time_konstant_pattern = r'(^|\W)Time::k\w+'
307 problem_re = input_api.re.compile(
308 r'(' + base_time_type_pattern + r')|(' + base_time_member_pattern + r')')
309 exception_re = input_api.re.compile(
310 r'(' + using_base_time_decl_pattern + r')|(' +
311 base_time_konstant_pattern + r')')
313 for f in input_api.AffectedSourceFiles(source_file_filter):
314 for line_number, line in f.ChangedContents():
315 if problem_re.search(line):
316 if not exception_re.search(line):
318 ' %s:%d\n %s' % (f.LocalPath(), line_number, line.strip()))
321 return [output_api.PresubmitPromptOrNotify(
322 'You added one or more references to the base::Time class and/or one\n'
323 'of its member functions (or base::Clock/DefaultClock). In cc code,\n'
324 'it is most certainly incorrect! Instead use base::TimeTicks.\n\n'
325 '\n'.join(problems))]
329 def CheckChangeOnUpload(input_api, output_api):
331 results += CheckAsserts(input_api, output_api)
332 results += CheckStdAbs(input_api, output_api)
333 results += CheckPassByValue(input_api, output_api)
334 results += CheckChangeLintsClean(input_api, output_api)
335 results += CheckTodos(input_api, output_api)
336 results += CheckDoubleAngles(input_api, output_api)
337 results += CheckScopedPtr(input_api, output_api)
338 results += CheckNamespace(input_api, output_api)
339 results += CheckForUseOfWrongClock(input_api, output_api)
340 results += FindUselessIfdefs(input_api, output_api)
341 results += input_api.canned_checks.CheckPatchFormatted(input_api, output_api)
344 def GetPreferredTryMasters(project, change):
347 'linux_blink_rel': set(['defaulttests']),