css_checker.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. # Copyright 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. """Presubmit script for Chromium WebUI resources.
  5. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
  6. for more details about the presubmit API built into depot_tools, and see
  7. https://chromium.googlesource.com/chromium/src/+/main/styleguide/web/web.md
  8. for the rules we're checking against here.
  9. """
  10. # TODO(dbeam): Real CSS parser? https://github.com/danbeam/css-py/tree/css3
  11. class CSSChecker(object):
  12. DISABLE_PREFIX = 'csschecker-disable'
  13. DISABLE_FORMAT = DISABLE_PREFIX + '(-[a-z]+)+ [a-z-]+(-[a-z-]+)*'
  14. DISABLE_LINE = DISABLE_PREFIX + '-line'
  15. def __init__(self, input_api, output_api, file_filter=None):
  16. self.input_api = input_api
  17. self.output_api = output_api
  18. self.file_filter = file_filter
  19. def RemoveAtBlocks(self, s):
  20. re = self.input_api.re
  21. def _remove_comments(s):
  22. return re.sub(r'/\*.*\*/', '', s)
  23. lines = s.splitlines()
  24. i = 0
  25. while i < len(lines):
  26. line = _remove_comments(lines[i]).strip()
  27. if (len(line) > 0 and line[0] == '@' and
  28. not line[1:].startswith(("apply", "page")) and
  29. line[-1] == '{' and not re.match("\d+x\b", line[1:])):
  30. j = i
  31. open_brackets = 1
  32. while open_brackets > 0:
  33. j += 1
  34. inner_line = _remove_comments(lines[j]).strip()
  35. if not inner_line:
  36. continue
  37. if inner_line[-1] == '{':
  38. open_brackets += 1
  39. elif inner_line[-1] == '}':
  40. # Ignore single line keyframes (from { height: 0; }).
  41. if not re.match(r'\s*(from|to|\d+%)\s*{', inner_line):
  42. open_brackets -= 1
  43. elif len(inner_line) > 1 and inner_line[-2:] == '};':
  44. # End of mixin. TODO(dbeam): worth detecting ": {" start?
  45. open_brackets -= 1
  46. del lines[j] # Later index first, as indices shift with deletion.
  47. del lines[i]
  48. else:
  49. i += 1
  50. return '\n'.join(lines)
  51. def RunChecks(self):
  52. # We use this a lot, so make a nick name variable.
  53. re = self.input_api.re
  54. def _collapseable_hex(s):
  55. return (len(s) == 6 and s[0] == s[1] and s[2] == s[3] and s[4] == s[5])
  56. def _is_gray(s):
  57. return s[0] == s[1] == s[2] if len(s) == 3 else s[0:2] == s[2:4] == s[4:6]
  58. def _extract_inline_style(s):
  59. return '\n'.join(re.findall(r'<style\b[^>]*>([^<]*)<\/style>', s))
  60. def _remove_comments_except_for_disables(s):
  61. return re.sub(r'/\*(?! %s \*/$).*?\*/' % self.DISABLE_FORMAT, '', s,
  62. flags=re.DOTALL | re.MULTILINE)
  63. def _remove_grit(s):
  64. return re.sub(r"""
  65. <if[^>]+>.*?<\s*/\s*if[^>]*>| # <if> contents </if>
  66. <include[^>]+> # <include>
  67. """, '', s, flags=re.DOTALL | re.VERBOSE)
  68. mixin_shim_reg = r'[\w-]+_-_[\w-]+'
  69. def _remove_valid_vars(s):
  70. valid_vars = r'--(?!' + mixin_shim_reg + r')[\w-]+:\s*([^;{}}]+);\s*'
  71. return re.sub(valid_vars, '', s, flags=re.DOTALL)
  72. def _remove_disable(content, lstrip=False):
  73. prefix_reg = ('\s*' if lstrip else '')
  74. disable_reg = '/\* %s \*/' % self.DISABLE_FORMAT
  75. return re.sub(prefix_reg + disable_reg, '', content, re.MULTILINE)
  76. def _remove_template_expressions(s):
  77. return re.sub(r'\$i18n(Raw)?{[^}]*}', '', s, flags=re.DOTALL)
  78. def _rgb_from_hex(s):
  79. if len(s) == 3:
  80. r, g, b = s[0] + s[0], s[1] + s[1], s[2] + s[2]
  81. else:
  82. r, g, b = s[0:2], s[2:4], s[4:6]
  83. return int(r, base=16), int(g, base=16), int(b, base=16)
  84. def _strip_prefix(s):
  85. return re.sub(r'^-(?:o|ms|moz|khtml|webkit)-', '', s)
  86. def alphabetize_props(contents):
  87. errors = []
  88. # TODO(dbeam): make this smart enough to detect issues in mixins.
  89. strip_rule = lambda t: _remove_disable(t).strip()
  90. for rule in re.finditer(r'{(.*?)}', contents, re.DOTALL):
  91. semis = [strip_rule(r) for r in rule.group(1).split(';')][:-1]
  92. rules = [r for r in semis if ': ' in r]
  93. props = [r[0:r.find(':')] for r in rules]
  94. if props != sorted(props):
  95. errors.append(' %s;\n' % (';\n '.join(rules)))
  96. return errors
  97. def braces_have_space_before_and_nothing_after(line):
  98. brace_space_reg = re.compile(r"""
  99. (?:^|\S){| # selector{ or selector\n{ or
  100. {\s*\S+\s* # selector { with stuff after it
  101. $ # must be at the end of a line
  102. """,
  103. re.VERBOSE)
  104. return brace_space_reg.search(line)
  105. def classes_use_dashes(line):
  106. # Intentionally dumbed down version of CSS 2.1 grammar for class without
  107. # non-ASCII, escape chars, or whitespace.
  108. class_reg = re.compile(r"""
  109. (?<!')\.(-?[\w-]+).* # ., then maybe -, then alpha numeric and -
  110. [,{]\s*$ # selectors should end with a , or {
  111. """,
  112. re.VERBOSE)
  113. m = class_reg.search(line)
  114. if not m:
  115. return False
  116. class_name = m.group(1)
  117. return class_name.lower() != class_name or '_' in class_name
  118. end_mixin_reg = re.compile(r'\s*};\s*$')
  119. def close_brace_on_new_line(line):
  120. # Ignore single frames in a @keyframe, i.e. 0% { margin: 50px; }
  121. frame_reg = re.compile(r"""
  122. \s*(from|to|\d+%)\s*{ # 50% {
  123. \s*[\w-]+: # rule:
  124. (\s*[\w\(\), -\.]+)+\s*; # value;
  125. \s*}\s* # }
  126. """,
  127. re.VERBOSE)
  128. return ('}' in line and re.search(r'[^ }]', line) and
  129. not frame_reg.match(line) and not end_mixin_reg.match(line))
  130. def colons_have_space_after(line):
  131. colon_space_reg = re.compile(r"""
  132. (?<!data) # ignore data URIs
  133. :(?!//) # ignore url(http://), etc.
  134. \S[^;]+;\s* # only catch one-line rules for now
  135. """,
  136. re.VERBOSE)
  137. return colon_space_reg.search(line)
  138. def favor_single_quotes(line):
  139. return '"' in line
  140. # Shared between hex_could_be_shorter and rgb_if_not_gray.
  141. hex_reg = re.compile(r"""
  142. \#([a-fA-F0-9]{3}|[a-fA-F0-9]{6}) # pound followed by 3 or 6 hex digits
  143. (?=[^\w-]|$) # no more alphanum chars or at EOL
  144. (?!.*(?:{.*|,\s*)$) # not in a selector
  145. """,
  146. re.VERBOSE)
  147. def hex_could_be_shorter(line):
  148. m = hex_reg.search(line)
  149. return (m and _is_gray(m.group(1)) and _collapseable_hex(m.group(1)))
  150. def rgb_if_not_gray(line):
  151. m = hex_reg.search(line)
  152. return (m and not _is_gray(m.group(1)))
  153. small_seconds_reg = re.compile(r"""
  154. (?:^|[^\w-]) # start of a line or a non-alphanumeric char
  155. (0?\.[0-9]+)s # 1.0s
  156. (?!-?[\w-]) # no following - or alphanumeric chars
  157. """,
  158. re.VERBOSE)
  159. def milliseconds_for_small_times(line):
  160. return small_seconds_reg.search(line)
  161. def suggest_ms_from_s(line):
  162. ms = int(float(small_seconds_reg.search(line).group(1)) * 1000)
  163. return ' (replace with %dms)' % ms
  164. def no_data_uris_in_source_files(line):
  165. return re.search(r'\(\s*\s*data:', line)
  166. def no_mixin_shims(line):
  167. return re.search(r'--' + mixin_shim_reg + r'\s*:', line)
  168. def no_quotes_in_url(line):
  169. return re.search('url\s*\(\s*["\']', line, re.IGNORECASE)
  170. def one_rule_per_line(line):
  171. line = _remove_disable(line)
  172. one_rule_reg = re.compile(r"""
  173. [\w-](?<!data): # a rule: but no data URIs
  174. (?!//)[^;]+; # value; ignoring colons in protocols:// and };
  175. \s*[^ }]\s* # any non-space after the end colon
  176. """,
  177. re.VERBOSE)
  178. return one_rule_reg.search(line) and not end_mixin_reg.match(line)
  179. def pseudo_elements_double_colon(contents):
  180. pseudo_elements = ['after',
  181. 'before',
  182. 'calendar-picker-indicator',
  183. 'color-swatch',
  184. 'color-swatch-wrapper',
  185. 'date-and-time-container',
  186. 'date-and-time-value',
  187. 'datetime-edit',
  188. 'datetime-edit-ampm-field',
  189. 'datetime-edit-day-field',
  190. 'datetime-edit-hour-field',
  191. 'datetime-edit-millisecond-field',
  192. 'datetime-edit-minute-field',
  193. 'datetime-edit-month-field',
  194. 'datetime-edit-second-field',
  195. 'datetime-edit-text',
  196. 'datetime-edit-week-field',
  197. 'datetime-edit-year-field',
  198. 'details-marker',
  199. 'file-upload-button',
  200. 'first-letter',
  201. 'first-line',
  202. 'inner-spin-button',
  203. 'input-placeholder',
  204. 'input-speech-button',
  205. 'media-slider-container',
  206. 'media-slider-thumb',
  207. 'meter-bar',
  208. 'meter-even-less-good-value',
  209. 'meter-inner-element',
  210. 'meter-optimum-value',
  211. 'meter-suboptimum-value',
  212. 'progress-bar',
  213. 'progress-inner-element',
  214. 'progress-value',
  215. 'resizer',
  216. 'scrollbar',
  217. 'scrollbar-button',
  218. 'scrollbar-corner',
  219. 'scrollbar-thumb',
  220. 'scrollbar-track',
  221. 'scrollbar-track-piece',
  222. 'search-cancel-button',
  223. 'search-decoration',
  224. 'search-results-button',
  225. 'search-results-decoration',
  226. 'selection',
  227. 'slider-container',
  228. 'slider-runnable-track',
  229. 'slider-thumb',
  230. 'textfield-decoration-container',
  231. 'validation-bubble',
  232. 'validation-bubble-arrow',
  233. 'validation-bubble-arrow-clipper',
  234. 'validation-bubble-heading',
  235. 'validation-bubble-message',
  236. 'validation-bubble-text-block']
  237. pseudo_reg = re.compile(r"""
  238. (?<!:): # a single colon, i.e. :after but not ::after
  239. ([a-zA-Z-]+) # a pseudo element, class, or function
  240. (?=[^{}]+?{) # make sure a selector, not inside { rules }
  241. """,
  242. re.MULTILINE | re.VERBOSE)
  243. errors = []
  244. for p in re.finditer(pseudo_reg, contents):
  245. pseudo = p.group(1).strip().splitlines()[0]
  246. if _strip_prefix(pseudo.lower()) in pseudo_elements:
  247. errors.append(' :%s (should be ::%s)' % (pseudo, pseudo))
  248. return errors
  249. def one_selector_per_line(contents):
  250. # Ignore all patterns nested in :any(), :is().
  251. any_reg = re.compile(
  252. r"""
  253. :(?:
  254. (?:-webkit-)?any # :-webkit-any(a, b, i) selector
  255. |is # :is(...) selector
  256. )\(
  257. """, re.DOTALL | re.VERBOSE)
  258. # Iteratively remove nested :is(), :any() patterns from |contents|.
  259. while True:
  260. m = re.search(any_reg, contents)
  261. if m is None:
  262. break
  263. start, end = m.span()
  264. # Find corresponding right parenthesis.
  265. pcount = 1
  266. while end < len(contents) and pcount > 0:
  267. if contents[end] == '(':
  268. pcount += 1
  269. elif contents[end] == ')':
  270. pcount -= 1
  271. end += 1
  272. contents = contents[:start] + contents[end:]
  273. multi_sels_reg = re.compile(r"""
  274. (?:}\s*)? # ignore 0% { blah: blah; }, from @keyframes
  275. ([^,]+,(?=[^{}]+?{) # selector junk {, not in a { rule }
  276. .*[,{])\s*$ # has to end with , or {
  277. """,
  278. re.MULTILINE | re.VERBOSE)
  279. errors = []
  280. for b in re.finditer(multi_sels_reg, contents):
  281. errors.append(' ' + b.group(1).strip().splitlines()[-1:][0])
  282. return errors
  283. def suggest_rgb_from_hex(line):
  284. suggestions = ['rgb(%d, %d, %d)' % _rgb_from_hex(h.group(1))
  285. for h in re.finditer(hex_reg, line)]
  286. return ' (replace with %s)' % ', '.join(suggestions)
  287. def suggest_short_hex(line):
  288. h = hex_reg.search(line).group(1)
  289. return ' (replace with #%s)' % (h[0] + h[2] + h[4])
  290. prefixed_logical_axis_reg = re.compile(r"""
  291. -webkit-(min-|max-|)logical-(height|width):
  292. """, re.VERBOSE)
  293. def suggest_unprefixed_logical_axis(line):
  294. prefix, prop = prefixed_logical_axis_reg.search(line).groups()
  295. block_or_inline = 'block' if prop == 'height' else 'inline'
  296. return ' (replace with %s)' % (prefix + block_or_inline + '-size')
  297. def prefixed_logical_axis(line):
  298. return prefixed_logical_axis_reg.search(line)
  299. prefixed_logical_side_reg = re.compile(r"""
  300. -webkit-(margin|padding|border)-(before|after|start|end)
  301. (?!-collapse)(-\w+|):
  302. """, re.VERBOSE)
  303. def suggest_unprefixed_logical_side(line):
  304. prop, pos, suffix = prefixed_logical_side_reg.search(line).groups()
  305. if pos == 'before' or pos == 'after':
  306. block_or_inline = 'block'
  307. else:
  308. block_or_inline = 'inline'
  309. if pos == 'start' or pos == 'before':
  310. start_or_end = 'start'
  311. else:
  312. start_or_end = 'end'
  313. return ' (replace with %s)' % (
  314. prop + '-' + block_or_inline + '-' + start_or_end + suffix)
  315. def prefixed_logical_side(line):
  316. return prefixed_logical_side_reg.search(line)
  317. _LEFT_RIGHT_REG = '(?:(border|margin|padding)-|(text-align): )' \
  318. '(left|right)' \
  319. '(?:(-[a-z-^:]+):)?(?!.*/\* %s left-right \*/)' % \
  320. self.DISABLE_LINE
  321. def start_end_instead_of_left_right(line):
  322. return re.search(_LEFT_RIGHT_REG, line, re.IGNORECASE)
  323. def suggest_start_end_from_left_right(line):
  324. groups = re.search(_LEFT_RIGHT_REG, line, re.IGNORECASE).groups()
  325. prop_start, text_align, left_right, prop_end = groups
  326. start_end = {'left': 'start', 'right': 'end'}[left_right]
  327. if text_align:
  328. return ' (replace with text-align: %s)' % start_end
  329. prop = '%s-inline-%s%s' % (prop_start, start_end, prop_end or '')
  330. return ' (replace with %s)' % prop
  331. def zero_width_lengths(contents):
  332. hsl_reg = re.compile(r"""
  333. hsl\([^\)]* # hsl(maybestuff
  334. (?:[, ]|(?<=\()) # a comma or space not followed by a (
  335. (?:0?\.?)?0% # some equivalent to 0%
  336. """,
  337. re.VERBOSE)
  338. zeros_reg = re.compile(r"""
  339. ^.*(?:^|[^0-9.]) # start/non-number
  340. (?:\.0|0(?:\.0? # .0, 0, or 0.0
  341. |px|em|%|in|cm|mm|pc|pt|ex)) # a length unit
  342. (?!svg|png|jpg)(?:\D|$) # non-number/end
  343. (?=[^{}]+?}).*$ # only { rules }
  344. """,
  345. re.MULTILINE | re.VERBOSE)
  346. errors = []
  347. for z in re.finditer(zeros_reg, contents):
  348. first_line = z.group(0).strip().splitlines()[0]
  349. if not hsl_reg.search(first_line):
  350. errors.append(' ' + first_line)
  351. return errors
  352. def mixins(line):
  353. return re.search(r'--[\w-]+:\s*({.*?)', line) or re.search(
  354. r'@apply', line)
  355. # NOTE: Currently multi-line checks don't support 'after'. Instead, add
  356. # suggestions while parsing the file so another pass isn't necessary.
  357. added_or_modified_files_checks = [
  358. { 'desc': 'Alphabetize properties and list vendor specific (i.e. '
  359. '-webkit) above standard.',
  360. 'test': alphabetize_props,
  361. 'multiline': True,
  362. },
  363. { 'desc': 'Start braces ({) end a selector, have a space before them '
  364. 'and no rules after.',
  365. 'test': braces_have_space_before_and_nothing_after,
  366. },
  367. { 'desc': 'Classes use .dash-form.',
  368. 'test': classes_use_dashes,
  369. },
  370. { 'desc': 'Always put a rule closing brace (}) on a new line.',
  371. 'test': close_brace_on_new_line,
  372. },
  373. { 'desc': 'Colons (:) should have a space after them.',
  374. 'test': colons_have_space_after,
  375. },
  376. { 'desc': 'Use single quotes (\') instead of double quotes (") in '
  377. 'strings.',
  378. 'test': favor_single_quotes,
  379. },
  380. { 'desc': 'Use abbreviated hex (#rgb) when in form #rrggbb.',
  381. 'test': hex_could_be_shorter,
  382. 'after': suggest_short_hex,
  383. },
  384. { 'desc': 'Use milliseconds for time measurements under 1 second.',
  385. 'test': milliseconds_for_small_times,
  386. 'after': suggest_ms_from_s,
  387. },
  388. { 'desc': "Don't use data URIs in source files. Use grit instead.",
  389. 'test': no_data_uris_in_source_files,
  390. },
  391. { 'desc': "Don't override custom properties created by Polymer's mixin "
  392. "shim. Set mixins or documented custom properties directly.",
  393. 'test': no_mixin_shims,
  394. },
  395. { 'desc': "Don't use quotes in url().",
  396. 'test': no_quotes_in_url,
  397. },
  398. { 'desc': 'One rule per line (what not to do: color: red; margin: 0;).',
  399. 'test': one_rule_per_line,
  400. },
  401. { 'desc': 'One selector per line (what not to do: a, b {}).',
  402. 'test': one_selector_per_line,
  403. 'multiline': True,
  404. },
  405. { 'desc': 'Pseudo-elements should use double colon (i.e. ::after).',
  406. 'test': pseudo_elements_double_colon,
  407. 'multiline': True,
  408. },
  409. { 'desc': 'Use rgb() over #hex when not a shade of gray (like #333).',
  410. 'test': rgb_if_not_gray,
  411. 'after': suggest_rgb_from_hex,
  412. },
  413. { 'desc': 'Unprefix logical axis property.',
  414. 'test': prefixed_logical_axis,
  415. 'after': suggest_unprefixed_logical_axis,
  416. },
  417. { 'desc': 'Unprefix logical side property.',
  418. 'test': prefixed_logical_side,
  419. 'after': suggest_unprefixed_logical_side,
  420. },
  421. {
  422. 'desc': 'Use -start/end instead of -left/right ' \
  423. '(https://goo.gl/gQYY7z, add /* %s left-right */ to ' \
  424. 'suppress)' % self.DISABLE_LINE,
  425. 'test': start_end_instead_of_left_right,
  426. 'after': suggest_start_end_from_left_right,
  427. },
  428. { 'desc': 'Use "0" for zero-width lengths (i.e. 0px -> 0)',
  429. 'test': zero_width_lengths,
  430. 'multiline': True,
  431. },
  432. { 'desc': 'Avoid using CSS mixins. Use CSS shadow parts, CSS ' \
  433. 'variables, or common CSS classes instead.',
  434. 'test': mixins,
  435. },
  436. ]
  437. results = []
  438. affected_files = self.input_api.AffectedFiles(include_deletes=False,
  439. file_filter=self.file_filter)
  440. files = []
  441. for f in affected_files:
  442. path = f.LocalPath()
  443. is_html = path.endswith('.html')
  444. if not is_html and not path.endswith('.css'):
  445. continue
  446. file_contents = '\n'.join(f.NewContents())
  447. # Remove all /*comments*/, @at-keywords, and grit <if|include> tags; we're
  448. # not using a real parser. TODO(dbeam): Check alpha in <if> blocks.
  449. file_contents = _remove_grit(file_contents) # Must be done first.
  450. if is_html:
  451. # The <style> extraction regex can't handle <if> nor /* <tag> */.
  452. prepped_html = _remove_comments_except_for_disables(file_contents)
  453. file_contents = _extract_inline_style(prepped_html)
  454. file_contents = self.RemoveAtBlocks(file_contents)
  455. if not is_html:
  456. file_contents = _remove_comments_except_for_disables(file_contents)
  457. file_contents = _remove_valid_vars(file_contents)
  458. file_contents = _remove_template_expressions(file_contents)
  459. files.append((path, file_contents))
  460. for f in files:
  461. file_errors = []
  462. for check in added_or_modified_files_checks:
  463. # If the check is multiline, it receives the whole file and gives us
  464. # back a list of things wrong. If the check isn't multiline, we pass it
  465. # each line and the check returns something truthy if there's an issue.
  466. if ('multiline' in check and check['multiline']):
  467. assert not 'after' in check
  468. check_errors = check['test'](f[1])
  469. if len(check_errors) > 0:
  470. file_errors.append('- %s\n%s' %
  471. (check['desc'], '\n'.join(check_errors).rstrip()))
  472. else:
  473. check_errors = []
  474. lines = f[1].splitlines()
  475. for lnum, line in enumerate(lines):
  476. if check['test'](line):
  477. error = ' ' + _remove_disable(line, lstrip=True).strip()
  478. if 'after' in check:
  479. error += check['after'](line)
  480. check_errors.append(error)
  481. if len(check_errors) > 0:
  482. file_errors.append('- %s\n%s' %
  483. (check['desc'], '\n'.join(check_errors)))
  484. if file_errors:
  485. results.append(self.output_api.PresubmitPromptWarning(
  486. '%s:\n%s' % (f[0], '\n\n'.join(file_errors))))
  487. return results