Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(328)

Side by Side Diff: chrome/browser/resources/PRESUBMIT.py

Issue 9323016: [WebUI] Add some presubmit checks (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: most rules working well, need to find home for tests (and write them) Created 8 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « no previous file | no next file » | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
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 import os
M-A Ruel 2012/02/06 20:40:51 Please use input_api.os_path and input_api.re inst
Dan Beam 2012/02/08 11:42:48 Done.
14 import re
15
16 def CheckChangeOnUpload(input_api, output_api):
17 results = []
18 results.extend(_CommonChecks(input_api, output_api))
19 return results
20
M-A Ruel 2012/02/06 20:40:51 Please use 2 vertical spaces between file level sy
Dan Beam 2012/02/08 11:42:48 Done.
21 def CheckChangeOnCommit(input_api, output_api):
22 results = []
23 results.extend(_CommonChecks(input_api, output_api))
24 return results
25
26 def _CommonChecks(input_api, output_api):
27 """Checks common to both upload and commit."""
28 ntp4_or_options2 = lambda f: input_api.FilterSourceFile(f,
29 white_list=os.path.join(os.getcwd(), '(?:ntp4|options2).*\.(?:cs|j)s$'))
30 return _CheckWebDevStyleGuide(
31 input_api,
32 output_api,
33 source_file_filter=ntp4_or_options2)
34
35 def _CheckWebDevStyleGuide(input_api, output_api, source_file_filter=None):
36 def _collapseable_hex(s):
37 return (len(s) == 6 and s[0] == s[1] and s[2] == s[3] and s[4] == s[5])
38
39 def _is_gray(s):
40 return s[0] == s[1] == s[2] if len(s) == 3 else s[0:2] == s[2:4] == s[4:6]
41
42 def _remove_ats(s):
43 return re.sub(re.compile(r'@\w+.*?{(.*{.*?})+.*?}', re.DOTALL), '\\1', s)
44
45 def _remove_comments(s):
46 return re.sub(re.compile(r'/\*.*?\*/', re.DOTALL), '', s)
47
48 def _rgb_from_hex(s):
49 if len(s) == 3:
50 r, g, b = s[0] + s[0], s[1] + s[1], s[2] + s[2]
51 else:
52 r, g, b = s[0:2], s[2:4], s[4:6]
53 return 'rgb(%d, %d, %d)' % (int(r, base=16),
54 int(g, base=16),
55 int(b, base=16))
56
57 # Shared between hex_could_be_shorter and rgb_if_not_gray.
58 hex_reg = r'#([a-fA-F0-9]{3}|[a-fA-F0-9]{6})(?=[^_a-zA-Z0-9-]|$)(?!.+[{,]$)'
59
60 def alphabetize_props(f):
61 errors = []
62 lines = _remove_ats(_remove_comments(input_api.ReadFile(f[0], 'rb')))
63 for block in re.finditer(r'{(.*?)}', lines, re.DOTALL):
64 rules = filter(lambda l: l.find(': ') >= 0,
65 map(lambda l: l.strip(), block.group(1).split(';'))[0:-1])
66 props = map(lambda l: l[0:l.find(':')], rules)
67 if props != sorted(props):
68 errors.append('%s:\n %s' % (f[1], '\n '.join(rules)))
69 return errors
70
71 def braces_and_colons_have_space_after(f):
72 errors = []
73 lines = _remove_comments(input_api.ReadFile(f[0], 'rb')).splitlines()
M-A Ruel 2012/02/06 20:40:51 This pattern is really slow. You are reading the s
Dan Beam 2012/02/08 11:42:48 Cool, I was waiting until this was slow to optimiz
74 for l in range(0, len(lines)):
75 if re.search(r'(^\s*{)|(?:{|:(?!\/\/|.*[{,]))\S', lines[l]):
76 errors.append(' %s:~%d:%s' % (f[1], l, lines[l]))
77 return errors
78
79 def classes_use_dashes(f):
80 errors = []
81 lines = _remove_comments(input_api.ReadFile(f[0], 'rb')).splitlines()
82 for l in range(0, len(lines)):
83 # Intentionally dumbed down version of CSS2.1 grammar for class without
84 # non-ASCII, escape chars, or whitespace.
85 m = re.search(r'(?:^| )\.(-?[_a-zA-Z0-9-]+)', lines[l])
86 if m:
87 c = m.group(1)
88 if (c.lower() != c or c.find('_') >= 0):
89 errors.append(' %s:~%d:%s' % (f[1], l, lines[l]))
90 return errors
91
92 def favor_single_quotes(f):
93 errors = []
94 lines = _remove_comments(input_api.ReadFile(f[0], 'rb')).splitlines()
95 for l in range(0, len(lines)):
96 if lines[l].find('"') >= 0:
97 errors.append(' %s:~%d:%s' % (f[1], l, lines[l]))
98 return errors
99
100 def hex_could_be_shorter(f):
101 errors = []
102 lines = input_api.ReadFile(f[0], 'rb').splitlines()
103 for l in range(0, len(lines)):
104 m = re.search(hex_reg, lines[l])
105 if (m and _collapseable_hex(m.group(1))):
106 errors.append(' %s:%d:%s' % (f[1], l, lines[l]))
107 return errors
108
109 def milliseconds_for_small_times(f):
110 errors = []
111 lines = _remove_comments(input_api.ReadFile(f[0], 'rb')).splitlines()
112 small_seconds = r'(?:^|[^_a-zA-Z0-9-])(0?\.[0-9]+)s(?!-?[_a-zA-Z0-9-])'
113 for l in range(0, len(lines)):
114 if re.search(small_seconds, lines[l]):
115 errors.append(' %s:~%d:%s' % (f[1], l, lines[l]))
116
117 def one_selector_per_line(f):
118 errors = []
119 lines = _remove_ats(_remove_comments(input_api.ReadFile(f[0], 'rb'))
120 ).splitlines()
121 for l in range(0, len(lines)):
122 if re.search(r'[^,]+,[^,]+{', lines[l]):
123 errors.append(' %s:~~%d:%s' % (f[1], l, lines[l]))
124 return errors
125
126 def rgb_if_not_gray(f):
127 errors = []
128 lines = _remove_comments(input_api.ReadFile(f[0], 'rb')).splitlines()
129 for l in range(0, len(lines)):
130 m = re.search(hex_reg, lines[l])
131 if (m and not _is_gray(m.group(1))):
132 rgb = _rgb_from_hex(m.group(1))
133 errors.append(' %s:~%d:%s /* = %s */ ' % (f[1], l, lines[l], rgb))
134 return errors
135
136 def zero_length_values(f):
137 errors = []
138 zeros = ''.join((r'[^0-9]0(?:\.0?)?',
139 r'(?:px|em|%|in|cm|mm|pc|pt|ex|deg|g?rad|m?s|k?hz)',
140 r'(?!\s*\{)'))
141 hsl = r'hsl\([^\)]*(?:[, ]|(?<=\())(?:0?\.?)?0%'
142 lines = input_api.ReadFile(f[0], 'rb').splitlines()
143 for l in range(0, len(lines)):
144 if (re.search(zeros, lines[l]) and not re.search(hsl, lines[l])):
145 errors.append(' %s:%d:%s' % (f[1], l, lines[l]))
146 return errors
147
148 added_or_modified_files_checks = [
149 { 'desc': 'Alphabetize properties, but list vendor specific (i.e. -webkit) '
150 'above standard.',
151 'test': alphabetize_props
152 },
153 { 'desc': 'Braces ({} and colons (:) should have a space after them and no '
154 'newlines before them.',
155 'test': braces_and_colons_have_space_after,
156 },
157 { 'desc': 'Classes use .dash-form.',
158 'test': classes_use_dashes,
159 },
160 { 'desc': 'Use single quotes (\') instead of double quotes (") in strings.',
161 'test': favor_single_quotes,
162 },
163 { 'desc': 'Favor short hex form (#rgb) when #rrggbb.',
164 'test': hex_could_be_shorter,
165 },
166 { 'desc': 'Use milliseconds for time measurements under 1 second.',
167 'test': milliseconds_for_small_times,
168 },
169 { 'desc': 'One selector per line (what not to do: a, b {}).',
170 'test': one_selector_per_line,
171 },
172 { 'desc': 'Use rgb() over #hex when not a shade of gray (like #333).',
173 'test': rgb_if_not_gray,
174 },
175 { 'desc': 'Make all zero length terms (i.e. 0px) 0 unless inside of hsl()'
176 'or @keyframe.',
177 'test': zero_length_values,
178 },
179 ]
180
181 errors = []
182 files = [(f.AbsoluteLocalPath(), f.LocalPath()) for f in
183 input_api.AffectedFiles(include_deletes=False,
184 file_filter=source_file_filter)]
185
186 # Only look at CSS files for now.
187 for f in filter(lambda l: l[1].endswith('.css'), files):
M-A Ruel 2012/02/06 20:40:51 Why not do instead ar: checks = [ list of lambd
Dan Beam 2012/02/08 11:42:48 Ended up doing something like that.
188 for check in added_or_modified_files_checks:
189 errs = check['test'](f)
190 if errs:
191 msg = '%s\n%s' % (check['desc'], '\n'.join(errs))
192 errors.append(output_api.PresubmitNotifyResult(msg))
193
194 return errors
195
196 def GetPreferredTrySlaves(project, change):
197 slaves = PRESUBMIT.GetPreferredTrySlaves(project, change)
198 cwd = os.getcwd()
199 options2, ntp4 = (os.path.join(cwd, 'options2'), os.path.join(cwd, 'ntp4'))
200 files = change.AffectedFiles()
201 if any(options2 in f.LocalPath() for f in files):
202 slaves.append('linux_chromeos')
203 elif any(ntp4 in f.LocalPath() for f in files):
204 slaves.append('win_aura', 'linux_aura')
205 return slaves
206
207 #TODO(dbeam): Where does this go?
208 def testCheckWebDevStyleGuide(self):
209 fake_file = 'fake.css'
210 fake_contents = """
211 /* Comment */
212 .badClass, #anotherSelector {
213 color:hsl(0, 5, 0%) #777777 .2s;
214 transition: blah 0.s;
215 background: #369 0px 10px 2; /* comment */ }
216
217 @media print /*
218 Comment.
219 */
220 {
221 @-webkit-keyframe {
222 0% {
223 blah: blah;
224 }
225 0%{blar: blug;}
226 }
227 } /** comment **/
228
229 .app-contents:active:not(.suppress-active),
230 .app:not(.click-focus):focus .app-contents:not(.suppress-active),
231 html[dir="rtl"] .drag-representation:not(.placing) .app-contents {
232 border-radius: 10px;
233 -webkit-border-radius: 5px;
234 }"""
235
236 change = presubmit.Change('fu', 'bar', self.fake_root_dir, None, 0, 0, None)
237
238 input_api = self.MockInputApi(change, False)
239 input_api.AffectedSourceFiles().MultipleTimes().AndReturn([fake_contents])
240 input_api.ReadFile(fake_file).MultipleTimes().AndReturn(fake_contents)
241
242 self.mox.ReplayAll()
243
244 output = _CheckWebDevStyleGuide(input_api, presubmit.OutputApi, None)
245
246 print "%s" % output
OLDNEW
« no previous file with comments | « no previous file | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698