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