# SPDX-License-Identifier: GPL-3.0-or-later """The run manifest (emu-tools contract, section 3), written beside every output.""" from __future__ import annotations import datetime import hashlib import json import platform import subprocess from pathlib import Path from . import CORES, TOOL, VERSION from .api import BUILD_RECORDS, OWN_BUILDS, TOOL_DIR #: The contract version this runner speaks (emu-tools docs/contract.md; 1 since 2026-11-25, which #: accepted the `end` field 0.3.0 already wrote). CONTRACT = 1 def sha1(path: Path) -> str: h = hashlib.sha1() with path.open("rb") as f: for block in iter(lambda: f.read(1 << 20), b""): h.update(block) return h.hexdigest() def tool_commit() -> str: """This repository's commit, with ``-dirty`` when the tool's files differ from it.""" try: head = subprocess.run( ["git", "-C", str(TOOL_DIR), "rev-parse", "HEAD"], capture_output=True, text=True, check=True, ).stdout.strip() # fmt: skip dirty = subprocess.run( ["git", "-C", str(TOOL_DIR), "status", "--porcelain", "--", "."], capture_output=True, text=True, check=True, ).stdout.strip() # fmt: skip except (OSError, subprocess.CalledProcessError): return "unknown" return head + ("-dirty" if dirty else "") def library_info(lib: Path) -> dict: """What is known of the library: its SHA-1, and, for this tool's own build, the commit and patches ``build.sh`` recorded. A library built elsewhere is described as such.""" info = {"file": lib.name, "sha1": sha1(lib)} core = own_core(lib) record = BUILD_RECORDS.get(core) if record is not None and record.exists(): info["built_by"] = "build.sh" info["core"] = core info.update(json.loads(record.read_text())) else: info["built_by"] = "elsewhere: commit and patches not checked by this tool" return info def own_core(lib: Path) -> str | None: """Which pinned core's own build ``lib`` is (``build.sh --core``), or None.""" for core, path in OWN_BUILDS.items(): try: if lib.resolve() == path.resolve(): return core except OSError: continue return None def write( out: Path, *, machine: str, args: list[str], inputs: list[dict], lib: Path, outputs: list[dict], status: str, seed: int, started: str, extra: dict | None = None, ) -> Path: library = library_info(lib) upstream = dict(CORES[library.pop("core", "mesen2")]) # The patches are known only for this tool's own build; a library built elsewhere may # carry any (famicom-python's documents built it with mesen2-detector-fixes.patch). upstream["patches"] = library.pop("patches", "unknown") if "commit" in library: upstream["commit"] = library.pop("commit") elif "mesence" in str(lib).lower(): # A MesenCE build passed with --lib (the NES adapter recognises it by its name, for its # controller numbering): named as what it is, its commit not known to this tool. upstream.update(name="MesenCE", url="https://github.com/nesdev-org/MesenCE", commit="unknown (not checked by this tool)") # fmt: skip upstream["library"] = library record = { "contract": CONTRACT, "tool": TOOL, "tool_version": VERSION, "tool_commit": tool_commit(), "tool_licence": "GPL-3.0-or-later", "upstream": upstream, "machine": machine, "inputs": inputs, "args": args, "seed": seed, "time_origin": "power-on", "host": {"os": platform.system().lower(), "arch": platform.machine()}, "started": started, "outputs": outputs, "status": status, "evidence": "OBSERVED", } if extra: record.update(extra) path = out / "manifest.json" path.write_text(json.dumps(record, indent=1) + "\n", encoding="utf-8") return path def now() -> str: return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")