Upstream version 10.39.225.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / web_dev_style / css_checker.py
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.
4
5 """Presubmit script for Chromium WebUI resources.
6
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.
11 """
12
13 # TODO(dbeam): Real CSS parser? https://github.com/danbeam/css-py/tree/css3
14
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
20
21   def RunChecks(self):
22     # We use this a lot, so make a nick name variable.
23     re = self.input_api.re
24
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])
27
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]
30
31     def _remove_all(s):
32       return _remove_grit(_remove_ats(_remove_comments(s)))
33
34     def _remove_ats(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)
41
42     def _remove_comments(s):
43       return re.sub(re.compile(r'/\*.*?\*/', re.DOTALL), '', s)
44
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)
51
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)
58
59     def _strip_prefix(s):
60       return re.sub(r'^-(?:o|ms|moz|khtml|webkit)-', '', s)
61
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
71
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)
79
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
92
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*\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))
103
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)
111
112     def favor_single_quotes(line):
113       return '"' in line
114
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)
121
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)))
125
126     def rgb_if_not_gray(line):
127       m = hex_reg.search(line)
128       return (m and not _is_gray(m.group(1)))
129
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)
135
136     def milliseconds_for_small_times(line):
137       return small_seconds_reg.search(line)
138
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
142
143     def no_data_uris_in_source_files(line):
144       return re.search(r'\(\s*\'?\s*data:', line)
145
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""",
151           re.VERBOSE)
152       return one_rule_reg.search(line)
153
154     def pseudo_elements_double_colon(contents):
155       pseudo_elements = ['after',
156                          'before',
157                          'calendar-picker-indicator',
158                          'color-swatch',
159                          'color-swatch-wrapper',
160                          'date-and-time-container',
161                          'date-and-time-value',
162                          'datetime-edit',
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',
173                          'details-marker',
174                          'file-upload-button',
175                          'first-letter',
176                          'first-line',
177                          'inner-spin-button',
178                          'input-placeholder',
179                          'input-speech-button',
180                          'keygen-select',
181                          'media-slider-container',
182                          'media-slider-thumb',
183                          'meter-bar',
184                          'meter-even-less-good-value',
185                          'meter-inner-element',
186                          'meter-optimum-value',
187                          'meter-suboptimum-value',
188                          'progress-bar',
189                          'progress-inner-element',
190                          'progress-value',
191                          'resizer',
192                          'scrollbar',
193                          'scrollbar-button',
194                          'scrollbar-corner',
195                          'scrollbar-thumb',
196                          'scrollbar-track',
197                          'scrollbar-track-piece',
198                          'search-cancel-button',
199                          'search-decoration',
200                          'search-results-button',
201                          'search-results-decoration',
202                          'selection',
203                          'slider-container',
204                          'slider-runnable-track',
205                          'slider-thumb',
206                          'textfield-decoration-container',
207                          'validation-bubble',
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)
218       errors = []
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))
223       return errors
224
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)
234       errors = []
235       for b in re.finditer(multi_sels_reg, re.sub(any_reg, '', contents)):
236         errors.append('    ' + b.group(1).strip().splitlines()[-1:][0])
237       return errors
238
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)
243
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])
247
248     def zero_length_values(contents):
249       hsl_reg = re.compile(r"""
250           hsl\([^\)]*       # hsl(<maybe stuff>
251           (?:[, ]|(?<=\())  # a comma or space not followed by a (
252           (?:0?\.?)?0%      # some equivalent to 0%""",
253           re.VERBOSE)
254       zeros_reg = re.compile(r"""
255           ^.*(?:^|[^0-9.])                                 # start/non-number
256           (?:\.0|0(?:\.0?                                  # .0, 0, or 0.0
257           |px|em|%|in|cm|mm|pc|pt|ex|deg|g?rad|m?s|k?hz))  # a length unit
258           (?:\D|$)                                         # non-number/end
259           (?=[^{}]+?}).*$                                  # only { rules }""",
260           re.MULTILINE | re.VERBOSE)
261       errors = []
262       for z in re.finditer(zeros_reg, contents):
263         first_line = z.group(0).strip().splitlines()[0]
264         if not hsl_reg.search(first_line):
265           errors.append('    ' + first_line)
266       return errors
267
268     # NOTE: Currently multi-line checks don't support 'after'. Instead, add
269     # suggestions while parsing the file so another pass isn't necessary.
270     added_or_modified_files_checks = [
271         { 'desc': 'Alphabetize properties and list vendor specific (i.e. '
272                   '-webkit) above standard.',
273           'test': alphabetize_props,
274           'multiline': True,
275         },
276         { 'desc': 'Start braces ({) end a selector, have a space before them '
277                   'and no rules after.',
278           'test': braces_have_space_before_and_nothing_after,
279         },
280         { 'desc': 'Classes use .dash-form.',
281           'test': classes_use_dashes,
282         },
283         { 'desc': 'Always put a rule closing brace (}) on a new line.',
284           'test': close_brace_on_new_line,
285         },
286         { 'desc': 'Colons (:) should have a space after them.',
287           'test': colons_have_space_after,
288         },
289         { 'desc': 'Use single quotes (\') instead of double quotes (") in '
290                   'strings.',
291           'test': favor_single_quotes,
292         },
293         { 'desc': 'Use abbreviated hex (#rgb) when in form #rrggbb.',
294           'test': hex_could_be_shorter,
295           'after': suggest_short_hex,
296         },
297         { 'desc': 'Use milliseconds for time measurements under 1 second.',
298           'test': milliseconds_for_small_times,
299           'after': suggest_ms_from_s,
300         },
301         { 'desc': "Don't use data URIs in source files. Use grit instead.",
302           'test': no_data_uris_in_source_files,
303         },
304         { 'desc': 'One rule per line (what not to do: color: red; margin: 0;).',
305           'test': one_rule_per_line,
306         },
307         { 'desc': 'One selector per line (what not to do: a, b {}).',
308           'test': one_selector_per_line,
309           'multiline': True,
310         },
311         { 'desc': 'Pseudo-elements should use double colon (i.e. ::after).',
312           'test': pseudo_elements_double_colon,
313           'multiline': True,
314         },
315         { 'desc': 'Use rgb() over #hex when not a shade of gray (like #333).',
316           'test': rgb_if_not_gray,
317           'after': suggest_rgb_from_hex,
318         },
319         { 'desc': 'Make all zero length terms (i.e. 0px) 0 unless inside of '
320                   'hsl() or part of @keyframe.',
321           'test': zero_length_values,
322           'multiline': True,
323         },
324     ]
325
326     results = []
327     affected_files = self.input_api.AffectedFiles(include_deletes=False,
328                                                   file_filter=self.file_filter)
329     files = []
330     for f in affected_files:
331       # Remove all /*comments*/, @at-keywords, and grit <if|include> tags; we're
332       # not using a real parser. TODO(dbeam): Check alpha in <if> blocks.
333       file_contents = _remove_all('\n'.join(f.NewContents()))
334       files.append((f.LocalPath(), file_contents))
335
336     # Only look at CSS files for now.
337     for f in filter(lambda f: f[0].endswith('.css'), files):
338       file_errors = []
339       for check in added_or_modified_files_checks:
340         # If the check is multiline, it receieves the whole file and gives us
341         # back a list of things wrong. If the check isn't multiline, we pass it
342         # each line and the check returns something truthy if there's an issue.
343         if ('multiline' in check and check['multiline']):
344           assert not 'after' in check
345           check_errors = check['test'](f[1])
346           if len(check_errors) > 0:
347             file_errors.append('- %s\n%s' %
348                 (check['desc'], '\n'.join(check_errors).rstrip()))
349         else:
350           check_errors = []
351           lines = f[1].splitlines()
352           for lnum, line in enumerate(lines):
353             if check['test'](line):
354               error = '    ' + line.strip()
355               if 'after' in check:
356                 error += check['after'](line)
357               check_errors.append(error)
358           if len(check_errors) > 0:
359             file_errors.append('- %s\n%s' %
360                 (check['desc'], '\n'.join(check_errors)))
361       if file_errors:
362         results.append(self.output_api.PresubmitPromptWarning(
363             '%s:\n%s' % (f[0], '\n\n'.join(file_errors))))
364
365     if results:
366       # Add your name if you're here often mucking around in the code.
367       authors = ['dbeam@chromium.org']
368       results.append(self.output_api.PresubmitNotifyResult(
369           'Was the CSS checker useful? Send feedback or hate mail to %s.' %
370           ', '.join(authors)))
371
372     return results