Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support PEP 723 run requirements #1100

Merged
merged 5 commits into from
Nov 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
## dev

- Support PEP 723 run requirements in `pipx run`.
- Imply `--include-apps` when running `pipx inject --include-deps`
- Add `--with-suffix` for `pipx inject` command
- `pipx install`: emit a warning when `--force` and `--python` were passed at the same time
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ dependencies = [
"colorama>=0.4.4; sys_platform == 'win32'",
"packaging>=20.0",
"platformdirs>=2.1.0",
"tomli; python_version < '3.11'",
"userpath>=1.6.0,!=1.9.0",
]
dynamic = ["version"]
Expand Down
66 changes: 39 additions & 27 deletions src/pipx/commands/run.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import datetime
import hashlib
import logging
import re
import sys
import time
import urllib.parse
import urllib.request
Expand All @@ -24,6 +26,11 @@
)
from pipx.venv import Venv

if sys.version_info < (3, 11):
import tomli as tomllib
else:
import tomllib

logger = logging.getLogger(__name__)


Expand Down Expand Up @@ -319,41 +326,46 @@ def _http_get_request(url: str) -> str:
raise PipxError(str(e)) from e


# This regex comes from PEP 723
PEP723 = re.compile(
r"(?m)^# /// (?P<type>[a-zA-Z0-9-]+)$\s(?P<content>(^#(| .*)$\s)+)^# ///$"
)
Comment on lines +330 to +332
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A comment on the regex pattern (and/or maybe using re.VERBOSE) would be a good idea

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd say comment as long as we match the PEP's suggested regex.



def _get_requirements_from_script(content: str) -> Optional[List[str]]:
# An iterator over the lines in the script. We will
# read through this in sections, so it needs to be an
# iterator, not just a list.
lines = iter(content.splitlines())

for line in lines:
if not line.startswith("#"):
continue
line_content = line[1:].strip()
if line_content == "Requirements:":
break
else:
# No "Requirements:" line in the file
"""
Supports PEP 723.
"""

name = "pyproject"

# Windows is currently getting un-normalized line endings, so normalize
content = content.replace("\r\n", "\n")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this needed? From what I can tell not normalising would simply produce some harmless empty lines that do not match anyway.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If a newline is multiple multiple chars, then it doesn't match the regex. I pre-process this so I can use exactly the regex in the PEP. Another option would be to modify the regex to handle all possible new lines and only that.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(The CI was breaking on Windows otherwise ;) )


matches = [m for m in PEP723.finditer(content) if m.group("type") == name]

if not matches:
return None

# We are now at the first requirement
requirements = []
for line in lines:
# Stop at the end of the comment block
if not line.startswith("#"):
break
line_content = line[1:].strip()
# Stop at a blank comment line
if not line_content:
break
if len(matches) > 1:
raise ValueError(f"Multiple {name} blocks found")

content = "".join(
line[2:] if line.startswith("# ") else line[1:]
for line in matches[0].group("content").splitlines(keepends=True)
)

pyproject = tomllib.loads(content)

requirements = []
for requirement in pyproject.get("run", {}).get("requirements", []):
# Validate the requirement
try:
req = Requirement(line_content)
req = Requirement(requirement)
except InvalidRequirement as e:
raise PipxError(f"Invalid requirement {line_content}: {str(e)}") from e
raise PipxError(f"Invalid requirement {requirement}: {e}") from e

# Use the normalised form of the requirement,
# not the original line.
# Use the normalised form of the requirement
requirements.append(str(req))

return requirements
19 changes: 11 additions & 8 deletions tests/test_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -208,8 +208,9 @@ def test_run_with_requirements(caplog, pipx_temp_env, tmp_path):
script.write_text(
textwrap.dedent(
f"""
# Requirements:
# requests==2.28.1
# /// pyproject
# run.requirements = ["requests==2.28.1"]
# ///

# Check requests can be imported
import requests
Expand All @@ -219,7 +220,8 @@ def test_run_with_requirements(caplog, pipx_temp_env, tmp_path):
from pathlib import Path
Path({repr(str(out))}).write_text(requests.__version__)
"""
).strip()
).strip(),
encoding="utf-8",
)
run_pipx_cli_exit(["run", script.as_uri()])
assert out.read_text() == "2.28.1"
Expand Down Expand Up @@ -249,9 +251,9 @@ def test_run_with_requirements_and_args(caplog, pipx_temp_env, tmp_path):
script.write_text(
textwrap.dedent(
f"""
# Requirements:
# packaging

# /// pyproject
# run.requirements = ["packaging"]
# ///
import packaging
import sys
from pathlib import Path
Expand All @@ -269,8 +271,9 @@ def test_run_with_invalid_requirement(capsys, pipx_temp_env, tmp_path):
script.write_text(
textwrap.dedent(
"""
# Requirements:
# this is an invalid requirement
# /// pyproject
# run.requirements = ["this is an invalid requirement"]
# ///
print()
"""
).strip()
Expand Down
Loading