| 1 |
""" |
| 2 |
Unpack conda packages without using a temporary file. |
| 3 |
""" |
| 4 |
|
| 5 |
from __future__ import annotations |
| 6 |
|
| 7 |
import bz2 |
| 8 |
import os |
| 9 |
import os.path |
| 10 |
import tarfile |
| 11 |
import zipfile |
| 12 |
from collections.abc import Generator |
| 13 |
from enum import Enum |
| 14 |
|
| 15 |
# acquire umask taking advantage of import system lock, instead of possibly in |
| 16 |
# multiple threads at once. |
| 17 |
UMASK = os.umask(0) |
| 18 |
os.umask(UMASK) |
| 19 |
|
| 20 |
try: |
| 21 |
import compression.zstd as zstd # Python 3.14+ |
| 22 |
except ImportError: |
| 23 |
try: |
| 24 |
import backports.zstd as zstd |
| 25 |
except ImportError: |
| 26 |
import warnings |
| 27 |
|
| 28 |
warnings.warn( |
| 29 |
"zstd module could not be imported. Running without .conda support." |
| 30 |
) |
| 31 |
|
| 32 |
zstd = None |
| 33 |
|
| 34 |
|
| 35 |
class CondaComponent(Enum): |
| 36 |
pkg = "pkg" |
| 37 |
info = "info" |
| 38 |
|
| 39 |
def __str__(self): |
| 40 |
return self.value |
| 41 |
|
| 42 |
|
| 43 |
class TarfileNoSameOwner(tarfile.TarFile): |
| 44 |
def __init__(self, *args, umask: int | None = None, **kwargs): |
| 45 |
"""Open an (uncompressed) tar archive `name'. `mode' is either 'r' to |
| 46 |
read from an existing archive, 'a' to append data to an existing |
| 47 |
file or 'w' to create a new file overwriting an existing one. `mode' |
| 48 |
defaults to 'r'. |
| 49 |
If `fileobj' is given, it is used for reading or writing data. If it |
| 50 |
can be determined, `mode' is overridden by `fileobj's mode. |
| 51 |
`fileobj' is not closed, when TarFile is closed. |
| 52 |
""" |
| 53 |
super().__init__(*args, **kwargs) |
| 54 |
self.umask = umask if umask is not None else UMASK |
| 55 |
|
| 56 |
def chown(self, tarinfo, targetpath, numeric_owner): |
| 57 |
""" |
| 58 |
Override chown to be a no-op, since we don't want to preserve ownership |
| 59 |
here. (tarfile.TarFile only lets us toggle all of (chown, chmod, mtime)) |
| 60 |
""" |
| 61 |
return |
| 62 |
|
| 63 |
def chmod(self, tarinfo, targetpath): |
| 64 |
""" |
| 65 |
Set file permissions of targetpath according to tarinfo, respecting |
| 66 |
umask. |
| 67 |
""" |
| 68 |
if tarinfo.mode is None: |
| 69 |
return |
| 70 |
|
| 71 |
try: |
| 72 |
os.chmod(targetpath, tarinfo.mode & (-1 & (~self.umask))) |
| 73 |
except OSError as e: |
| 74 |
raise tarfile.ExtractError("could not change mode") from e |
| 75 |
|
| 76 |
|
| 77 |
def tar_generator( |
| 78 |
fileobj, tarfile_open=TarfileNoSameOwner.open, closefd=False, *, encoding="utf-8" |
| 79 |
) -> Generator[tuple[tarfile.TarFile, tarfile.TarInfo]]: |
| 80 |
""" |
| 81 |
Yield (tar, member) from fileobj. |
| 82 |
|
| 83 |
Args: |
| 84 |
fileobj: file-like object |
| 85 |
|
| 86 |
encoding: "utf-8" passed to TarFile.open(); can be changed for testing. |
| 87 |
""" |
| 88 |
# tarfile will not close fileobj because _extfileobj is True |
| 89 |
# caller should take care to close files all the way back to the http request... |
| 90 |
try: |
| 91 |
with tarfile_open(fileobj=fileobj, mode="r|", encoding=encoding) as tar: |
| 92 |
for member in tar: |
| 93 |
yield tar, member |
| 94 |
finally: |
| 95 |
if closefd: |
| 96 |
fileobj.close() |
| 97 |
|
| 98 |
|
| 99 |
def stream_conda_info( |
| 100 |
filename, fileobj=None |
| 101 |
) -> Generator[tuple[tarfile.TarFile, tarfile.TarInfo]]: |
| 102 |
""" |
| 103 |
Yield members from conda's embedded info/ tarball. |
| 104 |
|
| 105 |
For .tar.bz2 packages, yield all members. |
| 106 |
|
| 107 |
Yields (tar, member) tuples. You must only use the current member to |
| 108 |
prevent tar seeks and scans. |
| 109 |
|
| 110 |
To extract to disk, it's possible to call ``tar.extractall(path)`` on the |
| 111 |
first result and then ignore the rest of this generator. ``extractall`` takes |
| 112 |
care of some directory permissions/mtime issues, compared to ``extract`` or |
| 113 |
writing out the file objects yourself. |
| 114 |
""" |
| 115 |
component = "info" |
| 116 |
return stream_conda_component(filename, fileobj, component) |
| 117 |
|
| 118 |
|
| 119 |
def stream_conda_component( |
| 120 |
filename, |
| 121 |
fileobj=None, |
| 122 |
component: CondaComponent | str = CondaComponent.pkg, |
| 123 |
*, |
| 124 |
encoding="utf-8", |
| 125 |
zf: zipfile.ZipFile | None = None, |
| 126 |
) -> Generator[tuple[tarfile.TarFile, tarfile.TarInfo]]: |
| 127 |
""" |
| 128 |
Yield members from .conda's embedded {component}- tarball. "info" or "pkg". |
| 129 |
|
| 130 |
For .tar.bz2 packages, yield all members. |
| 131 |
|
| 132 |
Yields (tar, member) tuples. You must only use the current member to |
| 133 |
prevent tar seeks and scans. |
| 134 |
|
| 135 |
To extract to disk, it's possible to call ``tar.extractall(path)`` on the |
| 136 |
first result and then ignore the rest of this generator. ``extractall`` takes |
| 137 |
care of some directory permissions/mtime issues, compared to ``extract`` or |
| 138 |
writing out the file objects yourself. |
| 139 |
|
| 140 |
Args: |
| 141 |
filename: path or file-like object to the .conda or .tar.bz2 file |
| 142 |
|
| 143 |
component: "pkg" or "info" component to extract |
| 144 |
|
| 145 |
encoding: "utf-8" passed to TarFile.open(); can be changed for testing. |
| 146 |
|
| 147 |
zf: optional pre-opened ``zipfile.ZipFile`` for .conda archives. |
| 148 |
When provided, reuses the already-opened ZipFile instead of |
| 149 |
parsing the central directory again. Callers that stream both |
| 150 |
the ``pkg`` and ``info`` components can open the zip once and |
| 151 |
pass it in both times, avoiding duplicate parsing. See #173. |
| 152 |
""" |
| 153 |
if str(filename).endswith(".conda"): |
| 154 |
if zstd is None: |
| 155 |
raise RuntimeError( |
| 156 |
"Cannot unpack `.conda` without `backports.zstd` or `compression.zstd`" |
| 157 |
) |
| 158 |
|
| 159 |
if zf is None: |
| 160 |
zf = zipfile.ZipFile(fileobj or filename) |
| 161 |
stem, _, _ = os.path.basename(filename).rpartition(".") |
| 162 |
component_name = f"{component}-{stem}" |
| 163 |
component_filename = [ |
| 164 |
info for info in zf.infolist() if info.filename.startswith(component_name) |
| 165 |
] |
| 166 |
if not component_filename: |
| 167 |
raise LookupError(f"didn't find {component_name} component in {filename}") |
| 168 |
assert len(component_filename) == 1 |
| 169 |
reader = zstd.open(zf.open(component_filename[0])) |
| 170 |
elif str(filename).endswith(".tar.bz2"): |
| 171 |
reader = bz2.open(fileobj or filename, mode="rb") |
| 172 |
else: |
| 173 |
raise ValueError("unsupported file extension") |
| 174 |
return tar_generator(reader, closefd=fileobj is None, encoding=encoding) |