In this section
- Build Homepage Fallback storage · globalgrid2050-homepage / scripts/build_homepage_fallback.py lines 1–112
- Fetch Active Pages storage · globalgrid2050-homepage / scripts/fetch_active_pages.py lines 1–217
- Releases storage · globalgrid2050-homepage / scripts/releases.py lines 1–261
Build Homepage Fallback
A Python command-line tool in the scripts folder of GlobalGrid2050 Homepage that works with app URL (`app_url`) and release app URL (`release_app_url`).
storageglobalgrid2050-homepage / scripts/build_homepage_fallback.py · lines 1–112 of 112 · Entry point · pattern app_url (shared by 2 files)
- What it does
- It loads data. Defines 6 functions or classes, including app_url, release_app_url, build, bounded, current. Uses libraries html, json, pathlib, re, urllib.parse. Side effects: reads or writes files.
- Inputs & outputs
- In: JSON file homepage.json; JSON file entity-types.json; JSON file presentation.json.
- Downstream impact
- Used directly by 5 files: Release GridAtlas (globalgrid2050-homepage); Build Homepage Release Candidate Workflow (globalgrid2050-homepage); Pages Workflow (globalgrid2050-homepage); PR Checks Workflow (globalgrid2050-homepage); and 1 more.
- What it achieves
- It is built from the build step (`build`), the bounded step (`bounded`) and the current step (`current`). Refresh the no-JavaScript nests and catalogue from the validated JSON source.
- Why it matters
- Run by 4 workflows and scripts, including Release GridAtlas, Build Homepage Release Candidate Workflow and Pages Workflow. Checked by Test Homepage Fallback Archives.
- Application
- globalgrid2050-homepage · scripts · Python CLI
- Uses
- Releases (import), html, json, pathlib, re, urllib.parse
- Used by
- run by Release GridAtlas (script call), run by Build Homepage Release Candidate Workflow (workflow run), run by Pages Workflow (workflow run), run by PR Checks Workflow (workflow run), imported by Test Homepage Fallback Archives (sys.path import)
- Produces
- app_url, release_app_url, build
- Defines here
- app_url, release_app_url, build, bounded, current, nest
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050-homepage@551a7625b02ddb7b3e6e0181cc643b8114c7fc06 scripts/build_homepage_fallback.py:1-112 · blob a331c3b65d98b33eb8c681ca1a856afd56bab537 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: supporting_data
"""Refresh the no-JavaScript nests and catalogue from the validated JSON source."""
from html import escape
import json
from pathlib import Path
import re
from urllib.parse import urlparse
from releases import load
ROOT = Path(__file__).resolve().parents[1]
def app_url(value):
parsed = urlparse(value)
hostname = parsed.hostname or ''
if parsed.scheme != 'https' or not hostname or parsed.username or parsed.password or any(hostname == h or hostname.endswith('.' + h) for h in ['github.com', 'githubusercontent.com']):
raise ValueError('Expected an HTTPS app URL')
return escape(value, quote=True)
def release_app_url(release, operative=False):
"""Match the JavaScript release row: archived app route, never a manifest."""
if not operative and release.get('archive_url') and release.get('archive_kind') != 'manifest':
try:
return app_url(release['archive_url'])
except ValueError:
pass # The JavaScript renderer also retains the app link.
return app_url(release['url'])
def build(root=ROOT):
root = Path(root)
data = load(root / 'data/homepage.json')
by_id = {entity['id']: entity for entity in data['entities']}
metadata = json.loads((root / 'data/entity-types.json').read_text(encoding='utf-8'))
types = {'engine', 'application', 'dataset', 'equipment', 'project', 'reference', 'drawing', 'catalogue'}
if metadata.get('schema_version') != 1 or not isinstance(metadata.get('records'), dict) or set(metadata['records']) != set(by_id):
raise ValueError('Invalid entity metadata keys')
def bounded(value, limit):
return isinstance(value, str) and bool(value.strip()) and len(value) <= limit
for meta in metadata['records'].values():
if not isinstance(meta, dict) or meta.get('type') not in types or not bounded(meta.get('purpose'), 1000) or not isinstance(meta.get('audience'), list) or not 1 <= len(meta['audience']) <= 10 or not all(bounded(value, 100) for value in meta['audience']):
raise ValueError('Invalid entity metadata record')
if not isinstance(meta.get('roles'), list) or len(meta['roles']) > 10 or not all(bounded(value, 100) for value in meta['roles']) or len(set(meta['roles'])) != len(meta['roles']):
raise ValueError('Invalid entity roles')
if 'capability_evidence' in meta:
evidence = meta['capability_evidence']
if not isinstance(evidence, dict) or not bounded(evidence.get('summary'), 1000):
raise ValueError('Invalid capability evidence')
app_url(evidence.get('url', ''))
presentation = json.loads((root / 'data/presentation.json').read_text(encoding='utf-8'))
if presentation.get('schema_version') != 1 or type(presentation.get('page_size')) is not int or not 1 <= presentation['page_size'] <= 100 or not isinstance(presentation.get('highlights'), list) or len(presentation['highlights']) > 4:
raise ValueError('Invalid presentation settings')
seen = set()
for item in presentation['highlights']:
if item.get('entity_id') not in by_id or item['entity_id'] in seen or not isinstance(item.get('label'), str) or not item['label'].strip() or len(item['label']) > 40:
raise ValueError('Invalid highlight')
seen.add(item['entity_id'])
def current(entity):
return next(release for release in entity['releases'] if release['id'] == entity['operative_release_id'])
def nest(entity, position, opened=False):
title = escape(entity['title'])
subtitle = '<small>' + escape(entity['subtitle']) + '</small>' if entity.get('subtitle') else ''
description = '<p>' + escape(entity['description']) + '</p>' if entity.get('description') else ''
launch = escape(entity.get('launch_label') or 'Open ' + entity['title'])
children = ''.join(nest(child, '↣') for child in data['entities'] if child.get('parent_id') == entity['id'])
return f'<details id="{escape(entity["id"], quote=True)}"' + (' open' if opened else '') + f'><summary><span class="number">{position}</span><span class="title">{title}{subtitle}</span></summary><div class="inside">{description}<a class="launch" href="{app_url(current(entity)["url"])}">{launch} →</a>{children}</div></details>'
nests = '\n'.join(nest(by_id[item['entity_id']], f'{index + 1:02}', item.get('open', False)) for index, item in enumerate(data['view']['items']))
rows = []
for entity in data['entities'][:presentation['page_size']]:
release = current(entity)
area = entity.get('subtitle') or by_id.get(entity.get('parent_id'), {}).get('title', '\u2014')
versions = []
for version in entity['releases']:
versions.append(f'<div class="release"><span class="release-state">{"Operative" if version["id"] == release["id"] else "Candidate" if version["status"] == "candidate" else "Archived"}</span><a href="{release_app_url(version, version["id"] == release["id"])}">{escape(version["label"])}</a><small class="entity-key">{escape(version["id"])}</small></div>')
meta = metadata['records'][entity['id']]
semantics = f'<details class="entity-type"><summary>{escape(meta["type"])}</summary><p>Intended purpose: {escape(meta["purpose"])}</p><p>For: {escape(", ".join(meta["audience"]))}</p>'
if meta['roles']:
semantics += f'<p>Intended roles: {escape(", ".join(meta["roles"]))}</p>'
if meta.get('capability_evidence'):
evidence = meta['capability_evidence']
semantics += f'<p>Recorded evidence: {escape(evidence["summary"])}</p><a href="{app_url(evidence["url"])}">View evidence</a>'
semantics += '</details>'
rows.append(f'<tr data-entity-id="{escape(entity["id"], quote=True)}"><th scope="row"><a href="{app_url(release["url"])}">{escape(entity["title"])}</a><small class="entity-key">{escape(entity["id"])}</small></th><td>{semantics}</td><td>{escape(area)}</td><td><details class="table-versions"><summary>{escape(release["label"])}</summary>{"".join(versions)}</details></td></tr>')
cards = []
for item in presentation['highlights']:
entity = by_id[item['entity_id']]
cards.append(f'<a class="highlight-card" data-entity-id="{escape(entity["id"], quote=True)}" href="{app_url(current(entity)["url"])}"><span class="highlight-label">{escape(item["label"])}</span><strong>{escape(entity["title"])}</strong><span class="highlight-description">{escape(entity.get("subtitle", ""))}</span></a>')
path = root / 'index.html'
html = path.read_text(encoding='utf-8')
html, count = re.subn(r'(<div id="highlightCards" class="highlight-cards">).*?(</div>)', lambda m: m[1] + ''.join(cards) + m[2], html, count=1, flags=re.S)
if count != 1:
raise ValueError('Missing highlights mount')
html, count = re.subn(r'(<section id="nests"[^>]*>).*?(</section>)', lambda m: m[1] + '\n' + nests + '\n' + m[2], html, count=1, flags=re.S)
if count != 1:
raise ValueError('Missing nests mount')
html, count = re.subn(r'(<tbody id="catalogueRows">).*?(</tbody>)', lambda m: m[1] + '\n' + '\n'.join(rows) + '\n' + m[2], html, count=1, flags=re.S)
if count != 1:
raise ValueError('Missing catalogue mount')
html = html.replace('aria-labelledby="catalogueHeading" hidden', 'aria-labelledby="catalogueHeading"')
html, count = re.subn(r'(<a id="archiveLink" href=")[^"]*(")', lambda m: m[1] + app_url(data['view']['archive_url']) + m[2], html, count=1)
if count != 1:
raise ValueError('Missing archive link')
path.write_text(html, encoding='utf-8')
print(f'Built {len(data["view"]["items"])} pinned nests and {len(rows)} catalogue rows')
if __name__ == '__main__':
build()Fetch Active Pages
A Python command-line tool in the scripts folder of GlobalGrid2050 Homepage using data from GitHub API. It verifies page (`verify_page`), creates ticker (`create_ticker`) and validates ticker (`validate_ticker`).
storageglobalgrid2050-homepage / scripts/fetch_active_pages.py · lines 1–217 of 217 · Entry point · pattern app_url (shared by 2 files)
- What it does
- It fetches data. Defines 13 functions or classes, including stamp, app_url, SafeRedirect, redirect_request, verify_page. Uses libraries argparse, datetime, json, os, pathlib. Side effects: reads or writes files; makes network requests; starts processes.
- Inputs & outputs
- In: data source: GitHub API; JSON file active-pages.json; command-line arguments.
- Downstream impact
- Used directly by 3 files: Build Homepage Release Candidate Workflow (globalgrid2050-homepage); Pages Workflow (globalgrid2050-homepage); PR Checks Workflow (globalgrid2050-homepage).
- What it achieves
- Refresh only homepage ticker from a bounded, explicitly described GitHub sample. It accepts `--config`, `--output` and `--offline-validation`.
- Why it matters
- Run by Build Homepage Release Candidate Workflow, Pages Workflow and PR Checks Workflow.
- Application
- globalgrid2050-homepage · scripts · Python CLI
- Uses
- argparse, datetime, json, os, pathlib, re, subprocess, sys
- Used by
- run by Build Homepage Release Candidate Workflow (workflow run), run by Pages Workflow (workflow run), run by PR Checks Workflow (workflow run)
- Produces
- stamp, app_url, SafeRedirect, verify_page, GitHub, activity, create_ticker, validate_ticker, refresh, main
- Defines here
- stamp, app_url, SafeRedirect, redirect_request, verify_page, GitHub, __init__, get, activity, create_ticker, validate_ticker, refresh, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050-homepage@551a7625b02ddb7b3e6e0181cc643b8114c7fc06 scripts/fetch_active_pages.py:1-217 · blob 9aa5e116a9bb5d27fc3465954e341c31cfadab1e · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, network, process · domain stage: unknown · users: none · canonical: supporting_data
"""Refresh only homepage ticker from a bounded, explicitly described GitHub sample.
Config is JSON-compatible YAML (stdlib only). GitHub metadata is authoritative for
Pages and commit activity; HTTPS GET proves current route availability. No repo
clones and no third-party credentials. On network/error, the prior feed survives.
Use --offline-validation in browser/CI checks without live API requests.
"""
import argparse
from datetime import datetime, timedelta, timezone
import json
import os
from pathlib import Path
import re
import subprocess
import sys
from urllib.error import HTTPError
from urllib.parse import urlencode, urlsplit, urlunsplit
from urllib.request import Request, HTTPRedirectHandler, build_opener
ROOT = Path(__file__).resolve().parents[1]
def stamp(now):
return now.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def app_url(url):
parsed = urlsplit(url)
host = (parsed.hostname or "").lower()
if parsed.scheme != "https" or parsed.username or parsed.password or not host:
raise ValueError("App destinations must use public HTTPS URLs")
if host in {"github.com", "www.github.com", "api.github.com", "raw.githubusercontent.com", "gitlab.com", "www.gitlab.com", "bitbucket.org", "www.bitbucket.org", "codeberg.org", "localhost"} or host.endswith(".githubusercontent.com"):
raise ValueError("Repository, API and raw-content URLs are not app pages")
if parsed.port not in (None, 443) or re.fullmatch(r"[\d.]+", host) or host.endswith(".local"):
raise ValueError("Non-public app destination")
return urlunsplit(("https", parsed.netloc.lower(), parsed.path or "/", parsed.query, ""))
class SafeRedirect(HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
app_url(newurl)
return super().redirect_request(req, fp, code, msg, headers, newurl)
def verify_page(url, max_bytes):
url = app_url(url)
request = Request(url, headers={"User-Agent": "GlobalGrid2050-homepage-ticker/1.0"})
try:
with build_opener(SafeRedirect()).open(request, timeout=25) as response:
if response.status != 200:
raise ValueError("App route did not return HTTP 200")
final = app_url(response.geturl())
if response.headers.get_content_type() != "text/html":
raise ValueError("App route is not HTML")
data = response.read(max_bytes + 1)
if len(data) > max_bytes or b"<html" not in data.lower():
raise ValueError("App HTML is absent or exceeds configured bound")
return final
except HTTPError as error:
if error.code in {404, 410}:
return None
raise RuntimeError(f"App route HTTP failure ({error.code}); prior feed preserved") from None
class GitHub:
def __init__(self):
token = os.environ.get("GH_TOKEN") or os.environ.get("GITHUB_TOKEN")
if not token:
result = subprocess.run(["gh", "auth", "token"], capture_output=True, text=True, check=False)
if result.returncode:
raise RuntimeError("GitHub authentication unavailable; prior feed preserved")
token = result.stdout.strip()
self.token = token
def get(self, path, missing_ok=False):
request = Request("https://api.github.com/" + path, headers={
"Authorization": "Bearer " + self.token, "Accept": "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28", "User-Agent": "GlobalGrid2050-homepage-ticker/1.0"})
try:
# No token in URLs, logs or external live-page requests.
with build_opener().open(request, timeout=25) as response:
data = response.read(8000001)
if len(data) > 8000000:
raise ValueError("GitHub response exceeds bound")
return json.loads(data)
except HTTPError as error:
if error.code == 404 and missing_ok:
return None
raise RuntimeError(f"GitHub HTTP failure ({error.code}); prior feed preserved") from None
def activity(commits, config, since):
qualifying = []
for item in commits:
commit = item["commit"]
date = commit["committer"]["date"]
if datetime.fromisoformat(date.replace("Z", "+00:00")) < since:
continue
message = commit["message"].splitlines()[0].lower()
if any(message.startswith(prefix.lower()) for prefix in config["exclude_commit_prefixes"]):
continue
qualifying.append(date)
return len(qualifying), max(qualifying, default=None), len(commits) >= config["commits_per_repository"]
def create_ticker(config, api, probe=verify_page, now=None):
now = now or datetime.now(timezone.utc)
since = now - timedelta(days=config["window_days"])
owner = config["owner"]
if not re.fullmatch(r"[A-Za-z0-9-]+", owner):
raise ValueError("Invalid GitHub owner")
listing = api.get(f"users/{owner}/repos?" + urlencode({"per_page": min(config["repository_listing_limit"], 100), "sort": "pushed", "direction": "desc"}))
listing = [item for item in listing if not item.get("private")]
repositories = {item["name"]: item for item in listing}
candidates = list(config["candidates"])
configured_repos = {item["repository"] for item in candidates}
for repo in listing:
if repo.get("has_pages") and not repo.get("archived") and repo["name"] not in configured_repos and repo["name"] not in config["exclude_repositories"] and not any(repo["name"].startswith(prefix) for prefix in config.get("exclude_repository_prefixes", [])):
candidates.append({"repository": repo["name"], "label": repo["name"].replace("-", " ").title()})
candidates = candidates[:min(config["max_candidates"], 20)]
cache, items, skipped, seen, checks = {}, [], [], set(), []
for candidate in candidates:
name = candidate["repository"]
if name not in repositories or not repositories[name].get("has_pages"):
skipped.append({"repository": name, "reason": "not_in_bounded_listing_or_no_pages"})
continue
if name not in cache:
pages = api.get(f"repos/{owner}/{name}/pages", missing_ok=True)
if not pages or pages.get("status") not in {"built", None} or not pages.get("html_url"):
cache[name] = None
else:
query = urlencode({"since": stamp(since), "until": stamp(now), "per_page": min(config["commits_per_repository"], 100)})
commits = api.get(f"repos/{owner}/{name}/commits?{query}")
cache[name] = (pages, activity(commits, config, since))
if cache[name] is None:
skipped.append({"repository": name, "reason": "pages_missing_or_not_built"})
continue
pages, (count, latest, capped) = cache[name]
if count == 0:
skipped.append({"repository": name, "reason": "no_qualifying_commits_in_window"})
continue
url = candidate.get("url", pages["html_url"])
final = probe(url, config["max_html_bytes"])
if final is None:
skipped.append({"repository": name, "reason": "live_route_missing"})
continue
final = app_url(final)
if final in seen:
skipped.append({"repository": name, "reason": "duplicate_final_url"})
continue
seen.add(final)
checks.append({"repository": f"{owner}/{name}", "url": final, "status": "verified_https_html_200", "activity_count": count, "activity_capped": capped})
items.append({"label": candidate["label"], "url": final, "repository": f"{owner}/{name}",
"activity_count": count, "activity_capped": capped, "last_activity": latest,
"verified_at": stamp(now), "pages_status": pages.get("status") or "not_reported",
"verification": "Pages API configured; final HTTPS HTML HTTP 200"})
items.sort(key=lambda item: (item["activity_count"], item["last_activity"], item["label"]), reverse=True)
if not items:
raise ValueError("No verified active app pages; prior feed preserved")
return {"schema_version": 1, "items": items[:min(config["max_items"], 12)], "updated_at": stamp(now), "window_days": config["window_days"],
"method": {"description": config["method_note"], "grain": "one verified final app URL", "key": "url",
"repository_sample_size": len(listing), "routes_considered": len(candidates),
"commits_per_repository_cap": config["commits_per_repository"], "checks": checks, "skipped": skipped}}
def validate_ticker(ticker):
if not 0 < len(ticker["items"]) <= 12 or ticker["window_days"] != 30:
raise ValueError("Invalid ticker bounds")
urls = [app_url(item["url"]) for item in ticker["items"]]
if len(urls) != len(set(urls)):
raise ValueError("Duplicate app URLs")
for item in ticker["items"]:
if not item["label"] or not isinstance(item["activity_count"], int) or not 0 < item["activity_count"] <= 100:
raise ValueError("Invalid ticker activity")
if not isinstance(item["activity_capped"], bool) or not item["last_activity"]:
raise ValueError("Missing activity provenance")
def refresh(config, output, api=None, probe=verify_page):
# Finish ALL network work before altering the last good feed.
ticker = create_ticker(config, api or GitHub(), probe)
validate_ticker(ticker)
encoded = json.dumps(ticker, indent=2, ensure_ascii=False) + "\n"
output.parent.mkdir(parents=True, exist_ok=True)
staging = output.with_suffix(".json.tmp")
try:
staging.write_text(encoded, encoding="utf-8", newline="\n")
validate_ticker(json.loads(staging.read_text(encoding="utf-8")))
staging.replace(output)
finally:
if staging.exists():
staging.unlink()
return ticker
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--config", type=Path, default=ROOT / "config/active-pages.yaml")
parser.add_argument("--output", type=Path, default=ROOT / "data/active-pages.json")
parser.add_argument("--offline-validation", "--check", dest="offline_validation", action="store_true")
args = parser.parse_args()
if args.offline_validation:
validate_ticker(json.loads(args.output.read_text(encoding="utf-8")))
print("Offline ticker schema/key checks passed; live availability is not rechecked")
else:
config = json.loads(args.config.read_text(encoding="utf-8"))
ticker = refresh(config, args.output)
print(f"Verified {len(ticker['items'])} live app pages; {ticker['method']['routes_considered']} candidate routes checked")
if __name__ == "__main__":
try:
main()
except Exception as error:
# Never print request headers, token, subprocess stdout or traceback locals.
print(f"Refresh failed; prior feed preserved: {type(error).__name__}: {error}", file=sys.stderr)
sys.exit(1)Releases
A Python command-line tool in the scripts folder of GlobalGrid2050 Homepage that writes validated (`write_validated`).
storageglobalgrid2050-homepage / scripts/releases.py · lines 1–261 of 261 · Entry point · pattern unique_object (shared by 2 files)
- What it does
- It loads data. Defines 12 functions or classes, including require, fields, nonempty, identifier, https_url. Uses libraries argparse, copy, datetime, json, os. Side effects: reads or writes files; starts processes.
- Inputs & outputs
- In: JSON file homepage.json; command-line arguments. Out: JSON file.
- Downstream impact
- Used directly by 6 files: Release GridAtlas (globalgrid2050-homepage); Build Homepage Release Candidate Workflow (globalgrid2050-homepage); Pages Workflow (globalgrid2050-homepage); PR Checks Workflow (globalgrid2050-homepage); and 2 more. Reached from 1 other entry point, including Test Homepage Fallback Archives (globalgrid2050-homepage).
- What it achieves
- It is built from the require step (`require`), the fields step (`fields`) and the nonempty step (`nonempty`). Validate homepage release metadata and explicitly promote an available release. It accepts `--file` and `--reason`.
- Why it matters
- Imported by Release GridAtlas and Build Homepage Fallback. Run by 4 workflows and scripts, including Build Homepage Release Candidate Workflow, Pages Workflow and PR Checks Workflow.
- Application
- globalgrid2050-homepage · scripts · Python CLI
- Uses
- argparse, copy, datetime, json, os, pathlib, re, sys
- Used by
- imported by Release GridAtlas (import), run by Build Homepage Release Candidate Workflow (workflow run), run by Pages Workflow (workflow run), run by PR Checks Workflow (workflow run), run by Validate Homepage Release Workflow (workflow run), imported by Build Homepage Fallback (import)
- Produces
- require, fields, nonempty, identifier, https_url, iso_date, validate, unique_object, load, promote, write_validated, main
- Defines here
- require, fields, nonempty, identifier, https_url, iso_date, validate, unique_object, load, promote, write_validated, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- globalgrid2050-homepage@551a7625b02ddb7b3e6e0181cc643b8114c7fc06 scripts/releases.py:1-261 · blob 84644926d65da5008a4ace8b8c9cf634b1d9d2c2 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: unknown · users: none · canonical: supporting_data
"""Validate homepage release metadata and explicitly promote an available release.
Run from the repository root:
python scripts/releases.py validate
python scripts/releases.py promote ENTITY RELEASE --reason "Reviewed and tested"
The catalogue grain is one entity per id, one release per (entity id, release id).
An available non-operative release is archived implicitly, never removed here.
Availability is a maintainer assertion: this tool does not test the linked app.
"""
import argparse
import copy
from datetime import date, datetime, timezone
import json
import os
from pathlib import Path
import re
import sys
import tempfile
from urllib.parse import urlsplit
DEFAULT_FILE = Path(__file__).resolve().parents[1] / "data" / "homepage.json"
def require(condition, message):
if not condition:
raise ValueError(message)
def fields(value, required, optional, context):
require(isinstance(value, dict), f"{context}: expected object")
require(set(required) <= value.keys(), f"{context}: missing fields {set(required) - value.keys()}")
require(value.keys() <= set(required) | set(optional), f"{context}: unknown fields {value.keys() - set(required) - set(optional)}")
def nonempty(value, context):
require(isinstance(value, str) and bool(value.strip()), f"{context}: expected nonempty text")
def identifier(value, context):
nonempty(value, context)
require(re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.:-]*", value) is not None, f"{context}: invalid identifier")
def https_url(value, context):
nonempty(value, context)
require(not any(c.isspace() or ord(c) < 32 or ord(c) == 127 for c in value), f"{context}: whitespace/control character in URL")
require("\\" not in value, f"{context}: backslash in URL")
try:
parts = urlsplit(value)
port = parts.port
require(parts.scheme == "https" and bool(parts.hostname), f"{context}: HTTPS URL required")
require(parts.username is None and parts.password is None, f"{context}: credentials forbidden")
require("%" not in parts.netloc, f"{context}: encoded hostname forbidden")
require(port is None or 0 < port <= 65535, f"{context}: invalid port")
except ValueError as exc:
raise ValueError(f"{context}: invalid URL ({exc})") from exc
def iso_date(value, context, utc_only=False):
nonempty(value, context)
try:
if re.fullmatch(r"\d{4}-\d{2}-\d{2}", value) and not utc_only:
date.fromisoformat(value)
else:
require("T" in value, f"{context}: ISO date or timezone-aware timestamp required")
parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
require(parsed.tzinfo is not None, f"{context}: timestamp needs timezone")
if utc_only:
require(parsed.utcoffset().total_seconds() == 0, f"{context}: UTC required")
except ValueError as exc:
raise ValueError(f"{context}: invalid date ({exc})") from exc
def validate(data):
fields(data, {"schema_version", "entities", "view"}, {"promotions", "development"}, "catalogue")
require(type(data["schema_version"]) is int and data["schema_version"] == 1, "schema_version must be 1")
require(isinstance(data["entities"], list), "entities must be an array")
entities = {}
releases = {}
for entity in data["entities"]:
fields(entity, {"id", "title", "subtitle", "description", "launch_label", "operative_release_id", "releases"}, {"parent_id"}, "entity")
identifier(entity["id"], "entity.id")
eid = entity["id"]
require(eid not in entities, f"duplicate entity id: {eid}")
entities[eid] = entity
for key in ("title", "subtitle", "description", "launch_label"):
nonempty(entity[key], f"{eid}.{key}")
if "parent_id" in entity:
identifier(entity["parent_id"], f"{eid}.parent_id")
identifier(entity["operative_release_id"], f"{eid}.operative_release_id")
require(isinstance(entity["releases"], list) and entity["releases"], f"{eid}: releases must be a nonempty array")
releases[eid] = {}
for release in entity["releases"]:
fields(release, {"id", "label", "url", "published_at", "status", "source_ref"}, {"archive_url", "archive_kind"}, f"{eid}.release")
identifier(release["id"], f"{eid}.release.id")
rid = release["id"]
require(rid not in releases[eid], f"{eid}: duplicate release id {rid}")
releases[eid][rid] = release
nonempty(release["label"], f"{eid}/{rid}.label")
nonempty(release["source_ref"], f"{eid}/{rid}.source_ref")
https_url(release["url"], f"{eid}/{rid}.url")
require(("archive_url" in release) == ("archive_kind" in release), f"{eid}/{rid}: archive_url and archive_kind must be supplied together")
if "archive_url" in release:
https_url(release["archive_url"], f"{eid}/{rid}.archive_url")
require(release["archive_kind"] in ("app", "manifest"), f"{eid}/{rid}: invalid archive_kind")
if release["published_at"] is not None:
iso_date(release["published_at"], f"{eid}/{rid}.published_at")
require(release["status"] in ("available", "candidate"), f"{eid}/{rid}: invalid status")
current = releases[eid].get(entity["operative_release_id"])
require(current is not None, f"{eid}: operative release reference missing")
require(current["status"] == "available", f"{eid}: operative release must be available")
# Iterative traversal supports deep product hierarchies without recursion limits.
complete = set()
for eid in entities:
path = set()
cursor = eid
while cursor is not None and cursor not in complete:
require(cursor in entities, f"{eid}: unknown parent {cursor}")
require(cursor not in path, f"{eid}: parent cycle")
path.add(cursor)
cursor = entities[cursor].get("parent_id")
complete.update(path)
view = data["view"]
fields(view, {"items", "archive_url"}, set(), "view")
https_url(view["archive_url"], "view.archive_url")
require(isinstance(view["items"], list), "view.items must be an array")
seen = set()
for item in view["items"]:
fields(item, {"entity_id", "open"}, set(), "view.item")
identifier(item["entity_id"], "view.item.entity_id")
eid = item["entity_id"]
require(eid in entities, f"view: unknown entity {eid}")
require(eid not in seen, f"view: duplicate entity {eid}")
require("parent_id" not in entities[eid], f"view: {eid} is not a root entity")
require(type(item["open"]) is bool, f"view/{eid}.open must be boolean")
seen.add(eid)
development = data.get("development", [])
require(isinstance(development, list), "development must be an array")
seen_development = set()
for entry in development:
fields(entry, {"entity_id", "label", "status", "url"}, {"description", "evidence_summary"}, "development entry")
identifier(entry["entity_id"], "development.entity_id")
eid = entry["entity_id"]
require(eid in entities, f"development: unknown entity {eid}")
require(eid not in seen_development, f"development: duplicate entity {eid}")
seen_development.add(eid)
nonempty(entry["label"], "development.label")
for key in ("description", "evidence_summary"):
if key in entry:
nonempty(entry[key], f"development.{key}")
require(entry["status"] == "In development", "development.status must be 'In development'")
https_url(entry["url"], "development.url")
audit = data.get("promotions", [])
require(isinstance(audit, list), "promotions must be an array")
last = {}
for entry in audit:
fields(entry, {"entity_id", "from_release_id", "to_release_id", "reason", "promoted_at"}, set(), "promotion")
identifier(entry["entity_id"], "promotion.entity_id")
eid = entry["entity_id"]
require(eid in entities, f"promotion: unknown entity {eid}")
for key in ("from_release_id", "to_release_id"):
identifier(entry[key], f"promotion.{key}")
require(entry[key] in releases[eid], f"promotion: unknown release {eid}/{entry[key]}")
require(entry["from_release_id"] != entry["to_release_id"], "promotion must change release")
require(eid not in last or last[eid] == entry["from_release_id"], f"{eid}: broken promotion history")
nonempty(entry["reason"], "promotion.reason")
iso_date(entry["promoted_at"], "promotion.promoted_at", utc_only=True)
last[eid] = entry["to_release_id"]
for eid, rid in last.items():
require(entities[eid]["operative_release_id"] == rid, f"{eid}: operative release differs from promotion history")
return data
def unique_object(pairs):
result = {}
for key, value in pairs:
require(key not in result, f"duplicate JSON property: {key}")
result[key] = value
return result
def load(path):
return validate(json.loads(Path(path).read_text(encoding="utf-8"), object_pairs_hook=unique_object))
def promote(data, entity_id, release_id, reason):
validate(data)
nonempty(reason, "promotion reason")
result = copy.deepcopy(data)
entity = next((e for e in result["entities"] if e["id"] == entity_id), None)
require(entity is not None, f"unknown entity: {entity_id}")
target = next((r for r in entity["releases"] if r["id"] == release_id), None)
require(target is not None, f"unknown release: {entity_id}/{release_id}")
require(target["status"] == "available", "candidate releases cannot be promoted; verify the release and mark it available first")
previous = entity["operative_release_id"]
require(previous != release_id, "release is already operative; no changes made")
entity["operative_release_id"] = release_id
result.setdefault("promotions", []).append({
"entity_id": entity_id,
"from_release_id": previous,
"to_release_id": release_id,
"reason": reason.strip(),
"promoted_at": datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z"),
})
return validate(result)
def write_validated(path, data):
"""Read back a staged file before atomically replacing the local configuration."""
path = Path(path)
staged = None
try:
with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", newline="\n", dir=path.parent, prefix=".homepage-", suffix=".json", delete=False) as output:
staged = Path(output.name)
json.dump(data, output, indent=2, ensure_ascii=False, allow_nan=False)
output.write("\n")
output.flush()
os.fsync(output.fileno())
load(staged)
os.replace(staged, path)
finally:
if staged is not None and staged.exists():
staged.unlink()
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--file", type=Path, default=DEFAULT_FILE)
commands = parser.add_subparsers(dest="command", required=True)
audit = commands.add_parser("validate", help="Validate the local homepage configuration")
promotion = commands.add_parser("promote", help="Change the operative release and append an audit entry")
for command in (audit, promotion):
command.add_argument("--file", type=Path, default=argparse.SUPPRESS)
promotion.add_argument("entity_id")
promotion.add_argument("release_id")
promotion.add_argument("--reason", required=True)
args = parser.parse_args(argv)
try:
data = load(args.file)
if args.command == "promote":
data = promote(data, args.entity_id, args.release_id, args.reason)
write_validated(args.file, data)
print(f"Promoted {args.entity_id} to {args.release_id}; previous releases retained. Review the diff before commit.")
else:
count = sum(len(entity["releases"]) for entity in data["entities"])
print(f"Valid: {len(data['entities'])} entities, {count} releases, {len(data['view']['items'])} root view items; duplicate keys and broken references: 0.")
except (ValueError, OSError) as exc:
print(f"Error: {exc}", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())