[Android] Expose utility methods for getting URL emphasis regions.
[chromium-blink-merge.git] / cc / PRESUBMIT.py
blob46c3a54349e54bd37d9ea158d7646c9c96b610d5
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 return errors
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):
201 errors = []
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())
207 if errors:
208 return [output_api.PresubmitError(
209 'Don\'t use #if '+'0; just delete the code.',
210 items=errors)]
211 return []
213 def FindNamespaceInBlock(pos, namespace, contents, whitelist=[]):
214 open_brace = -1
215 close_brace = -1
216 quote = -1
217 name = -1
218 brace_count = 1
219 quote_count = 0
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)
226 if name < 0:
227 return False # The namespace is not used at all.
228 if open_brace < 0:
229 open_brace = len(contents)
230 if close_brace < 0:
231 close_brace = len(contents)
232 if quote < 0:
233 quote = len(contents)
235 next = min(open_brace, min(close_brace, min(quote, name)))
237 if next == open_brace:
238 brace_count += 1
239 elif next == close_brace:
240 brace_count -= 1
241 elif next == quote:
242 quote_count = 0 if quote_count else 1
243 elif next == name and not quote_count:
244 in_whitelist = False
245 for w in whitelist:
246 if re.match(w, contents[next:]):
247 in_whitelist = True
248 break
249 if not in_whitelist:
250 return True
251 pos = next + 1
252 return False
254 # Checks for the use of cc:: within the cc namespace, which is usually
255 # redundant.
256 def CheckNamespace(input_api, output_api):
257 errors = []
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)
263 if match:
264 whitelist = [
265 r"cc::remove_if\b",
267 if FindNamespaceInBlock(match.end(), 'cc', contents, whitelist=whitelist):
268 errors.append(f.LocalPath())
270 if errors:
271 return [output_api.PresubmitError(
272 'Do not use cc:: inside of the cc namespace.',
273 items=errors)]
274 return []
276 def CheckForUseOfWrongClock(input_api,
277 output_api,
278 white_list=CC_SOURCE_FILES,
279 black_list=None):
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,
283 white_list,
284 black_list)
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:
298 # using base::Time;
299 # ...
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')')
312 problems = []
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):
317 problems.append(
318 ' %s:%d\n %s' % (f.LocalPath(), line_number, line.strip()))
320 if problems:
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))]
326 else:
327 return []
329 def CheckChangeOnUpload(input_api, output_api):
330 results = []
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)
342 return results
344 def GetPreferredTryMasters(project, change):
345 return {
346 'tryserver.blink': {
347 'linux_blink_rel': set(['defaulttests']),