#!/usr/bin/env python3 """Linux-first toolchain doctor: probe only, never installs.""" from __future__ import annotations import argparse import hashlib import json import os import shutil import subprocess import sys from datetime import datetime, timezone from pathlib import Path from typing import Any ROOT = Path(__file__).resolve().parents[1] def _sha256_file(path: Path) -> str | None: if not path.is_file(): return None digest = hashlib.sha256() with path.open("rb") as handle: for chunk in iter(lambda: handle.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def _run(cmd: list[str], *, timeout: float = 20.0, env: dict[str, str] | None = None) -> dict[str, Any]: clean_env = os.environ.copy() # TD libraries must not pollute doctor/smoke commands. for key in ("LD_LIBRARY_PATH", "LD_PRELOAD", "QT_PLUGIN_PATH"): clean_env.pop(key, None) if env: clean_env.update(env) try: completed = subprocess.run( cmd, capture_output=True, text=True, timeout=timeout, check=False, env=clean_env, ) return { "command": cmd, "exit_code": completed.returncode, "stdout": (completed.stdout or "")[:2000], "stderr": (completed.stderr or "")[:2000], } except FileNotFoundError as exc: return {"command": cmd, "exit_code": 127, "error": str(exc)} except subprocess.TimeoutExpired: return {"command": cmd, "exit_code": 124, "error": "timeout"} def _which(name: str) -> Path | None: found = shutil.which(name) return Path(found).resolve() if found else None def probe_binary(name: str, version_args: list[str] | None = None) -> dict[str, Any]: path = _which(name) result: dict[str, Any] = { "name": name, "resolved_path": str(path) if path else None, "present": path is not None, "sha256": _sha256_file(path) if path else None, } if path and version_args is not None: result["version_probe"] = _run([str(path), *version_args]) return result def probe_td2026() -> dict[str, Any]: path = _which("td2026") home = Path(os.environ.get("ANLOGIC_TD_HOME", "/data/anlogic/TD_Release_2026.1_SP2_NL")) license_path = home / "license" / "Anlogic.lic" result: dict[str, Any] = { "name": "td2026", "resolved_path": str(path) if path else None, "present": path is not None, "wrapper_sha256": _sha256_file(path) if path else None, "install_root": str(home) if home.is_dir() else None, "bw_root": "/data/anlogic/BW_Release_2026.1_SP2" if Path("/data/anlogic/BW_Release_2026.1_SP2").is_dir() else None, "license_present": license_path.is_file(), "license_readable": os.access(license_path, os.R_OK) if license_path.is_file() else False, } if path: # Run version probe with TD libraries only for this subprocess. td_env = { "LD_LIBRARY_PATH": f"{home}/lib:{home}/lib/Qt/lib", "QT_PLUGIN_PATH": f"{home}/lib/Qt/plugins", "ANLOGIC_TD_HOME": str(home), } result["version_probe"] = _run([str(path), "-version"], env=td_env) return result def probe_python_venv(venv: Path) -> dict[str, Any]: python = venv / "bin" / "python" result = { "name": "verify_venv", "path": str(venv), "present": python.is_file(), "python": str(python) if python.is_file() else None, } if python.is_file(): result["imports"] = _run( [str(python), "-c", "import pytest,jsonschema,psutil; print('ok')"] ) return result def build_report() -> dict[str, Any]: venv = Path(os.environ.get("PRODU2_VERIFY_VENV", str(Path.home() / ".cache/prod2u/venvs/verify"))) tools = [ probe_binary("python3", ["--version"]), probe_binary("git", ["--version"]), probe_binary("iverilog", ["-V"]), probe_binary("vvp", ["-V"]), probe_binary("verilator", ["--version"]), probe_binary("yosys", ["-V"]), probe_binary("sby", ["--version"]), probe_binary("unzip", ["-v"]), probe_binary("zstd", ["--version"]), probe_binary("jq", ["--version"]), probe_td2026(), probe_python_venv(venv), ] missing = [item["name"] for item in tools if not item.get("present")] return { "schema": "prod2u-toolchain-doctor-v1", "generated_at_utc": datetime.now(timezone.utc).isoformat(), "repository_root": str(ROOT), "platform": { "python": sys.version, "executable": sys.executable, }, "tools": tools, "missing": missing, "status": "pass" if "td2026" not in missing and "python3" not in missing and "iverilog" not in missing else "degraded", } def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--json-out", type=Path, default=None) args = parser.parse_args() report = build_report() text = json.dumps(report, indent=2) + "\n" if args.json_out: args.json_out.parent.mkdir(parents=True, exist_ok=True) args.json_out.write_text(text, encoding="utf-8") print(text) return 0 if report["status"] in {"pass", "degraded"} else 1 if __name__ == "__main__": raise SystemExit(main())