Skip to content

Commit

Permalink
Run a command from a [pipx.run] entry point
Browse files Browse the repository at this point in the history
  • Loading branch information
uranusjr authored Feb 24, 2021
1 parent be9edb3 commit 7ce040f
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 4 deletions.
1 change: 1 addition & 0 deletions docs/changelog.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
dev

- Introduce the `pipx.run` entry point group as an alternative way to declare an application for `pipx run`.
- Fix cursor show/hide to work with older versions of Windows. (#610)
- Support text colors on Windows. (#612)
- Better platform unicode detection to avoid errors and allow showing emojis when possible. (#614)
Expand Down
4 changes: 2 additions & 2 deletions src/pipx/commands/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ def run(
bin_path = venv.bin_path / app_filename
_prepare_venv_cache(venv, bin_path, use_cache)

if bin_path.exists():
if venv.has_app(app, app_filename):
logger.info(f"Reusing cached venv {venv_dir}")
venv.run_app(app, app_filename, app_args)
else:
Expand Down Expand Up @@ -144,7 +144,7 @@ def _download_and_run(
is_main_package=True,
)

if not (venv.bin_path / app_filename).exists():
if not venv.has_app(app, app_filename):
apps = venv.pipx_metadata.main_package.apps
raise PipxError(
f"""
Expand Down
54 changes: 52 additions & 2 deletions src/pipx/venv.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
import json
import logging
import re
import time
from pathlib import Path
from subprocess import CompletedProcess
from typing import Dict, Generator, List, NoReturn, Set
from typing import Dict, Generator, List, NoReturn, Optional, Set

try:
from importlib.metadata import Distribution, EntryPoint
except ImportError:
from importlib_metadata import Distribution, EntryPoint # type: ignore

from packaging.utils import canonicalize_name

Expand Down Expand Up @@ -35,6 +41,15 @@

logger = logging.getLogger(__name__)

_entry_point_value_pattern = re.compile(
r"""
^(?P<module>[\w.]+)\s*
(:\s*(?P<attr>[\w.]+))?\s*
(?P<extras>\[.*\])?\s*$
""",
re.VERBOSE,
)


class VenvContainer:
"""A collection of venvs managed by pipx."""
Expand Down Expand Up @@ -336,8 +351,43 @@ def list_installed_packages(self) -> Set[str]:
pip_list = json.loads(cmd_run.stdout.strip())
return set([x["name"] for x in pip_list])

def _find_entry_point(self, app: str) -> Optional[EntryPoint]:
if not self.python_path.exists():
return None
dists = Distribution.discover(
name=self.main_package_name,
path=[str(get_site_packages(self.python_path))],
)
for dist in dists:
for ep in dist.entry_points:
if ep.group == "pipx.run" and ep.name == app:
return ep
return None

def run_app(self, app: str, filename: str, app_args: List[str]) -> NoReturn:
exec_app([str(self.bin_path / filename)] + app_args)
entry_point = self._find_entry_point(app)

# No [pipx.run] entry point; default to run console script.
if entry_point is None:
exec_app([str(self.bin_path / filename)] + app_args)

# Evaluate and execute the entry point.
# TODO: After dropping support for Python < 3.9, use
# "entry_point.module" and "entry_point.attr" instead.
match = _entry_point_value_pattern.match(entry_point.value)
assert match is not None, "invalid entry point"
module, attr = match.group("module", "attr")
code = (
f"import sys, {module}\n"
f"sys.argv[0] = {entry_point.name!r}\n"
f"sys.exit({module}.{attr}())\n"
)
exec_app([str(self.python_path), "-c", code] + app_args)

def has_app(self, app: str, filename: str) -> bool:
if self._find_entry_point(app) is not None:
return True
return (self.bin_path / filename).is_file()

def _upgrade_package_no_metadata(self, package: str, pip_args: List[str]) -> None:
with animate(
Expand Down

0 comments on commit 7ce040f

Please sign in to comment.