chore: type and tidy the remaining site scripts

This commit is contained in:
Abdessamad Derraz committed 2026-11-17 09:33:10 +01:00
1 parent a6985449b3
commit f2b7118fe3
5 files changed
+33 -16

No files matched your search

+1 -1
View File
@@ -91,7 +91,7 @@ def square_image(data: bytes, size: int, kind: str = "PNG", flip: bool = False,
def is_svg(data: bytes) -> bool:
head = data[:512].lstrip().lower()
return head.startswith(b"<?xml") or head.startswith(b"<svg")
return head.startswith((b"<?xml", b"<svg"))
def safe_svg(data: bytes, url: str) -> bytes:
+5 -4
View File
@@ -23,11 +23,12 @@ import argparse
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT / "scripts"))
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts"))
from common import list_registered_platforms, load_platform_config # noqa: E402
from sitediagrams import OG_SECTIONS, og_card_svg, wrap # noqa: E402
from common import list_registered_platforms, load_platform_config
from sitediagrams import OG_SECTIONS, og_card_svg, wrap
ROOT = Path(__file__).resolve().parent.parent
OUT = ROOT / "docs_assets" / "og"
LOGO = ROOT / "docs_assets" / "brand" / "logo.svg"
+4
View File
@@ -116,6 +116,8 @@ def fetch_queries(start: dt.date, end: dt.date) -> list[Query]:
answer = _get_json(url, {"Authorization": f"Bearer {token}"}, {
"startDate": start.isoformat(), "endDate": end.isoformat(),
"dimensions": ["query", "page"], "rowLimit": 25000, "startRow": len(rows)})
if not isinstance(answer, dict):
raise SystemExit("Search Console answered with something other than an object")
batch = answer.get("rows", [])
rows += [Query(r["keys"][0], r["keys"][1], int(r["clicks"]), int(r["impressions"]),
float(r["position"])) for r in batch]
@@ -133,6 +135,8 @@ def fetch_goatcounter(start: dt.date, end: dt.date) -> dict:
while True:
params = urllib.parse.urlencode({**span, "limit": 100, "exclude_paths": ",".join(exclude)})
answer = _get_json(f"{GOATCOUNTER}/stats/hits?{params}", auth)
if not isinstance(answer, dict):
raise SystemExit("GoatCounter answered with something other than an object")
for hit in answer.get("hits", []):
hits.append((hit["path"] + (" [404]" if hit.get("title") == "404" else ""), int(hit["count"])))
exclude.append(str(hit["path_id"]))
+18 -9
View File
@@ -39,11 +39,12 @@ from functools import cache
from pathlib import Path
from xml.sax.saxutils import escape
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT / "scripts"))
sys.path.insert(0, str(Path(__file__).resolve().parent))
import siteinputs # noqa: E402
import sitemarkup as markup # noqa: E402
import siteinputs
import sitemarkup as markup
ROOT = Path(__file__).resolve().parent.parent
PLACEHOLDER = re.compile(r"(?m)^([ \t]*)<!--\s*image:\s*([A-Za-z0-9_-]+)\s*-->[ \t]*$")
PLACEHOLDER_ANYWHERE = re.compile(r"<!--\s*image:\s*([A-Za-z0-9_-]+)\s*-->")
@@ -626,9 +627,15 @@ def _pipeline_boxes() -> list[Box]:
"""The steps pipeline.py runs, read from its STEP_LABELS literal."""
tree = ast.parse((ROOT / "scripts" / "pipeline.py").read_text(encoding="utf-8"))
for node in ast.walk(tree):
target = getattr(node, "target", None) or (getattr(node, "targets", [None]) or [None])[0]
if isinstance(target, ast.Name) and target.id == "STEP_LABELS":
labels = ast.literal_eval(node.value)
if isinstance(node, ast.Assign):
target: ast.expr = node.targets[0]
value: ast.expr | None = node.value
elif isinstance(node, ast.AnnAssign):
target, value = node.target, node.value
else:
continue
if isinstance(target, ast.Name) and target.id == "STEP_LABELS" and value is not None:
labels = ast.literal_eval(value)
break
else:
raise RuntimeError("STEP_LABELS not found in scripts/pipeline.py")
@@ -945,7 +952,8 @@ def installer_options() -> tuple[tuple[str, str], ...]:
if not (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)
and node.func.attr == "add_argument"):
continue
flags = [arg.value for arg in node.args if isinstance(arg, ast.Constant)]
flags = [arg.value for arg in node.args
if isinstance(arg, ast.Constant) and isinstance(arg.value, str)]
keywords = {kw.arg: kw.value for kw in node.keywords}
action = keywords.get("action")
takes_value = not (isinstance(action, ast.Constant)
@@ -953,7 +961,8 @@ def installer_options() -> tuple[tuple[str, str], ...]:
metavar = ""
if takes_value:
given = keywords.get("metavar")
metavar = given.value if isinstance(given, ast.Constant) else flags[0].lstrip("-").upper()
metavar = (given.value if isinstance(given, ast.Constant) and isinstance(given.value, str)
else flags[0].lstrip("-").upper())
usage = ", ".join(f"{flag} {metavar}".strip() for flag in flags)
options.append((usage, _string(keywords["help"], constants) if "help" in keywords else ""))
# argparse's own, added to every parser.
+5 -2
View File
@@ -143,7 +143,10 @@ def load_observations(path: Path) -> dict[str, dict]:
return {}
out = {}
for issue, entries in (yaml.safe_load(path.read_text(encoding="utf-8")) or {}).items():
number = ISSUE_SUBJECT.match(f"{issue}-")["number"]
named = ISSUE_SUBJECT.match(f"{issue}-")
if named is None:
raise ValueError(f"{path}: {issue!r} is not an issue<number> key")
number = named["number"]
for entry in entries:
for key in [*entry.get("records", ()), *entry.get("subjects", ())]:
out[key] = {"issue": number, "said": entry["said"]}
@@ -221,7 +224,7 @@ def build_index(stored: list[mr.Stored], source: dict | None, profiles: dict,
entries = by_subject[key]
latest = max(entries, key=lambda s: (s.record["recorded_at"], s.line))
profile = profiles.get(key[0]) or {}
records = [{"url": permalink((source or {}).get("repo"), (source or {}).get("commit"),
records = [{"url": permalink((source or {})["repo"], (source or {})["commit"],
mr.records_path(s.emulator), s.line),
"proves": proves(ancestors.get(s.record["id"]) or {s.record["id"]}, profile),
"shown": shown_of(s.record),