Debian Codegraph @

src/installer/utils.py

raw symbols SCIP
1 """Utilities related to handling / interacting with wheel files."""
2
3 import base64
4 import contextlib
5 import csv
6 import hashlib
7 import io
8 import os
9 import re
10 import sys
11 from collections import namedtuple
12 from collections.abc import Callable, Iterable, Iterator
13 from configparser import ConfigParser
14 from email.message import Message
15 from email.parser import FeedParser
16 from email.policy import compat32
17 from pathlib import Path
18 from typing import (
19 TYPE_CHECKING,
20 BinaryIO,
21 NewType,
22 cast,
23 )
24
25 if TYPE_CHECKING:
26 from installer.records import RecordEntry
27 from installer.scripts import LauncherKind, ScriptSection
28
29 Scheme = NewType("Scheme", str)
30 AllSchemes = tuple[Scheme, ...]
31
32 __all__ = [
33 "SCHEME_NAMES",
34 "WheelFilename",
35 "construct_record_file",
36 "copyfileobj_with_hashing",
37 "fix_shebang",
38 "get_launcher_kind",
39 "make_file_executable",
40 "parse_entrypoints",
41 "parse_metadata_file",
42 "parse_wheel_filename",
43 ]
44
45 # Borrowed from https://github.com/python/cpython/blob/v3.9.1/Lib/shutil.py#L52
46 _WINDOWS = os.name == "nt"
47 _COPY_BUFSIZE = 1024 * 1024 if _WINDOWS else 64 * 1024
48
49 # According to https://www.python.org/dev/peps/pep-0427/#file-name-convention
50 _WHEEL_FILENAME_REGEX = re.compile(
51 r"""
52 ^
53 (?P<distribution>.+?)
54 -(?P<version>.*?)
55 (?:-(?P<build_tag>\d[^-]*?))?
56 -(?P<tag>.+?-.+?-.+?)
57 \.whl
58 $
59 """,
60 re.VERBOSE | re.UNICODE,
61 )
62 WheelFilename = namedtuple(
63 "WheelFilename", ["distribution", "version", "build_tag", "tag"]
64 )
65
66 # Adapted from https://github.com/python/importlib_metadata/blob/v3.4.0/importlib_metadata/__init__.py#L90
67 _ENTRYPOINT_REGEX = re.compile(
68 r"""
69 (?P<module>[\w.]+)\s*
70 (:\s*(?P<attrs>[\w.]+))\s*
71 (?P<extras>\[.*\])?\s*$
72 """,
73 re.VERBOSE | re.UNICODE,
74 )
75
76 # According to https://www.python.org/dev/peps/pep-0427/#id7
77 SCHEME_NAMES = cast("AllSchemes", ("purelib", "platlib", "headers", "scripts", "data"))
78
79
80 def parse_metadata_file(contents: str) -> Message:
81 """Parse :pep:`376` ``PKG-INFO``-style metadata files.
82
83 ``METADATA`` and ``WHEEL`` files (as per :pep:`427`) use the same syntax
84 and can also be parsed using this function.
85
86 :param contents: The entire contents of the file
87 """
88 feed_parser = FeedParser(policy=compat32)
89 feed_parser.feed(contents)
90 return feed_parser.close()
91
92
93 def canonicalize_name(name: str) -> str:
94 """Canonicalize a project name according to PEP-503.
95
96 :param name: The project name to canonicalize
97 """
98 return re.sub(r"[-_.]+", "-", name).lower()
99
100
101 def parse_wheel_filename(filename: str) -> WheelFilename:
102 """Parse a wheel filename, into it's various components.
103
104 :param filename: The filename to parse
105 """
106 wheel_info = _WHEEL_FILENAME_REGEX.match(filename)
107 if not wheel_info:
108 raise ValueError(f"Not a valid wheel filename: {filename}")
109 return WheelFilename(*wheel_info.groups())
110
111
112 def copyfileobj_with_hashing(
113 source: BinaryIO,
114 dest: BinaryIO,
115 hash_algorithm: str,
116 ) -> tuple[str, int]:
117 """Copy a buffer while computing the content's hash and size.
118
119 Copies the source buffer into the destination buffer while computing the
120 hash of the contents. Adapted from :any:`shutil.copyfileobj`.
121
122 :param source: buffer holding the source data
123 :param dest: destination buffer
124 :param hash_algorithm: hashing algorithm
125
126 :return: hash digest of the contents, size of the contents
127 """
128 hasher = hashlib.new(hash_algorithm)
129 size = 0
130 while True:
131 buf = source.read(_COPY_BUFSIZE)
132 if not buf:
133 break
134 hasher.update(buf)
135 dest.write(buf)
136 size += len(buf)
137
138 return base64.urlsafe_b64encode(hasher.digest()).decode("ascii").rstrip("="), size
139
140
141 def get_stream_length(source: BinaryIO) -> int:
142 """Read a buffer while computing the content's size.
143
144 :param source: buffer holding the source data
145 :return: size of the contents
146 """
147 size = 0
148 while True:
149 buf = source.read(_COPY_BUFSIZE)
150 if not buf:
151 break
152 size += len(buf)
153
154 return size
155
156
157 def get_launcher_kind() -> "LauncherKind": # pragma: no cover
158 """Get the launcher kind for the current machine."""
159 if os.name != "nt":
160 return "posix"
161
162 if "amd64" in sys.version.lower():
163 return "win-amd64"
164 if "(arm64)" in sys.version.lower():
165 return "win-arm64"
166 if "(arm)" in sys.version.lower():
167 return "win-arm"
168 if sys.platform == "win32":
169 return "win-ia32"
170
171 raise NotImplementedError("Unknown launcher kind for this machine")
172
173
174 @contextlib.contextmanager
175 def fix_shebang(stream: BinaryIO, interpreter: str) -> Iterator[BinaryIO]:
176 """Replace ``#!python`` shebang in a stream with the correct interpreter.
177
178 :param stream: stream to modify
179 :param interpreter: "correct interpreter" to substitute the shebang with
180
181 :returns: A context manager, that provides an appropriately modified stream.
182 """
183 stream.seek(0)
184 if stream.read(8) == b"#!python":
185 new_stream = io.BytesIO()
186 # write our new shebang
187 new_stream.write(f"#!{interpreter}\n".encode())
188 # copy the rest of the stream
189 stream.seek(0)
190 stream.readline() # skip first line
191 while True:
192 buf = stream.read(_COPY_BUFSIZE)
193 if not buf:
194 break
195 new_stream.write(buf)
196 new_stream.seek(0)
197 yield new_stream
198 new_stream.close()
199 else:
200 stream.seek(0)
201 yield stream
202
203
204 def construct_record_file(
205 records: Iterable[tuple[Scheme, "RecordEntry"]],
206 prefix_for_scheme: Callable[[Scheme], str | None] = lambda _: None,
207 ) -> BinaryIO:
208 """Construct a RECORD file.
209
210 :param records:
211 ``records`` as passed into :any:`WheelDestination.finalize_installation`
212 :param prefix_for_scheme:
213 function to get a prefix to add for RECORD entries, within a scheme
214
215 :return: A stream that can be written to file. Must be closed by the caller.
216 """
217 stream = io.TextIOWrapper(
218 io.BytesIO(), encoding="utf-8", write_through=True, newline=""
219 )
220 writer = csv.writer(stream, delimiter=",", quotechar='"', lineterminator="\n")
221 for scheme, record in sorted(records, key=lambda x: x[1].path):
222 writer.writerow(record.to_row(prefix_for_scheme(scheme)))
223 stream.seek(0)
224 return stream.detach()
225
226
227 def parse_entrypoints(text: str) -> Iterable[tuple[str, str, str, "ScriptSection"]]:
228 """Parse ``entry_points.txt``-style files.
229
230 :param text: entire contents of the file
231 :return:
232 name of the script, module to use, attribute to call, kind of script (cli / gui)
233 """
234 # Borrowed from https://github.com/python/importlib_metadata/blob/v3.4.0/importlib_metadata/__init__.py#L115
235 config = ConfigParser(delimiters="=")
236 config.optionxform = str # type: ignore[assignment, method-assign]
237 config.read_string(text)
238
239 for section in config.sections():
240 if section not in ["console_scripts", "gui_scripts"]:
241 continue
242
243 for name, value in config.items(section):
244 assert isinstance(name, str)
245 match = _ENTRYPOINT_REGEX.match(value)
246 assert match
247
248 module = match.group("module")
249 assert isinstance(module, str)
250
251 attrs = match.group("attrs")
252 # TODO: make this a proper error, which can be caught.
253 assert attrs is not None
254 assert isinstance(attrs, str)
255
256 script_section = cast("ScriptSection", section[: -len("_scripts")])
257
258 yield name, module, attrs, script_section
259
260
261 def _current_umask() -> int:
262 """Get the current umask which involves having to set it temporarily."""
263 mask = os.umask(0)
264 os.umask(mask)
265 return mask
266
267
268 # Borrowed from:
269 # https://github.com/pypa/pip/blob/0f21fb92/src/pip/_internal/utils/unpacking.py#L93
270 def make_file_executable(path: Path) -> None:
271 """Make the file at the provided path executable."""
272 path.chmod(0o777 & ~_current_umask() | 0o111)