From f2b7118fe3d0e6afab73311a6f93f8f18218bfb4 Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:33:10 +0100 Subject: [PATCH] chore: type and tidy the remaining site scripts --- scripts/fetch_site_images.py | 2 +- scripts/make_og_cards.py | 9 +++++---- scripts/site_insights.py | 4 ++++ scripts/sitediagrams.py | 27 ++++++++++++++++++--------- scripts/sitemeasurements.py | 7 +++++-- 5 files changed, 33 insertions(+), 16 deletions(-) diff --git a/scripts/fetch_site_images.py b/scripts/fetch_site_images.py index 468ebaef8..64496b7f1 100644 --- a/scripts/fetch_site_images.py +++ b/scripts/fetch_site_images.py @@ -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" bytes: diff --git a/scripts/make_og_cards.py b/scripts/make_og_cards.py index e35bf3441..9f4e20c7f 100644 --- a/scripts/make_og_cards.py +++ b/scripts/make_og_cards.py @@ -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" diff --git a/scripts/site_insights.py b/scripts/site_insights.py index d55a8312f..5392b85b4 100644 --- a/scripts/site_insights.py +++ b/scripts/site_insights.py @@ -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"])) diff --git a/scripts/sitediagrams.py b/scripts/sitediagrams.py index c33fa6933..e0c5173fc 100644 --- a/scripts/sitediagrams.py +++ b/scripts/sitediagrams.py @@ -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]*)[ \t]*$") PLACEHOLDER_ANYWHERE = re.compile(r"") @@ -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. diff --git a/scripts/sitemeasurements.py b/scripts/sitemeasurements.py index dfa03af49..44c6d2ea9 100644 --- a/scripts/sitemeasurements.py +++ b/scripts/sitemeasurements.py @@ -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 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),