-
Notifications
You must be signed in to change notification settings - Fork 47
/
noshadows.py
241 lines (186 loc) · 6.97 KB
/
noshadows.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
import argparse
from datetime import datetime
from functools import partial, singledispatch
from pathlib import Path
import sys
import unittest
try:
from tinycss2 import parse_stylesheet
from tinycss2 import ast as tokens
except ImportError:
print("Missing requirement: tinycss2", file=sys.stderr)
sys.exit(1)
def get_parser():
parser = argparse.ArgumentParser(
description="Scan trac's CSS files to detect box-shadow rules and generate a stylesheet that resets them."
)
parser.add_argument("cssfiles", nargs="*", type=Path, help="The CSS files to scan")
parser.add_argument(
"--outfile",
"-o",
type=argparse.FileType("w"),
default="-",
help="Where to write the output",
)
parser.add_argument("--tests", action="store_true")
return parser
def tripletwise(iterable): # no relation to Jeff
"""
Like itertools.pairwise, but for triplets instead of pairs.
"""
i = iter(iterable)
try:
x, y, z = next(i), next(i), next(i)
except StopIteration:
return
yield x, y, z
for el in i:
x, y, z = y, z, el
yield x, y, z
def skip_whitespace(nodes):
return filter(lambda node: node.type != "whitespace", nodes)
SHADOW_CSS_PROPERTIES = {
"box-shadow",
"text-shadow",
}
def has_shadow(rule):
if not rule.content:
return False
for a, b, c in tripletwise(skip_whitespace(rule.content)):
if isinstance(a, tokens.IdentToken) and a.value in SHADOW_CSS_PROPERTIES:
assert isinstance(
c, (tokens.IdentToken, tokens.DimensionToken, tokens.NumberToken)
), f"Unexpected node type {c.type}"
if isinstance(c, (tokens.DimensionToken, tokens.NumberToken)):
return True
return False
def find_shadow(rules):
for rule in rules:
if has_shadow(rule):
yield rule
@singledispatch
def tokenstr(token: tokens.Node):
return token.value
@tokenstr.register
def _(token: tokens.WhitespaceToken):
return " "
@tokenstr.register
def _(token: tokens.SquareBracketsBlock):
return "[" + tokenlist_to_str(token.content) + "]"
@tokenstr.register
def _(token: tokens.HashToken):
return f"#{token.value}"
@tokenstr.register
def _(token: tokens.StringToken):
return f'"{token.value}"'
def tokenlist_to_str(tokens):
return "".join(map(tokenstr, tokens))
def selector_str(rule):
"""
Return the given rule's selector as a string
"""
return tokenlist_to_str(rule.prelude).strip()
def reset_css_str(selector):
return f"{selector}{{\n @include noshadow;\n}}"
class NoShadowTestCase(unittest.TestCase):
@classmethod
def run_and_exit(cls):
"""
Run all tests on the class and exit with the proper exit status (1 if any failures occured,
0 otherwise)
"""
runner = unittest.TextTestRunner()
suite = unittest.defaultTestLoader.loadTestsFromTestCase(cls)
result = runner.run(suite)
retval = 0 if result.wasSuccessful() else 1
sys.exit(retval)
def test_tripletwise(self):
self.assertEqual(
list(tripletwise("ABCDEF")),
[("A", "B", "C"), ("B", "C", "D"), ("C", "D", "E"), ("D", "E", "F")],
)
def test_tripletwise_too_short(self):
self.assertEqual(list(tripletwise("AB")), [])
def test_skip_whitespace(self):
rules = parse_stylesheet("html { color: red ; }")
self.assertEqual(len(rules), 1)
non_whitespace_content = list(skip_whitespace(rules[0].content))
self.assertEqual(
len(non_whitespace_content), 4
) # attr, colon, value, semicolon
def test_has_shadow(self):
for expected, css in [
(True, "html {box-shadow: 10px 5px 5px red;}"),
(True, "html {text-shadow: 1px 1px 2px pink;}"),
(True, "html {text-shadow: 5px 5px #558ABB;}"),
(False, "html {box-shadow: none;}"),
(False, "html {text-shadow: none;}"),
(True, "html {text-shadow: 5px 5px #558ABB; box-shadow: none;}"),
(True, "html {text-shadow: none; box-shadow: 10px 5px 5px red;}"),
(False, "html {}"),
(False, "html {color: red; font-weight: bold;}"),
]:
with self.subTest(css=css, expected=expected):
(rule,) = parse_stylesheet(css)
assert_method = self.assertTrue if expected else self.assertFalse
assert_method(has_shadow(rule))
def test_selector_str_tag(self):
(rule,) = parse_stylesheet("html {}")
self.assertEqual(selector_str(rule), "html")
def test_selector_str_classname(self):
(rule,) = parse_stylesheet(".className {}")
self.assertEqual(selector_str(rule), ".className")
def test_selector_str_id(self):
(rule,) = parse_stylesheet("#identifier {}")
self.assertEqual(selector_str(rule), "#identifier")
def test_selector_str_with_brackets(self):
(rule,) = parse_stylesheet('input[type="text"] {}')
self.assertEqual(selector_str(rule), 'input[type="text"]')
def test_selector_str_with_brackets_noquotes(self):
(rule,) = parse_stylesheet("input[type=text] {}")
self.assertEqual(selector_str(rule), "input[type=text]")
def test_selector_str_with_comma(self):
(rule,) = parse_stylesheet("a, button {}")
self.assertEqual(selector_str(rule), "a, button")
def test_selector_str_with_comma_and_newline(self):
(rule,) = parse_stylesheet("a,\nbutton {}")
self.assertEqual(selector_str(rule), "a, button")
def test_selector_str_pseudoclass(self):
(rule,) = parse_stylesheet("a:visited {}")
self.assertEqual(selector_str(rule), "a:visited")
def test_selector_str_pseudoclass_nonstandard(self):
(rule,) = parse_stylesheet("button::-moz-focus-inner {}")
self.assertEqual(selector_str(rule), "button::-moz-focus-inner")
SCSS_NOSHADOW_MIXIN_HEADER = """\
// Trac uses box-shadow and text-shadow everywhere but their 90s look doesn't
// fit well with our design.
@mixin noshadow {
box-shadow: none;
text-shadow: none;
border-radius: unset;
}
"""
if __name__ == "__main__":
parser = get_parser()
options = parser.parse_args()
if options.tests:
NoShadowTestCase.run_and_exit()
echo = partial(print, file=options.outfile)
echo(
f"// Generated by {Path(__file__).name} on {datetime.now().isoformat()}",
end="\n\n",
)
echo(SCSS_NOSHADOW_MIXIN_HEADER)
echo()
for i, filepath in enumerate(sorted(options.cssfiles)):
rules = parse_stylesheet(
filepath.read_text(), skip_comments=True, skip_whitespace=True
)
shadowrules = list(find_shadow(rules))
if shadowrules:
if i > 0:
echo()
echo()
echo(f"// {filepath.name}")
combined_selector = ",\n".join(map(selector_str, shadowrules))
echo(reset_css_str(combined_selector))