resume_page

Log | Files | Refs | README

run.py (4722B)


      1 """Run all checks, report every failure, and leave the checkout unchanged."""
      2 
      3 import re
      4 import subprocess
      5 import tempfile
      6 from html.parser import HTMLParser
      7 from pathlib import Path
      8 
      9 ROOT = Path.cwd()
     10 CONFIG = ROOT / "linting"
     11 EXCLUDED = {".git", ".venv", "node_modules", "__pycache__"}
     12 
     13 
     14 class Prose(HTMLParser):
     15     """Preserve source line numbers while extracting text and accessible labels."""
     16 
     17     def __init__(self, source):
     18         super().__init__(convert_charrefs=True)
     19         self.lines = [""] * (source.count("\n") + 1)
     20         self.hidden = 0
     21         self.feed(re.sub(r"{{.*?}}|{%.*?%}|{#.*?#}",
     22                          lambda m: "\n" * m[0].count("\n"), source, flags=re.S))
     23 
     24     def add(self, value):
     25         for offset, line in enumerate(value.split("\n")):
     26             self.lines[self.getpos()[0] - 1 + offset] += " " + line
     27 
     28     def handle_starttag(self, tag, attrs):
     29         if tag in {"script", "style", "code", "pre"}:
     30             self.hidden += 1
     31         if not self.hidden:
     32             for key, value in attrs:
     33                 if value and key in {"alt", "title", "aria-label"}:
     34                     self.add(value)
     35             attributes = dict(attrs)
     36             if tag == "meta" and attributes.get("name") == "description":
     37                 self.add(attributes.get("content", ""))
     38 
     39     def handle_endtag(self, tag):
     40         if tag in {"script", "style", "code", "pre"}:
     41             self.hidden = max(0, self.hidden - 1)
     42 
     43     def handle_data(self, data):
     44         if not self.hidden:
     45             self.add(data)
     46 
     47 
     48 def main():
     49     files = sorted(path.relative_to(ROOT) for path in ROOT.rglob("*")
     50                    if path.is_file() and not EXCLUDED.intersection(path.parts))
     51     failed = []
     52     checked = set()
     53     checks = 0
     54 
     55     def check(label, command, sources):
     56         nonlocal checks
     57         checks += 1
     58         checked.update(sources)
     59         print(f"\n--- {label} ---", flush=True)
     60         print(f"Checking {len(sources)} file(s):", flush=True)
     61         for source in sources:
     62             print(f"  {source.as_posix()}", flush=True)
     63         result = subprocess.run([str(arg) for arg in command], check=False)
     64         if result.returncode:
     65             failed.append(label)
     66         print(f"{'FAIL' if result.returncode else 'PASS'}: {label} "
     67               f"(exit {result.returncode})", flush=True)
     68 
     69     def matching(suffix):
     70         return [path for path in files if path.suffix == suffix]
     71 
     72     html = matching(".html")
     73     if html:
     74         check("HTML", ["htmlhint", "--config", CONFIG / "htmlhint.json", *html], html)
     75     if css := matching(".css"):
     76         check("CSS", ["stylelint", "--config", CONFIG / "stylelint.json", *css], css)
     77     if python := matching(".py"):
     78         check("Python", ["ruff", "check", "--no-cache", "--config",
     79                          CONFIG / "ruff.toml", *python], python)
     80     with tempfile.TemporaryDirectory() as directory:
     81         for path in html:
     82             prose = Path(directory) / "prose.txt"
     83             prose.write_text("\n".join(Prose(path.read_text(encoding="utf-8")).lines),
     84                              encoding="utf-8")
     85             print(f"\nEnglish source: {path} (line numbers match HTML)", flush=True)
     86             check(f"Spelling: {path}", ["cspell", "--config", CONFIG / "cspell.json",
     87                                        "--root", directory, "--no-progress", prose], [path])
     88             check(f"English style: {path}", ["write-good", "--parse",
     89                                            "--no-adverb", "--no-weasel", prose], [path])
     90     yaml = matching(".yml") + matching(".yaml")
     91     if yaml:
     92         check("YAML", ["yamllint", "-c", CONFIG / "yamllint.yml", *yaml], yaml)
     93     for path in yaml:
     94         if path.name in {"compose.yml", "compose.yaml", "docker-compose.yml",
     95                          "docker-compose.yaml"}:
     96             check(f"Compose: {path}", ["docker", "compose", "-f", path,
     97                                       "config", "--quiet", "--no-path-resolution"], [path])
     98     for path in files:
     99         if path.name == "Dockerfile" or path.name.endswith(".Dockerfile"):
    100             check(f"Dockerfile: {path}", ["hadolint", path], [path])
    101     if shell := matching(".sh"):
    102         check("Shell", ["shellcheck", "--external-sources", *shell], shell)
    103     print(f"\nRan {checks} checks across {len(checked)} unique files.", flush=True)
    104     unchecked = sorted(set(files) - checked)
    105     if unchecked:
    106         print("Files without a configured lint check:", flush=True)
    107         for path in unchecked:
    108             print(f"  {path.as_posix()}", flush=True)
    109     print("\n" + ("Failed: " + ", ".join(failed) if failed else "All checks passed."))
    110     return bool(failed)
    111 
    112 
    113 if __name__ == "__main__":
    114     raise SystemExit(main())