| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423 |
- """Offline KiCad import and generated board-viewer asset pipeline."""
- from __future__ import annotations
- import json
- import os
- import platform
- import shutil
- import subprocess
- import tempfile
- import uuid
- import xml.etree.ElementTree as ET
- from collections.abc import Callable, Mapping
- from dataclasses import dataclass
- from datetime import UTC, datetime
- from pathlib import Path
- from typing import Any, Protocol
- from jsonschema import Draft202012Validator
- from .assets import sha256_file, validate_generated_assets
- from .data import build_board_data
- from .ipcd356 import IpCd356AlignmentError, validate_ipcd356_alignment
- from .pcb import parse_kicad_pcb
- from .photo import PhotoOverlayError, prepare_photo_overlay
- from .regression import BoardRegressionError, validate_product_regression
- ROOT = Path(__file__).resolve().parents[3]
- DATA_SCHEMA = ROOT / "schemas" / "board_viewer_data.schema.json"
- ANNOTATION_SCHEMA = ROOT / "schemas" / "board_viewer_annotations.schema.json"
- GENERATOR_VERSION = "1.1.0"
- GENERATOR_SOURCE_PATHS = {
- "generator_pipeline": Path(__file__).resolve(),
- "generator_data": ROOT / "tools" / "board-viewer" / "board_viewer" / "data.py",
- "generator_annotations": ROOT / "tools" / "board-viewer" / "board_viewer" / "annotations.py",
- "generator_eligibility": ROOT / "tools" / "board-viewer" / "board_viewer" / "eligibility.py",
- "generator_pcb": ROOT / "tools" / "board-viewer" / "board_viewer" / "pcb.py",
- "generator_sexpr": ROOT / "tools" / "board-viewer" / "board_viewer" / "sexpr.py",
- "generator_ipcd356": ROOT / "tools" / "board-viewer" / "board_viewer" / "ipcd356.py",
- "generator_photo": ROOT / "tools" / "board-viewer" / "board_viewer" / "photo.py",
- "generator_regression": ROOT / "tools" / "board-viewer" / "board_viewer" / "regression.py",
- "schema_data": DATA_SCHEMA,
- "schema_annotations": ANNOTATION_SCHEMA,
- }
- class GenerationError(RuntimeError):
- """Raised when a generated bundle cannot be completed and validated."""
- class CommandResult(Protocol):
- returncode: int
- stdout: str
- stderr: str
- Runner = Callable[[list[str], Path], CommandResult]
- @dataclass
- class GenerationConfig:
- brd_path: Path
- inventory_path: Path
- annotations_path: Path
- output_dir: Path
- kicad_cli: Path
- board_name: str
- required_kicad_version: str = "10.0.4"
- expected_counts: Mapping[str, int] | None = None
- expected_front_only: bool = True
- product_regression: bool = False
- photo_root: Path = ROOT
- temp_parent: Path | None = None
- def _default_runner(command: list[str], cwd: Path) -> subprocess.CompletedProcess[str]:
- return subprocess.run(
- command,
- cwd=cwd,
- check=False,
- capture_output=True,
- text=True,
- encoding="utf-8",
- errors="replace",
- )
- def _run_checked(runner: Runner, command: list[str], cwd: Path) -> CommandResult:
- result = runner(command, cwd)
- if result.returncode != 0:
- detail = (result.stderr or result.stdout or "command failed").strip()
- raise GenerationError(detail)
- return result
- def _load_json(path: Path) -> dict[str, Any]:
- try:
- payload = json.loads(path.read_text(encoding="utf-8"))
- except (OSError, json.JSONDecodeError) as exc:
- raise GenerationError(f"cannot read JSON {path}: {exc}") from exc
- if not isinstance(payload, dict):
- raise GenerationError(f"JSON root must be an object: {path}")
- return payload
- def _validate_schema(payload: object, schema_path: Path, label: str) -> None:
- schema = _load_json(schema_path)
- errors = sorted(Draft202012Validator(schema).iter_errors(payload), key=lambda item: list(item.path))
- if errors:
- locations = [".".join(str(part) for part in error.path) or "<root>" for error in errors[:5]]
- raise GenerationError(f"{label} schema validation failed at: {', '.join(locations)}")
- def _ensure_outside_repository(path: Path) -> Path:
- resolved = path.resolve()
- try:
- resolved.relative_to(ROOT.resolve())
- except ValueError:
- return resolved
- raise GenerationError("temporary directory must be outside repository")
- def _verify_inputs(config: GenerationConfig) -> Path:
- for path, label in (
- (config.brd_path, "BRD source"),
- (config.inventory_path, "pin inventory"),
- (config.annotations_path, "annotations"),
- (config.kicad_cli, "KiCad CLI"),
- ):
- if not Path(path).is_file():
- raise GenerationError(f"missing {label}: {path}")
- temp_parent = config.temp_parent or Path(tempfile.gettempdir())
- temp_parent = _ensure_outside_repository(Path(temp_parent))
- temp_parent.mkdir(parents=True, exist_ok=True)
- return temp_parent
- def _verify_kicad_version(config: GenerationConfig, runner: Runner, cwd: Path) -> str:
- result = _run_checked(runner, [str(config.kicad_cli), "--version"], cwd)
- version = result.stdout.strip().splitlines()[0] if result.stdout.strip() else "unknown"
- if version != config.required_kicad_version:
- raise GenerationError(
- f"board viewer generation requires KiCad {config.required_kicad_version}, found {version}"
- )
- return version
- def _write_json(path: Path, payload: object) -> None:
- path.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
- def _normalize_svg(path: Path, title: str) -> tuple[float, float]:
- try:
- tree = ET.parse(path)
- except (OSError, ET.ParseError) as exc:
- raise GenerationError(f"invalid SVG {path.name}: {exc}") from exc
- root = tree.getroot()
- if root.tag.rsplit("}", 1)[-1] != "svg":
- raise GenerationError(f"invalid SVG root: {path.name}")
- title_element = next((item for item in root if item.tag.rsplit("}", 1)[-1] == "title"), None)
- if title_element is not None:
- title_element.text = title
- view_box = root.get("viewBox", "").replace(",", " ").split()
- if len(view_box) != 4:
- raise GenerationError(f"SVG has no usable viewBox: {path.name}")
- try:
- width, height = float(view_box[2]), float(view_box[3])
- except ValueError as exc:
- raise GenerationError(f"SVG has invalid viewBox: {path.name}") from exc
- ET.register_namespace("", "http://www.w3.org/2000/svg")
- ET.register_namespace("xlink", "http://www.w3.org/1999/xlink")
- tree.write(path, encoding="utf-8", xml_declaration=True)
- return width, height
- def _validate_counts(payload: Mapping[str, object], config: GenerationConfig) -> None:
- counts = payload["counts"]
- if not isinstance(counts, Mapping):
- raise GenerationError("generated board counts are missing")
- if config.expected_counts:
- mismatches = [
- f"{name}={counts.get(name)} expected {expected}"
- for name, expected in config.expected_counts.items()
- if counts.get(name) != expected
- ]
- if mismatches:
- raise GenerationError("board regression mismatch: " + ", ".join(mismatches))
- sides = counts.get("sides", {})
- if config.expected_front_only and isinstance(sides, Mapping) and sides.get("back") != 0:
- raise GenerationError(f"board regression mismatch: target back-side count is {sides.get('back')}")
- def _import_board(config: GenerationConfig, runner: Runner, work: Path) -> tuple[Path, dict[str, Any]]:
- imported = work / "board.kicad_pcb"
- report_path = work / "import-report.json"
- command = [
- str(config.kicad_cli),
- "pcb",
- "import",
- "--format",
- "auto",
- "--output",
- str(imported),
- "--report-format",
- "json",
- "--report-file",
- str(report_path),
- str(config.brd_path.resolve()),
- ]
- _run_checked(runner, command, work)
- if not imported.is_file() or not report_path.is_file():
- raise GenerationError("KiCad import did not create the board and report")
- report = _load_json(report_path)
- if report.get("errors"):
- raise GenerationError(f"KiCad import report contains errors: {report['errors']}")
- return imported, report
- SVG_LAYERS = {
- "board-mask-edge.svg": "F.Mask,Edge.Cuts",
- "board-silkscreen.svg": "F.SilkS,Edge.Cuts",
- "board-copper.svg": "F.Cu,Edge.Cuts",
- }
- def _export_svgs(
- config: GenerationConfig,
- runner: Runner,
- imported: Path,
- assets_dir: Path,
- board_data: Mapping[str, object],
- ) -> None:
- board_meta = board_data["board"]
- if not isinstance(board_meta, Mapping) or not isinstance(board_meta.get("view_box"), Mapping):
- raise GenerationError("generated board view box is missing")
- expected_width = float(board_meta["view_box"]["width"])
- expected_height = float(board_meta["view_box"]["height"])
- for filename, layers in SVG_LAYERS.items():
- output = assets_dir / filename
- command = [
- str(config.kicad_cli),
- "pcb",
- "export",
- "svg",
- "--mode-single",
- "--output",
- str(output),
- "--layers",
- layers,
- "--page-size-mode",
- "2",
- "--fit-page-to-board",
- "--exclude-drawing-sheet",
- str(imported),
- ]
- _run_checked(runner, command, assets_dir)
- if not output.is_file():
- raise GenerationError(f"KiCad SVG export did not create {filename}")
- width, height = _normalize_svg(output, f"FCB board viewer {filename}")
- if abs(width - expected_width) > 0.1 or abs(height - expected_height) > 0.1:
- raise GenerationError(
- f"SVG viewBox mismatch for {filename}: {width}x{height}, expected {expected_width}x{expected_height}"
- )
- def _export_and_validate_ipcd356(
- config: GenerationConfig,
- runner: Runner,
- imported: Path,
- work: Path,
- board_data: Mapping[str, object],
- ) -> dict[str, object]:
- output = work / "board.d356"
- command = [
- str(config.kicad_cli),
- "pcb",
- "export",
- "ipcd356",
- "--output",
- str(output),
- str(imported),
- ]
- _run_checked(runner, command, work)
- if not output.is_file():
- raise GenerationError("KiCad IPC-D-356 export did not create board.d356")
- try:
- return validate_ipcd356_alignment(board_data, output)
- except IpCd356AlignmentError as exc:
- raise GenerationError(f"IPC-D-356 cross-check failed: {exc}") from exc
- def _asset_metadata(path: Path) -> dict[str, object]:
- return {"sha256": sha256_file(path), "bytes": path.stat().st_size}
- def manifest_source_path(path: Path | str, repository_root: Path | str = ROOT) -> str:
- resolved = Path(path).resolve()
- repository = Path(repository_root).resolve()
- try:
- return resolved.relative_to(repository).as_posix()
- except ValueError:
- return str(resolved)
- def _publish_directory(source: Path, target: Path) -> None:
- target.parent.mkdir(parents=True, exist_ok=True)
- suffix = uuid.uuid4().hex
- staging = target.parent / f".{target.name}.stage-{suffix}"
- backup = target.parent / f".{target.name}.backup-{suffix}"
- shutil.copytree(source, staging)
- validate_generated_assets(staging)
- moved_old = False
- try:
- if target.exists():
- os.replace(target, backup)
- moved_old = True
- os.replace(staging, target)
- except Exception:
- if moved_old and backup.exists() and not target.exists():
- os.replace(backup, target)
- raise
- finally:
- if staging.exists():
- shutil.rmtree(staging)
- if backup.exists():
- shutil.rmtree(backup)
- def generate_assets(config: GenerationConfig, *, runner: Runner = _default_runner) -> dict[str, object]:
- temp_parent = _verify_inputs(config)
- inventory = _load_json(config.inventory_path)
- annotations = _load_json(config.annotations_path)
- _validate_schema(annotations, ANNOTATION_SCHEMA, "annotations")
- with tempfile.TemporaryDirectory(prefix="cpld-board-viewer-", dir=temp_parent) as temporary:
- work = Path(temporary)
- kicad_version = _verify_kicad_version(config, runner, work)
- imported, import_report = _import_board(config, runner, work)
- parsed = parse_kicad_pcb(imported)
- board_data = build_board_data(
- parsed,
- inventory,
- annotations,
- board_name=config.board_name,
- )
- assets_dir = work / "generated"
- assets_dir.mkdir()
- try:
- prepared_photo = prepare_photo_overlay(
- annotations.get("photo_overlay"),
- repository_root=config.photo_root,
- assets_dir=assets_dir,
- board_bounds=parsed.bounds,
- )
- except PhotoOverlayError as exc:
- raise GenerationError(f"photo overlay validation failed: {exc}") from exc
- board_data["photo_overlay"] = prepared_photo.data if prepared_photo else None
- _validate_counts(board_data, config)
- if config.product_regression:
- try:
- validate_product_regression(board_data)
- except BoardRegressionError as exc:
- raise GenerationError(f"product board regression failed: {exc}") from exc
- _validate_schema(board_data, DATA_SCHEMA, "board data")
- ipcd356_verification = _export_and_validate_ipcd356(
- config,
- runner,
- imported,
- work,
- board_data,
- )
- _write_json(assets_dir / "board-data.json", board_data)
- _write_json(assets_dir / "import-report.json", import_report)
- _export_svgs(config, runner, imported, assets_dir, board_data)
- asset_names = ["board-data.json", *SVG_LAYERS, "import-report.json"]
- if prepared_photo:
- asset_names.append(prepared_photo.asset_path.name)
- counts = board_data["counts"]
- sources = {
- "brd": {"path": manifest_source_path(config.brd_path), "sha256": sha256_file(config.brd_path)},
- "inventory": {
- "path": manifest_source_path(config.inventory_path),
- "sha256": sha256_file(config.inventory_path),
- },
- "annotations": {
- "path": manifest_source_path(config.annotations_path),
- "sha256": sha256_file(config.annotations_path),
- },
- **{
- name: {"path": manifest_source_path(path), "sha256": sha256_file(path)}
- for name, path in GENERATOR_SOURCE_PATHS.items()
- },
- }
- if prepared_photo:
- sources["photo"] = {
- "path": manifest_source_path(prepared_photo.source_path),
- "sha256": sha256_file(prepared_photo.source_path),
- }
- build_info = {
- "schema": "board-viewer-build-info-v1",
- "generated_at": datetime.now(UTC).isoformat().replace("+00:00", "Z"),
- "generator_version": GENERATOR_VERSION,
- "toolchain": {"python": platform.python_version(), "kicad": kicad_version},
- "sources": sources,
- "assets": {name: _asset_metadata(assets_dir / name) for name in asset_names},
- "verification": {"ipcd356": ipcd356_verification},
- "counts": {
- "footprints": counts["footprints"],
- "touchpoints": counts["touchpoints"],
- "pads": counts["pads"],
- },
- }
- _write_json(assets_dir / "build-info.json", build_info)
- validate_generated_assets(assets_dir)
- try:
- _publish_directory(assets_dir, config.output_dir)
- except OSError as exc:
- raise GenerationError(f"cannot publish generated assets: {exc}") from exc
- return {"status": "pass", "output_dir": str(config.output_dir), "build_info": build_info}
|