""" The 'new' conda format, introduced in late 2018/early 2019. https://docs.conda.io/projects/conda/en/latest/user-guide/concepts/packages.html """ from __future__ import annotations import json import os import stat import tarfile import time from collections.abc import Callable from contextlib import closing from typing import BinaryIO, Protocol from zipfile import ZIP_STORED, ZipFile from conda_package_streaming.package_streaming import stream_conda_component from conda_package_streaming.url import conda_reader_for_url from . import utils from .interface import AbstractBaseFormat from .streaming import _extract, _list try: import compression.zstd as zstd except ImportError: import backports.zstd as zstd class LegacyCompressor(Protocol): def stream_writer( self, writer: BinaryIO, *, size: int, closefd: bool, ) -> BinaryIO: ... LegacyCompressorOrFactory = LegacyCompressor | Callable[[], LegacyCompressor] CONDA_PACKAGE_FORMAT_VERSION = 2 DEFAULT_COMPRESSION_TUPLE = (".tar.zst", "zstd", "zstd:compression-level=19") # higher "ultra" levels have dramatically higher memory usage ZSTD_COMPRESS_LEVEL = 19 # usually a good idea to increase threads ZSTD_COMPRESS_THREADS = 1 def _translate_zstd_level_threads(zstd_compress_level, zstd_compress_threads) -> tuple[int, int]: """Called by _convert to get integer level, threads from arguments.""" if zstd_compress_level is None: zstd_compress_level = ZSTD_COMPRESS_LEVEL if zstd_compress_threads is None: zstd_compress_threads = ZSTD_COMPRESS_THREADS elif zstd_compress_threads == -1: zstd_compress_threads = os.cpu_count() or 1 return zstd_compress_level, zstd_compress_threads class CondaFormat_v2(AbstractBaseFormat): """If there's another conda format or breaking changes, please create a new class and keep this one, so that handling of v2 stays working.""" @staticmethod def supported(fn): return fn.endswith(".conda") @staticmethod def extract(fn, dest_dir, **kw): components = utils.ensure_list(kw.get("components")) or ("info", "pkg") if not os.path.isabs(fn): fn = os.path.normpath(os.path.join(os.getcwd(), fn)) if not os.path.isdir(dest_dir): os.makedirs(dest_dir) _extract(str(fn), str(dest_dir), components=components) @staticmethod def extract_info(fn, dest_dir=None): return CondaFormat_v2.extract(fn, dest_dir, components=["info"]) @staticmethod def create( prefix, file_list, out_fn, out_folder=None, *, compressor: LegacyCompressorOrFactory | None = None, compression_level: int | None = None, compression_threads: int | None = None, compression_tuple=(None, None, None), **kw, # to satisfy AbstractBaseFormat.create signature ): if out_folder is None: out_folder = os.getcwd() if os.path.isabs(out_fn): out_folder = os.path.dirname(out_fn) out_fn = os.path.basename(out_fn) conda_pkg_fn = os.path.join(out_folder, out_fn) file_id = out_fn[: -len(".conda")] pkg_files, info_files = [], [] for f in file_list: (info_files if utils.is_info_member_path(f) else pkg_files).append(f) if compressor and (compression_tuple != (None, None, None)): raise ValueError("Supply one of compressor= or (deprecated) compression_tuple=") if compressor and (compression_level is not None or compression_threads is not None): raise ValueError( "`compressor` overrides `compression_level` and `compression_threads`" ) # Handle legacy compression_tuple for libarchive compatibility if compressor is None and compression_level is None: ext, comp_filter, filter_opts = compression_tuple if filter_opts and filter_opts.startswith("zstd:compression-level="): compression_level = int(filter_opts.split("=", 1)[-1]) compression_level, compression_threads = _translate_zstd_level_threads( compression_level, compression_threads ) class NullWriter: """ zstd uses less memory on extract if size is known. """ def __init__(self): self.size = 0 def write(self, bytes): self.size += len(bytes) return len(bytes) def tell(self): return self.size def _open_component_writer(component_file, pledged_size: int): """Open a zstd writer for a component file. Args: component_file: File-like object to write compressed data to. pledged_size: The exact size of the data that will be compressed. This allows the compressor to optimize compression. Returns: A file-like object that accepts uncompressed data. """ if compressor is not None: legacy_compressor = compressor() if callable(compressor) else compressor if not hasattr(legacy_compressor, "stream_writer"): raise TypeError("compressor must provide stream_writer(...)") return legacy_compressor.stream_writer( component_file, size=pledged_size, closefd=False, ) else: zstd_file = zstd.open( component_file, mode="w", options={ zstd.CompressionParameter.compression_level: compression_level, zstd.CompressionParameter.nb_workers: compression_threads, }, ) # backports.zstd >= 0.3.0 or compression.zstd has set_pledged_input_size() zstd_file._compressor.set_pledged_input_size(pledged_size) return zstd_file with ( ZipFile(conda_pkg_fn, "w", compression=ZIP_STORED) as conda_file, utils.tmp_chdir(prefix), ): pkg_metadata = {"conda_pkg_format_version": CONDA_PACKAGE_FORMAT_VERSION} conda_file.writestr("metadata.json", json.dumps(pkg_metadata)) components_files = ( (f"pkg-{file_id}.tar.zst", pkg_files), ( f"info-{file_id}.tar.zst", info_files, ), ) for component, files in components_files: # If size is known, the decompressor may be able to allocate less memory. # The compressor will error if size is not correct. with tarfile.TarFile(fileobj=NullWriter(), mode="w") as sizer: # type: ignore for file in files: sizer.add(file, filter=utils.anonymize_tarinfo) size = sizer.fileobj.size # type: ignore with conda_file.open(component, "w", force_zip64=True) as component_file: component_stream = _open_component_writer(component_file, size) component_tar = tarfile.TarFile(fileobj=component_stream, mode="w") for file in files: component_tar.add(file, filter=utils.anonymize_tarinfo) component_tar.close() component_stream.close() return conda_pkg_fn @staticmethod def get_pkg_details(in_file): stat_result = os.stat(in_file) size = stat_result.st_size md5, sha256 = utils.checksums(in_file, ("md5", "sha256")) return {"size": size, "md5": md5, "sha256": sha256} @classmethod def list_contents(cls, fn, verbose=False, **kw): components = utils.ensure_list(kw.get("components")) or ("info", "pkg") if "://" in fn: return cls._list_remote_contents(fn, components=components, verbose=verbose) # local resource if not os.path.isabs(fn): fn = os.path.abspath(fn) _list(fn, components=components, verbose=verbose) @staticmethod def _list_remote_contents(url, verbose=False, components=("info", "pkg")): """ List contents of a remote .conda artifact (by URL). It only fetches the 'info' component and uses the metadata to infer details of the 'pkg' component. Some fields like modification time or permissions will be missing in verbose mode. """ components = utils.ensure_list(components or ("info", "pkg")) lines = {} filename, conda = conda_reader_for_url(url) with closing(conda): for tar, member in stream_conda_component(filename, conda, component="info"): path = member.name + ("/" if member.isdir() else "") if "info" in components: line = "" if verbose: line = ( f"{stat.filemode(member.mode)} " f"{member.uname or member.uid}/{member.gname or member.gid} " f"{member.size:10d} " ) line += time.strftime("%Y-%m-%d %H:%M:%S ", time.localtime(member.mtime)) lines[path] = line + path if "pkg" in components and member.name == "info/paths.json": data = json.loads(tar.extractfile(member).read().decode()) assert data.get("paths_version", 1) == 1, data for path in data.get("paths", ()): line = "" if verbose: size = path["size_in_bytes"] line = f"?????????? ?/? {size:10d} ????-??-?? ??:??:?? " lines[path["_path"]] = line + path["_path"] print(*[line for _, line in sorted(lines.items())], sep="\n")