1 # Copyright 2013 The Chromium Authors
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 Chromium media component.
7 See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
8 for more details about the presubmit API built into depot_tools.
13 PRESUBMIT_VERSION = '2.0.0'
15 # Well-defined simple classes containing only <= 4 ints, or <= 2 floats.
22 BASE_TIME_TYPES_RE = re.compile(r'\bconst (%s)&' % '|'.join(BASE_TIME_TYPES))
24 def _FilterFile(affected_file):
25 """Return true if the file could contain code requiring a presubmit check."""
26 return affected_file.LocalPath().endswith(
27 ('.h', '.cc', '.cpp', '.cxx', '.mm'))
30 def _CheckForUseOfWrongClock(input_api, output_api):
31 """Make sure new lines of media code don't use a clock susceptible to skew."""
33 # Regular expression that should detect any explicit references to the
34 # base::Time type (or base::Clock/DefaultClock), whether in using decls,
35 # typedefs, or to call static methods.
36 base_time_type_pattern = r'(^|\W)base::(Time|Clock|DefaultClock)(\W|$)'
38 # Regular expression that should detect references to the base::Time class
39 # members, such as a call to base::Time::Now.
40 base_time_member_pattern = r'(^|\W)(Time|Clock|DefaultClock)::'
42 # Regular expression to detect "using base::Time" declarations. We want to
43 # prevent these from triggerring a warning. For example, it's perfectly
44 # reasonable for code to be written like this:
48 # int64_t foo_us = foo_s * Time::kMicrosecondsPerSecond;
49 using_base_time_decl_pattern = r'^\s*using\s+(::)?base::Time\s*;'
51 # Regular expression to detect references to the kXXX constants in the
52 # base::Time class. We want to prevent these from triggerring a warning.
53 base_time_konstant_pattern = r'(^|\W)Time::k\w+'
55 # Regular expression to detect usage of openscreen clock types, which are
56 # allowed depending on DEPS rules.
57 openscreen_time_pattern = r'(^|\W)openscreen::Clock\s*'
59 problem_re = input_api.re.compile(
60 r'(' + base_time_type_pattern + r')|(' + base_time_member_pattern + r')')
61 exception_re = input_api.re.compile(
62 r'(' + using_base_time_decl_pattern + r')|(' +
63 base_time_konstant_pattern + r')|(' +
64 openscreen_time_pattern + r')')
66 for f in input_api.AffectedSourceFiles(_FilterFile):
67 for line_number, line in f.ChangedContents():
68 if problem_re.search(line):
69 if not exception_re.search(line):
71 ' %s:%d\n %s' % (f.LocalPath(), line_number, line.strip()))
74 return [output_api.PresubmitPromptOrNotify(
75 'You added one or more references to the base::Time class and/or one\n'
76 'of its member functions (or base::Clock/DefaultClock). In media\n'
77 'code, it is rarely correct to use a clock susceptible to time skew!\n'
78 'Instead, could you use base::TimeTicks to track the passage of\n'
79 'real-world time?\n\n' +
85 def _CheckForHistogramOffByOne(input_api, output_api):
86 """Make sure histogram enum maxes are used properly"""
88 # A general-purpose chunk of regex to match whitespace and/or comments
89 # that may be interspersed with the code we're interested in:
90 comment = r'/\*.*?\*/|//[^\n]*'
91 whitespace = r'(?:[\n\t ]|(?:' + comment + r'))*'
93 # The name is assumed to be a literal string.
94 histogram_name = r'"[^"]*"'
96 # This can be an arbitrary expression, so just ensure it isn't a ; to prevent
97 # matching past the end of this statement.
98 histogram_value = r'[^;]*'
100 # In parens so we can retrieve it for further checks.
101 histogram_max = r'([^;,]*)'
103 # This should match a uma histogram enumeration macro expression.
104 uma_macro_re = input_api.re.compile(
105 r'\bUMA_HISTOGRAM_ENUMERATION\(' + whitespace + histogram_name + r',' +
106 whitespace + histogram_value + r',' + whitespace + histogram_max +
107 whitespace + r'\)' + whitespace + r';(?:' + whitespace +
108 r'\/\/ (PRESUBMIT_IGNORE_UMA_MAX))?')
110 uma_max_re = input_api.re.compile(r'.*(?:Max|MAX).* \+ 1')
114 for f in input_api.AffectedSourceFiles(_FilterFile):
115 contents = input_api.ReadFile(f)
117 # We want to match across lines, but still report a line number, so we keep
118 # track of the line we're on as we search through the file.
121 # We search the entire file, then check if any violations are in the changed
122 # areas, this is inefficient, but simple. A UMA_HISTOGRAM_ENUMERATION call
123 # will often span multiple lines, so finding a match looking just at the
124 # deltas line-by-line won't catch problems.
125 match = uma_macro_re.search(contents)
127 line_number += contents.count('\n', 0, match.start())
128 max_arg = match.group(1) # The third argument.
130 if (not uma_max_re.match(max_arg) and match.group(2) !=
131 'PRESUBMIT_IGNORE_UMA_MAX'):
132 uma_range = range(match.start(), match.end() + 1)
133 # Check if any part of the match is in the changed lines:
134 for num, line in f.ChangedContents():
135 if line_number <= num <= line_number + match.group().count('\n'):
136 problems.append('%s:%d' % (f, line_number))
139 # Strip off the file contents up to the end of the match and update the
141 contents = contents[match.end():]
142 line_number += match.group().count('\n')
143 match = uma_macro_re.search(contents)
146 return [output_api.PresubmitError(
147 'UMA_HISTOGRAM_ENUMERATION reports in src/media/ are expected to adhere\n'
148 'to the following guidelines:\n'
149 ' - The max value (3rd argument) should be an enum value equal to the\n'
150 ' last valid value, e.g. FOO_MAX = LAST_VALID_FOO.\n'
151 ' - 1 must be added to that max value.\n'
152 'Contact dalecurtis@chromium.org if you have questions.' , problems)]
157 def _CheckPassByValue(input_api, output_api):
158 """Check that base::Time and derived classes are passed by value, and not by
163 for f in input_api.AffectedSourceFiles(_FilterFile):
164 for line_number, line in f.ChangedContents():
165 if BASE_TIME_TYPES_RE.search(line):
166 problems.append('%s:%d' % (f, line_number))
169 return [output_api.PresubmitError(
170 'base::Time and derived classes should be passed by value and not by\n'
171 'const ref, see base/time/time.h for more information.', problems)]
175 def _CheckForUseOfLazyInstance(input_api, output_api):
176 """Check that base::LazyInstance is not used."""
180 lazy_instance_re = re.compile(r'(^|\W)base::LazyInstance<')
182 for f in input_api.AffectedSourceFiles(_FilterFile):
183 for line_number, line in f.ChangedContents():
184 if lazy_instance_re.search(line):
185 problems.append('%s:%d' % (f, line_number))
188 return [output_api.PresubmitError(
189 'base::LazyInstance is deprecated; use a thread safe static.', problems)]
192 def _CheckNoLoggingOverrideInHeaders(input_api, output_api):
193 """Checks to make sure no .h files include logging_override_if_enabled.h."""
195 pattern = input_api.re.compile(
196 r'^#include\s*"media/base/logging_override_if_enabled.h"',
197 input_api.re.MULTILINE)
198 for f in input_api.AffectedSourceFiles(input_api.FilterSourceFile):
199 if not f.LocalPath().endswith('.h'):
201 contents = input_api.ReadFile(f)
202 if pattern.search(contents):
206 return [output_api.PresubmitError(
207 'Do not #include "logging_override_if_enabled.h" in header files, '
208 'since it overrides DVLOG() in every file including the header. '
209 'Instead, only include it in source files.',
213 def _CheckForNoV4L2AggregateInitialization(input_api, output_api):
214 """Check that struct v4l2_* are not initialized as aggregates with a
219 v4l2_aggregate_initializer_re = re.compile(r'(^|\W)struct.+v4l2_.+=.+{+}+;')
221 for f in input_api.AffectedSourceFiles(_FilterFile):
222 for line_number, line in f.ChangedContents():
223 if v4l2_aggregate_initializer_re.search(line):
224 problems.append('%s:%d' % (f, line_number))
227 return [output_api.PresubmitPromptWarning(
228 'Avoid initializing V4L2 structures with braced-init-lists, i.e. as '
229 'aggregates. V4L2 structs often contain unions of various sized members: '
230 'when a union is initialized by aggregate initialization, only the first '
231 'non-static member is initialized, leaving other members unitialized if '
232 'they are larger. Use memset instead.',
236 def _CheckChangeInBundle(input_api, output_api):
238 old_sys_path = sys.path[:]
241 sys.path.append(input_api.change.RepositoryRoot())
242 from build.ios import presubmit_support
243 results += presubmit_support.CheckBundleData(input_api, output_api,
244 'unit_tests_bundle_data')
246 sys.path = old_sys_path
249 def _CheckChange(input_api, output_api):
251 results.extend(_CheckForUseOfWrongClock(input_api, output_api))
252 results.extend(_CheckPassByValue(input_api, output_api))
253 results.extend(_CheckForHistogramOffByOne(input_api, output_api))
254 results.extend(_CheckForUseOfLazyInstance(input_api, output_api))
255 results.extend(_CheckNoLoggingOverrideInHeaders(input_api, output_api))
256 results.extend(_CheckForNoV4L2AggregateInitialization(input_api, output_api))
257 results.extend(_CheckChangeInBundle(input_api, output_api))
261 def CheckChangeOnUpload(input_api, output_api):
262 return _CheckChange(input_api, output_api)
265 def CheckChangeOnCommit(input_api, output_api):
266 return _CheckChange(input_api, output_api)