Debian Codegraph @

src/conda_package_handling/streaming.py

raw
1 """
2 Exception-compatible adapter from conda_package_streaming.
3 """
4
5 from __future__ import annotations
6
7 import io
8 import tarfile
9 import zipfile
10 from collections.abc import Generator
11 from contextlib import redirect_stdout
12 from pathlib import Path
13 from tarfile import TarError
14 from zipfile import BadZipFile
15
16 from conda_package_streaming.extract import exceptions as cps_exceptions
17 from conda_package_streaming.extract import extract_stream, package_streaming
18
19 from . import exceptions
20
21
22 def _stream_components(
23 filename: str | Path,
24 components: list[str],
25 dest_dir: str | Path = "",
26 ) -> Generator[Generator[tuple[tarfile.TarFile, tarfile.TarInfo]]]:
27 if str(filename).endswith(".tar.bz2"):
28 assert components == ["pkg"]
29
30 try:
31 with open(filename, "rb") as fileobj:
32 # Open the .conda's ZipFile once and reuse it for every
33 # component instead of letting ``stream_conda_component``
34 # rebuild it per component. Saves the central-directory
35 # parse on the second component; ~50 us per archive.
36 # .tar.bz2 ignores ``zf=``. See #318 (depends on
37 # conda/conda-package-streaming#173).
38 zf: zipfile.ZipFile | None = None
39 if str(filename).endswith(".conda"):
40 zf = zipfile.ZipFile(fileobj)
41 try:
42 for component in components:
43 yield package_streaming.stream_conda_component(
44 filename,
45 fileobj,
46 component=component,
47 zf=zf,
48 )
49 finally:
50 if zf is not None:
51 zf.close()
52 except cps_exceptions.CaseInsensitiveFileSystemError as e:
53 raise exceptions.CaseInsensitiveFileSystemError(filename, dest_dir) from e
54 except (OSError, TarError, BadZipFile) as e:
55 raise exceptions.InvalidArchiveError(filename, f"failed with error: {str(e)}") from e
56
57
58 def _extract(filename: str | Path, dest_dir: str | Path, components: list[str]):
59 """
60 Extract .conda or .tar.bz2 package to dest_dir.
61
62 If it's a conda package, components may be ["pkg", "info"]
63
64 If it's a .tar.bz2 package, components must equal ["pkg"]
65
66 Internal. Skip directly to conda-package-streaming if you don't need
67 exception compatibility.
68 """
69 for stream in _stream_components(filename, components, dest_dir=dest_dir):
70 try:
71 extract_stream(stream, dest_dir)
72 except cps_exceptions.CaseInsensitiveFileSystemError as e:
73 raise exceptions.CaseInsensitiveFileSystemError(filename, dest_dir) from e
74 except (OSError, TarError, BadZipFile) as e:
75 raise exceptions.InvalidArchiveError(filename, f"failed with error: {str(e)}") from e
76
77
78 def _list(filename: str, components: list[str], verbose=True):
79 memfile = io.StringIO()
80 for component in _stream_components(filename, components):
81 for tar, _ in component:
82 with redirect_stdout(memfile):
83 tar.list(verbose=verbose)
84 # next iteraton of for loop raises GeneratorExit in stream
85 # see comments in conda_package_streaming.extract:extract_stream
86 # and docstring in conda_package_streaming.package_streaming:stream_conda_info
87 component.close()
88 memfile.seek(0)
89 if verbose:
90 lines = sorted(
91 memfile.readlines(),
92 # verbose Tarfile.list() produces lines like:
93 # ?rw-r--r-- 502/20 2342 2018-10-04 14:02:00 info/about.json
94 # We only want the last part but we need to be mindful of paths containing spaces
95 key=lambda line: line.split(None, 5)[-1],
96 )
97 else:
98 lines = sorted(memfile.readlines())
99 print("".join(lines), end="")