In this section
- Build Pages Promotion Wrapper storage · pipelinenews / tools/publication/build_pages_promotion_wrapper.py lines 1–319
- Pages Release Classifier automation · pipelinenews / tools/publication/pages_release_classifier.py lines 1–300
Build Pages Promotion Wrapper
A Python command-line tool in the publication folder of PipelineNews that reads atlas link, using SHA-256 from the GridAtlas repository. It writes JSON (`write_json`) and verifies source release (`verify_source_release`).
storagepipelinenews / tools/publication/build_pages_promotion_wrapper.py · lines 1–319 of 319 · Entry point · pattern sha256_bytes (shared by 14 files)
- What it does
- It loads atlas link. Defines 15 functions or classes, including require, git, require_clean_checkout, sha256_bytes, sha256. Uses libraries __future__, argparse, datetime, hashlib, json. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'pipelinenews'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
- Inputs & outputs
- In: data source: gridatlas data; JSON file atlas-link-manifest.json; JSON file build-manifest.json; JSON file release-manifest.json; JSON file current.json; command-line arguments.
- Downstream impact
- Used directly by 1 file: Test Pages Promotion Tooling (pipelinenews).
- What it achieves
- Build one immutable Pages wrapper around an additive Pipeline release. It writes `atlas-link-manifest.json`. It accepts `--repo`, `--source-release` and `--source-commit`.
- Why it matters
- Checked by Test Pages Promotion Tooling.
- Application
- pipelinenews · tools/publication · Python CLI
- Uses
- GridAtlas — Atlas Page (estate URL), __future__, argparse, datetime, hashlib, json, pathlib, posixpath, re
- Used by
- imported by Test Pages Promotion Tooling (import)
- Produces
- require, git, require_clean_checkout, sha256_bytes, sha256, record, compact_digest, write_json, committed_tree_files, verify_source_release, grid_file_record, receiver_contract
- Defines here
- require, git, require_clean_checkout, sha256_bytes, sha256, record, compact_digest, write_json, committed_tree_files, verify_source_release, grid_file_record, receiver_contract, cartridge, build, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 tools/publication/build_pages_promotion_wrapper.py:1-319 · blob fa1c96e1ab3ad1d7d8d7ce3d0e9507f1a9909fac · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""Build one immutable Pages wrapper around an additive Pipeline release.
The source release is copied byte-for-byte. Only the four wrapper-control
files (the release, build, Atlas-binding and SHA manifests) are new. The
receiver contract is derived from a clean GridAtlas checkout at an exact
commit; no branch name or moving pointer is accepted.
"""
from __future__ import annotations
import argparse
from datetime import datetime, timezone
import hashlib
import json
from pathlib import Path
import posixpath
import re
import shutil
import subprocess
RELEASE_RE = re.compile(r"^(\d{12})-pipelinenews$")
COMMIT_RE = re.compile(r"^[0-9a-f]{40}$")
SHA256_RE = re.compile(r"^[0-9a-f]{64}$")
CONTROL_FILES = frozenset({
"atlas-link-manifest.json",
"build-manifest.json",
"release-manifest.json",
"sha256sums.txt",
})
def require(condition: bool, message: str) -> None:
if not condition:
raise AssertionError(message)
def git(repo: Path, *args: str) -> str:
return subprocess.check_output(["git", *args], cwd=repo, text=True).strip()
def require_clean_checkout(repo: Path, label: str) -> None:
require(not git(repo, "status", "--porcelain"), f"{label} checkout is dirty")
def sha256_bytes(payload: bytes) -> str:
return hashlib.sha256(payload).hexdigest()
def sha256(path: Path) -> str:
return sha256_bytes(path.read_bytes())
def record(path: Path, local: str) -> dict[str, object]:
return {"path": local, "bytes": path.stat().st_size, "sha256": sha256(path)}
def compact_digest(value: object) -> str:
payload = json.dumps(
value, ensure_ascii=False, sort_keys=True, separators=(",", ":")
).encode("utf-8")
return sha256_bytes(payload)
def write_json(path: Path, value: object) -> None:
path.write_text(
json.dumps(value, ensure_ascii=False, indent=2, sort_keys=True) + "\n",
encoding="utf-8",
newline="\n",
)
def committed_tree_files(repo: Path, commit: str, release_id: str) -> list[str]:
prefix = f"releases/{release_id}/"
lines = git(repo, "ls-tree", "-r", "--name-only", commit, "--", prefix).splitlines()
files = [line.removeprefix(prefix) for line in lines if line.startswith(prefix)]
require(files, f"source release is absent from {commit}: {release_id}")
return sorted(files)
def verify_source_release(repo: Path, release_id: str, source_commit: str) -> list[str]:
require(COMMIT_RE.fullmatch(source_commit) is not None, "source commit must be exact")
match = RELEASE_RE.fullmatch(release_id)
require(match is not None, "source release id must be timestamped")
subprocess.run(
["git", "cat-file", "-e", f"{source_commit}^{{commit}}"],
cwd=repo, check=True, capture_output=True,
)
source = repo / "releases" / release_id
require(source.is_dir() and not source.is_symlink(), "source release folder is missing")
committed = committed_tree_files(repo, source_commit, release_id)
actual = sorted(
path.relative_to(source).as_posix() for path in source.rglob("*") if path.is_file()
)
require(actual == committed, "source release working tree differs from committed closure")
for local in committed:
disk = (source / local).read_bytes()
blob = subprocess.check_output(
["git", "show", f"{source_commit}:releases/{release_id}/{local}"], cwd=repo
)
require(disk == blob, f"source release byte drift: {local}")
manifest = json.loads((source / "release-manifest.json").read_text(encoding="utf-8"))
require(manifest.get("release_id") == release_id, "source manifest identity changed")
require(
manifest.get("schema") == "pipelinenews.additive-cartridge-release.v1"
and manifest.get("deployment") == "not-authorised",
"source is not an unpromoted additive release",
)
return committed
def grid_file_record(grid: Path, local: str) -> dict[str, object]:
target = grid / local
require(target.is_file() and not target.is_symlink(), f"Grid receiver file missing: {local}")
return record(target, local)
def receiver_contract(grid: Path, exact_commit: str) -> dict[str, object]:
require(COMMIT_RE.fullmatch(exact_commit) is not None, "Grid commit must be exact")
require_clean_checkout(grid, "Grid receiver")
require(git(grid, "rev-parse", "HEAD") == exact_commit, "Grid checkout is not exact commit")
current_path = grid / "atlas" / "current.json"
current = json.loads(current_path.read_text(encoding="utf-8"))
require(current.get("schema") == "gridatlas.current.v2", "Grid current schema changed")
generation = str(current.get("generation", ""))
require(re.fullmatch(r"\d{12}", generation) is not None, "Grid generation changed")
cartridges = {item.get("id"): item for item in current.get("cartridges", [])}
measurement = cartridges.get("sld-sandbox") or {}
engine = cartridges.get("substation-intelligence") or {}
require(re.fullmatch(r"v9\.\d+", str(measurement.get("version", ""))) is not None,
"Grid receiver version changed")
def cartridge(item: dict, label: str) -> dict[str, object]:
relative = str(item.get("path", "")).removeprefix("./")
require(
relative.startswith("cartridges/")
and posixpath.normpath(relative) == relative
and all(part not in ("", ".", "..") for part in relative.split("/")),
f"{label} path left cartridges",
)
result = grid_file_record(grid, f"atlas/{relative}")
require(result["sha256"] == item.get("sha256"), f"{label} current digest changed")
result["generation"] = item.get("generation")
result["version"] = item.get("version")
return result
measurement_record = cartridge(measurement, "measurement receiver")
engine_record = cartridge(engine, "engine receiver")
composition = grid_file_record(
grid, f"atlas/manifests/{generation}-composition.json"
)
proof = grid_file_record(grid, f"tools/proofs/{generation}-sld-sandbox.proof.mjs")
return {
"schema": "pipelinenews.gridatlas-production-receiver.v1",
"repository": "Ventusltd/gridatlas",
"commit": exact_commit,
"generation": generation,
"version": measurement_record["version"],
"base_url": "https://ventusltd.github.io/gridatlas/atlas/",
"measurement_cartridge": measurement_record,
"engine_cartridge": engine_record,
"composition_manifest": composition,
"production_proof": proof,
"required_result": "MEASURE_LINK_FIRST",
"identity_reconciliation": "VERIFY_CONCURRENTLY_AND_REMEASURE_AT_RESOLVED_POINT",
}
def build(
repo: Path,
source_release_id: str,
source_commit: str,
grid: Path,
grid_commit: str,
generation: str,
) -> str:
require(re.fullmatch(r"\d{12}", generation) is not None, "generation must be UTC YYYYMMDDHHMM")
require_clean_checkout(repo, "Pipeline validator")
source_match = RELEASE_RE.fullmatch(source_release_id)
require(source_match is not None, "source release id must be timestamped")
source_generation = source_match.group(1)
require(generation > source_generation, "wrapper generation must follow source")
source_files = verify_source_release(repo, source_release_id, source_commit)
validator_commit = git(repo, "rev-parse", "HEAD")
subprocess.run(
["git", "merge-base", "--is-ancestor", source_commit, validator_commit],
cwd=repo, check=True, capture_output=True,
)
receiver = receiver_contract(grid, grid_commit)
release_id = f"{generation}-pipelinenews"
target = repo / "releases" / release_id
require(not target.exists(), f"wrapper already exists: {release_id}")
target.mkdir(parents=True)
source = repo / "releases" / source_release_id
copied: list[dict[str, object]] = []
for local in source_files:
if local in CONTROL_FILES:
continue
destination = target / local
destination.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(source / local, destination)
copied.append(record(destination, local))
copied.sort(key=lambda item: str(item["path"]))
copied_digest = compact_digest(copied)
source_manifest_record = record(
source / "release-manifest.json",
f"releases/{source_release_id}/release-manifest.json",
)
promotion = {
"schema": "pipelinenews.pages-promotion-wrapper.v1",
"source_release_id": source_release_id,
"source_commit": source_commit,
"validator_commit": validator_commit,
"copied_file_count": len(copied),
"copied_files_sha256": copied_digest,
"source_release_manifest": source_manifest_record,
"receiver_contract_sha256": compact_digest(receiver),
}
atlas = {
"schema": "pipelinenews.atlas-current-link-manifest.v2",
"classification": "VERIFIED_GRIDATLAS_PRODUCTION_RECEIVER_BOUND",
"generation": generation,
"pipeline_release_id": release_id,
"source_pipeline_release_id": source_release_id,
"source_commit": source_commit,
"transport": {
"identity_rule": "EXACT_REPD_REF",
"query_parameter_order": [
"repd_ref", "project", "technology", "capacity_mw",
"latitude", "longitude", "zoom",
],
"source_rows": 8756,
"clickable_rows": 8743,
"unresolved_rows": 13,
},
"receiver": receiver,
"receiver_contract_sha256": promotion["receiver_contract_sha256"],
}
write_json(target / "atlas-link-manifest.json", atlas)
files = copied + [record(target / "atlas-link-manifest.json", "atlas-link-manifest.json")]
files.sort(key=lambda item: str(item["path"]))
build_manifest = {
"schema": "pipelinenews.current-atlas-link-build-manifest.v2",
"classification": "DETERMINISTIC_SOURCE_RELEASE_PROMOTION",
"generation": generation,
"release_id": release_id,
"source_release_id": source_release_id,
"source_commit": source_commit,
"validator_commit": validator_commit,
"promotion_wrapper": promotion,
"receiver": receiver,
"files": files,
}
write_json(target / "build-manifest.json", build_manifest)
release_manifest = {
"schema": "pipelinenews.current-atlas-link-release.v2",
"classification": "CURRENT_ATLAS_LINK_CANDIDATE",
"generation": generation,
"release_id": release_id,
"immutable_after_publication": True,
"deployment": "candidate",
"parent_release_id": source_release_id,
"product_surface": "BYTE_IDENTICAL_ADDITIVE_RELEASE_PLUS_FINAL_GRID_RECEIVER",
"application_changes": 0,
"data_changes": 0,
"news_changes": 0,
"project_changes": 0,
"promotion_wrapper": promotion,
"atlas_live_url": receiver["base_url"],
"atlas_receiver_commit": receiver["commit"],
"atlas_receiver_version": receiver["version"],
}
write_json(target / "release-manifest.json", release_manifest)
ledger_files = sorted(path for path in target.rglob("*") if path.is_file())
ledger = "".join(
f"{sha256(path)} {path.relative_to(target).as_posix()}\n" for path in ledger_files
)
(target / "sha256sums.txt").write_text(ledger, encoding="utf-8", newline="\n")
print(json.dumps({
"release_id": release_id,
"source_commit": source_commit,
"validator_commit": validator_commit,
"grid_commit": grid_commit,
"copied_files": len(copied),
"receiver_version": receiver["version"],
}, sort_keys=True))
return release_id
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--repo", type=Path, default=Path(__file__).resolve().parents[2])
parser.add_argument("--source-release", required=True)
parser.add_argument("--source-commit", required=True)
parser.add_argument("--gridatlas", type=Path)
parser.add_argument("--grid-commit")
parser.add_argument("--generation")
parser.add_argument("--check-source", action="store_true")
args = parser.parse_args()
repo = args.repo.resolve()
if args.check_source:
files = verify_source_release(repo, args.source_release, args.source_commit)
print(json.dumps({"status": "PASS", "files": len(files)}, sort_keys=True))
return 0
require(args.gridatlas is not None and args.grid_commit is not None,
"--gridatlas and --grid-commit are required")
generation = args.generation or datetime.now(timezone.utc).strftime("%Y%m%d%H%M")
build(
repo, args.source_release, args.source_commit,
args.gridatlas.resolve(), args.grid_commit, generation,
)
return 0
if __name__ == "__main__":
raise SystemExit(main())Pages Release Classifier
A Python command-line tool in the publication folder of PipelineNews that writes GitHub output (`write_github_output`) and receipt (`write_receipt`) and resolves live pointer (`resolve_live_pointer`), using SHA-256.
automationpipelinenews / tools/publication/pages_release_classifier.py · lines 1–300 of 300 · Entry point · pattern write_receipt (shared by 6 files)
- What it does
- Defines 13 functions or classes, including ClassificationError, Decision, release_ids_from_paths, require_commit, discover_release. Uses libraries __future__, argparse, hashlib, json, re. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (repository name word 'pipelinenews'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
- Inputs & outputs
- In: JSON file release-manifest.json; JSON file live-set.json; JSON file current-v3.json; JSON file current-v4.json; command-line arguments.
- Downstream impact
- Used directly by 4 files: Build 30x Ledger (pipelinenews); Run Pages Candidate Gate (pipelinenews); Test Pages Release Classifier (pipelinenews); PipelineNews Pages Workflow (pipelinenews). Reached from 1 other entry point, including PipelineNews Pages Routing Candidate Workflow (pipelinenews).
- What it achieves
- It classifies release (`classify_release`) and is built from the classification error class (`ClassificationError`) and the decision class (`Decision`). Classify one immutable Pipeline News release for the Pages workflow. It accepts `--repo`, `--release` and `--base`.
- Why it matters
- Imported by Run Pages Candidate Gate. Run by Build 30x Ledger and PipelineNews Pages Workflow. Checked by Test Pages Release Classifier.
- Application
- pipelinenews · tools/publication · Python CLI
- Uses
- __future__, argparse, hashlib, json, re, subprocess, tempfile, dataclasses
- Used by
- run by Build 30x Ledger (script call), imported by Run Pages Candidate Gate (import), imported by Test Pages Release Classifier (import), run by PipelineNews Pages Workflow (workflow run)
- Produces
- ClassificationError, Decision, release_ids_from_paths, require_commit, discover_release, classify_release, write_github_output, write_receipt, resolve_live_pointer, main
- Defines here
- ClassificationError, Decision, release_ids_from_paths, require_commit, discover_release, _read_manifest, reject_duplicates, _load_manifest, classify_release, write_github_output, write_receipt, resolve_live_pointer, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- pipelinenews@45c944c8640a9d7ae65edb51d66032ba204f3f46 tools/publication/pages_release_classifier.py:1-300 · blob 3ec36ba10b39ca561670e94d9a370d1c4da10d9f · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""Classify one immutable Pipeline News release for the Pages workflow.
The classifier is deliberately independent of GitHub Actions. It reads the
release manifest and returns one of two routes: ``pages`` for release classes
the Pages builder understands, or ``source-only`` for additive cartridges
whose publisher is GlobalGrid2050. Unknown input fails closed.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import re
import subprocess
import tempfile
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Any
PAGES_SCHEMAS = frozenset(
{
"pipelinenews.timestamp-folder-successor.v1",
"pipelinenews.current-atlas-link-release.v2",
}
)
SOURCE_ONLY_SCHEMAS = frozenset({"pipelinenews.additive-cartridge-release.v1"})
RELEASE_ID_RE = re.compile(r"^[0-9]{12}-pipelinenews$")
RELEASE_PATH_RE = re.compile(r"^releases/([0-9]{12}-pipelinenews)(?:/|$)")
COMMIT_RE = re.compile(r"^[0-9a-f]{40}$")
MAX_MANIFEST_BYTES = 1024 * 1024
class ClassificationError(ValueError):
"""Input cannot be classified safely."""
@dataclass(frozen=True)
class Decision:
release_id: str
schema: str
route: str
reason: str
manifest_path: str
manifest_sha256: str
manifest_bytes: int
deployment: str | None
def release_ids_from_paths(paths: list[str]) -> list[str]:
"""Return sorted distinct release ids named by repository-relative paths."""
found: set[str] = set()
for path in paths:
match = RELEASE_PATH_RE.match(path.replace("\\", "/"))
if match:
found.add(match.group(1))
return sorted(found)
def require_commit(repo: Path, value: str, label: str) -> None:
if not COMMIT_RE.fullmatch(value):
raise ClassificationError(f"{label} must be a full lowercase commit oid")
process = subprocess.run(
["git", "cat-file", "-e", f"{value}^{{commit}}"],
cwd=repo,
check=False,
capture_output=True,
)
if process.returncode:
raise ClassificationError(f"{label} is not an available commit: {value}")
def discover_release(
repo: Path, base: str, head: str, *, allow_pointer_fallback: bool = False
) -> str:
require_commit(repo, base, "base")
require_commit(repo, head, "head")
process = subprocess.run(
["git", "diff", "--name-status", "-z", "--find-renames", base, head, "--", "releases"],
cwd=repo,
check=False,
capture_output=True,
)
if process.returncode:
raise ClassificationError(
"git diff failed: " + process.stderr.decode("utf-8", "replace").strip()
)
tokens = [item.decode("utf-8") for item in process.stdout.split(b"\0") if item]
paths: list[str] = []
index = 0
while index < len(tokens):
status = tokens[index]
index += 1
count = 2 if status[:1] in {"R", "C"} else 1
if index + count > len(tokens):
raise ClassificationError("malformed git name-status output")
record_paths = tokens[index : index + count]
index += count
touched_release = any(RELEASE_PATH_RE.match(path.replace("\\", "/")) for path in record_paths)
if touched_release and status != "A":
raise ClassificationError(
f"immutable release path has destructive status {status}: {record_paths}"
)
paths.extend(record_paths)
releases = release_ids_from_paths(paths)
if not releases and allow_pointer_fallback:
return resolve_live_pointer(repo)
if len(releases) != 1:
raise ClassificationError(
f"expected exactly one changed release, found {len(releases)}: {releases}"
)
return releases[0]
def _read_manifest(path: Path) -> tuple[dict[str, Any], bytes]:
def reject_duplicates(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
result: dict[str, Any] = {}
for key, value in pairs:
if key in result:
raise ClassificationError(f"duplicate JSON key: {key}")
result[key] = value
return result
try:
if not path.is_file():
raise ClassificationError(f"manifest is not a regular file: {path}")
raw = path.read_bytes()
if len(raw) > MAX_MANIFEST_BYTES:
raise ClassificationError("release manifest exceeds 1 MiB limit")
value = json.loads(
raw.decode("utf-8"), object_pairs_hook=reject_duplicates
)
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
raise ClassificationError(f"cannot read manifest {path}: {exc}") from exc
if not isinstance(value, dict):
raise ClassificationError("release manifest must be a JSON object")
return value, raw
def _load_manifest(path: Path) -> dict[str, Any]:
return _read_manifest(path)[0]
def classify_release(repo: Path, release_id: str) -> Decision:
if not RELEASE_ID_RE.fullmatch(release_id):
raise ClassificationError(f"invalid release id: {release_id!r}")
manifest_path = repo / "releases" / release_id / "release-manifest.json"
manifest, raw = _read_manifest(manifest_path)
if manifest.get("release_id") != release_id:
raise ClassificationError("manifest release_id does not match its directory")
if manifest.get("generation") != release_id[:12]:
raise ClassificationError("manifest generation does not match its release id")
schema = manifest.get("schema")
if not isinstance(schema, str) or not schema:
raise ClassificationError("release manifest has no non-empty schema")
if schema != "pipelinenews.timestamp-folder-successor.v1" and manifest.get(
"immutable_after_publication"
) is not True:
raise ClassificationError("release must declare immutable_after_publication: true")
if schema in PAGES_SCHEMAS:
return Decision(
release_id, schema, "pages", "Pages timestamp-folder contract", str(manifest_path),
hashlib.sha256(raw).hexdigest(), len(raw), manifest.get("deployment"),
)
if schema in SOURCE_ONLY_SCHEMAS:
if manifest.get("deployment") != "not-authorised":
raise ClassificationError(
"additive releases must declare deployment: not-authorised"
)
parent = manifest.get("parent_release_id")
if not isinstance(parent, str) or not RELEASE_ID_RE.fullmatch(parent):
raise ClassificationError("additive release has no valid parent_release_id")
if parent >= release_id:
raise ClassificationError("additive release parent must precede its child")
parent_path = repo / "releases" / parent / "release-manifest.json"
parent_manifest = _load_manifest(parent_path)
if parent_manifest.get("release_id") != parent:
raise ClassificationError("additive release parent identity is invalid")
return Decision(
release_id,
schema,
"source-only",
"additive cartridge is validated but not published by Pages",
str(manifest_path),
hashlib.sha256(raw).hexdigest(),
len(raw),
manifest.get("deployment"),
)
raise ClassificationError(f"unsupported release schema: {schema}")
def write_github_output(decision: Decision, path: Path) -> None:
values = {
"release_id": decision.release_id,
"schema": decision.schema,
"route": decision.route,
"pages_applicable": str(decision.route == "pages").lower(),
"manifest_sha256": decision.manifest_sha256,
"manifest_bytes": str(decision.manifest_bytes),
}
with path.open("a", encoding="utf-8", newline="\n") as stream:
for key, value in values.items():
if "\n" in value or "\r" in value:
raise ClassificationError(f"unsafe workflow output value for {key}")
stream.write(f"{key}={value}\n")
def write_receipt(decision: Decision, path: Path) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
payload = json.dumps(asdict(decision), indent=2, sort_keys=True) + "\n"
with tempfile.NamedTemporaryFile(
"w", encoding="utf-8", newline="\n", dir=path.parent, delete=False
) as stream:
stream.write(payload)
temporary = Path(stream.name)
temporary.replace(path)
def resolve_live_pointer(repo: Path) -> str:
"""Resolve the one current pointer that is byte-identical to live-set."""
live_path = repo / "state" / "live-set.json"
try:
live_bytes = live_path.read_bytes()
except OSError as exc:
raise ClassificationError(f"cannot read live pointer: {exc}") from exc
supported = [repo / "releases" / "current-v3.json", repo / "releases" / "current-v4.json"]
matches = [path for path in supported if path.is_file() and path.read_bytes() == live_bytes]
if len(matches) != 1:
raise ClassificationError(
f"expected one current pointer identical to live-set, found {len(matches)}"
)
pointer_path = matches[0]
pointer = _load_manifest(pointer_path)
expected_schema = "pipelinenews.live-pointer." + pointer_path.stem.removeprefix("current-")
if pointer.get("schema") != expected_schema:
raise ClassificationError("current pointer schema does not match its filename")
release_id = pointer.get("release_id")
if not isinstance(release_id, str) or not RELEASE_ID_RE.fullmatch(release_id):
raise ClassificationError("current pointer has no valid release_id")
if pointer.get("generation") != release_id[:12]:
raise ClassificationError("current pointer generation does not match release_id")
if pointer.get("entrypoint") != f"releases/{release_id}/index.html":
raise ClassificationError("current pointer entrypoint does not name its release")
manifest_ref = pointer.get("release_manifest")
if not isinstance(manifest_ref, dict):
raise ClassificationError("current pointer has no release_manifest receipt")
manifest_path = repo / "releases" / release_id / "release-manifest.json"
manifest_bytes = manifest_path.read_bytes()
if manifest_ref.get("path") != f"releases/{release_id}/release-manifest.json":
raise ClassificationError("current pointer manifest path is inconsistent")
if manifest_ref.get("bytes") != len(manifest_bytes):
raise ClassificationError("current pointer manifest byte count is stale")
if manifest_ref.get("sha256") != hashlib.sha256(manifest_bytes).hexdigest():
raise ClassificationError("current pointer manifest digest is stale")
if classify_release(repo, release_id).route != "pages":
raise ClassificationError("current pointer does not target a Pages release class")
return release_id
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--repo", type=Path, default=Path.cwd())
parser.add_argument("--release")
parser.add_argument("--base")
parser.add_argument("--head")
parser.add_argument("--allow-pointer-fallback", action="store_true")
parser.add_argument("--live-pointer", action="store_true")
parser.add_argument("--github-output", type=Path)
parser.add_argument("--receipt", type=Path)
args = parser.parse_args(argv)
try:
repo = args.repo.resolve()
modes = int(args.release is not None) + int(bool(args.base or args.head)) + int(args.live_pointer)
if modes != 1:
raise ClassificationError("choose one of --release, --base/--head, or --live-pointer")
if args.release is not None:
release_id = args.release
elif args.live_pointer:
release_id = resolve_live_pointer(repo)
else:
if not args.base or not args.head:
raise ClassificationError("both --base and --head are required")
release_id = discover_release(
repo, args.base, args.head, allow_pointer_fallback=args.allow_pointer_fallback
)
decision = classify_release(repo, release_id)
except ClassificationError as exc:
parser.error(str(exc))
if args.github_output:
write_github_output(decision, args.github_output)
if args.receipt:
write_receipt(decision, args.receipt)
print(json.dumps(asdict(decision), sort_keys=True))
return 0
if __name__ == "__main__":
raise SystemExit(main())