File size: 3,071 Bytes
71687cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
"""
Exception-compatible adapter from conda_package_streaming.
"""

from __future__ import annotations

import io
import tarfile
from contextlib import redirect_stdout
from tarfile import TarError
from typing import Generator
from zipfile import BadZipFile

from conda_package_streaming.extract import exceptions as cps_exceptions
from conda_package_streaming.extract import extract_stream, package_streaming

from . import exceptions


def _stream_components(
    filename: str,
    components: list[str],
    dest_dir: str = "",
) -> Generator[Generator[tuple[tarfile.TarFile, tarfile.TarInfo]]]:
    if str(filename).endswith(".tar.bz2"):
        assert components == ["pkg"]

    try:
        with open(filename, "rb") as fileobj:
            for component in components:
                # will parse zipfile twice
                yield package_streaming.stream_conda_component(
                    filename, fileobj, component=component
                )
    except cps_exceptions.CaseInsensitiveFileSystemError as e:
        raise exceptions.CaseInsensitiveFileSystemError(filename, dest_dir) from e
    except (OSError, TarError, BadZipFile) as e:
        raise exceptions.InvalidArchiveError(filename, f"failed with error: {str(e)}") from e


def _extract(filename: str, dest_dir: str, components: list[str]):
    """
    Extract .conda or .tar.bz2 package to dest_dir.

    If it's a conda package, components may be ["pkg", "info"]

    If it's a .tar.bz2 package, components must equal ["pkg"]

    Internal. Skip directly to conda-package-streaming if you don't need
    exception compatibility.
    """
    for stream in _stream_components(filename, components, dest_dir=dest_dir):
        try:
            extract_stream(stream, dest_dir)
        except cps_exceptions.CaseInsensitiveFileSystemError as e:
            raise exceptions.CaseInsensitiveFileSystemError(filename, dest_dir) from e
        except (OSError, TarError, BadZipFile) as e:
            raise exceptions.InvalidArchiveError(filename, f"failed with error: {str(e)}") from e


def _list(filename: str, components: list[str], verbose=True):
    memfile = io.StringIO()
    for component in _stream_components(filename, components):
        for tar, _ in component:
            with redirect_stdout(memfile):
                tar.list(verbose=verbose)
            # next iteraton of for loop raises GeneratorExit in stream
            # see comments in conda_package_streaming.extract:extract_stream
            # and docstring in conda_package_streaming.package_streaming:stream_conda_info
            component.close()
    memfile.seek(0)
    if verbose:
        lines = sorted(
            memfile.readlines(),
            # verbose Tarfile.list() produces lines like:
            # ?rw-r--r-- 502/20 2342 2018-10-04 14:02:00 info/about.json
            # We only want the last part but we need to be mindful of paths containing spaces
            key=lambda line: line.split(None, 5)[-1],
        )
    else:
        lines = sorted(memfile.readlines())
    print("".join(lines), end="")