from __future__ import annotations import os import shlex from pathlib import Path from typing import Sequence WORKSPACE_BASE_ENV = "ACUPEDIA_WORKSPACE_BASE_PATH" def workspace_base_path( value: str | Path | None = None, *, required: bool = True, ) -> Path | None: """Return the AccuPedia workspace base path. Resolution order: 1. explicit value 2. ACUPEDIA_WORKSPACE_BASE_PATH The workspace base path itself must be absolute. This removes any dependency on the caller's current working directory. """ raw = str(value).strip() if value is not None else os.environ.get( WORKSPACE_BASE_ENV, "", ).strip() if not raw: if required: raise RuntimeError( f"{WORKSPACE_BASE_ENV} is required for relative AccuPedia paths." ) return None path = Path(raw).expanduser() if not path.is_absolute(): raise ValueError( f"{WORKSPACE_BASE_ENV} must be an absolute path: {raw!r}" ) return path.resolve() def resolve_workspace_path( value: str | Path, *, base_path: Path | None = None, ) -> Path: """Resolve an AccuPedia path deterministically. Absolute paths are used as-is. Relative paths are always resolved against ACUPEDIA_WORKSPACE_BASE_PATH, never against the process current working directory. """ path = Path(value).expanduser() if path.is_absolute(): return path.resolve() base = base_path or workspace_base_path(required=True) assert base is not None return (base / path).resolve() def resolve_env_path( env_name: str, *, required: bool = True, base_path: Path | None = None, ) -> Path | None: raw = os.environ.get(env_name, "").strip() if not raw: if required: raise RuntimeError(f"Missing required environment variable: {env_name}") return None return resolve_workspace_path(raw, base_path=base_path) def resolve_command( raw_command: str, *, base_path: Path | None = None, ) -> list[str]: """Parse a command and resolve a relative executable path against workspace. Only the executable token is path-resolved when it clearly names a path (contains '/' or begins with '.'). Remaining arguments are preserved. """ command = shlex.split(raw_command) if not command: raise ValueError("Command cannot be empty") executable = command[0] if "/" in executable or executable.startswith("."): command[0] = str( resolve_workspace_path( executable, base_path=base_path, ) ) return command