master
AdityaAngajala Preserve source for molecule-publish-3.0.0 33f54d8
#!/usr/bin/env python3
"""The versions molecule-publish 3.0.0 needs, checked before its first registry step.

  versions_check.py [--json]

adom-wiki must be 1.8.0 or newer: older CLIs have no `model` verbs and no `--wait` on
`pkg publish`. The Hydrogen handoff is `adom-wiki model import`, so it needs no other
CLI. Each exporter installed in ~/.claude/skills/<name>/ must be at least the release that depends
on molecule-publish ^3.0.0; its version is read from the package.json its install script
copies there, and an installed exporter with no package.json there is older than that
release (the releases before it did not copy one). The messages are the ones the molecule
contract sets (section 8.2).

Exit 1 when adom-wiki is missing or too old (stop: nothing else in the skill works without
it). Update lines for the exporters are printed and exit 0: the publish can go ahead,
and the bundle check finds what an old exporter left in the folder.
Python 3.9 or newer, standard library only. It runs adom-wiki locally and reads no
network.
"""
import json
import re
import subprocess
import sys
from pathlib import Path

CLI_MINIMUM = "1.8.0"
# The release of each package that depends on adom/molecule-publish ^3.0.0.
EXPORTERS = {
    "kicad-export-molecule": "2.0.0",
    "fusion-export-molecule": "2.0.0",
    "altium-export-molecule": "3.0.0",
    "molecule-pipeline": "2.0.0",
}
VERSION = re.compile(r"(\d+)\.(\d+)\.(\d+)")
UNKNOWN_MODEL = "is not an adom-wiki command"


def parse(text):
    """The first x.y.z in text, as a tuple, or None."""
    m = VERSION.search(text or "")
    return tuple(int(g) for g in m.groups()) if m else None


def older(found, minimum):
    """True when found (a string or None) is missing or below minimum."""
    have = parse(found) if isinstance(found, str) else found
    return have is None or have < parse(minimum)


def run(cmd):
    """stdout and stderr of a local command, or None when it cannot start."""
    try:
        p = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
    except (OSError, subprocess.TimeoutExpired):
        return None
    return (p.stdout or "") + (p.stderr or "")


def cli_message(found):
    return f"This skill needs adom-wiki {CLI_MINIMUM} or newer (found {found or 'none'}). Run: adom-wiki self-update"


def update_line(name, minimum):
    return f"Update adom/{name} to {minimum}: adom-wiki pkg install adom/{name}"


def check_cli(runner=run):
    out = runner(["adom-wiki", "--version"])
    if out is None:
        return {"ok": False, "found": None,
                "message": cli_message(None) + " (adom-wiki is not on PATH: install it from the adom/adom-wiki-cli page on wiki.adom.inc)"}
    found = ".".join(map(str, parse(out))) if parse(out) else out.strip()[:40] or None
    if older(out, CLI_MINIMUM):
        return {"ok": False, "found": found, "message": cli_message(found)}
    probe = runner(["adom-wiki", "model", "--help"]) or ""
    if UNKNOWN_MODEL in probe or "UNKNOWN_COMMAND" in probe:
        return {"ok": False, "found": found, "message": cli_message(found)}
    return {"ok": True, "found": found}


def installed_version(skills, name):
    """(installed, version or None) for ~/.claude/skills/<name>/package.json."""
    folder = Path(skills) / name
    if not folder.is_dir():
        return False, None
    try:
        return True, str(json.loads((folder / "package.json").read_text(encoding="utf-8")).get("version") or "") or None
    except (OSError, ValueError, AttributeError):
        return True, None


def check_exporters(skills):
    out = []
    for name, minimum in EXPORTERS.items():
        installed, version = installed_version(skills, name)
        if not installed:
            continue
        row = {"name": name, "found": version, "minimum": minimum, "ok": not older(version, minimum)}
        if not row["ok"]:
            row["message"] = update_line(name, minimum)
        out.append(row)
    return out


def main(argv):
    skills = Path.home() / ".claude" / "skills"
    result = {"cli": check_cli(), "exporters": check_exporters(skills)}
    lines = [r["message"] for r in [result["cli"], *result["exporters"]] if not r["ok"]]
    if "--json" in argv:
        print(json.dumps(result, indent=2))
    else:
        print(f"adom-wiki {result['cli']['found'] or 'none'}")
        for r in result["exporters"]:
            print(f"  {r['name']} {r['found'] or '(no package.json)'}")
    for line in lines:
        print(line, file=sys.stderr)
    return 0 if result["cli"]["ok"] else 1


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))