master
AdityaAngajala Publish 3.1.0 c9dc94a
#!/usr/bin/env python3
"""Which molecule recipe a page builds from, checked before the page is published.

The molecule recipes and the generated-path rule are contract.json beside this script, a
byte copy of the wiki's lib/registry/contracts/molecule/contract.json (schema
adom.molecule-contract/1). The recipes are applied the way the wiki's recipe engine applies
them (lib/registry/recipes.js, resolveSources and recipeForPage): a pattern without '/'
matches a file name at any depth and a pattern with '/' the whole path; '*' stays inside one
path segment and a segment '**' matches zero or more segments; case is ignored; excludes are
removed first; the patterns of a role are tried in order and the first with a hit wins;
among its hits the shallowest wins, and two hits at that depth are ambiguous. An ambiguous
role, or a `many` role over its cap, ends the search; a role that matches nothing rules out
only its own recipe. The recipes apply to pages of kind molecule only.

  bundle_check.py <folder> --slug <page slug> [--page-files <listing>] [--json]

The tree checked is every file in <folder> (the package folder that `adom-wiki pkg publish`
packs; node_modules, .git, *.tgz and the ignore files are skipped as the CLI skips them)
plus, with --page-files, the files the page already holds: one repo path per line, or the
JSON that `adom-wiki --json api "/api/pages/<owner>/<slug>/files?recursive=1"` prints. Old
files stay in a page repo, so they take part in the choice.

Problems (exit 1): no-recipe, ambiguous, overflow (no build would run); board-file-required
(the step route: a STEP with no board file, which the build refuses, since a molecule's model
is placed from its board file); generated (a file in <folder> that the registry generates for
the page, which it refuses in a write); fab-pair (<slug>-fab.zip without export.json, the
reverse, or the two in different folders); export-record (export.json records a STEP or board
other than the one the build selects); export-stackup (export.json's stackup has a shape the
build's fab-bundle check refuses, by fab_bundle.py beside this script; a value the board look
does not draw is a note); kind (package.json in <folder> declares a kind other than molecule). Exit 0 otherwise, and 2 on a usage error. Python 3.9 or newer, standard
library only; it reads no network.
"""
import importlib.util
import json
import re
import sys
from pathlib import Path, PurePosixPath

HERE = Path(__file__).resolve().parent
SKIP_DIRS = {"node_modules", ".git", ".adompkg", ".adompkg-build", "__MACOSX"}
SKIP_FILES = {".adomignore", ".pkgignore", ".DS_Store", "Thumbs.db"}
IGNORE_FILES = (".gitignore", ".adomignore", ".pkgignore")


def _fab_bundle():
    """fab_bundle.py beside this script: the export record's rules, the ones the build runs."""
    spec = importlib.util.spec_from_file_location("fab_bundle", HERE / "fab_bundle.py")
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


stackup_problems = _fab_bundle().stackup_problems


def matcher(pattern, slug):
    """recipes.js patternMatcher: a predicate over repo paths for one pattern."""
    segs = [s for i, s in enumerate(pattern.split("/")) if not (s == "**" and i and pattern.split("/")[i - 1] == "**")]

    def seg_re(seg):
        out = ""
        for part in re.split(r"(\{slug\}|\*)", seg):
            out += re.escape(slug) if part == "{slug}" else "[^/]*" if part == "*" else re.escape(part)
        return out

    rx = ""
    for i, s in enumerate(segs):
        first, last = i == 0, i == len(segs) - 1
        if s != "**":
            rx += ("" if first or segs[i - 1] == "**" else "/") + seg_re(s)
        elif first and last:
            rx += "[^/]+(?:/[^/]+)*"
        elif last:
            rx += "(?:/[^/]+)*"
        else:
            rx += ("" if first else "/") + "(?:[^/]+/)*"
    compiled = re.compile("^" + rx + "$", re.I)
    whole = "/" in pattern
    return lambda path: bool(compiled.match(path if whole else path.rsplit("/", 1)[-1]))


def depth(path):
    return path.count("/")


def resolve_sources(recipe, tree, slug):
    """recipes.js resolveSources: (ok, sources [(role, path)], reason, ambiguous, overflow)."""
    sources = []
    for role, spec in recipe["sources"].items():
        excluded = [matcher(p, slug) for p in spec.get("exclude", [])]
        candidates = [p for p in tree if not any(m(p) for m in excluded)]
        if spec.get("many"):
            ms = [matcher(p, slug) for p in spec["match"]]
            hits = sorted(p for p in candidates if any(m(p) for m in ms))
            if len(hits) > spec["many"]:
                return False, sources, f"source {role}: {len(hits)} files match {', '.join(spec['match'])}, more than its cap of {spec['many']}", None, {"role": role, "count": len(hits), "cap": spec["many"]}
            if not hits and not spec.get("optional"):
                return False, sources, f"source {role}: no file matches {', '.join(spec['match'])}", None, None
            sources += [(f"{role}.{i + 1}", p) for i, p in enumerate(hits)]
            continue
        picked = None
        for pattern in spec["match"]:
            m = matcher(pattern, slug)
            hits = [p for p in candidates if m(p)]
            if not hits:
                continue
            top = min(depth(p) for p in hits)
            best = sorted(p for p in hits if depth(p) == top)
            if len(best) > 1:
                return False, sources, f"source {role} ({pattern}): ambiguous: {', '.join(best)}", {"role": role, "paths": best}, None
            picked = best[0]
            break
        if picked:
            sources.append((role, picked))
        elif not spec.get("optional"):
            return False, sources, f"source {role}: no file matches {', '.join(spec['match'])}", None, None
    return True, sources, None, None, None


def recipe_for_page(recipes, tree, slug, kind="molecule"):
    """recipes.js recipeForPage: {recipe, sources} or {recipe: None, reasons, ambiguous|overflow}."""
    reasons = []
    for recipe in recipes:
        label = f"{recipe['name']}/{recipe['version']}"
        if kind not in recipe["applies"]["kinds"]:
            reasons.append(f"{label}: does not apply to kind {kind}")
            continue
        ok, sources, reason, ambiguous, overflow = resolve_sources(recipe, tree, slug)
        if ok:
            return {"recipe": recipe, "label": label, "sources": sources, "reasons": reasons}
        reasons.append(f"{label}: {reason}")
        if ambiguous or overflow:
            return {"recipe": None, "reasons": reasons, "ambiguous": ambiguous and {"recipe": label, **ambiguous}, "overflow": overflow and {"recipe": label, **overflow}}
    return {"recipe": None, "reasons": reasons or ["no recipes are listed"]}


def generated(path, recipe, rule, slug):
    """contract.json generatedPaths: is `path` a file the registry generates for the page?"""
    if recipe and any(path == s["path"].replace("{slug}", slug) for s in recipe["slots"].values()):
        return True
    if "/" in path:
        return False
    if path in (n.replace("{slug}", slug) for n in rule["rootNames"]):
        return True
    return bool(recipe) and any(k in recipe["slots"] for k in rule["suffixSlots"]) and path.endswith(tuple(rule["rootSuffixes"]))


def folder_files(root):
    out = []
    for p in sorted(root.rglob("*")):
        rel = p.relative_to(root).as_posix()
        if not p.is_file() or set(rel.split("/")[:-1]) & SKIP_DIRS or p.name in SKIP_FILES or p.name.endswith(".tgz"):
            continue
        out.append(rel)
    return out


def page_files(spec):
    """Repo paths from a listing file: a path per line, or the files API JSON (enveloped or not)."""
    text = Path(spec).read_text(encoding="utf-8")
    try:
        doc = json.loads(text)
    except ValueError:
        return [line.strip() for line in text.splitlines() if line.strip()]
    if isinstance(doc, dict):
        doc = (doc.get("data") or doc) if isinstance(doc.get("data"), dict) else doc
        doc = doc.get("files") or doc.get("tree") or []
    return [e["path"] if isinstance(e, dict) else str(e) for e in doc
            if isinstance(e, str) or (isinstance(e, dict) and e.get("path") and e.get("type", "blob") not in ("tree", "dir"))]


def check(root, slug, listing=None, contract=None):
    contract = json.loads(Path(contract or HERE / "contract.json").read_text(encoding="utf-8"))
    mine = folder_files(root)
    tree = sorted(set(mine) | set(page_files(listing) if listing else []))
    res = recipe_for_page(contract["recipes"], tree, slug)
    recipe = res["recipe"]
    problems, notes = [], []
    if not recipe:
        if res.get("ambiguous"):
            a = res["ambiguous"]
            problems.append({"id": "ambiguous", "detail": f"{a['recipe']}: role {a['role']} matches {', '.join(a['paths'])} at one depth, so no recipe applies and no build runs. Keep one, or name the one the build should read <slug>.<ext>."})
        elif res.get("overflow"):
            o = res["overflow"]
            problems.append({"id": "overflow", "detail": f"{o['recipe']}: role {o['role']} matches {o['count']} files, more than its cap of {o['cap']}, so no build runs."})
        else:
            problems.append({"id": "no-recipe", "detail": "no molecule recipe resolves, so no build runs: " + "; ".join(res["reasons"])})
    gen = [p for p in mine if generated(p, recipe, contract["generatedPaths"], slug)]
    if gen:
        problems.append({"id": "generated", "detail": "the registry generates " + ", ".join(gen) + " for this page and refuses a write that adds or changes them; remove them from the folder"})
    roles = dict(recipe and res["sources"] or [])
    route = recipe and recipe["pipeline"]["options"]["route"]
    if route == "step":
        problems.append({"id": "board-file-required", "detail": f"{roles.get('step')} has no board file beside it, so the build refuses the page (board-file-required): a molecule's model is placed from its board file, which says where its machine pins are. Add the board (.kicad_pcb, .brd, .PcbDoc or Fusion .fbrd) the STEP was exported from, with its <slug>-fab.zip and export.json."})
    if route == "board":
        fab, exp = roles.get("fab"), roles.get("export")
        if bool(fab) != bool(exp):
            problems.append({"id": "fab-pair", "detail": f"{fab or exp} came without {'export.json' if fab else 'its <slug>-fab.zip'}; publish both, or neither"})
        elif fab and PurePosixPath(fab).parent != PurePosixPath(exp).parent:
            problems.append({"id": "fab-pair", "detail": f"export.json and {PurePosixPath(fab).name} must sit in the same folder; found {exp} and {fab}"})
        elif exp and exp in mine:
            base = PurePosixPath(exp).parent
            try:
                record = json.loads((root / exp).read_text(encoding="utf-8"))
                files = record.get("files") or []
            except (ValueError, OSError, AttributeError):
                record, files = None, None
            if isinstance(record, dict):
                errors, warnings = stackup_problems(record.get("stackup"))
                for e in errors:
                    problems.append({"id": "export-stackup", "detail": f"{e}. The build refuses it (fab-bundle); write the record again with fab_bundle.py create"})
                notes.extend(warnings)
            if not isinstance(files, list):
                problems.append({"id": "export-record", "detail": f"{exp} has no files list; export again"})
            else:
                for f in files:
                    r = str(f.get("role")) if isinstance(f, dict) else ""
                    kind = "STEP" if r == "step" else "board" if r.startswith("board_") else None
                    if not kind:
                        continue
                    rec = (base / f.get("path", "")).as_posix() if str(base) != "." else f.get("path", "")
                    want = roles.get("step" if kind == "STEP" else "board")
                    if rec != want:
                        problems.append({"id": "export-record", "detail": f"export.json records {kind} {rec}; the build selects {want or 'none'}. Export again so the record names the files on the page."})
        if fab and PurePosixPath(fab).name.lower() != f"{slug}-fab.zip":
            notes.append(f"{fab} is not named {slug}-fab.zip; the build still finds it (*-fab.zip) and checks it under its own name")
    elif route == "circuit" and any(p.lower().endswith("-fab.zip") or PurePosixPath(p).name == "export.json" for p in tree):
        notes.append("the circuit route reads no fabrication bundle; a fab zip or export.json on this page is not checked")
    pkg = root / "package.json"
    if pkg.is_file():
        try:
            kind = json.loads(pkg.read_text(encoding="utf-8")).get("kind")
        except ValueError:
            kind = None
        if kind != "molecule":
            problems.append({"id": "kind", "detail": f"package.json declares kind {kind!r}; the molecule recipes apply only to kind \"molecule\""})
    ignores = [n for n in IGNORE_FILES if (root / n).is_file()]
    if ignores:
        notes.append(", ".join(ignores) + " in the folder: this check reads every file, while pkg publish leaves out what they match")
    used = {p for _, p in res.get("sources", [])} if recipe else set()
    return {"slug": slug, "recipe": res.get("label"), "route": route,
            "sources": [{"role": r, "path": p, "inFolder": p in mine} for r, p in (res["sources"] if recipe else [])],
            "unread": [p for p in mine if p not in used and p not in gen], "generated": gen,
            "problems": problems, "notes": notes, "reasons": res["reasons"]}


def main(argv):
    args, opts, i = [], {}, 0
    while i < len(argv):
        if argv[i] in ("--slug", "--page-files", "--contract"):
            if i + 1 >= len(argv):
                print(f"error: {argv[i]} needs a value", file=sys.stderr)
                return 2
            opts[argv[i]] = argv[i + 1]
            i += 2
        elif argv[i] == "--json":
            opts["--json"] = True
            i += 1
        else:
            args.append(argv[i])
            i += 1
    if len(args) != 1 or "--slug" not in opts or not Path(args[0]).is_dir():
        print(__doc__.split("\n\n")[2], file=sys.stderr)
        return 2
    if not re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", opts["--slug"]):
        print("error: --slug must be the page slug: lowercase words separated by hyphens", file=sys.stderr)
        return 2
    out = check(Path(args[0]), opts["--slug"], opts.get("--page-files"), opts.get("--contract"))
    if opts.get("--json"):
        print(json.dumps(out, indent=2))
    else:
        print(f"recipe {out['recipe'] or 'none'}" + (f" (route {out['route']})" if out["route"] else ""))
        for s in out["sources"]:
            print(f"  {s['role']:<10} {s['path']}" + ("" if s["inFolder"] else "   (already on the page)"))
        if out["unread"]:
            print("not read by the build: " + ", ".join(out["unread"]))
        for n in out["notes"]:
            print(f"note: {n}")
        for p in out["problems"]:
            print(f"problem {p['id']}: {p['detail']}")
    return 1 if out["problems"] else 0


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