#!/usr/bin/env python3
"""
_css_scan.py — the static/ scanning primitives every check-*.py script shares.
The guardrail scripts under scripts/ each used to re-declare the repo root, the
stylesheet list, a comment stripper and a git-diff reader. The copies drifted:
four of them stripped comments without preserving newlines while still
reporting `file:line` against the file on disk, which put their findings up to
560 lines away from the offending rule (measured on common.css). This module is
the one home for those primitives, and `strip_comments` here is the
newline-preserving implementation every caller needs.
Not a package: scripts/ is a flat directory of entry points, so import it as
`from _css_scan import ...` next to the script that uses it.
"""
from __future__ import annotations
import re
import subprocess
import sys
from pathlib import Path
REPO = Path(__file__).resolve().parent.parent
STATIC = REPO / "static"
CSS_DIR = STATIC / "css"
CSS_FILES = tuple(sorted(CSS_DIR.glob("*.css")))
HTML_FILES = tuple(sorted(STATIC.glob("*.html")))
TS_FILES = tuple(sorted((STATIC / "js").rglob("*.ts")))
# The shadow-DOM host: the only file with CSS inside TS. STY-3.4a moves it to
# static/css/, and this path goes with it.
SHADOW_HOST = STATIC / "js" / "features" / "shared" / "chart-card-element.ts"
SHADOW_CSS = CSS_DIR / "chart-card.css"
RE_COMMENT = re.compile(r"/\*.*?\*/", re.S)
def read(path: Path) -> str:
return path.read_text(encoding="utf8")
def line_of(src: str, index: int) -> int:
"""1-based line number of `index` in `src`.
Only correct on text that kept its newlines: see `strip_comments`.
"""
return src[:index].count("\n") + 1
def strip_comments(src: str) -> str:
"""Remove comments but keep every newline, so a line number computed on the
result still points at the rule in the file on disk. Stripping naively
shifts every report up by the length of the comment above it, which is how
a worklist ends up pointing into a comment."""
return RE_COMMENT.sub(lambda m: "\n" * m.group(0).count("\n"), src)
def diff_added_lines(base: str, paths: tuple[str, ...] = ("static",)) -> list[tuple[str, str]]:
"""(path, added line text) for every line the diff against `base` adds."""
try:
raw = subprocess.run(
["git", "diff", "-U0", base, "--", *paths],
cwd=REPO,
capture_output=True,
text=True,
check=True,
).stdout
except (subprocess.CalledProcessError, FileNotFoundError) as exc:
print(f"could not diff against {base!r}: {exc}", file=sys.stderr)
return []
added: list[tuple[str, str]] = []
path = ""
for line in raw.splitlines():
if line.startswith("+++ b/"):
path = line[6:]
elif line.startswith("+") and not line.startswith("+++"):
added.append((path, line[1:]))
return added
def shadow_blocks(host_lines: list[str]) -> list[str]:
"""The CSS of every `" not in host_lines[j]:
j += 1
blocks.append("\n".join(host_lines[i + 1 : j]))
i = j
i += 1
return blocks
def extracted_css() -> str:
"""The shadow CSS in its home since STY-3.4a: static/css/chart-card.css."""
if not SHADOW_CSS.exists():
return ""
return strip_comments(read(SHADOW_CSS))
def shadow_css() -> str:
"""The card's CSS: the host file's `