|
| 1 | +""" |
| 2 | +Manage pipx (python) applications. |
| 3 | +""" |
| 4 | + |
| 5 | +from pyinfra import host |
| 6 | +from pyinfra.api import operation |
| 7 | +from pyinfra.facts.pipx import PipxEnvironment, PipxPackages |
| 8 | +from pyinfra.facts.server import Path |
| 9 | + |
| 10 | +from .util.packaging import ensure_packages |
| 11 | + |
| 12 | + |
| 13 | +@operation() |
| 14 | +def packages( |
| 15 | + packages=None, |
| 16 | + present=True, |
| 17 | + latest=False, |
| 18 | + extra_args=None, |
| 19 | +): |
| 20 | + """ |
| 21 | + Install/remove/update pipx packages. |
| 22 | +
|
| 23 | + + packages: list of packages to ensure |
| 24 | + + present: whether the packages should be installed |
| 25 | + + latest: whether to upgrade packages without a specified version |
| 26 | + + extra_args: additional arguments to the pipx command |
| 27 | +
|
| 28 | + Versions: |
| 29 | + Package versions can be pinned like pip: ``<pkg>==<version>``. |
| 30 | +
|
| 31 | + **Example:** |
| 32 | +
|
| 33 | + .. code:: python |
| 34 | +
|
| 35 | + pipx.packages( |
| 36 | + name="Install ", |
| 37 | + packages=["pyinfra"], |
| 38 | + ) |
| 39 | + """ |
| 40 | + |
| 41 | + prep_install_command = ["pipx", "install"] |
| 42 | + |
| 43 | + if extra_args: |
| 44 | + prep_install_command.append(extra_args) |
| 45 | + install_command = " ".join(prep_install_command) |
| 46 | + |
| 47 | + uninstall_command = "pipx uninstall" |
| 48 | + upgrade_command = "pipx upgrade" |
| 49 | + |
| 50 | + current_packages = host.get_fact(PipxPackages) |
| 51 | + |
| 52 | + # pipx support only one package name at a time |
| 53 | + for package in packages: |
| 54 | + yield from ensure_packages( |
| 55 | + host, |
| 56 | + [package], |
| 57 | + current_packages, |
| 58 | + present, |
| 59 | + install_command=install_command, |
| 60 | + uninstall_command=uninstall_command, |
| 61 | + upgrade_command=upgrade_command, |
| 62 | + version_join="==", |
| 63 | + latest=latest, |
| 64 | + ) |
| 65 | + |
| 66 | + |
| 67 | +@operation() |
| 68 | +def upgrade_all(): |
| 69 | + """ |
| 70 | + Upgrade all pipx packages. |
| 71 | + """ |
| 72 | + yield "pipx upgrade-all" |
| 73 | + |
| 74 | + |
| 75 | +@operation() |
| 76 | +def ensure_path(): |
| 77 | + """ |
| 78 | + Ensure pipx bin dir is in the PATH. |
| 79 | + """ |
| 80 | + |
| 81 | + # Fetch the current user's PATH |
| 82 | + path = host.get_fact(Path) |
| 83 | + # Fetch the pipx environment variables |
| 84 | + pipx_env = host.get_fact(PipxEnvironment) |
| 85 | + |
| 86 | + # If the pipx bin dir is already in the user's PATH, we're done |
| 87 | + if "PIPX_BIN_DIR" in pipx_env and pipx_env["PIPX_BIN_DIR"] in path.split(":"): |
| 88 | + host.noop("pipx bin dir is already in the PATH") |
| 89 | + else: |
| 90 | + yield "pipx ensurepath" |
0 commit comments