Skip to content

Commit

Permalink
Implement [pipx.run] entry point support
Browse files Browse the repository at this point in the history
  • Loading branch information
uranusjr committed Jan 29, 2021
1 parent 5802848 commit 8e240d7
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 2 deletions.
1 change: 1 addition & 0 deletions docs/changelog.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
dev

- Fix cursor show/hide to work with older versions of Windows. (#610)
- [feature] Introduce the `pipx.run` entry point group as an alternative way to declare an application for `pipx run`.

0.16.0.0

Expand Down
45 changes: 43 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 @@ -34,6 +40,16 @@

logger = logging.getLogger(__name__)

# This regex was only introduced into importlib.metadata in Python 3.9.
_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 @@ -327,8 +343,33 @@ 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
site_packages = get_site_packages(self.python_path)
for dist in Distribution.discover(path=[str(site_packages)]):
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.
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:
Expand Down

0 comments on commit 8e240d7

Please sign in to comment.