Spaces:
Running
Running
Download scripts/check-classes.py from Arrechenash/stocks: direct link, hf CLI and curl.
- Browser
- Download file 7.89 kB
-
https://huggingface.co/spaces/Arrechenash/stocks/resolve/main/scripts/check-classes.py
- Command line
-
hf download hf://spaces/Arrechenash/stocks/scripts/check-classes.py
-
curl -L -o check-classes.py https://huggingface.co/spaces/Arrechenash/stocks/resolve/main/scripts/check-classes.py
7.89 kB
| #!/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()) | |