#!/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: 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())