import os
import sys
from importlib.metadata import PackageNotFoundError, PackagePath, distribution
_DIST_NAME = "warden-cli"
_REMEDY = f"Reinstall warden from a wheel, e.g. `pip install {_DIST_NAME}`."
class WardenNotFound(FileNotFoundError):
pass
def _is_script_entry(entry: PackagePath, exe_name: str) -> bool:
if entry.name != exe_name:
return False
first_segment = entry.parts[0]
return first_segment != "warden" and not first_segment.endswith(".dist-info")
def find_warden_bin() -> str:
exe_name = "warden" + (".exe" if sys.platform == "win32" else "")
try:
dist = distribution(_DIST_NAME)
except PackageNotFoundError as exc:
raise WardenNotFound(
f"No installed `{_DIST_NAME}` distribution was found via "
"importlib.metadata (e.g. running from a source checkout rather "
f"than an installed wheel). {_REMEDY}"
) from exc
files = dist.files
if files is None:
raise WardenNotFound(
f"The installed `{_DIST_NAME}` distribution has no RECORD, so the "
f"binary's location cannot be resolved. {_REMEDY}"
)
entry = next((f for f in files if _is_script_entry(f, exe_name)), None)
if entry is None:
raise WardenNotFound(
f"No `{exe_name}` script entry was found among the {len(files)} "
f"RECORD entries for the `{_DIST_NAME}` distribution. {_REMEDY}"
)
resolved = os.path.normpath(entry.locate())
if not os.path.isfile(resolved):
raise WardenNotFound(
f"RECORD names `{resolved}` as the `warden` binary, but no file "
f"exists there. {_REMEDY}"
)
return resolved