| 1 |
""" |
| 2 |
The 'new' conda format, introduced in late 2018/early 2019. |
| 3 |
|
| 4 |
https://docs.conda.io/projects/conda/en/latest/user-guide/concepts/packages.html |
| 5 |
""" |
| 6 |
|
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
import json |
| 10 |
import os |
| 11 |
import stat |
| 12 |
import tarfile |
| 13 |
import time |
| 14 |
from collections.abc import Callable |
| 15 |
from contextlib import closing |
| 16 |
from typing import BinaryIO, Protocol |
| 17 |
from zipfile import ZIP_STORED, ZipFile |
| 18 |
|
| 19 |
from conda_package_streaming.package_streaming import stream_conda_component |
| 20 |
from conda_package_streaming.url import conda_reader_for_url |
| 21 |
|
| 22 |
from . import utils |
| 23 |
from .interface import AbstractBaseFormat |
| 24 |
from .streaming import _extract, _list |
| 25 |
|
| 26 |
try: |
| 27 |
import compression.zstd as zstd |
| 28 |
except ImportError: |
| 29 |
import backports.zstd as zstd |
| 30 |
|
| 31 |
|
| 32 |
class LegacyCompressor(Protocol): |
| 33 |
def stream_writer( |
| 34 |
self, |
| 35 |
writer: BinaryIO, |
| 36 |
*, |
| 37 |
size: int, |
| 38 |
closefd: bool, |
| 39 |
) -> BinaryIO: ... |
| 40 |
|
| 41 |
|
| 42 |
LegacyCompressorOrFactory = LegacyCompressor | Callable[[], LegacyCompressor] |
| 43 |
|
| 44 |
|
| 45 |
CONDA_PACKAGE_FORMAT_VERSION = 2 |
| 46 |
DEFAULT_COMPRESSION_TUPLE = (".tar.zst", "zstd", "zstd:compression-level=19") |
| 47 |
|
| 48 |
# higher "ultra" levels have dramatically higher memory usage |
| 49 |
ZSTD_COMPRESS_LEVEL = 19 |
| 50 |
# usually a good idea to increase threads |
| 51 |
ZSTD_COMPRESS_THREADS = 1 |
| 52 |
|
| 53 |
|
| 54 |
def _translate_zstd_level_threads(zstd_compress_level, zstd_compress_threads) -> tuple[int, int]: |
| 55 |
"""Called by _convert to get integer level, threads from arguments.""" |
| 56 |
if zstd_compress_level is None: |
| 57 |
zstd_compress_level = ZSTD_COMPRESS_LEVEL |
| 58 |
if zstd_compress_threads is None: |
| 59 |
zstd_compress_threads = ZSTD_COMPRESS_THREADS |
| 60 |
elif zstd_compress_threads == -1: |
| 61 |
zstd_compress_threads = os.cpu_count() or 1 |
| 62 |
return zstd_compress_level, zstd_compress_threads |
| 63 |
|
| 64 |
|
| 65 |
class CondaFormat_v2(AbstractBaseFormat): |
| 66 |
"""If there's another conda format or breaking changes, please create a new class and keep this |
| 67 |
one, so that handling of v2 stays working.""" |
| 68 |
|
| 69 |
@staticmethod |
| 70 |
def supported(fn): |
| 71 |
return fn.endswith(".conda") |
| 72 |
|
| 73 |
@staticmethod |
| 74 |
def extract(fn, dest_dir, **kw): |
| 75 |
components = utils.ensure_list(kw.get("components")) or ("info", "pkg") |
| 76 |
if not os.path.isabs(fn): |
| 77 |
fn = os.path.normpath(os.path.join(os.getcwd(), fn)) |
| 78 |
if not os.path.isdir(dest_dir): |
| 79 |
os.makedirs(dest_dir) |
| 80 |
|
| 81 |
_extract(str(fn), str(dest_dir), components=components) |
| 82 |
|
| 83 |
@staticmethod |
| 84 |
def extract_info(fn, dest_dir=None): |
| 85 |
return CondaFormat_v2.extract(fn, dest_dir, components=["info"]) |
| 86 |
|
| 87 |
@staticmethod |
| 88 |
def create( |
| 89 |
prefix, |
| 90 |
file_list, |
| 91 |
out_fn, |
| 92 |
out_folder=None, |
| 93 |
*, |
| 94 |
compressor: LegacyCompressorOrFactory | None = None, |
| 95 |
compression_level: int | None = None, |
| 96 |
compression_threads: int | None = None, |
| 97 |
compression_tuple=(None, None, None), |
| 98 |
**kw, # to satisfy AbstractBaseFormat.create signature |
| 99 |
): |
| 100 |
if out_folder is None: |
| 101 |
out_folder = os.getcwd() |
| 102 |
if os.path.isabs(out_fn): |
| 103 |
out_folder = os.path.dirname(out_fn) |
| 104 |
out_fn = os.path.basename(out_fn) |
| 105 |
conda_pkg_fn = os.path.join(out_folder, out_fn) |
| 106 |
file_id = out_fn[: -len(".conda")] |
| 107 |
pkg_files, info_files = [], [] |
| 108 |
for f in file_list: |
| 109 |
(info_files if utils.is_info_member_path(f) else pkg_files).append(f) |
| 110 |
|
| 111 |
if compressor and (compression_tuple != (None, None, None)): |
| 112 |
raise ValueError("Supply one of compressor= or (deprecated) compression_tuple=") |
| 113 |
if compressor and (compression_level is not None or compression_threads is not None): |
| 114 |
raise ValueError( |
| 115 |
"`compressor` overrides `compression_level` and `compression_threads`" |
| 116 |
) |
| 117 |
|
| 118 |
# Handle legacy compression_tuple for libarchive compatibility |
| 119 |
if compressor is None and compression_level is None: |
| 120 |
ext, comp_filter, filter_opts = compression_tuple |
| 121 |
if filter_opts and filter_opts.startswith("zstd:compression-level="): |
| 122 |
compression_level = int(filter_opts.split("=", 1)[-1]) |
| 123 |
|
| 124 |
compression_level, compression_threads = _translate_zstd_level_threads( |
| 125 |
compression_level, compression_threads |
| 126 |
) |
| 127 |
|
| 128 |
class NullWriter: |
| 129 |
""" |
| 130 |
zstd uses less memory on extract if size is known. |
| 131 |
""" |
| 132 |
|
| 133 |
def __init__(self): |
| 134 |
self.size = 0 |
| 135 |
|
| 136 |
def write(self, bytes): |
| 137 |
self.size += len(bytes) |
| 138 |
return len(bytes) |
| 139 |
|
| 140 |
def tell(self): |
| 141 |
return self.size |
| 142 |
|
| 143 |
def _open_component_writer(component_file, pledged_size: int): |
| 144 |
"""Open a zstd writer for a component file. |
| 145 |
|
| 146 |
Args: |
| 147 |
component_file: File-like object to write compressed data to. |
| 148 |
pledged_size: The exact size of the data that will be compressed. |
| 149 |
This allows the compressor to optimize compression. |
| 150 |
|
| 151 |
Returns: |
| 152 |
A file-like object that accepts uncompressed data. |
| 153 |
""" |
| 154 |
if compressor is not None: |
| 155 |
legacy_compressor = compressor() if callable(compressor) else compressor |
| 156 |
if not hasattr(legacy_compressor, "stream_writer"): |
| 157 |
raise TypeError("compressor must provide stream_writer(...)") |
| 158 |
return legacy_compressor.stream_writer( |
| 159 |
component_file, |
| 160 |
size=pledged_size, |
| 161 |
closefd=False, |
| 162 |
) |
| 163 |
else: |
| 164 |
zstd_file = zstd.open( |
| 165 |
component_file, |
| 166 |
mode="w", |
| 167 |
options={ |
| 168 |
zstd.CompressionParameter.compression_level: compression_level, |
| 169 |
zstd.CompressionParameter.nb_workers: compression_threads, |
| 170 |
}, |
| 171 |
) |
| 172 |
# backports.zstd >= 0.3.0 or compression.zstd has set_pledged_input_size() |
| 173 |
zstd_file._compressor.set_pledged_input_size(pledged_size) |
| 174 |
return zstd_file |
| 175 |
|
| 176 |
with ( |
| 177 |
ZipFile(conda_pkg_fn, "w", compression=ZIP_STORED) as conda_file, |
| 178 |
utils.tmp_chdir(prefix), |
| 179 |
): |
| 180 |
pkg_metadata = {"conda_pkg_format_version": CONDA_PACKAGE_FORMAT_VERSION} |
| 181 |
conda_file.writestr("metadata.json", json.dumps(pkg_metadata)) |
| 182 |
|
| 183 |
components_files = ( |
| 184 |
(f"pkg-{file_id}.tar.zst", pkg_files), |
| 185 |
( |
| 186 |
f"info-{file_id}.tar.zst", |
| 187 |
info_files, |
| 188 |
), |
| 189 |
) |
| 190 |
|
| 191 |
for component, files in components_files: |
| 192 |
# If size is known, the decompressor may be able to allocate less memory. |
| 193 |
# The compressor will error if size is not correct. |
| 194 |
with tarfile.TarFile(fileobj=NullWriter(), mode="w") as sizer: # type: ignore |
| 195 |
for file in files: |
| 196 |
sizer.add(file, filter=utils.anonymize_tarinfo) |
| 197 |
size = sizer.fileobj.size # type: ignore |
| 198 |
|
| 199 |
with conda_file.open(component, "w", force_zip64=True) as component_file: |
| 200 |
component_stream = _open_component_writer(component_file, size) |
| 201 |
component_tar = tarfile.TarFile(fileobj=component_stream, mode="w") |
| 202 |
|
| 203 |
for file in files: |
| 204 |
component_tar.add(file, filter=utils.anonymize_tarinfo) |
| 205 |
|
| 206 |
component_tar.close() |
| 207 |
component_stream.close() |
| 208 |
|
| 209 |
return conda_pkg_fn |
| 210 |
|
| 211 |
@staticmethod |
| 212 |
def get_pkg_details(in_file): |
| 213 |
stat_result = os.stat(in_file) |
| 214 |
size = stat_result.st_size |
| 215 |
md5, sha256 = utils.checksums(in_file, ("md5", "sha256")) |
| 216 |
return {"size": size, "md5": md5, "sha256": sha256} |
| 217 |
|
| 218 |
@classmethod |
| 219 |
def list_contents(cls, fn, verbose=False, **kw): |
| 220 |
components = utils.ensure_list(kw.get("components")) or ("info", "pkg") |
| 221 |
if "://" in fn: |
| 222 |
return cls._list_remote_contents(fn, components=components, verbose=verbose) |
| 223 |
# local resource |
| 224 |
if not os.path.isabs(fn): |
| 225 |
fn = os.path.abspath(fn) |
| 226 |
_list(fn, components=components, verbose=verbose) |
| 227 |
|
| 228 |
@staticmethod |
| 229 |
def _list_remote_contents(url, verbose=False, components=("info", "pkg")): |
| 230 |
""" |
| 231 |
List contents of a remote .conda artifact (by URL). It only fetches the 'info' component |
| 232 |
and uses the metadata to infer details of the 'pkg' component. Some fields like |
| 233 |
modification time or permissions will be missing in verbose mode. |
| 234 |
""" |
| 235 |
components = utils.ensure_list(components or ("info", "pkg")) |
| 236 |
lines = {} |
| 237 |
filename, conda = conda_reader_for_url(url) |
| 238 |
with closing(conda): |
| 239 |
for tar, member in stream_conda_component(filename, conda, component="info"): |
| 240 |
path = member.name + ("/" if member.isdir() else "") |
| 241 |
if "info" in components: |
| 242 |
line = "" |
| 243 |
if verbose: |
| 244 |
line = ( |
| 245 |
f"{stat.filemode(member.mode)} " |
| 246 |
f"{member.uname or member.uid}/{member.gname or member.gid} " |
| 247 |
f"{member.size:10d} " |
| 248 |
) |
| 249 |
line += time.strftime("%Y-%m-%d %H:%M:%S ", time.localtime(member.mtime)) |
| 250 |
lines[path] = line + path |
| 251 |
if "pkg" in components and member.name == "info/paths.json": |
| 252 |
data = json.loads(tar.extractfile(member).read().decode()) |
| 253 |
assert data.get("paths_version", 1) == 1, data |
| 254 |
for path in data.get("paths", ()): |
| 255 |
line = "" |
| 256 |
if verbose: |
| 257 |
size = path["size_in_bytes"] |
| 258 |
line = f"?????????? ?/? {size:10d} ????-??-?? ??:??:?? " |
| 259 |
lines[path["_path"]] = line + path["_path"] |
| 260 |
print(*[line for _, line in sorted(lines.items())], sep="\n") |