File size: 8,495 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
# Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
"""Disk utility functions for reading and processing file contents."""

from __future__ import annotations

import hashlib
import os
from base64 import b64encode
from collections import namedtuple
from errno import ENOENT
from functools import partial
from itertools import chain
from logging import getLogger
from os.path import isdir, isfile, join  # noqa
from pathlib import Path
from typing import TYPE_CHECKING

from ...auxlib.collection import first
from ...auxlib.compat import shlex_split_unicode
from ...auxlib.ish import dals
from ...base.constants import PREFIX_PLACEHOLDER
from ...common.compat import open_utf8
from ...common.serialize import json
from ...deprecations import deprecated
from ...exceptions import CondaUpgradeError, CondaVerificationError, PathNotFoundError
from ...models.channel import Channel
from ...models.enums import FileMode, PathEnum
from ...models.package_info import PackageInfo, PackageMetadata
from ...models.records import PathDataV1, PathsData
from .create import TemporaryDirectory
from .link import islink, lexists  # noqa

if TYPE_CHECKING:
    from typing import Literal

log = getLogger(__name__)

listdir = lambda d: list(entry.name for entry in os.scandir(d))


def yield_lines(path):
    """Generator function for lines in file.  Empty generator if path does not exist.

    Args:
        path (str): path to file

    Returns:
        iterator: each line in file, not starting with '#'

    """
    try:
        path = Path(path)
        with path.open() as f:
            for line in f:
                line = line.strip()
                if line and not line.startswith("#"):
                    yield line
    except FileNotFoundError:
        pass
    except OSError as e:
        if e.errno == ENOENT:
            pass
        else:
            raise


def compute_sum(path: str | os.PathLike, algo: Literal["md5", "sha256"]) -> str:
    path = Path(path)
    if not path.is_file():
        raise PathNotFoundError(path)

    # FUTURE: Python 3.11+, replace with hashlib.file_digest
    hasher = hashlib.new(algo)
    with path.open("rb") as fh:
        for chunk in iter(partial(fh.read, 8192), b""):
            hasher.update(chunk)
    return hasher.hexdigest()


# ####################################################
# functions supporting read_package_info()
# ####################################################


def read_package_info(record, package_cache_record):
    epd = package_cache_record.extracted_package_dir
    icondata = read_icondata(epd)
    package_metadata = read_package_metadata(epd)
    paths_data = read_paths_json(epd)

    return PackageInfo(
        extracted_package_dir=epd,
        package_tarball_full_path=package_cache_record.package_tarball_full_path,
        channel=Channel(record.channel_name or record.channel),
        repodata_record=record,
        url=package_cache_record.url,
        icondata=icondata,
        package_metadata=package_metadata,
        paths_data=paths_data,
    )


def read_index_json(extracted_package_directory):
    with open_utf8(join(extracted_package_directory, "info", "index.json")) as fi:
        return json.load(fi)


def read_index_json_from_tarball(package_tarball_full_path):
    import conda_package_handling.api

    with TemporaryDirectory() as tmpdir:
        conda_package_handling.api.extract(package_tarball_full_path, tmpdir, "info")
        with open_utf8(join(tmpdir, "info", "index.json")) as f:
            json_data = json.load(f)
    return json_data


def read_repodata_json(extracted_package_directory):
    with open_utf8(
        join(extracted_package_directory, "info", "repodata_record.json")
    ) as fi:
        return json.load(fi)


def read_icondata(extracted_package_directory):
    icon_file_path = join(extracted_package_directory, "info", "icon.png")
    if isfile(icon_file_path):
        with open_utf8(icon_file_path, "rb") as f:
            data = f.read()
        return b64encode(data).decode("utf-8")
    else:
        return None


def read_package_metadata(extracted_package_directory):
    def _paths():
        yield join(extracted_package_directory, "info", "link.json")
        yield join(extracted_package_directory, "info", "package_metadata.json")

    path = first(_paths(), key=isfile)
    if not path:
        return None
    else:
        with open_utf8(path) as f:
            data = json.loads(f.read())
            if data.get("package_metadata_version") != 1:
                raise CondaUpgradeError(
                    dals(
                        """
                The current version of conda is too old to install this package. (This version
                only supports link.json schema version 1.)  Please update conda to install
                this package.
                """
                    )
                )
        package_metadata = PackageMetadata(**data)
        return package_metadata


def read_paths_json(extracted_package_directory):
    info_dir = join(extracted_package_directory, "info")
    paths_json_path = join(info_dir, "paths.json")
    if isfile(paths_json_path):
        with open_utf8(paths_json_path) as paths_json:
            data = json.load(paths_json)
        if data.get("paths_version") != 1:
            raise CondaUpgradeError(
                dals(
                    """
            The current version of conda is too old to install this package. (This version
            only supports paths.json schema version 1.)  Please update conda to install
            this package."""
                )
            )
        paths_data = PathsData(
            paths_version=1,
            paths=(PathDataV1(**f) for f in data["paths"]),
        )
    else:
        has_prefix_files = read_has_prefix(join(info_dir, "has_prefix"))
        no_link = read_no_link(info_dir)

        def read_files_file():
            files_path = join(info_dir, "files")
            for f in (
                ln for ln in (line.strip() for line in yield_lines(files_path)) if ln
            ):
                path_info = {"_path": f}
                if f in has_prefix_files.keys():
                    path_info["prefix_placeholder"] = has_prefix_files[f][0]
                    path_info["file_mode"] = has_prefix_files[f][1]
                if f in no_link:
                    path_info["no_link"] = True
                if islink(join(extracted_package_directory, f)):
                    path_info["path_type"] = PathEnum.softlink
                else:
                    path_info["path_type"] = PathEnum.hardlink
                yield PathDataV1(**path_info)

        paths = tuple(read_files_file())
        paths_data = PathsData(
            paths_version=0,
            paths=paths,
        )
    return paths_data


def read_has_prefix(path):
    """Reads `has_prefix` file and return dict mapping filepaths to tuples(placeholder, FileMode).

    A line in `has_prefix` contains one of:
      * filepath
      * placeholder mode filepath

    Mode values are one of:
      * text
      * binary
    """
    ParseResult = namedtuple("ParseResult", ("placeholder", "filemode", "filepath"))

    def parse_line(line):
        # placeholder, filemode, filepath
        parts = tuple(x.strip("\"'") for x in shlex_split_unicode(line, posix=False))
        if len(parts) == 1:
            return ParseResult(PREFIX_PLACEHOLDER, FileMode.text, parts[0])
        elif len(parts) == 3:
            return ParseResult(parts[0], FileMode(parts[1]), parts[2])
        else:
            raise CondaVerificationError(f"Invalid has_prefix file at path: {path}")

    parsed_lines = (parse_line(line) for line in yield_lines(path))
    return {pr.filepath: (pr.placeholder, pr.filemode) for pr in parsed_lines}


def read_no_link(info_dir):
    return set(
        chain(
            yield_lines(join(info_dir, "no_link")),
            yield_lines(join(info_dir, "no_softlink")),
        )
    )


def read_soft_links(extracted_package_directory, files):
    return tuple(f for f in files if islink(join(extracted_package_directory, f)))


@deprecated(
    "25.9",
    "26.3",
    addendum="Use 'conda.plugins.prefix_data_loaders.pypi.pkg_format.read_python_record'",
)
def read_python_record(prefix_path, anchor_file, python_version):
    from ...plugins.prefix_data_loaders.pypi.pkg_format import read_python_record

    return read_python_record(prefix_path, anchor_file, python_version)