check / check (push) Canceled after 0s
The relay's simulator now reports runs where an operator has no legal action as unfinished. Those no longer count as wins, and any stuck run fails the check. Version ordering follows the relay: numeric pre-release parts and build metadata are handled as semver says.
211 lines
9.1 KiB
Python
Executable File
211 lines
9.1 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Check campaign submissions and build the catalog.
|
|
|
|
tools/catalog.py check --server PATH [--base-ref REF]
|
|
tools/catalog.py build --server PATH
|
|
|
|
PATH is the de-praxis relay launcher (server/build/install/server/bin/server).
|
|
`check` validates and simulates every campaign, checks the submission rules and
|
|
verifies that catalog/ matches what `build` would produce.
|
|
"""
|
|
import argparse
|
|
import filecmp
|
|
import json
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parent.parent
|
|
CAMPAIGNS = ROOT / "campaigns"
|
|
CATALOG = ROOT / "catalog"
|
|
NAME = "de-praxis community campaigns"
|
|
DESCRIPTION = "Campaigns written by players, reviewed and play-tested before they are listed."
|
|
BUILT_IN = {"dead-channel", "hollow-point"}
|
|
LICENSES = {"CC0-1.0", "CC-BY-4.0", "CC-BY-SA-4.0"}
|
|
ALLOWED_FILES = {"campaign.json", "cover.png", "README.md"}
|
|
RUNS = 1000
|
|
SEED = "1986"
|
|
MIN_WIN_RATE = 0.5 # share of expert games that end in a `best` or `mixed` ending
|
|
|
|
|
|
def run(server, *args):
|
|
return subprocess.run([server, "campaign", *args], capture_output=True, text=True)
|
|
|
|
|
|
def compare_versions(a, b):
|
|
"""Semantic version precedence, matching the relay: build metadata is ignored, pre-releases sort
|
|
before their release, and pre-release parts compare numerically when both are numbers."""
|
|
def parts(v):
|
|
v = v.split("+", 1)[0]
|
|
core, _, pre = v.partition("-")
|
|
nums = [int(p) if p.isdigit() else 0 for p in core.split(".")][:3]
|
|
return nums + [0] * (3 - len(nums)), pre.split(".") if pre else []
|
|
(na, pa), (nb, pb) = parts(a), parts(b)
|
|
if na != nb:
|
|
return -1 if na < nb else 1
|
|
if pa == pb:
|
|
return 0
|
|
if not pa or not pb:
|
|
return 1 if not pa else -1
|
|
for x, y in zip(pa, pb):
|
|
if x == y:
|
|
continue
|
|
if x.isdigit() and y.isdigit():
|
|
return -1 if int(x) < int(y) else 1
|
|
if x.isdigit() or y.isdigit():
|
|
return -1 if x.isdigit() else 1
|
|
return -1 if x < y else 1
|
|
return (len(pa) > len(pb)) - (len(pa) < len(pb))
|
|
|
|
|
|
def newer(a, b):
|
|
return compare_versions(a, b) > 0
|
|
|
|
|
|
def campaign_dirs():
|
|
return sorted(p for p in CAMPAIGNS.iterdir() if p.is_dir()) if CAMPAIGNS.is_dir() else []
|
|
|
|
|
|
def base_files(ref, folder):
|
|
"""The folder's files at the base ref, or None when the campaign is new there."""
|
|
rel = folder.relative_to(ROOT).as_posix()
|
|
listed = subprocess.run(["git", "-C", str(ROOT), "ls-tree", "-r", "--name-only", ref, "--", rel], capture_output=True, text=True)
|
|
if listed.returncode != 0 or not listed.stdout.strip():
|
|
return None
|
|
files = {}
|
|
for path in listed.stdout.split():
|
|
files[Path(path).name] = subprocess.run(["git", "-C", str(ROOT), "show", f"{ref}:{path}"], capture_output=True).stdout
|
|
return files
|
|
|
|
|
|
def check_campaign(server, folder, base_ref):
|
|
"""Returns a list of problems; prints the simulation summary."""
|
|
problems = []
|
|
name = folder.name
|
|
extra = {p.name for p in folder.iterdir()} - ALLOWED_FILES
|
|
if extra:
|
|
problems.append(f"unexpected files {sorted(extra)}; a campaign folder holds only {sorted(ALLOWED_FILES)}")
|
|
source = folder / "campaign.json"
|
|
if not source.is_file():
|
|
return problems + ["campaign.json is missing"]
|
|
try:
|
|
meta = json.loads(source.read_text(encoding="utf-8"))["meta"]
|
|
except (ValueError, KeyError, TypeError) as e:
|
|
return problems + [f"campaign.json can't be read: {e}"]
|
|
|
|
if meta.get("id") != name:
|
|
problems.append(f"meta.id is '{meta.get('id')}', but the folder is '{name}'; they must match")
|
|
if name in BUILT_IN:
|
|
problems.append(f"'{name}' is a built-in campaign id; choose your own")
|
|
if meta.get("license") not in LICENSES:
|
|
problems.append(f"meta.license must be one of {sorted(LICENSES)}")
|
|
if "warnings" not in meta:
|
|
problems.append('meta.warnings is required: list content warnings, or write "warnings": [] if there are none')
|
|
if not re.fullmatch(r"\d+\.\d+\.\d+(-[0-9A-Za-z.]+)?", str(meta.get("version", ""))):
|
|
problems.append("meta.version must look like 1.0.0")
|
|
|
|
validated = run(server, "validate", "--strict", "--json", str(source))
|
|
try:
|
|
report = json.loads(validated.stdout)[0]
|
|
except (ValueError, IndexError):
|
|
return problems + [f"validate failed: {validated.stderr.strip() or validated.stdout.strip()}"]
|
|
for issue in report["issues"]:
|
|
problems.append(f"{issue['severity']}: {issue['path']}: {issue['message']}")
|
|
if not report["valid"]:
|
|
return problems or ["validate --strict failed"]
|
|
|
|
for strategy in ("expert", "explore"):
|
|
simulated = run(server, "simulate", str(source), "--runs", str(RUNS), "--seed", SEED, "--strategy", strategy, "--json")
|
|
if simulated.returncode != 0:
|
|
problems.append(f"simulate ({strategy}) failed: {simulated.stderr.strip()}")
|
|
continue
|
|
sim = json.loads(simulated.stdout)
|
|
grades = {g: n / sim["runs"] for g, n in sim["grades"].items()}
|
|
endings = ", ".join(f"{t} {n * 100 / sim['runs']:.0f}%" for t, n in sorted(sim["endings"].items(), key=lambda e: -e[1]))
|
|
print(f" {strategy:8} {endings}; rounds {sim['averageRounds']:.1f} avg")
|
|
if strategy == "expert":
|
|
if grades.get("best", 0) == 0:
|
|
problems.append("expert play never reaches a `best` ending")
|
|
# Only finished games with a best or mixed ending count as wins; a stalled run is a campaign bug.
|
|
stuck = sim["endings"].get("(unfinished)", 0)
|
|
if stuck:
|
|
problems.append(f"expert play gets stuck with no legal action in {stuck} of {sim['runs']} games")
|
|
win = grades.get("best", 0) + grades.get("mixed", 0)
|
|
if win < MIN_WIN_RATE:
|
|
problems.append(f"expert play reaches a `best` or `mixed` ending in {win:.0%} of games; at least {MIN_WIN_RATE:.0%} is required")
|
|
|
|
if base_ref:
|
|
before = base_files(base_ref, folder)
|
|
if before is not None:
|
|
now = {p.name: p.read_bytes() for p in folder.iterdir() if p.is_file()}
|
|
if now != before:
|
|
try:
|
|
old = json.loads(before["campaign.json"])["meta"]["version"]
|
|
except (KeyError, ValueError, TypeError):
|
|
old = "0.0.0"
|
|
if not newer(str(meta.get("version", "")), old):
|
|
problems.append(f"the campaign changed, so raise meta.version above {old}")
|
|
return problems
|
|
|
|
|
|
def build(server, target):
|
|
"""Packs every campaign into target/ and writes target/index.json."""
|
|
target.mkdir(parents=True, exist_ok=True)
|
|
for old in target.glob("*.dpc"):
|
|
old.unlink()
|
|
for folder in campaign_dirs():
|
|
meta = json.loads((folder / "campaign.json").read_text(encoding="utf-8"))["meta"]
|
|
args = ["pack", str(folder / "campaign.json"), "--out", str(target / f"{meta['id']}-{meta['version']}.dpc")]
|
|
for flag, file in (("--cover", "cover.png"), ("--readme", "README.md")):
|
|
if (folder / file).is_file():
|
|
args += [flag, str(folder / file)]
|
|
packed = run(server, *args)
|
|
if packed.returncode != 0:
|
|
sys.exit(f"{folder.name}: pack failed: {packed.stderr.strip()}")
|
|
indexed = run(server, "catalog", "--name", NAME, "--description", DESCRIPTION, "--out", str(target / "index.json"), str(target))
|
|
if indexed.returncode != 0:
|
|
sys.exit(f"catalog failed: {indexed.stderr.strip()}")
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
parser.add_argument("command", choices=["check", "build"])
|
|
parser.add_argument("--server", required=True, help="the de-praxis relay launcher")
|
|
parser.add_argument("--base-ref", help="git ref to compare versions against, e.g. origin/main")
|
|
args = parser.parse_args()
|
|
|
|
if args.command == "build":
|
|
build(args.server, CATALOG)
|
|
print(f"Built {CATALOG.relative_to(ROOT)}/ with {len(campaign_dirs())} campaign(s).")
|
|
return
|
|
|
|
failed = False
|
|
for folder in campaign_dirs():
|
|
print(f"{folder.name}:")
|
|
problems = check_campaign(args.server, folder, args.base_ref)
|
|
for p in problems:
|
|
print(f" ✗ {p}")
|
|
print(" ✓ ok" if not problems else "")
|
|
failed |= bool(problems)
|
|
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
fresh = Path(tmp) / "catalog"
|
|
if not failed:
|
|
build(args.server, fresh)
|
|
expected = sorted(p.name for p in fresh.iterdir())
|
|
actual = sorted(p.name for p in CATALOG.iterdir()) if CATALOG.is_dir() else []
|
|
mismatch = expected != actual or any(not filecmp.cmp(fresh / n, CATALOG / n, shallow=False) for n in expected)
|
|
if mismatch:
|
|
print("catalog/ is out of date: run `tools/catalog.py build --server …` and commit the result.")
|
|
failed = True
|
|
else:
|
|
print(f"catalog/ is up to date ({len(campaign_dirs())} campaign(s)).")
|
|
sys.exit(1 if failed else 0)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|