Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / chrome / browser / web_dev_style / css_checker.py
blob3713561e5e129acc137b5a5bc8f790624a62d3b0
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 """Presubmit script for Chromium WebUI resources.
7 See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
8 for more details about the presubmit API built into depot_tools, and see
9 http://www.chromium.org/developers/web-development-style-guide for the rules
10 we're checking against here.
11 """
13 # TODO(dbeam): Real CSS parser? https://github.com/danbeam/css-py/tree/css3
15 class CSSChecker(object):
16 def __init__(self, input_api, output_api, file_filter=None):
17 self.input_api = input_api
18 self.output_api = output_api
19 self.file_filter = file_filter
21 def RunChecks(self):
22 # We use this a lot, so make a nick name variable.
23 re = self.input_api.re
25 def _collapseable_hex(s):
26 return (len(s) == 6 and s[0] == s[1] and s[2] == s[3] and s[4] == s[5])
28 def _is_gray(s):
29 return s[0] == s[1] == s[2] if len(s) == 3 else s[0:2] == s[2:4] == s[4:6]
31 def _remove_all(s):
32 s = _remove_grit(s)
33 s = _remove_ats(s)
34 s = _remove_comments(s)
35 s = _remove_template_expressions(s)
36 s = _remove_mixins(s)
37 return s
39 def _remove_ats(s):
40 at_reg = re.compile(r"""
41 @(?!\d+x\b)\w+[^'"]*?{ # @at-keyword selector junk {, not @2x
42 (.*{.*?})+ # inner { curly } blocks, rules, and selector
43 .*?} # stuff up to the first end curly }
44 """,
45 re.DOTALL | re.VERBOSE)
46 return at_reg.sub('\\1', s)
48 def _remove_comments(s):
49 return re.sub(re.compile(r'/\*.*?\*/', re.DOTALL), '', s)
51 def _remove_mixins(s):
52 return re.sub(re.compile(r'--[\d\w-]+: {.*?};', re.DOTALL), '', s)
54 def _remove_template_expressions(s):
55 return re.sub(re.compile(r'\${[^}]*}', re.DOTALL), '', s)
57 def _remove_grit(s):
58 grit_reg = re.compile(r"""
59 <if[^>]+>.*?<\s*/\s*if[^>]*>| # <if> contents </if>
60 <include[^>]+> # <include>
61 """,
62 re.DOTALL | re.VERBOSE)
63 return re.sub(grit_reg, '', s)
65 def _rgb_from_hex(s):
66 if len(s) == 3:
67 r, g, b = s[0] + s[0], s[1] + s[1], s[2] + s[2]
68 else:
69 r, g, b = s[0:2], s[2:4], s[4:6]
70 return int(r, base=16), int(g, base=16), int(b, base=16)
72 def _strip_prefix(s):
73 return re.sub(r'^-(?:o|ms|moz|khtml|webkit)-', '', s)
75 def alphabetize_props(contents):
76 errors = []
77 # TODO(dbeam): make this smart enough to detect issues in mixins.
78 for rule in re.finditer(r'{(.*?)}', contents, re.DOTALL):
79 semis = map(lambda t: t.strip(), rule.group(1).split(';'))[:-1]
80 rules = filter(lambda r: ': ' in r, semis)
81 props = map(lambda r: r[0:r.find(':')], rules)
82 if props != sorted(props):
83 errors.append(' %s;\n' % (';\n '.join(rules)))
84 return errors
86 def braces_have_space_before_and_nothing_after(line):
87 brace_space_reg = re.compile(r"""
88 (?:^|\S){| # selector{ or selector\n{ or
89 {\s*\S+\s* # selector { with stuff after it
90 $ # must be at the end of a line
91 """,
92 re.VERBOSE)
93 return brace_space_reg.search(line)
95 def classes_use_dashes(line):
96 # Intentionally dumbed down version of CSS 2.1 grammar for class without
97 # non-ASCII, escape chars, or whitespace.
98 class_reg = re.compile(r"""
99 \.(-?[\w-]+).* # ., then maybe -, then alpha numeric and -
100 [,{]\s*$ # selectors should end with a , or {
101 """,
102 re.VERBOSE)
103 m = class_reg.search(line)
104 if not m:
105 return False
106 class_name = m.group(1)
107 return class_name.lower() != class_name or '_' in class_name
109 end_mixin_reg = re.compile(r'\s*};\s*$')
111 def close_brace_on_new_line(line):
112 # Ignore single frames in a @keyframe, i.e. 0% { margin: 50px; }
113 frame_reg = re.compile(r"""
114 \s*(from|to|\d+%)\s*{ # 50% {
115 \s*[\w-]+: # rule:
116 (\s*[\w\(\), -]+)+\s*; # value;
117 \s*}\s* # }
118 """,
119 re.VERBOSE)
120 return ('}' in line and re.search(r'[^ }]', line) and
121 not frame_reg.match(line) and not end_mixin_reg.match(line))
123 def colons_have_space_after(line):
124 colon_space_reg = re.compile(r"""
125 (?<!data) # ignore data URIs
126 :(?!//) # ignore url(http://), etc.
127 \S[^;]+;\s* # only catch one-line rules for now
128 """,
129 re.VERBOSE)
130 return colon_space_reg.search(line)
132 def favor_single_quotes(line):
133 return '"' in line
135 # Shared between hex_could_be_shorter and rgb_if_not_gray.
136 hex_reg = re.compile(r"""
137 \#([a-fA-F0-9]{3}|[a-fA-F0-9]{6}) # pound followed by 3 or 6 hex digits
138 (?=[^\w-]|$) # no more alphanum chars or at EOL
139 (?!.*(?:{.*|,\s*)$) # not in a selector
140 """,
141 re.VERBOSE)
143 def hex_could_be_shorter(line):
144 m = hex_reg.search(line)
145 return (m and _is_gray(m.group(1)) and _collapseable_hex(m.group(1)))
147 def rgb_if_not_gray(line):
148 m = hex_reg.search(line)
149 return (m and not _is_gray(m.group(1)))
151 small_seconds_reg = re.compile(r"""
152 (?:^|[^\w-]) # start of a line or a non-alphanumeric char
153 (0?\.[0-9]+)s # 1.0s
154 (?!-?[\w-]) # no following - or alphanumeric chars
155 """,
156 re.VERBOSE)
158 def milliseconds_for_small_times(line):
159 return small_seconds_reg.search(line)
161 def suggest_ms_from_s(line):
162 ms = int(float(small_seconds_reg.search(line).group(1)) * 1000)
163 return ' (replace with %dms)' % ms
165 def no_data_uris_in_source_files(line):
166 return re.search(r'\(\s*\s*data:', line)
168 def no_quotes_in_url(line):
169 return re.search('url\s*\(\s*["\']', line, re.IGNORECASE)
171 def one_rule_per_line(line):
172 one_rule_reg = re.compile(r"""
173 [\w-](?<!data): # a rule: but no data URIs
174 (?!//)[^;]+; # value; ignoring colons in protocols:// and };
175 \s*[^ }]\s* # any non-space after the end colon
176 """,
177 re.VERBOSE)
178 return one_rule_reg.search(line) and not end_mixin_reg.match(line)
180 def pseudo_elements_double_colon(contents):
181 pseudo_elements = ['after',
182 'before',
183 'calendar-picker-indicator',
184 'color-swatch',
185 'color-swatch-wrapper',
186 'date-and-time-container',
187 'date-and-time-value',
188 'datetime-edit',
189 'datetime-edit-ampm-field',
190 'datetime-edit-day-field',
191 'datetime-edit-hour-field',
192 'datetime-edit-millisecond-field',
193 'datetime-edit-minute-field',
194 'datetime-edit-month-field',
195 'datetime-edit-second-field',
196 'datetime-edit-text',
197 'datetime-edit-week-field',
198 'datetime-edit-year-field',
199 'details-marker',
200 'file-upload-button',
201 'first-letter',
202 'first-line',
203 'inner-spin-button',
204 'input-placeholder',
205 'input-speech-button',
206 'keygen-select',
207 'media-slider-container',
208 'media-slider-thumb',
209 'meter-bar',
210 'meter-even-less-good-value',
211 'meter-inner-element',
212 'meter-optimum-value',
213 'meter-suboptimum-value',
214 'progress-bar',
215 'progress-inner-element',
216 'progress-value',
217 'resizer',
218 'scrollbar',
219 'scrollbar-button',
220 'scrollbar-corner',
221 'scrollbar-thumb',
222 'scrollbar-track',
223 'scrollbar-track-piece',
224 'search-cancel-button',
225 'search-decoration',
226 'search-results-button',
227 'search-results-decoration',
228 'selection',
229 'slider-container',
230 'slider-runnable-track',
231 'slider-thumb',
232 'textfield-decoration-container',
233 'validation-bubble',
234 'validation-bubble-arrow',
235 'validation-bubble-arrow-clipper',
236 'validation-bubble-heading',
237 'validation-bubble-message',
238 'validation-bubble-text-block']
239 pseudo_reg = re.compile(r"""
240 (?<!:): # a single colon, i.e. :after but not ::after
241 ([a-zA-Z-]+) # a pseudo element, class, or function
242 (?=[^{}]+?{) # make sure a selector, not inside { rules }
243 """,
244 re.MULTILINE | re.VERBOSE)
245 errors = []
246 for p in re.finditer(pseudo_reg, contents):
247 pseudo = p.group(1).strip().splitlines()[0]
248 if _strip_prefix(pseudo.lower()) in pseudo_elements:
249 errors.append(' :%s (should be ::%s)' % (pseudo, pseudo))
250 return errors
252 def one_selector_per_line(contents):
253 any_reg = re.compile(r"""
254 :(?:-webkit-)?any\(.*?\) # :-webkit-any(a, b, i) selector
255 """,
256 re.DOTALL | re.VERBOSE)
257 multi_sels_reg = re.compile(r"""
258 (?:}\s*)? # ignore 0% { blah: blah; }, from @keyframes
259 ([^,]+,(?=[^{}]+?{) # selector junk {, not in a { rule }
260 .*[,{])\s*$ # has to end with , or {
261 """,
262 re.MULTILINE | re.VERBOSE)
263 errors = []
264 for b in re.finditer(multi_sels_reg, re.sub(any_reg, '', contents)):
265 errors.append(' ' + b.group(1).strip().splitlines()[-1:][0])
266 return errors
268 def suggest_rgb_from_hex(line):
269 suggestions = ['rgb(%d, %d, %d)' % _rgb_from_hex(h.group(1))
270 for h in re.finditer(hex_reg, line)]
271 return ' (replace with %s)' % ', '.join(suggestions)
273 def suggest_short_hex(line):
274 h = hex_reg.search(line).group(1)
275 return ' (replace with #%s)' % (h[0] + h[2] + h[4])
277 webkit_before_or_after_reg = re.compile(r'-webkit-(\w+-)(after|before):')
279 def suggest_top_or_bottom(line):
280 prop, pos = webkit_before_or_after_reg.search(line).groups()
281 top_or_bottom = 'top' if pos == 'before' else 'bottom'
282 return ' (replace with %s)' % (prop + top_or_bottom)
284 def webkit_before_or_after(line):
285 return webkit_before_or_after_reg.search(line)
287 def zero_width_lengths(contents):
288 hsl_reg = re.compile(r"""
289 hsl\([^\)]* # hsl(maybestuff
290 (?:[, ]|(?<=\()) # a comma or space not followed by a (
291 (?:0?\.?)?0% # some equivalent to 0%
292 """,
293 re.VERBOSE)
294 zeros_reg = re.compile(r"""
295 ^.*(?:^|[^0-9.]) # start/non-number
296 (?:\.0|0(?:\.0? # .0, 0, or 0.0
297 |px|em|%|in|cm|mm|pc|pt|ex)) # a length unit
298 (?:\D|$) # non-number/end
299 (?=[^{}]+?}).*$ # only { rules }
300 """,
301 re.MULTILINE | re.VERBOSE)
302 errors = []
303 for z in re.finditer(zeros_reg, contents):
304 first_line = z.group(0).strip().splitlines()[0]
305 if not hsl_reg.search(first_line):
306 errors.append(' ' + first_line)
307 return errors
309 # NOTE: Currently multi-line checks don't support 'after'. Instead, add
310 # suggestions while parsing the file so another pass isn't necessary.
311 added_or_modified_files_checks = [
312 { 'desc': 'Alphabetize properties and list vendor specific (i.e. '
313 '-webkit) above standard.',
314 'test': alphabetize_props,
315 'multiline': True,
317 { 'desc': 'Start braces ({) end a selector, have a space before them '
318 'and no rules after.',
319 'test': braces_have_space_before_and_nothing_after,
321 { 'desc': 'Classes use .dash-form.',
322 'test': classes_use_dashes,
324 { 'desc': 'Always put a rule closing brace (}) on a new line.',
325 'test': close_brace_on_new_line,
327 { 'desc': 'Colons (:) should have a space after them.',
328 'test': colons_have_space_after,
330 { 'desc': 'Use single quotes (\') instead of double quotes (") in '
331 'strings.',
332 'test': favor_single_quotes,
334 { 'desc': 'Use abbreviated hex (#rgb) when in form #rrggbb.',
335 'test': hex_could_be_shorter,
336 'after': suggest_short_hex,
338 { 'desc': 'Use milliseconds for time measurements under 1 second.',
339 'test': milliseconds_for_small_times,
340 'after': suggest_ms_from_s,
342 { 'desc': "Don't use data URIs in source files. Use grit instead.",
343 'test': no_data_uris_in_source_files,
345 { 'desc': "Don't use quotes in url().",
346 'test': no_quotes_in_url,
348 { 'desc': 'One rule per line (what not to do: color: red; margin: 0;).',
349 'test': one_rule_per_line,
351 { 'desc': 'One selector per line (what not to do: a, b {}).',
352 'test': one_selector_per_line,
353 'multiline': True,
355 { 'desc': 'Pseudo-elements should use double colon (i.e. ::after).',
356 'test': pseudo_elements_double_colon,
357 'multiline': True,
359 { 'desc': 'Use rgb() over #hex when not a shade of gray (like #333).',
360 'test': rgb_if_not_gray,
361 'after': suggest_rgb_from_hex,
363 { 'desc': 'Use *-top/bottom instead of -webkit-*-before/after.',
364 'test': webkit_before_or_after,
365 'after': suggest_top_or_bottom,
367 { 'desc': 'Use "0" for zero-width lengths (i.e. 0px -> 0)',
368 'test': zero_width_lengths,
369 'multiline': True,
373 results = []
374 affected_files = self.input_api.AffectedFiles(include_deletes=False,
375 file_filter=self.file_filter)
376 files = []
377 for f in affected_files:
378 # Remove all /*comments*/, @at-keywords, and grit <if|include> tags; we're
379 # not using a real parser. TODO(dbeam): Check alpha in <if> blocks.
380 file_contents = _remove_all('\n'.join(f.NewContents()))
381 files.append((f.LocalPath(), file_contents))
383 # Only look at CSS files for now.
384 for f in filter(lambda f: f[0].endswith('.css'), files):
385 file_errors = []
386 for check in added_or_modified_files_checks:
387 # If the check is multiline, it receieves the whole file and gives us
388 # back a list of things wrong. If the check isn't multiline, we pass it
389 # each line and the check returns something truthy if there's an issue.
390 if ('multiline' in check and check['multiline']):
391 assert not 'after' in check
392 check_errors = check['test'](f[1])
393 if len(check_errors) > 0:
394 file_errors.append('- %s\n%s' %
395 (check['desc'], '\n'.join(check_errors).rstrip()))
396 else:
397 check_errors = []
398 lines = f[1].splitlines()
399 for lnum, line in enumerate(lines):
400 if check['test'](line):
401 error = ' ' + line.strip()
402 if 'after' in check:
403 error += check['after'](line)
404 check_errors.append(error)
405 if len(check_errors) > 0:
406 file_errors.append('- %s\n%s' %
407 (check['desc'], '\n'.join(check_errors)))
408 if file_errors:
409 results.append(self.output_api.PresubmitPromptWarning(
410 '%s:\n%s' % (f[0], '\n\n'.join(file_errors))))
412 return results