File size: 4,213 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
#!/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 `<style>` block, matched on the tag alone.

    A line that merely mentions the tag (a comment, a string) is not a block.
    """
    blocks: list[str] = []
    i = 0
    while i < len(host_lines):
        if host_lines[i].strip() == "<style>":
            j = i
            while "</style>" 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 `<style>` blocks, or, since STY-3.4a,
    static/css/chart-card.css.

    The shadow root carries its own stylesheet, so a scan of static/css/ alone
    calls every class in the card template undefined — 40-odd false positives
    from one file. It is also the reason guardrail 13.9 exists.
    """
    if not SHADOW_HOST.exists():
        return ""
    blocks = shadow_blocks(read(SHADOW_HOST).split("\n"))
    if blocks:
        return strip_comments("\n".join(blocks))
    return extracted_css()