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
7See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
8for more details about the presubmit API built into gcl/git cl, and see
9http://www.chromium.org/developers/web-development-style-guide for the rules
10we're checking against here.
11"""
12
13# TODO(dbeam): Real CSS parser? pycss? http://code.google.com/p/pycss/
14
15class 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      return re.sub(re.compile(r'@\w+.*?{(.*{.*?})+.*?}', re.DOTALL), '\\1', s)
36
37    def _remove_comments(s):
38      return re.sub(re.compile(r'/\*.*?\*/', re.DOTALL), '', s)
39
40    def _remove_grit(s):
41      grit_reg = r'<if[^>]+>.*?<\s*/\s*if[^>]*>|<include[^>]+>'
42      return re.sub(re.compile(grit_reg, re.DOTALL), '', s)
43
44    def _rgb_from_hex(s):
45      if len(s) == 3:
46        r, g, b = s[0] + s[0], s[1] + s[1], s[2] + s[2]
47      else:
48        r, g, b = s[0:2], s[2:4], s[4:6]
49      return int(r, base=16), int(g, base=16), int(b, base=16)
50
51    def alphabetize_props(contents):
52      errors = []
53      for rule in re.finditer(r'{(.*?)}', contents, re.DOTALL):
54        semis = map(lambda t: t.strip(), rule.group(1).split(';'))[:-1]
55        rules = filter(lambda r: ': ' in r, semis)
56        props = map(lambda r: r[0:r.find(':')], rules)
57        if props != sorted(props):
58          errors.append('    %s;\n' % (';\n    '.join(rules)))
59      return errors
60
61    def braces_have_space_before_and_nothing_after(line):
62      return re.search(r'(?:^|\S){|{\s*\S+\s*$', line)
63
64    def classes_use_dashes(line):
65      # Intentionally dumbed down version of CSS 2.1 grammar for class without
66      # non-ASCII, escape chars, or whitespace.
67      m = re.search(r'\.(-?[_a-zA-Z0-9-]+).*[,{]\s*$', line)
68      return (m and (m.group(1).lower() != m.group(1) or
69                     m.group(1).find('_') >= 0))
70
71    # Ignore single frames in a @keyframe, i.e. 0% { margin: 50px; }
72    frame_reg = r'\s*\d+%\s*{\s*[_a-zA-Z0-9-]+:(\s*[_a-zA-Z0-9-]+)+\s*;\s*}\s*'
73    def close_brace_on_new_line(line):
74      return (line.find('}') >= 0 and re.search(r'[^ }]', line) and
75              not re.match(frame_reg, line))
76
77    def colons_have_space_after(line):
78      return re.search(r'(?<!data):(?!//)\S[^;]+;\s*', line)
79
80    def favor_single_quotes(line):
81      return line.find('"') >= 0
82
83    # Shared between hex_could_be_shorter and rgb_if_not_gray.
84    hex_reg = (r'#([a-fA-F0-9]{3}|[a-fA-F0-9]{6})(?=[^_a-zA-Z0-9-]|$)'
85               r'(?!.*(?:{.*|,\s*)$)')
86    def hex_could_be_shorter(line):
87      m = re.search(hex_reg, line)
88      return (m and _is_gray(m.group(1)) and _collapseable_hex(m.group(1)))
89
90    small_seconds = r'(?:^|[^_a-zA-Z0-9-])(0?\.[0-9]+)s(?!-?[_a-zA-Z0-9-])'
91    def milliseconds_for_small_times(line):
92      return re.search(small_seconds, line)
93
94    def no_data_uris_in_source_files(line):
95      return re.search(r'\(\s*\'?\s*data:', line)
96
97    def one_rule_per_line(line):
98      return re.search(r'[_a-zA-Z0-9-](?<!data):(?!//)[^;]+;\s*[^ }]\s*', line)
99
100    any_reg = re.compile(r':(?:-webkit-)?any\(.*?\)', re.DOTALL)
101    multi_sels = re.compile(r'(?:}[\n\s]*)?([^,]+,(?=[^{}]+?{).*[,{])\s*$',
102                            re.MULTILINE)
103    def one_selector_per_line(contents):
104      errors = []
105      for b in re.finditer(multi_sels, re.sub(any_reg, '', contents)):
106        errors.append('    ' + b.group(1).strip().splitlines()[-1:][0])
107      return errors
108
109    def rgb_if_not_gray(line):
110      m = re.search(hex_reg, line)
111      return (m and not _is_gray(m.group(1)))
112
113    def suggest_ms_from_s(line):
114      ms = int(float(re.search(small_seconds, line).group(1)) * 1000)
115      return ' (replace with %dms)' % ms
116
117    def suggest_rgb_from_hex(line):
118      suggestions = ['rgb(%d, %d, %d)' % _rgb_from_hex(h.group(1))
119          for h in re.finditer(hex_reg, line)]
120      return ' (replace with %s)' % ', '.join(suggestions)
121
122    def suggest_short_hex(line):
123      h = re.search(hex_reg, line).group(1)
124      return ' (replace with #%s)' % (h[0] + h[2] + h[4])
125
126    hsl = r'hsl\([^\)]*(?:[, ]|(?<=\())(?:0?\.?)?0%'
127    zeros = (r'^.*(?:^|\D)'
128             r'(?:\.0|0(?:\.0?|px|em|%|in|cm|mm|pc|pt|ex|deg|g?rad|m?s|k?hz))'
129             r'(?:\D|$)(?=[^{}]+?}).*$')
130    def zero_length_values(contents):
131      errors = []
132      for z in re.finditer(re.compile(zeros, re.MULTILINE), contents):
133        first_line = z.group(0).strip().splitlines()[0]
134        if not re.search(hsl, first_line):
135          errors.append('    ' + first_line)
136      return errors
137
138    added_or_modified_files_checks = [
139        { 'desc': 'Alphabetize properties and list vendor specific (i.e. '
140                  '-webkit) above standard.',
141          'test': alphabetize_props,
142          'multiline': True,
143        },
144        { 'desc': 'Start braces ({) end a selector, have a space before them '
145                  'and no rules after.',
146          'test': braces_have_space_before_and_nothing_after,
147        },
148        { 'desc': 'Classes use .dash-form.',
149          'test': classes_use_dashes,
150        },
151        { 'desc': 'Always put a rule closing brace (}) on a new line.',
152          'test': close_brace_on_new_line,
153        },
154        { 'desc': 'Colons (:) should have a space after them.',
155          'test': colons_have_space_after,
156        },
157        { 'desc': 'Use single quotes (\') instead of double quotes (") in '
158                  'strings.',
159          'test': favor_single_quotes,
160        },
161        { 'desc': 'Use abbreviated hex (#rgb) when in form #rrggbb.',
162          'test': hex_could_be_shorter,
163          'after': suggest_short_hex,
164        },
165        { 'desc': 'Use milliseconds for time measurements under 1 second.',
166          'test': milliseconds_for_small_times,
167          'after': suggest_ms_from_s,
168        },
169        { 'desc': 'Don\'t use data URIs in source files. Use grit instead.',
170          'test': no_data_uris_in_source_files,
171        },
172        { 'desc': 'One rule per line (what not to do: color: red; margin: 0;).',
173          'test': one_rule_per_line,
174        },
175        { 'desc': 'One selector per line (what not to do: a, b {}).',
176          'test': one_selector_per_line,
177          'multiline': True,
178        },
179        { 'desc': 'Use rgb() over #hex when not a shade of gray (like #333).',
180          'test': rgb_if_not_gray,
181          'after': suggest_rgb_from_hex,
182        },
183        { 'desc': 'Make all zero length terms (i.e. 0px) 0 unless inside of '
184                  'hsl() or part of @keyframe.',
185          'test': zero_length_values,
186          'multiline': True,
187        },
188    ]
189
190    results = []
191    try: # Workaround AffectedFiles exploding on deleted files.
192      affected_files = self.input_api.AffectedFiles(include_deletes=False,
193                                                    file_filter=self.file_filter)
194    except:
195      affected_files = []
196    files = []
197    for f in affected_files:
198      # Remove all /*comments*/, @at-keywords, and grit <if|include> tags; we're
199      # not using a real parser. TODO(dbeam): Check alpha in <if> blocks.
200      file_contents = _remove_all('\n'.join(f.NewContents()))
201      files.append((f.LocalPath(), file_contents))
202
203    # Only look at CSS files for now.
204    for f in filter(lambda f: f[0].endswith('.css'), files):
205      file_errors = []
206      for check in added_or_modified_files_checks:
207        # If the check is multiline, it receieves the whole file and gives us
208        # back a list of things wrong. If the check isn't multiline, we pass it
209        # each line and the check returns something truthy if there's an issue.
210        if ('multiline' in check and check['multiline']):
211          check_errors = check['test'](f[1])
212          if len(check_errors) > 0:
213            # There are currently no multiline checks with ['after'].
214            file_errors.append('- %s\n%s' %
215                (check['desc'], '\n'.join(check_errors).rstrip()))
216        else:
217          check_errors = []
218          lines = f[1].splitlines()
219          for lnum in range(0, len(lines)):
220            line = lines[lnum]
221            if check['test'](line):
222              error = '    ' + line.strip()
223              if 'after' in check:
224                error += check['after'](line)
225              check_errors.append(error)
226          if len(check_errors) > 0:
227            file_errors.append('- %s\n%s' %
228                (check['desc'], '\n'.join(check_errors)))
229      if file_errors:
230        results.append(self.output_api.PresubmitPromptWarning(
231            '%s:\n%s' % (f[0], '\n\n'.join(file_errors))))
232
233    if results:
234      # Add your name if you're here often mucking around in the code.
235      authors = ['dbeam@chromium.org']
236      results.append(self.output_api.PresubmitNotifyResult(
237          'Was the CSS checker useful? Send feedback or hate mail to %s.' %
238          ', '.join(authors)))
239
240    return results
241