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