Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / chrome / browser / web_dev_style / css_checker.py
blobc41d1bdc84a343bbdadf74553995b61841d091e6
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 return s
38 def _remove_ats(s):
39 at_reg = re.compile(r"""
40 @(?!\d+x\b)\w+[^'"]*?{ # @at-keyword selector junk {, not @2x
41 (.*{.*?})+ # inner { curly } blocks, rules, and selector
42 .*?} # stuff up to the first end curly }
43 """,
44 re.DOTALL | re.VERBOSE)
45 return at_reg.sub('\\1', s)
47 def _remove_comments(s):
48 return re.sub(re.compile(r'/\*.*?\*/', re.DOTALL), '', s)
50 def _remove_template_expressions(s):
51 return re.sub(re.compile(r'\${[^}]*}', re.DOTALL), '', s)
53 def _remove_grit(s):
54 grit_reg = re.compile(r"""
55 <if[^>]+>.*?<\s*/\s*if[^>]*>| # <if> contents </if>
56 <include[^>]+> # <include>
57 """,
58 re.DOTALL | re.VERBOSE)
59 return re.sub(grit_reg, '', s)
61 def _rgb_from_hex(s):
62 if len(s) == 3:
63 r, g, b = s[0] + s[0], s[1] + s[1], s[2] + s[2]
64 else:
65 r, g, b = s[0:2], s[2:4], s[4:6]
66 return int(r, base=16), int(g, base=16), int(b, base=16)
68 def _strip_prefix(s):
69 return re.sub(r'^-(?:o|ms|moz|khtml|webkit)-', '', s)
71 def alphabetize_props(contents):
72 errors = []
73 for rule in re.finditer(r'{(.*?)}', contents, re.DOTALL):
74 semis = map(lambda t: t.strip(), rule.group(1).split(';'))[:-1]
75 rules = filter(lambda r: ': ' in r, semis)
76 props = map(lambda r: r[0:r.find(':')], rules)
77 if props != sorted(props):
78 errors.append(' %s;\n' % (';\n '.join(rules)))
79 return errors
81 def braces_have_space_before_and_nothing_after(line):
82 brace_space_reg = re.compile(r"""
83 (?:^|\S){| # selector{ or selector\n{ or
84 {\s*\S+\s* # selector { with stuff after it
85 $ # must be at the end of a line
86 """,
87 re.VERBOSE)
88 return brace_space_reg.search(line)
90 def classes_use_dashes(line):
91 # Intentionally dumbed down version of CSS 2.1 grammar for class without
92 # non-ASCII, escape chars, or whitespace.
93 class_reg = re.compile(r"""
94 \.(-?[\w-]+).* # ., then maybe -, then alpha numeric and -
95 [,{]\s*$ # selectors should end with a , or {
96 """,
97 re.VERBOSE)
98 m = class_reg.search(line)
99 if not m:
100 return False
101 class_name = m.group(1)
102 return class_name.lower() != class_name or '_' in class_name
104 end_mixin_reg = re.compile(r'\s*};\s*$')
106 def close_brace_on_new_line(line):
107 # Ignore single frames in a @keyframe, i.e. 0% { margin: 50px; }
108 frame_reg = re.compile(r"""
109 \s*(from|to|\d+%)\s*{ # 50% {
110 \s*[\w-]+: # rule:
111 (\s*[\w\(\), -]+)+\s*; # value;
112 \s*}\s* # }
113 """,
114 re.VERBOSE)
115 return ('}' in line and re.search(r'[^ }]', line) and
116 not frame_reg.match(line) and not end_mixin_reg.match(line))
118 def colons_have_space_after(line):
119 colon_space_reg = re.compile(r"""
120 (?<!data) # ignore data URIs
121 :(?!//) # ignore url(http://), etc.
122 \S[^;]+;\s* # only catch one-line rules for now
123 """,
124 re.VERBOSE)
125 return colon_space_reg.search(line)
127 def favor_single_quotes(line):
128 return '"' in line
130 # Shared between hex_could_be_shorter and rgb_if_not_gray.
131 hex_reg = re.compile(r"""
132 \#([a-fA-F0-9]{3}|[a-fA-F0-9]{6}) # pound followed by 3 or 6 hex digits
133 (?=[^\w-]|$) # no more alphanum chars or at EOL
134 (?!.*(?:{.*|,\s*)$) # not in a selector
135 """,
136 re.VERBOSE)
138 def hex_could_be_shorter(line):
139 m = hex_reg.search(line)
140 return (m and _is_gray(m.group(1)) and _collapseable_hex(m.group(1)))
142 def rgb_if_not_gray(line):
143 m = hex_reg.search(line)
144 return (m and not _is_gray(m.group(1)))
146 small_seconds_reg = re.compile(r"""
147 (?:^|[^\w-]) # start of a line or a non-alphanumeric char
148 (0?\.[0-9]+)s # 1.0s
149 (?!-?[\w-]) # no following - or alphanumeric chars
150 """,
151 re.VERBOSE)
153 def milliseconds_for_small_times(line):
154 return small_seconds_reg.search(line)
156 def suggest_ms_from_s(line):
157 ms = int(float(small_seconds_reg.search(line).group(1)) * 1000)
158 return ' (replace with %dms)' % ms
160 def no_data_uris_in_source_files(line):
161 return re.search(r'\(\s*\s*data:', line)
163 def no_quotes_in_url(line):
164 return re.search('url\s*\(\s*["\']', line, re.IGNORECASE)
166 def one_rule_per_line(line):
167 one_rule_reg = re.compile(r"""
168 [\w-](?<!data): # a rule: but no data URIs
169 (?!//)[^;]+; # value; ignoring colons in protocols:// and };
170 \s*[^ }]\s* # any non-space after the end colon
171 """,
172 re.VERBOSE)
173 return one_rule_reg.search(line) and not end_mixin_reg.match(line)
175 def pseudo_elements_double_colon(contents):
176 pseudo_elements = ['after',
177 'before',
178 'calendar-picker-indicator',
179 'color-swatch',
180 'color-swatch-wrapper',
181 'date-and-time-container',
182 'date-and-time-value',
183 'datetime-edit',
184 'datetime-edit-ampm-field',
185 'datetime-edit-day-field',
186 'datetime-edit-hour-field',
187 'datetime-edit-millisecond-field',
188 'datetime-edit-minute-field',
189 'datetime-edit-month-field',
190 'datetime-edit-second-field',
191 'datetime-edit-text',
192 'datetime-edit-week-field',
193 'datetime-edit-year-field',
194 'details-marker',
195 'file-upload-button',
196 'first-letter',
197 'first-line',
198 'inner-spin-button',
199 'input-placeholder',
200 'input-speech-button',
201 'keygen-select',
202 'media-slider-container',
203 'media-slider-thumb',
204 'meter-bar',
205 'meter-even-less-good-value',
206 'meter-inner-element',
207 'meter-optimum-value',
208 'meter-suboptimum-value',
209 'progress-bar',
210 'progress-inner-element',
211 'progress-value',
212 'resizer',
213 'scrollbar',
214 'scrollbar-button',
215 'scrollbar-corner',
216 'scrollbar-thumb',
217 'scrollbar-track',
218 'scrollbar-track-piece',
219 'search-cancel-button',
220 'search-decoration',
221 'search-results-button',
222 'search-results-decoration',
223 'selection',
224 'slider-container',
225 'slider-runnable-track',
226 'slider-thumb',
227 'textfield-decoration-container',
228 'validation-bubble',
229 'validation-bubble-arrow',
230 'validation-bubble-arrow-clipper',
231 'validation-bubble-heading',
232 'validation-bubble-message',
233 'validation-bubble-text-block']
234 pseudo_reg = re.compile(r"""
235 (?<!:): # a single colon, i.e. :after but not ::after
236 ([a-zA-Z-]+) # a pseudo element, class, or function
237 (?=[^{}]+?{) # make sure a selector, not inside { rules }
238 """,
239 re.MULTILINE | re.VERBOSE)
240 errors = []
241 for p in re.finditer(pseudo_reg, contents):
242 pseudo = p.group(1).strip().splitlines()[0]
243 if _strip_prefix(pseudo.lower()) in pseudo_elements:
244 errors.append(' :%s (should be ::%s)' % (pseudo, pseudo))
245 return errors
247 def one_selector_per_line(contents):
248 any_reg = re.compile(r"""
249 :(?:-webkit-)?any\(.*?\) # :-webkit-any(a, b, i) selector
250 """,
251 re.DOTALL | re.VERBOSE)
252 multi_sels_reg = re.compile(r"""
253 (?:}\s*)? # ignore 0% { blah: blah; }, from @keyframes
254 ([^,]+,(?=[^{}]+?{) # selector junk {, not in a { rule }
255 .*[,{])\s*$ # has to end with , or {
256 """,
257 re.MULTILINE | re.VERBOSE)
258 errors = []
259 for b in re.finditer(multi_sels_reg, re.sub(any_reg, '', contents)):
260 errors.append(' ' + b.group(1).strip().splitlines()[-1:][0])
261 return errors
263 def suggest_rgb_from_hex(line):
264 suggestions = ['rgb(%d, %d, %d)' % _rgb_from_hex(h.group(1))
265 for h in re.finditer(hex_reg, line)]
266 return ' (replace with %s)' % ', '.join(suggestions)
268 def suggest_short_hex(line):
269 h = hex_reg.search(line).group(1)
270 return ' (replace with #%s)' % (h[0] + h[2] + h[4])
272 webkit_before_or_after_reg = re.compile(r'-webkit-(\w+-)(after|before):')
274 def suggest_top_or_bottom(line):
275 prop, pos = webkit_before_or_after_reg.search(line).groups()
276 top_or_bottom = 'top' if pos == 'before' else 'bottom'
277 return ' (replace with %s)' % (prop + top_or_bottom)
279 def webkit_before_or_after(line):
280 return webkit_before_or_after_reg.search(line)
282 def zero_width_lengths(contents):
283 hsl_reg = re.compile(r"""
284 hsl\([^\)]* # hsl(maybestuff
285 (?:[, ]|(?<=\()) # a comma or space not followed by a (
286 (?:0?\.?)?0% # some equivalent to 0%
287 """,
288 re.VERBOSE)
289 zeros_reg = re.compile(r"""
290 ^.*(?:^|[^0-9.]) # start/non-number
291 (?:\.0|0(?:\.0? # .0, 0, or 0.0
292 |px|em|%|in|cm|mm|pc|pt|ex)) # a length unit
293 (?:\D|$) # non-number/end
294 (?=[^{}]+?}).*$ # only { rules }
295 """,
296 re.MULTILINE | re.VERBOSE)
297 errors = []
298 for z in re.finditer(zeros_reg, contents):
299 first_line = z.group(0).strip().splitlines()[0]
300 if not hsl_reg.search(first_line):
301 errors.append(' ' + first_line)
302 return errors
304 # NOTE: Currently multi-line checks don't support 'after'. Instead, add
305 # suggestions while parsing the file so another pass isn't necessary.
306 added_or_modified_files_checks = [
307 { 'desc': 'Alphabetize properties and list vendor specific (i.e. '
308 '-webkit) above standard.',
309 'test': alphabetize_props,
310 'multiline': True,
312 { 'desc': 'Start braces ({) end a selector, have a space before them '
313 'and no rules after.',
314 'test': braces_have_space_before_and_nothing_after,
316 { 'desc': 'Classes use .dash-form.',
317 'test': classes_use_dashes,
319 { 'desc': 'Always put a rule closing brace (}) on a new line.',
320 'test': close_brace_on_new_line,
322 { 'desc': 'Colons (:) should have a space after them.',
323 'test': colons_have_space_after,
325 { 'desc': 'Use single quotes (\') instead of double quotes (") in '
326 'strings.',
327 'test': favor_single_quotes,
329 { 'desc': 'Use abbreviated hex (#rgb) when in form #rrggbb.',
330 'test': hex_could_be_shorter,
331 'after': suggest_short_hex,
333 { 'desc': 'Use milliseconds for time measurements under 1 second.',
334 'test': milliseconds_for_small_times,
335 'after': suggest_ms_from_s,
337 { 'desc': "Don't use data URIs in source files. Use grit instead.",
338 'test': no_data_uris_in_source_files,
340 { 'desc': "Don't use quotes in url().",
341 'test': no_quotes_in_url,
343 { 'desc': 'One rule per line (what not to do: color: red; margin: 0;).',
344 'test': one_rule_per_line,
346 { 'desc': 'One selector per line (what not to do: a, b {}).',
347 'test': one_selector_per_line,
348 'multiline': True,
350 { 'desc': 'Pseudo-elements should use double colon (i.e. ::after).',
351 'test': pseudo_elements_double_colon,
352 'multiline': True,
354 { 'desc': 'Use rgb() over #hex when not a shade of gray (like #333).',
355 'test': rgb_if_not_gray,
356 'after': suggest_rgb_from_hex,
358 { 'desc': 'Use *-top/bottom instead of -webkit-*-before/after.',
359 'test': webkit_before_or_after,
360 'after': suggest_top_or_bottom,
362 { 'desc': 'Use "0" for zero-width lengths (i.e. 0px -> 0)',
363 'test': zero_width_lengths,
364 'multiline': True,
368 results = []
369 affected_files = self.input_api.AffectedFiles(include_deletes=False,
370 file_filter=self.file_filter)
371 files = []
372 for f in affected_files:
373 # Remove all /*comments*/, @at-keywords, and grit <if|include> tags; we're
374 # not using a real parser. TODO(dbeam): Check alpha in <if> blocks.
375 file_contents = _remove_all('\n'.join(f.NewContents()))
376 files.append((f.LocalPath(), file_contents))
378 # Only look at CSS files for now.
379 for f in filter(lambda f: f[0].endswith('.css'), files):
380 file_errors = []
381 for check in added_or_modified_files_checks:
382 # If the check is multiline, it receieves the whole file and gives us
383 # back a list of things wrong. If the check isn't multiline, we pass it
384 # each line and the check returns something truthy if there's an issue.
385 if ('multiline' in check and check['multiline']):
386 assert not 'after' in check
387 check_errors = check['test'](f[1])
388 if len(check_errors) > 0:
389 file_errors.append('- %s\n%s' %
390 (check['desc'], '\n'.join(check_errors).rstrip()))
391 else:
392 check_errors = []
393 lines = f[1].splitlines()
394 for lnum, line in enumerate(lines):
395 if check['test'](line):
396 error = ' ' + line.strip()
397 if 'after' in check:
398 error += check['after'](line)
399 check_errors.append(error)
400 if len(check_errors) > 0:
401 file_errors.append('- %s\n%s' %
402 (check['desc'], '\n'.join(check_errors)))
403 if file_errors:
404 results.append(self.output_api.PresubmitPromptWarning(
405 '%s:\n%s' % (f[0], '\n\n'.join(file_errors))))
407 if results:
408 # Add your name if you're here often mucking around in the code.
409 authors = ['dbeam@chromium.org']
410 results.append(self.output_api.PresubmitNotifyResult(
411 'Was the CSS checker useful? Send feedback or hate mail to %s.' %
412 ', '.join(authors)))
414 return results