File size: 4,527 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
#!/usr/bin/env python3
"""check-css-usage.py — Static CSS usage audit (report-only, exit 0).

Extracts class/id/tag selectors from every static/*.html page and reports CSS
rules whose selectors never appear in any HTML. Heuristic only: classes built
dynamically by JS will false-positive. Review manually before removing.

Usage: python3 scripts/check-css-usage.py
"""

from __future__ import annotations

import re
import sys
from pathlib import Path

CSS_DIR = Path("static/css")
HTML_DIR = Path("static")


def collect_html_selectors() -> set[str]:
    """Return every class, id, and tag name found in static HTML files."""
    selectors: set[str] = set()
    for html_file in sorted(HTML_DIR.glob("*.html")):
        text = html_file.read_text(errors="ignore")
        # class="..." and id="..." — capture each token
        for m in re.finditer(r'(?:class|id)="([^"]*)"', text):
            for token in m.group(1).split():
                selectors.add(token)
        # plain tag names: <tag ...
        for m in re.finditer(r"<([a-z][a-z0-9]*)\b", text):
            selectors.add(m.group(1))
    return selectors


def strip_comment_css(text: str) -> str:
    """Remove /* ... */ block comments from CSS."""
    return re.sub(r"/\*.*?\*/", "", text, flags=re.DOTALL)


def iter_css_rules(css_text: str):
    """Yield (selector_raw, rule_start_line) for each CSS rule."""
    # Remove @import, @charset, @namespace (single-line at-rules)
    text = re.sub(r"@(import|charset|namespace)[^;]*;", "", css_text, flags=re.MULTILINE)
    # Remove @media/@supports/@keyframes/@container blocks (keep inner rules)
    # We just strip the at-rule header lines, leaving inner content.
    text = re.sub(r"@[a-z-]+[^{]*\{", "", text, flags=re.MULTILINE)
    text = re.sub(r"\}", "}", text)  # keep closing braces

    for line in text.splitlines():
        line = line.strip()
        if not line or line.startswith("}"):
            continue
        if "{" in line:
            selector_part = line.split("{", 1)[0].strip()
            if selector_part:
                yield selector_part


def base_token(selector: str) -> str:
    """Return the base class/id/tag token from a selector, or empty string."""
    sel = selector.strip()
    # Skip at-remnants, pseudo-only, and complex selectors we can't trust
    if not sel or sel.startswith("@") or sel.startswith(":"):
        return ""
    # Remove pseudo-classes/:not()/etc. suffixes
    sel = re.sub(r":\w+\([^)]*\)", "", sel)
    sel = re.sub(r":\w+$", "", sel)
    # Remove attribute selectors [...]
    sel = re.sub(r"\[[^]]*\]", "", sel)
    # Strip leading combinators and pseudo-elements
    sel = re.sub(r"^[ >+~]+", "", sel)
    sel = re.sub(r"::.*$", "", sel)
    # Remove leading . or #
    sel = re.sub(r"^[.#]", "", sel)
    # Take the first token (for compound selectors like "nav.main-nav")
    sel = re.split(r"[ >+~]", sel, maxsplit=1)[0].strip()
    sel = re.sub(r"[^a-zA-Z0-9_-]", "", sel)
    return sel


def main() -> int:
    if not CSS_DIR.exists():
        print(f"check-css-usage: {CSS_DIR} not found — skipping.")
        return 0

    html_selectors = collect_html_selectors()
    print(f"check-css-usage: {len(html_selectors)} distinct selectors found in HTML")

    total_rules = 0
    unused = 0

    for css_file in sorted(CSS_DIR.glob("*.css")):
        text = strip_comment_css(css_file.read_text(errors="ignore"))
        file_unused: list[str] = []
        for raw_selector in iter_css_rules(text):
            total_rules += 1
            token = base_token(raw_selector)
            if not token:
                continue
            # Also check the raw selector itself in case it's a compound like "nav.main-nav"
            if token not in html_selectors and raw_selector not in html_selectors:
                # Also try with leading dot/hash stripped variants
                variants = {token, f".{token}", f"#{token}"}
                if not any(v in html_selectors for v in variants):
                    unused += 1
                    file_unused.append(raw_selector)
        if file_unused:
            print(f"\n  {css_file} ({len(file_unused)} potentially unused):")
            for sel in file_unused:
                print(f"    - {sel}")

    print(f"\ncheck-css-usage: {total_rules} rules scanned, {unused} potentially unused (candidates only).")
    print("                 Review manually before removing — JS-built classes will false-positive.")
    return 0


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