main
Colby Knox 0.2.63 source (not yet released, needs signing): altium-wiki-part (an Adom wiki component page onto an Altium sheet in… 317c990
#!/usr/bin/env python3
"""altium-wiki-part: an Adom wiki component page into Altium in one command.

  altium-wiki-part import <page> [--schlib C:\\...\\Lib.SchLib] [--pcblib C:\\...\\Lib.PcbLib] [--target BOX]
      Clones the page (adom/tps54202ddcr), converts its KiCad symbol and footprint with altium-symbol-modes and
      altium-kicad2altium, stages them and its STEP model on the Windows machine, and imports the part with
      altium_import_part: symbol, footprint, 3D body, and the page's identity (MPN, manufacturer, package,
      datasheet, Mouser / DigiKey / LCSC numbers). Default libraries: Documents\\Adom\\WikiParts\\AdomWiki.*
  altium-wiki-part place <page> --sheet C:\\...\\Main.SchDoc [--x MIL --y MIL] [--designator U7] [--schlib ..] [--pcblib ..]
      The same import, then the part placed on the sheet with altium_sch_place_part.

Every command prints OK:/ERROR: first and Hint: lines after, like the other Adom CLIs.
"""
import argparse
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path

HERE = Path(__file__).resolve().parent


def ok(msg, hints=()):
    print("OK: " + msg)
    for h in hints:
        if h:
            print("Hint: " + h)


def err(msg, hints=()):
    print("ERROR: " + msg)
    for h in hints:
        if h:
            print("Hint: " + h)
    sys.exit(1)


def bridge(verb, args, target=None, timeout=900):
    cmd = ["adom-bridge", "--ai-thread", os.environ.get("ADOM_AI_THREAD", "altium-wiki-part")]
    if target:
        cmd += ["--target", target]
    cmd += [verb, json.dumps(args)]
    try:
        out = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, stdin=subprocess.DEVNULL).stdout
    except subprocess.TimeoutExpired:
        err("%s did not answer within %d s" % (verb, timeout))
    except FileNotFoundError:
        err("adom-bridge is not on PATH", ["This runs in an Adom workspace with Adom Bridge connected to the Windows machine running Altium."])
    try:
        d = json.loads(out)
    except ValueError:
        err("%s answered something that is not JSON: %s" % (verb, out[:300]))
    o = d.get("output", d)
    if isinstance(o, str) and o.startswith("{"):
        try:
            o = json.loads(o)
        except ValueError:
            pass
    return o if isinstance(o, dict) else d


def tool(name, script):
    """The converter: the installed command, else the script beside this one."""
    exe = shutil.which(name)
    return [exe] if exe else [sys.executable, str(HERE / script)]


def run(cmd):
    r = subprocess.run(cmd, capture_output=True, text=True, stdin=subprocess.DEVNULL)
    if r.returncode != 0:
        err("%s failed: %s" % (" ".join(cmd[:2]), (r.stderr or r.stdout)[-400:]))
    return r.stdout


def windows_home(target):
    r = bridge("shell_execute", {"command": "cmd /c echo %USERPROFILE%", "reason": "find the user's Documents folder for the wiki parts library"}, target)
    home = (r.get("stdout") or "").strip()
    if not home or "%" in home:
        err("could not read %USERPROFILE% on the Windows machine", ["Pass --schlib and --pcblib explicitly."])
    return home.replace("/", "\\")


def fetch(page, work):
    """Clone the page; answer (folder, page.json's component)."""
    r = subprocess.run(["adom-wiki", "repo", "clone", page], cwd=work, capture_output=True, text=True, stdin=subprocess.DEVNULL)
    dirs = [d for d in Path(work).iterdir() if d.is_dir()]
    if r.returncode != 0 or not dirs:
        err("could not clone %s: %s" % (page, (r.stderr or r.stdout)[-300:]), ["Use the page reference, owner/slug (adom-wiki search \"<MPN>\" finds it)."])
    folder = dirs[0]
    try:
        meta = json.loads((folder / "page.json").read_text())
    except (OSError, ValueError):
        err("%s has no readable page.json" % page)
    comp = meta.get("component") or {}
    if not comp.get("parts"):
        err("%s is not a component page (no component.parts in page.json)" % page,
            ["Component pages carry a KiCad symbol and footprint; a Cloud Library exports whole with adom-wiki library export --format altium."])
    return folder, meta, comp


def do_import(a):
    work = tempfile.mkdtemp(prefix="altium-wiki-part-")
    folder, meta, comp = fetch(a.page, work)
    parts = comp["parts"]
    mpn = (comp.get("mpn") or meta.get("title") or folder.name).strip()
    name = re.sub(r"[^A-Za-z0-9_.+-]", "_", mpn.upper())
    sym, fp = folder / parts.get("symbol", ""), folder / parts.get("footprint", "")
    step = folder / (parts.get("model_3d_step") or parts.get("model_3d_step_plain") or "")
    if not sym.is_file() or not fp.is_file():
        err("%s lacks its KiCad symbol or footprint (%s, %s)" % (a.page, sym.name, fp.name))
    desc = (meta.get("brief") or comp.get("description") or mpn)[:200].replace("|", "/")
    fp_spec, sym_spec = Path(work) / ("%s.fp.spec" % name), Path(work) / ("%s.sym.spec" % name)
    run(tool("altium-kicad2altium", "kicad2altium.py") + [str(fp), str(fp_spec), name, desc])
    run(tool("altium-symbol-modes", "symbol_modes.py") + [str(sym), str(sym_spec), name, desc])
    # the libraries and the staging folder on the Windows machine
    home = None
    if not a.schlib or not a.pcblib:
        home = windows_home(a.target)
    base = (home + "\\Documents\\Adom\\WikiParts") if home else None
    schlib = a.schlib or base + "\\AdomWiki.SchLib"
    pcblib = a.pcblib or base + "\\AdomWiki.PcbLib"
    stage = (base or str(Path(schlib.replace("\\", "/")).parent).replace("/", "\\")) + "\\staging\\" + name
    files = [str(fp_spec), str(sym_spec)] + ([str(step)] if step.is_file() else [])
    s = bridge("send_files", {"filePaths": files, "dest": stage, "destIsFolder": True, "reason": "stage a wiki part's converted symbol, footprint and STEP for Altium"}, a.target)
    if s.get("success") is False:
        err("could not stage the files on the Windows machine: %s" % (s.get("error") or s), ["send_files needs Adom Bridge connected; check adom-bridge targets."])
    remote = lambda p: stage + "\\" + Path(p).name
    links = comp.get("distributor_links") or {}
    params = {k: v for k, v in {
        "MPN": mpn, "Manufacturer Part Number": mpn, "Manufacturer": comp.get("manufacturer"), "Package": comp.get("package"),
        "Datasheet": comp.get("datasheet"), "Mouser Part #": links.get("mouser"), "DigiKey Part #": links.get("digikey"),
        "LCSC Part #": links.get("lcsc"), "Adom Wiki": "https://wiki.adom.inc/" + a.page,
    }.items() if v}
    args = {"schLib": schlib, "pcbLib": pcblib, "footprintSpec": remote(fp_spec), "symbolSpec": remote(sym_spec),
            "params": params, "comment": mpn, "description": desc, "timeout": 290}
    if step.is_file():
        args["step"] = remote(step)
    r = bridge("altium_import_part", args, a.target, timeout=330)
    if r.get("success") is not True:
        err("altium_import_part failed at %s: %s" % (r.get("failedAt") or "?", r.get("error") or r.get("errorCode") or json.dumps(r)[:300]),
            [r.get("_hint"), "altium_check_dialogs shows what Altium is waiting on."])
    # registered in Installed Libraries, so every project's change order finds the footprint (idempotent)
    installed = []
    if not a.no_install:
        for lib in (schlib, pcblib):
            i = bridge("altium_install_library", {"libraryPath": lib, "timeout": 90}, a.target, timeout=150)
            installed.append({"library": lib, "ok": i.get("success")})
    shutil.rmtree(work, ignore_errors=True)
    return {"installed": installed, "mpn": mpn, "symbol": r.get("symbol") or name, "footprint": r.get("footprint") or name, "schLib": schlib, "pcbLib": pcblib,
            "params": params, "step": step.is_file(), "steps": r.get("steps")}


def cmd_import(a):
    p = do_import(a)
    ok("%s imported: symbol %s and footprint %s%s in %s" % (p["mpn"], p["symbol"], p["footprint"], " with its 3D body" if p["step"] else "", p["schLib"]),
       ["Parameters written: " + ", ".join(sorted(p["params"])),
        "Installed Libraries: " + ", ".join("%s %s" % (Path(i["library"].replace("\\", "/")).name, "ok" if i["ok"] else "FAILED") for i in p["installed"]) if p["installed"] else None,
        "Place it: altium-wiki-part place %s --sheet <C:\\...\\Main.SchDoc>, or altium_sch_place_part {sheet, library:%s, symbol:%s}." % (a.page, json.dumps(p["schLib"]), p["symbol"])])


def cmd_place(a):
    if not a.sheet.lower().endswith(".schdoc"):
        err("--sheet must be a .SchDoc path on the Windows machine")
    p = do_import(a)
    args = {"sheet": a.sheet, "library": p["schLib"], "symbol": p["symbol"]}
    for k in ("x", "y"):
        if getattr(a, k) is not None:
            args[k] = getattr(a, k)
    if a.designator:
        args["designator"] = a.designator
    r = bridge("altium_sch_place_part", args, a.target, timeout=200)
    if r.get("success") is not True:
        err("the part was imported into %s but not placed: %s" % (p["schLib"], r.get("error") or r.get("errorCode") or json.dumps(r)[:300]), [r.get("_hint")])
    ok("%s placed on %s as %s at %s mil" % (p["mpn"], a.sheet, r.get("designator"), r.get("atMil")),
       ["It carries %s; its footprint %s is in %s." % (", ".join(sorted(p["params"])), p["footprint"], p["pcbLib"]),
        "Number it with altium_annotate (a '?' designator), wire it with altium_sch_connect, and carry it to the board with altium_update_pcb: the libraries are in Altium's Installed Libraries%s, so the change order finds the footprint." % ("" if all(i["ok"] for i in p["installed"]) and p["installed"] else " (NOT registered: pass the footprint library to the project)")])


def main():
    ap = argparse.ArgumentParser(prog="altium-wiki-part", description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    sub = ap.add_subparsers(dest="cmd", required=True)
    for n in ("import", "place"):
        s = sub.add_parser(n)
        s.add_argument("page", help="the component page, owner/slug (e.g. adom/tps54202ddcr)")
        s.add_argument("--schlib", help="target .SchLib on the Windows machine (default Documents\\Adom\\WikiParts\\AdomWiki.SchLib)")
        s.add_argument("--pcblib", help="target .PcbLib (default Documents\\Adom\\WikiParts\\AdomWiki.PcbLib)")
        s.add_argument("--target", help="the adom-bridge machine running Altium")
        s.add_argument("--no-install", action="store_true", help="do not register the libraries in Altium's Installed Libraries")
        if n == "place":
            s.add_argument("--sheet", required=True, help="the .SchDoc on the Windows machine")
            s.add_argument("--x", type=int, help="mils")
            s.add_argument("--y", type=int, help="mils")
            s.add_argument("--designator")
    a = ap.parse_args()
    {"import": cmd_import, "place": cmd_place}[a.cmd](a)


if __name__ == "__main__":
    main()