liab-deployments/liab_deployments/operations/uv.py
Michael Hanke a664f7e403
feat: deploy_uv operation
This is an entrypoint for pyinfra's own `uv` operation, which do not
include a deployment helper for `uv` itself.
2026-09-30 13:08:35 +02:00

111 lines
2.6 KiB
Python

import re
import shlex
from pyinfra.api import operation
_VERSION_RE = re.compile(
r"^\d+\.\d+\.\d+(?:[.-][0-9A-Za-z.-]+)?$"
)
@operation()
def deploy_uv(
version=None,
replace=False,
install_dir=None,
):
"""
Install uv with the upstream installer.
If `replace` is False, an existing uv installation is left unchangeg.
If `replace` is True:
- with version set, install that version if it differs;
- without version set, install the latest version.
If `install_dir` is set, it must be an absolute path. If it is not set,
it defaults to `$HOME/.local/bin` of the effective user.
The installation directory is not added to shell startup files. Configure
pyinfra's remote environment before using subsequent uv operations:
```
from pyinfra import config
config.ENV = {
"PATH": (
# uv install_dir
"/home/app/.local/bin:"
"/usr/local/sbin:/usr/local/bin:"
"/usr/sbin:/usr/bin:/sbin:/bin"
),
}
```
"""
if version is not None:
if not isinstance(version, str) or not _VERSION_RE.fullmatch(version):
raise ValueError(
"version must be a uv version such as '0.9.5'"
)
installer_url = f"https://astral.sh/uv/{version}/install.sh"
else:
installer_url = "https://astral.sh/uv/install.sh"
installer_url = shlex.quote(installer_url)
if install_dir is None:
# These are intentionally shell expressions so they resolve for the
# effective remote user.
install_dir_expr = "$HOME/.local/bin"
uv_expr = "$HOME/.local/bin/uv"
else:
if not install_dir.startswith("/"):
raise ValueError("install_dir must be an absolute path")
install_dir_expr = shlex.quote(install_dir)
uv_expr = shlex.quote(f"{install_dir}/uv")
install_command = f"""\
curl -LsSf {installer_url} |
env UV_INSTALL_DIR={install_dir_expr} \
UV_NO_MODIFY_PATH=1 \
sh
"""
if not replace:
command = f"""\
set -eu
uv_bin={uv_expr}
if [ ! -x "$uv_bin" ]; then
{install_command}
fi
"""
elif version is None:
# replace=True with no version means install the latest release.
command = f"""\
set -eu
{install_command}
"""
else:
# replace=True with a version means converge to that version.
command = f"""\
set -eu
uv_bin={uv_expr}
current_version="$("$uv_bin" --version 2>/dev/null |
sed -n 's/^uv \\([^ ]*\\).*$/\\1/p' || true)"
if [ "$current_version" != {shlex.quote(version)} ]; then
{install_command}
fi
"""
yield command