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 gcl/git cl, and see
9 http://www.chromium.org/developers/web-development-style-guide for the rules
10 we're checking against here.
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
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])
29 return s
[0] == s
[1] == s
[2] if len(s
) == 3 else s
[0:2] == s
[2:4] == s
[4:6]
32 return _remove_grit(_remove_ats(_remove_comments(s
)))
35 at_reg
= re
.compile(r
"""
36 @\w+[^'"]*?{ # @at-keyword selector junk {
37 (.*{.*?})+ # inner { curly } blocks, rules, and selector junk
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
)
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
)
54 r
, g
, b
= s
[0] + s
[0], s
[1] + s
[1], s
[2] + s
[2]
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)
60 return re
.sub(r
'^-(?:o|ms|moz|khtml|webkit)-', '', s
)
62 def alphabetize_props(contents
):
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
)))
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""",
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 {""",
87 m
= class_reg
.search(line
)
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
"""
98 (\s*[\w-]+)+\s*; # value;
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""",
110 return colon_space_reg
.search(line
)
112 def favor_single_quotes(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""",
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
133 (?!-?[\w-]) # no following - or alphanumeric chars""",
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 one_rule_per_line(line):
147 one_rule_reg = re.compile(r"""
148 [\w-](?<!data): # a rule: but no data URIs
149 (?!//)[^;]+; # value; ignoring colons in protocols://
150 \s*[^ }]\s* # any non-space after the end colon""",
152 return one_rule_reg.search(line)
154 def pseudo_elements_double_colon(contents):
155 pseudo_elements = ['after
',
157 'calendar
-picker
-indicator
',
159 'color
-swatch
-wrapper
',
160 'date
-and-time
-container
',
161 'date
-and-time
-value
',
163 'datetime
-edit
-ampm
-field
',
164 'datetime
-edit
-day
-field
',
165 'datetime
-edit
-hour
-field
',
166 'datetime
-edit
-millisecond
-field
',
167 'datetime
-edit
-minute
-field
',
168 'datetime
-edit
-month
-field
',
169 'datetime
-edit
-second
-field
',
170 'datetime
-edit
-text
',
171 'datetime
-edit
-week
-field
',
172 'datetime
-edit
-year
-field
',
174 'file-upload
-button
',
179 'input-speech
-button
',
181 'media
-slider
-container
',
182 'media
-slider
-thumb
',
184 'meter
-even
-less
-good
-value
',
185 'meter
-inner
-element
',
186 'meter
-optimum
-value
',
187 'meter
-suboptimum
-value
',
189 'progress
-inner
-element
',
197 'scrollbar
-track
-piece
',
198 'search
-cancel
-button
',
200 'search
-results
-button
',
201 'search
-results
-decoration
',
204 'slider
-runnable
-track
',
206 'textfield
-decoration
-container
',
208 'validation
-bubble
-arrow
',
209 'validation
-bubble
-arrow
-clipper
',
210 'validation
-bubble
-heading
',
211 'validation
-bubble
-message
',
212 'validation
-bubble
-text
-block
']
213 pseudo_reg = re.compile(r"""
214 (?<!:): # a single colon, i.e. :after but not ::after
215 ([a-zA-Z-]+) # a pseudo element, class, or function
216 (?=[^{}]+?{) # make sure a selector, not inside { rules }""",
217 re.MULTILINE | re.VERBOSE)
219 for p in re.finditer(pseudo_reg, contents):
220 pseudo = p.group(1).strip().splitlines()[0]
221 if _strip_prefix(pseudo.lower()) in pseudo_elements:
222 errors.append(' :%s (should be
::%s)' % (pseudo, pseudo))
225 def one_selector_per_line(contents):
226 any_reg = re.compile(r"""
227 :(?:-webkit-)?any\(.*?\) # :-webkit-any(a, b, i) selector""",
228 re.DOTALL | re.VERBOSE)
229 multi_sels_reg = re.compile(r"""
230 (?:}\s*)? # ignore 0% { blah: blah; }, from @keyframes
231 ([^,]+,(?=[^{}]+?{) # selector junk {, not in a { rule }
232 .*[,{])\s*$ # has to end with , or {""",
233 re.MULTILINE | re.VERBOSE)
235 for b in re.finditer(multi_sels_reg, re.sub(any_reg, '', contents)):
236 errors.append(' ' + b.group(1).strip().splitlines()[-1:][0])
239 def suggest_rgb_from_hex(line):
240 suggestions = ['rgb(%d, %d, %d)' % _rgb_from_hex(h.group(1))
241 for h in re.finditer(hex_reg, line)]
242 return ' (replace with
%s)' % ', '.join(suggestions)
244 def suggest_short_hex(line):
245 h = hex_reg.search(line).group(1)
246 return ' (replace with
#%s)' % (h[0] + h[2] + h[4])
248 webkit_before_or_after_reg
= re
.compile(r
'-webkit-(\w+-)(after|before):')
250 def suggest_top_or_bottom(line
):
251 prop
, pos
= webkit_before_or_after_reg
.search(line
).groups()
252 top_or_bottom
= 'top' if pos
== 'before' else 'bottom'
253 return ' (replace with %s)' % (prop
+ top_or_bottom
)
255 def webkit_before_or_after(line
):
256 return webkit_before_or_after_reg
.search(line
)
258 def zero_length_values(contents
):
259 hsl_reg
= re
.compile(r
"""
260 hsl\([^\)]* # hsl(<maybe stuff>
261 (?:[, ]|(?<=\()) # a comma or space not followed by a (
262 (?:0?\.?)?0% # some equivalent to 0%""",
264 zeros_reg
= re
.compile(r
"""
265 ^.*(?:^|[^0-9.]) # start/non-number
266 (?:\.0|0(?:\.0? # .0, 0, or 0.0
267 |px|em|%|in|cm|mm|pc|pt|ex|deg|g?rad|m?s|k?hz)) # a length unit
268 (?:\D|$) # non-number/end
269 (?=[^{}]+?}).*$ # only { rules }""",
270 re
.MULTILINE | re
.VERBOSE
)
272 for z
in re
.finditer(zeros_reg
, contents
):
273 first_line
= z
.group(0).strip().splitlines()[0]
274 if not hsl_reg
.search(first_line
):
275 errors
.append(' ' + first_line
)
278 # NOTE: Currently multi-line checks don't support 'after'. Instead, add
279 # suggestions while parsing the file so another pass isn't necessary.
280 added_or_modified_files_checks
= [
281 { 'desc': 'Alphabetize properties and list vendor specific (i.e. '
282 '-webkit) above standard.',
283 'test': alphabetize_props
,
286 { 'desc': 'Start braces ({) end a selector, have a space before them '
287 'and no rules after.',
288 'test': braces_have_space_before_and_nothing_after
,
290 { 'desc': 'Classes use .dash-form.',
291 'test': classes_use_dashes
,
293 { 'desc': 'Always put a rule closing brace (}) on a new line.',
294 'test': close_brace_on_new_line
,
296 { 'desc': 'Colons (:) should have a space after them.',
297 'test': colons_have_space_after
,
299 { 'desc': 'Use single quotes (\') instead of double quotes (") in '
301 'test': favor_single_quotes
,
303 { 'desc': 'Use abbreviated hex (#rgb) when in form #rrggbb.',
304 'test': hex_could_be_shorter
,
305 'after': suggest_short_hex
,
307 { 'desc': 'Use milliseconds for time measurements under 1 second.',
308 'test': milliseconds_for_small_times
,
309 'after': suggest_ms_from_s
,
311 { 'desc': "Don't use data URIs in source files. Use grit instead.",
312 'test': no_data_uris_in_source_files
,
314 { 'desc': 'One rule per line (what not to do: color: red; margin: 0;).',
315 'test': one_rule_per_line
,
317 { 'desc': 'One selector per line (what not to do: a, b {}).',
318 'test': one_selector_per_line
,
321 { 'desc': 'Pseudo-elements should use double colon (i.e. ::after).',
322 'test': pseudo_elements_double_colon
,
325 { 'desc': 'Use rgb() over #hex when not a shade of gray (like #333).',
326 'test': rgb_if_not_gray
,
327 'after': suggest_rgb_from_hex
,
329 { 'desc': 'Use *-top/bottom instead of -webkit-*-before/after.',
330 'test': webkit_before_or_after
,
331 'after': suggest_top_or_bottom
,
333 { 'desc': 'Make all zero length terms (i.e. 0px) 0 unless inside of '
334 'hsl() or part of @keyframe.',
335 'test': zero_length_values
,
341 affected_files
= self
.input_api
.AffectedFiles(include_deletes
=False,
342 file_filter
=self
.file_filter
)
344 for f
in affected_files
:
345 # Remove all /*comments*/, @at-keywords, and grit <if|include> tags; we're
346 # not using a real parser. TODO(dbeam): Check alpha in <if> blocks.
347 file_contents
= _remove_all('\n'.join(f
.NewContents()))
348 files
.append((f
.LocalPath(), file_contents
))
350 # Only look at CSS files for now.
351 for f
in filter(lambda f
: f
[0].endswith('.css'), files
):
353 for check
in added_or_modified_files_checks
:
354 # If the check is multiline, it receieves the whole file and gives us
355 # back a list of things wrong. If the check isn't multiline, we pass it
356 # each line and the check returns something truthy if there's an issue.
357 if ('multiline' in check
and check
['multiline']):
358 assert not 'after' in check
359 check_errors
= check
['test'](f
[1])
360 if len(check_errors
) > 0:
361 file_errors
.append('- %s\n%s' %
362 (check
['desc'], '\n'.join(check_errors
).rstrip()))
365 lines
= f
[1].splitlines()
366 for lnum
, line
in enumerate(lines
):
367 if check
['test'](line
):
368 error
= ' ' + line
.strip()
370 error
+= check
['after'](line
)
371 check_errors
.append(error
)
372 if len(check_errors
) > 0:
373 file_errors
.append('- %s\n%s' %
374 (check
['desc'], '\n'.join(check_errors
)))
376 results
.append(self
.output_api
.PresubmitPromptWarning(
377 '%s:\n%s' % (f
[0], '\n\n'.join(file_errors
))))
380 # Add your name if you're here often mucking around in the code.
381 authors
= ['dbeam@chromium.org']
382 results
.append(self
.output_api
.PresubmitNotifyResult(
383 'Was the CSS checker useful? Send feedback or hate mail to %s.' %