| 1 |
""" |
| 2 |
Tools for creating ``.conda``-format archives. |
| 3 |
|
| 4 |
Uses ``tempfile.SpooledTemporaryFile`` to buffer ``pkg-*.tar`` and |
| 5 |
``info-*.tar``, then compress directly into an open `ZipFile` at the end. |
| 6 |
`SpooledTemporaryFile` buffers the first 10MB of the package and its metadata in |
| 7 |
memory, but writes out to disk for larger packages. |
| 8 |
|
| 9 |
Uses more disk space than ``conda-package-handling`` (temporary uncompressed |
| 10 |
tarballs of the package contents) but accepts streams instead of just |
| 11 |
files-on-the-filesystem. |
| 12 |
""" |
| 13 |
|
| 14 |
from __future__ import annotations |
| 15 |
|
| 16 |
import json |
| 17 |
import shutil |
| 18 |
import tarfile |
| 19 |
import tempfile |
| 20 |
import zipfile |
| 21 |
from collections.abc import Iterator |
| 22 |
from contextlib import contextmanager |
| 23 |
from pathlib import Path |
| 24 |
from typing import TYPE_CHECKING |
| 25 |
|
| 26 |
try: |
| 27 |
import compression.zstd as zstd |
| 28 |
except ImportError: |
| 29 |
import backports.zstd as zstd |
| 30 |
|
| 31 |
if TYPE_CHECKING: |
| 32 |
from collections.abc import Callable |
| 33 |
from typing import BinaryIO, Protocol |
| 34 |
|
| 35 |
class LegacyCompressor(Protocol): |
| 36 |
def stream_writer( |
| 37 |
self, |
| 38 |
writer: BinaryIO, |
| 39 |
*, |
| 40 |
size: int, |
| 41 |
closefd: bool, |
| 42 |
) -> BinaryIO: ... |
| 43 |
|
| 44 |
LegacyCompressorOrFactory = LegacyCompressor | Callable[[], LegacyCompressor] |
| 45 |
|
| 46 |
# increase to reduce speed and increase compression (levels above 19 use much |
| 47 |
# more memory) |
| 48 |
ZSTD_COMPRESS_LEVEL = 19 |
| 49 |
# increase for greater speed |
| 50 |
ZSTD_COMPRESS_THREADS = 1 |
| 51 |
|
| 52 |
CONDA_PACKAGE_FORMAT_VERSION = 2 |
| 53 |
|
| 54 |
# Account for growth from "2 GB of /dev/urandom" to not exceed ZIP64_LIMIT after |
| 55 |
# compression |
| 56 |
CONDA_ZIP64_LIMIT = zipfile.ZIP64_LIMIT - (1 << 18) - 1 |
| 57 |
|
| 58 |
|
| 59 |
def anonymize(tarinfo: tarfile.TarInfo): |
| 60 |
""" |
| 61 |
Pass to ``tarfile.add(..., filter=anonymize)`` to anonymize uid/gid. |
| 62 |
|
| 63 |
Does not anonymize mtime or any other field. |
| 64 |
""" |
| 65 |
tarinfo.uid = tarinfo.gid = 0 |
| 66 |
tarinfo.uname = tarinfo.gname = "" |
| 67 |
return tarinfo |
| 68 |
|
| 69 |
|
| 70 |
class CondaTarFile(tarfile.TarFile): |
| 71 |
""" |
| 72 |
Subclass of :external+python:py:class:`tarfile.TarFile` that adds members to |
| 73 |
a second ``info`` tar if they match ``is_info(name)``. |
| 74 |
|
| 75 |
Create this with ``conda_builder(...)`` which sets up the component |
| 76 |
archives, then wraps them into a ``.conda`` on exit. |
| 77 |
|
| 78 |
Only useful for creating, not extracting ``.conda``. |
| 79 |
""" |
| 80 |
|
| 81 |
info_tar: tarfile.TarFile |
| 82 |
is_info: Callable |
| 83 |
|
| 84 |
def __init__( |
| 85 |
self, |
| 86 |
*args, |
| 87 |
info_tar: tarfile.TarFile, |
| 88 |
is_info=lambda name: name.startswith("info/"), |
| 89 |
**kwargs, |
| 90 |
): |
| 91 |
super().__init__(*args, **kwargs) |
| 92 |
self.info_tar = info_tar |
| 93 |
self.is_info = is_info |
| 94 |
|
| 95 |
def addfile(self, tarinfo, fileobj=None): |
| 96 |
""" |
| 97 |
Add the TarInfo object ``tarinfo`` to the archive. If ``fileobj`` is |
| 98 |
given, it should be a binary file, and tarinfo.size bytes are read from |
| 99 |
it and added to the archive. You can create TarInfo objects directly, or |
| 100 |
by using ``gettarinfo()``. |
| 101 |
|
| 102 |
If ``self.is_info(tarinfo.name)`` returns ``True``, add ``tarinfo`` to |
| 103 |
``self.info_tar`` instead. |
| 104 |
""" |
| 105 |
if self.is_info(tarinfo.name): |
| 106 |
return self.info_tar.addfile(tarinfo, fileobj=fileobj) |
| 107 |
else: |
| 108 |
return super().addfile(tarinfo, fileobj) |
| 109 |
|
| 110 |
|
| 111 |
class _ZstdFile(zstd.ZstdFile): |
| 112 |
""" |
| 113 |
ZstdFile adding pledged_input_size. |
| 114 |
|
| 115 |
For the older zstandard binding, a pledged size was important for |
| 116 |
decompression memory usage. Check if that is still true in compression.zstd. |
| 117 |
""" |
| 118 |
|
| 119 |
def __init__(self, *args, pledged_input_size=0, **kwargs): |
| 120 |
super().__init__(*args, **kwargs) |
| 121 |
self._compressor.set_pledged_input_size(pledged_input_size) |
| 122 |
|
| 123 |
|
| 124 |
def _open_writer( |
| 125 |
output, |
| 126 |
*, |
| 127 |
pledged_input_size: int, |
| 128 |
compressor: LegacyCompressorOrFactory | None, |
| 129 |
compression_level: int | None = None, |
| 130 |
compression_threads: int | None = None, |
| 131 |
): |
| 132 |
if compressor is not None: |
| 133 |
if compression_level is not None or compression_threads is not None: |
| 134 |
msg = "`compressor` overrides `compression_level` and `compression_threads`" |
| 135 |
raise ValueError(msg) |
| 136 |
legacy_compressor = compressor() if callable(compressor) else compressor |
| 137 |
if not hasattr(legacy_compressor, "stream_writer"): |
| 138 |
msg = "compressor must provide stream_writer(...)" |
| 139 |
raise TypeError(msg) |
| 140 |
return legacy_compressor.stream_writer( |
| 141 |
output, |
| 142 |
size=pledged_input_size, |
| 143 |
closefd=False, |
| 144 |
) |
| 145 |
|
| 146 |
if compression_level is None: |
| 147 |
compression_level = ZSTD_COMPRESS_LEVEL |
| 148 |
if compression_threads is None: |
| 149 |
compression_threads = ZSTD_COMPRESS_THREADS |
| 150 |
|
| 151 |
return _ZstdFile( |
| 152 |
output, |
| 153 |
mode="w", |
| 154 |
pledged_input_size=pledged_input_size, |
| 155 |
options={ |
| 156 |
zstd.CompressionParameter.compression_level: compression_level, |
| 157 |
zstd.CompressionParameter.nb_workers: compression_threads, |
| 158 |
}, |
| 159 |
) |
| 160 |
|
| 161 |
|
| 162 |
@contextmanager |
| 163 |
def conda_builder( |
| 164 |
stem, |
| 165 |
path, |
| 166 |
*, |
| 167 |
compressor: LegacyCompressorOrFactory | None = None, |
| 168 |
compression_level: int | None = None, |
| 169 |
compression_threads: int | None = None, |
| 170 |
is_info: Callable[[str], bool] = lambda filename: filename.startswith("info/"), |
| 171 |
encoding="utf-8", |
| 172 |
) -> Iterator[CondaTarFile]: |
| 173 |
""" |
| 174 |
Produce a ``TarFile`` subclass used to build a ``.conda`` package. The |
| 175 |
subclass delegates ``addfile()`` to the ``info-`` component when ``is_info`` |
| 176 |
returns True. |
| 177 |
|
| 178 |
When the context manager exits, ``{path}/{stem}.conda`` is written with |
| 179 |
the component tar archives. |
| 180 |
|
| 181 |
Args: |
| 182 |
stem: output filename without extension |
| 183 |
|
| 184 |
path: destination path for transmuted .conda package. |
| 185 |
|
| 186 |
compressor: Legacy ``zstandard`` compressor object (or factory |
| 187 |
returning one) with ``stream_writer(...)``. Mutually exclusive with |
| 188 |
``compression_level`` and ``compression_threads``. |
| 189 |
|
| 190 |
compression_level: zstd compression level for ``compression.zstd`` or |
| 191 |
``backports.zstd`` code path. Defaults to ``ZSTD_COMPRESS_LEVEL`` if not |
| 192 |
specified and ``compressor`` is None. |
| 193 |
|
| 194 |
compression_threads: Number of zstd worker threads for |
| 195 |
``compression.zstd`` or ``backports.zstd`` code path. Defaults to |
| 196 |
``ZSTD_COMPRESS_THREADS`` if not specified and ``compressor`` is None. |
| 197 |
|
| 198 |
encoding: passed to TarFile constructor. Keep default "utf-8" for valid |
| 199 |
.conda. |
| 200 |
|
| 201 |
Yields: |
| 202 |
``CondaTarFile`` |
| 203 |
""" |
| 204 |
output_path = Path(path, f"{stem}.conda") |
| 205 |
with ( |
| 206 |
tempfile.SpooledTemporaryFile() as info_file, |
| 207 |
tempfile.SpooledTemporaryFile() as pkg_file, |
| 208 |
): |
| 209 |
with ( |
| 210 |
tarfile.TarFile(fileobj=info_file, mode="w", encoding=encoding) as info_tar, |
| 211 |
CondaTarFile( |
| 212 |
fileobj=pkg_file, |
| 213 |
mode="w", |
| 214 |
info_tar=info_tar, |
| 215 |
is_info=is_info, |
| 216 |
encoding=encoding, |
| 217 |
) as pkg_tar, |
| 218 |
): |
| 219 |
# If we wanted to compress these at a low setting to save temporary |
| 220 |
# space, we could insert a file object that counts bytes written in |
| 221 |
# front of a zstd (level between 1..3) compressor. |
| 222 |
yield pkg_tar |
| 223 |
|
| 224 |
info_tar.close() |
| 225 |
pkg_tar.close() |
| 226 |
|
| 227 |
info_size = info_file.tell() |
| 228 |
pkg_size = pkg_file.tell() |
| 229 |
|
| 230 |
info_file.seek(0) |
| 231 |
pkg_file.seek(0) |
| 232 |
|
| 233 |
with zipfile.ZipFile( |
| 234 |
output_path, |
| 235 |
"x", # x to not append to existing |
| 236 |
compresslevel=zipfile.ZIP_STORED, |
| 237 |
) as conda_file: |
| 238 |
pkg_metadata = {"conda_pkg_format_version": CONDA_PACKAGE_FORMAT_VERSION} |
| 239 |
conda_file.writestr("metadata.json", json.dumps(pkg_metadata)) |
| 240 |
|
| 241 |
with ( |
| 242 |
conda_file.open( |
| 243 |
f"pkg-{stem}.tar.zst", |
| 244 |
"w", |
| 245 |
force_zip64=(pkg_size > CONDA_ZIP64_LIMIT), |
| 246 |
) as pkg_file_zip, |
| 247 |
_open_writer( |
| 248 |
pkg_file_zip, |
| 249 |
pledged_input_size=pkg_size, |
| 250 |
compressor=compressor, |
| 251 |
compression_level=compression_level, |
| 252 |
compression_threads=compression_threads, |
| 253 |
) as pkg_stream, |
| 254 |
): |
| 255 |
shutil.copyfileobj(pkg_file._file, pkg_stream) |
| 256 |
|
| 257 |
with ( |
| 258 |
conda_file.open( |
| 259 |
f"info-{stem}.tar.zst", |
| 260 |
"w", |
| 261 |
force_zip64=(info_size > CONDA_ZIP64_LIMIT), |
| 262 |
) as info_file_zip, |
| 263 |
_open_writer( |
| 264 |
info_file_zip, |
| 265 |
pledged_input_size=info_size, |
| 266 |
compressor=compressor, |
| 267 |
compression_level=compression_level, |
| 268 |
compression_threads=compression_threads, |
| 269 |
) as info_stream, |
| 270 |
): |
| 271 |
shutil.copyfileobj(info_file._file, info_stream) |