Refactor find_uv_bin and add a better error message

This commit is contained in:
Zanie Blue 2025-06-21 06:58:32 -05:00
parent db356ab8d4
commit db969e5a5c

View file

@ -5,36 +5,38 @@ import sys
import sysconfig import sysconfig
class UvNotFound(FileNotFoundError): ...
def find_uv_bin() -> str: def find_uv_bin() -> str:
"""Return the uv binary path.""" """Return the uv binary path."""
uv_exe = "uv" + sysconfig.get_config_var("EXE") uv_exe = "uv" + sysconfig.get_config_var("EXE")
# Search in the scripts directory for the current prefix targets = [
path = os.path.join(sysconfig.get_path("scripts"), uv_exe) # The scripts directory for the current Python
if os.path.isfile(path): sysconfig.get_path("scripts"),
return path # The scripts directory for the base prefix (if different)
sysconfig.get_path("scripts", vars={"base": sys.base_prefix}),
# The user scheme scripts directory, e.g., `~/.local/bin`
sysconfig.get_path("scripts", scheme=_user_scheme()),
# Adjacent to the package root, e.g. from, `pip install --target`
os.path.join(os.path.dirname(os.path.dirname(__file__)), "bin"),
]
# If in a virtual environment, also search in the base prefix's scripts directory seen = set()
if sys.prefix != sys.base_prefix: for target in targets:
path = os.path.join( if target in seen:
sysconfig.get_path("scripts", vars={"base": sys.base_prefix}), uv_exe continue
) seen.add(target)
path = os.path.join(target, uv_exe)
if os.path.isfile(path): if os.path.isfile(path):
return path return path
# Search in the user scheme scripts directory, e.g., `~/.local/bin` raise UvNotFound(
path = os.path.join(sysconfig.get_path("scripts", scheme=_user_scheme()), uv_exe) f"Could not find the uv binary in any of the following locations:\n"
if os.path.isfile(path): f"{os.linesep.join(f' - {target}' for target in seen)}\n"
return path )
# Search in `bin` adjacent to package root (as created by `pip install --target`).
pkg_root = os.path.dirname(os.path.dirname(__file__))
target_path = os.path.join(pkg_root, "bin", uv_exe)
if os.path.isfile(target_path):
return target_path
raise FileNotFoundError(path)
def _user_scheme() -> str: def _user_scheme() -> str: