File size: 7,890 Bytes
ee446e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
check-classes.py — guardrail 13.7: every class in the markup is defined, and
every class in the CSS is used.

Two directions, one rule: a class is a name shared between markup and a
stylesheet, and a name that exists on only one side is a bug in both
directions.

  markup -> CSS   An unstyled class is invisible in the editor and in the
                  stylesheet, so nobody notices it is unstyled. `.spinner`
                  without `.spinner--small` renders nothing; `.btn-ghost`
                  that was renamed in CSS but not in the template looks
                  styled and is not.
  CSS -> markup   Dead rules. Cheap to keep, and what makes a 5,700-line
                  common.css unreadable: the next reader cannot tell which
                  of the four `.tab-btn` rules is live.

The shadow root is part of "defined somewhere": `chart-card-element.ts`
carries 756 lines of CSS in `<style>` blocks, and a scan of static/css/
alone calls ~40 of its template classes undefined. That is false noise, and
noise is what teaches a reader to ignore a check.

Usage:
    .venv/bin/python scripts/check-classes.py            # report, exit 0
    .venv/bin/python scripts/check-classes.py --strict   # today's orphans fail too
    .venv/bin/python scripts/check-classes.py --base main  # widen the diff gate
    .venv/bin/python scripts/check-classes.py --verbose  # print every site

Exit 1 when a class on an added line has no definition. That covers both a
brand-new class and a pre-existing orphan on a line you touched: either way
the line is yours now. Today is not a failure:
there is real debt here (the classes listed below) and it belongs to the
migration waves, not to the check.

Sibling of scripts/check-styles-audit.py, which prints the whole audit at
once. This one is the gate: it fails, and it is diff-scoped, so the list of
existing orphans never has to be pasted into an allow-list that rots.
"""

from __future__ import annotations

import argparse
import re
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
from _css_scan import (  # noqa: E402
    CSS_DIR,
    CSS_FILES,
    HTML_FILES,
    SHADOW_HOST,
    STATIC,
    TS_FILES,
    diff_added_lines,
    line_of,
    read,
    shadow_css,
    strip_comments,
)

RE_CLASS_SELECTOR = re.compile(r"\.(-?[a-zA-Z_][\w-]*)")
RE_CLASS_NAME = re.compile(r"[a-zA-Z][\w-]*")
RE_CLASS_ATTR = re.compile(r'class="([^"${}]*)"')
RE_RULE_SELECTOR = re.compile(r"(?:^|[{}])\s*([^{}]*?)\s*\{", re.S)
# Baseline debt, printed on every run. Measured, not inherited: the audit
# listed 5 examples; there are more, and they are the migration waves' work.
KNOWN_ORPHANS = (
    "ac-error",
    "at-risk-panel",
    "bt-empty-row",
    "chart-tf-selector",
    "dash-notify__label",
    "modal-input",
    "pagination-controls",
    "spinner",
    "trade-annotations-bar",
)


def class_tokens() -> dict[str, set[str]]:
    """Class names used in markup -> "file:line" of each use.

    Tokens are filtered one at a time, not group at a time. A `class="..."`
    value is often half literal, half interpolated (`class="cal-day ${extra}"`),
    and the literal half is a real class the stylesheet has to answer for. And
    markup is built by string concatenation in several places
    (`'<span class="' + x + '">'`), where a group-wide scan reads the code
    between the quotes as class names — `class="0"`, `class="==="` — so every
    token has to be class-name shaped before it counts, and `${...}` never is.
    """
    used: dict[str, set[str]] = {}
    for path in [*HTML_FILES, *TS_FILES]:
        src = read(path)
        for m in RE_CLASS_ATTR.finditer(src):
            names = [n for n in m.group(1).split() if RE_CLASS_NAME.fullmatch(n)]
            if not names:
                continue
            where = f"{path.relative_to(STATIC)}:{line_of(src, m.start())}"
            for name in names:
                used.setdefault(name, set()).add(where)
    return used


def defined_classes() -> dict[str, list[tuple[str, int]]]:
    """Class name -> every (stylesheet, line) that defines it."""
    owners: dict[str, list[tuple[str, int]]] = {}
    for path in CSS_FILES:
        src = strip_comments(read(path))
        for m in RE_RULE_SELECTOR.finditer(src):
            selector = m.group(1)
            # Skip a declaration's value that looks like a selector: only
            # positions before the first brace are selectors.
            for name in RE_CLASS_SELECTOR.findall(selector):
                owners.setdefault(name, []).append((path.name, line_of(src, m.start(1))))
    shadow = shadow_css()
    for name in RE_CLASS_SELECTOR.findall(shadow):
        owners.setdefault(name, []).append((SHADOW_HOST.name, 0))
    return owners


def duplicate_owners(owners: dict[str, list[tuple[str, int]]]) -> dict[str, list[tuple[str, int]]]:
    """Classes defined in more than one stylesheet (guardrail 3.1, reported
    here because it is the same data, not because it is the same rule)."""
    return {name: sites for name, sites in owners.items() if len({f for f, _ in sites}) > 1}


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--strict", action="store_true", help="fail on today's orphans and dead CSS too")
    parser.add_argument("--base", default="HEAD", help="git ref the diff gate compares against")
    parser.add_argument("--verbose", action="store_true", help="print every use site")
    args = parser.parse_args()

    if not CSS_FILES:
        print(f"no stylesheets under {CSS_DIR}", file=sys.stderr)
        return 2

    used = class_tokens()
    owners = defined_classes()
    orphans = sorted(name for name in used if name not in owners)
    dead = sorted(name for name in owners if name not in used)
    dupes = duplicate_owners(owners)
    shadow_names = set(RE_CLASS_SELECTOR.findall(shadow_css()))

    print(f"class names in markup: {len(used)}   defined in CSS or the shadow root: {len(owners)}")
    print(f"orphans (in markup, defined nowhere): {len(orphans)}")
    for name in orphans:
        known = " [known]" if name in KNOWN_ORPHANS else ""
        sites = sorted(used[name]) if args.verbose else sorted(used[name])[:2]
        print(f"  {name}{known:<10} {sites}")
    print(f"dead CSS (defined, never in markup): {len(dead)}")
    print(f"  {' '.join(dead[:40])}")
    print(f"classes in more than one stylesheet (guardrail 3.1): {len(dupes)}")
    for name, sites in sorted(dupes.items()):
        print(f"  {name:<30} {sorted({f for f, _ in sites})}")
    print(f"of which styled only by the shadow root: {len([n for n in owners if n in shadow_names])}")

    # The gate: a class on an added line with no definition anywhere.
    failures: list[str] = []
    for path, line in diff_added_lines(args.base):
        for m in RE_CLASS_ATTR.finditer(line):
            for name in (n for n in m.group(1).split() if RE_CLASS_NAME.fullmatch(n)):
                if name not in owners:
                    failures.append(f"{path}: class {name} has no definition in static/css or the shadow root")

    for failure in sorted(set(failures)):
        print(failure, file=sys.stderr)
    if args.strict:
        for name in orphans:
            print(f"orphan class {name} (used in {sorted(used[name])[0]})", file=sys.stderr)

    if failures or (args.strict and (orphans or dead)):
        print(
            f"check-classes: {len(set(failures))} orphan class(es) on added lines; "
            f"baseline {len(orphans)} orphans, {len(dead)} dead rules",
            file=sys.stderr,
        )
        return 1
    print(f"check-classes: clean; baseline {len(orphans)} orphans, {len(dead)} dead rules, {len(dupes)} double-owned")
    return 0


if __name__ == "__main__":
    sys.exit(main())