-
Notifications
You must be signed in to change notification settings - Fork 0
[#3] Download dev headers if not present #4
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
Open
nickatundo
wants to merge
1
commit into
main
Choose a base branch
from
3-download-dev-headers
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
140 changes: 140 additions & 0 deletions
140
python/src/ubeacon/extension/download_python_headers.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,140 @@ | ||
| """ | ||
| Download Python development headers for a given version into a temporary directory. | ||
|
|
||
| Works without root on Ubuntu, RHEL, Fedora, and OpenSUSE by downloading (not installing) | ||
| the appropriate package and extracting it locally. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import subprocess | ||
| from pathlib import Path | ||
|
|
||
| import distro | ||
|
|
||
|
|
||
| def _run_command(command: list[str], **kwargs: object) -> subprocess.CompletedProcess: | ||
| """ | ||
| Run a command with subprocess.run and check for errors. | ||
|
|
||
| command: The command to run, as a list of arguments. | ||
| kwargs: Additional keyword arguments to pass to subprocess.run. | ||
|
|
||
| Returns the CompletedProcess object returned by subprocess.run. | ||
| """ | ||
| return subprocess.run(command, check=True, capture_output=True, text=True, **kwargs) | ||
|
|
||
|
|
||
| def _get_download_package_uri(version: str) -> str: | ||
| """ | ||
| Return the URL of a distribution package file. | ||
| """ | ||
|
|
||
| match distro.id(): | ||
| case dist if dist in {"ubuntu", "debian"}: | ||
|
|
||
| return ( | ||
| _run_command( | ||
| ["apt-get", "--print-uris", "download", f"libpython{version}-dev"] | ||
| ) | ||
| .stdout.splitlines()[0] | ||
| .split()[0] | ||
| .strip("'") | ||
| ) | ||
|
|
||
| case dist if dist in {"fedora", "rhel", "rocky", "centos", "amzn"}: | ||
|
|
||
| def dnf(package_name: str) -> str: | ||
| # TODO support on ARM | ||
| return _run_command( | ||
| [ | ||
| "dnf", | ||
| "repoquery", | ||
| "--location", | ||
| package_name, | ||
| "--archlist", | ||
| "x86_64", | ||
| ] | ||
| ).stdout.strip() | ||
|
|
||
| rpms = dnf(f"python{version}-devel") | ||
| if not rpms: | ||
| # The package may be named python3-devel if it's the default | ||
| # Python version for the current distro version. | ||
| rpms = dnf("python3-devel") | ||
| if version not in rpms: | ||
| raise ValueError( | ||
| f"Could not find a suitable python-devel package for version {version} in dnf output: {rpms}" | ||
| ) | ||
| return rpms.splitlines()[ | ||
| 0 | ||
| ] # Take the first result if there are multiple matches. | ||
|
|
||
| case _: | ||
| raise ValueError(f"Unsupported distribution: {distro.id()}") | ||
|
|
||
|
|
||
| def _extract_deb(package_path: Path, extract_dir: Path) -> None: | ||
| """Extract a .deb package into the given directory.""" | ||
| _run_command(["dpkg-deb", "-x", str(package_path), str(extract_dir)]) | ||
|
|
||
|
|
||
| def _extract_rpm(package_path: Path, extract_dir: Path) -> None: | ||
| """Extract a .rpm package into the given directory.""" | ||
| with subprocess.Popen( | ||
| ["rpm2cpio", str(package_path)], stdout=subprocess.PIPE | ||
| ) as rpm2cpio: | ||
| _run_command(["cpio", "-idm"], stdin=rpm2cpio.stdout, cwd=extract_dir) | ||
| rpm2cpio.wait() | ||
| if rpm2cpio.returncode != 0: | ||
| raise subprocess.CalledProcessError( | ||
| rpm2cpio.returncode, ["rpm2cpio", str(package_path)] | ||
| ) | ||
|
|
||
|
|
||
| def python_dev_headers( | ||
| version: str, storage_dir: Path, uri_override: str | None = None | ||
| ) -> Path: | ||
| """ | ||
| Download the appropriate python-dev/python-devel package for the current Linux | ||
| distribution if necessary, extract it, and return the path to the | ||
| extracted headers. | ||
nickatundo marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| Args: | ||
| version: The Python version string, e.g. "3.11". | ||
| storage_dir: The directory to use for downloading and extracting packages. | ||
| uri_override: If provided, this URI will be used instead of determining | ||
| the package URL based on the distribution. This is intended for testing. | ||
|
|
||
| Returns: | ||
| The root of the unpacked headers. | ||
|
|
||
| Raises: | ||
| ValueError: If the current distribution is not supported. | ||
| subprocess.CalledProcessError: If downloading or extracting the package fails. | ||
| """ | ||
nickatundo marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| download_dir = storage_dir / "packages" | ||
| download_dir.mkdir(exist_ok=True) | ||
|
|
||
| uri = uri_override or _get_download_package_uri(version) | ||
|
|
||
| # Fetch the package file to the download directory. | ||
| package_path = download_dir / uri.split("/")[-1] | ||
| if not package_path.exists(): | ||
| _run_command(["curl", "--fail","-L", "-o", str(package_path), uri]) | ||
|
|
||
| extract_dir = storage_dir / (package_path.stem + "_extracted") | ||
| if not extract_dir.exists(): | ||
| if package_path.suffix == ".deb": | ||
| extract = _extract_deb | ||
| elif package_path.suffix == ".rpm": | ||
| extract = _extract_rpm | ||
| else: | ||
| raise ValueError( | ||
| f"""Unknown package format: {package_path.suffix}. Expected .deb or .rpm.""" | ||
| ) | ||
|
|
||
| extract_dir.mkdir(exist_ok=True) | ||
| extract(package_path, extract_dir) | ||
|
|
||
| return extract_dir | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.