"""Isolated UT replicas for evaluators that must rerun the environment.""" from __future__ import annotations import shutil import subprocess from pathlib import Path _RTL_SUFFIXES = {".sv", ".v", ".svh", ".vh", ".f"} def rewrite_filelist_rtl(filelist: Path, rtl_path: Path) -> None: """Point only the RTL section at ``rtl_path``. Leave the TB section as it is.""" lines = filelist.read_text(encoding="utf-8").splitlines(keepends=True) start = next((index for index, line in enumerate(lines) if "RTL" in line), None) end = next((index for index, line in enumerate(lines) if start is not None and index > start and "TB" in line), None) if start is None or end is None: raise ValueError(f"{filelist} has no RTL section") replacement = [lines[start], "// RTL set by the evaluation replica\n", *_rtl_lines(rtl_path), "\n"] filelist.write_text("".join([*lines[:start], *replacement, *lines[end:]]), encoding="utf-8") def _rtl_lines(rtl_path: Path) -> list[str]: path = rtl_path.expanduser().resolve() if path.is_file(): listed = f"-f {path}" if path.suffix.lower() == ".f" else str(path) return [listed + "\n"] files = sorted( item.resolve() for item in path.rglob("*") if item.is_file() and item.suffix.lower() in _RTL_SUFFIXES ) if not files: return [str(path) + "\n"] return [ (f"-f {item}\n" if item.suffix.lower() == ".f" else f"{item}\n") for item in files ] def prepare_replica(env_dir: Path, replica_dir: Path, rtl_path: Path) -> Path: """Copy one environment tree and retarget its filelist. Return the copy's sim directory.""" destination = replica_dir / env_dir.name if destination.exists(): shutil.rmtree(destination) destination.parent.mkdir(parents=True, exist_ok=True) shutil.copytree(env_dir, destination, ignore=shutil.ignore_patterns(".comp.stamp")) sim_dir = destination / "sim" rewrite_filelist_rtl(sim_dir / "filelist.f", rtl_path) return sim_dir def run_steps(sim_dir: Path, steps: list[list[str]]) -> bool: """Run each build step in ``sim_dir``. A missing tool or a failed step stops the run.""" for step in steps: try: completed = subprocess.run( step, cwd=sim_dir, check=False, capture_output=True, text=True, timeout=180, ) except (OSError, subprocess.TimeoutExpired): return False if completed.returncode != 0: return False return True