Debian Codegraph @

src/installer/destinations.py

raw symbols SCIP
1 """Handles all file writing and post-installation processing."""
2
3 import io
4 import os
5 from collections.abc import Collection, Iterable
6 from dataclasses import dataclass
7 from pathlib import Path
8 from typing import (
9 TYPE_CHECKING,
10 BinaryIO,
11 Union,
12 )
13
14 from installer.records import Hash, RecordEntry
15 from installer.scripts import Script
16 from installer.utils import (
17 _WINDOWS,
18 Scheme,
19 construct_record_file,
20 copyfileobj_with_hashing,
21 fix_shebang,
22 make_file_executable,
23 )
24
25 if TYPE_CHECKING:
26 from installer.scripts import LauncherKind, ScriptSection
27
28
29 class WheelDestination:
30 """Handles writing the unpacked files, script generation and ``RECORD`` generation.
31
32 Subclasses provide the concrete script generation logic, as well as the RECORD file
33 (re)writing.
34 """
35
36 def write_script(
37 self, name: str, module: str, attr: str, section: "ScriptSection"
38 ) -> RecordEntry:
39 """Write a script in the correct location to invoke given entry point.
40
41 :param name: name of the script
42 :param module: module path, to load the entry point from
43 :param attr: final attribute access, for the entry point
44 :param section: Denotes the "entry point section" where this was specified.
45 Valid values are ``"gui"`` and ``"console"``.
46 :type section: str
47
48 Example usage/behaviour::
49
50 >>> dest.write_script("pip", "pip._internal.cli", "main", "console")
51
52 """
53 raise NotImplementedError
54
55 def write_file(
56 self,
57 scheme: Scheme,
58 path: Union[str, "os.PathLike[str]"],
59 stream: BinaryIO,
60 is_executable: bool,
61 ) -> RecordEntry:
62 """Write a file to correct ``path`` within the ``scheme``.
63
64 :param scheme: scheme to write the file in (like "purelib", "platlib" etc).
65 :param path: path within that scheme
66 :param stream: contents of the file
67 :param is_executable: whether the file should be made executable
68
69 The stream would be closed by the caller, after this call.
70
71 Example usage/behaviour::
72
73 >>> with open("__init__.py") as stream:
74 ... dest.write_file("purelib", "pkg/__init__.py", stream)
75
76 """
77 raise NotImplementedError
78
79 def finalize_installation(
80 self,
81 scheme: Scheme,
82 record_file_path: str,
83 records: Iterable[tuple[Scheme, RecordEntry]],
84 ) -> None:
85 """Finalize installation, after all the files are written.
86
87 Handles (re)writing of the ``RECORD`` file.
88
89 :param scheme: scheme to write the ``RECORD`` file in
90 :param record_file_path: path of the ``RECORD`` file with that scheme
91 :param records: entries to write to the ``RECORD`` file
92
93 Example usage/behaviour::
94
95 >>> dest.finalize_installation("purelib")
96
97 """
98 raise NotImplementedError
99
100
101 @dataclass
102 class SchemeDictionaryDestination(WheelDestination):
103 """Destination, based on a mapping of {scheme: file-system-path}."""
104
105 scheme_dict: dict[str, str]
106 """A mapping of {scheme: file-system-path}"""
107
108 interpreter: str
109 """The interpreter to use for generating scripts."""
110
111 script_kind: "LauncherKind"
112 """The "kind" of launcher script to use."""
113
114 hash_algorithm: str = "sha256"
115 """
116 The hashing algorithm to use, which is a member of
117 :any:`hashlib.algorithms_available` (ideally from
118 :any:`hashlib.algorithms_guaranteed`).
119 """
120
121 bytecode_optimization_levels: Collection[int] = ()
122 """
123 Compile cached bytecode for installed .py files with these optimization
124 levels. The bytecode is specific to the minor version of Python (e.g. 3.10)
125 used to generate it.
126 """
127
128 destdir: str | None = None
129 """
130 A staging directory in which to write all files. This is expected to be the
131 filesystem root at runtime, so embedded paths will be written as though
132 this was the root.
133 """
134
135 overwrite_existing: bool = False
136 """Silently overwrite existing files."""
137
138 def _path_with_destdir(self, scheme: Scheme, path: str) -> Path:
139 # See https://docs.python.org/3/library/zipfile.html#zipfile.Path:
140 # When handling untrusted archives,
141 # consider resolving filenames using os.path.abspath()
142 # and checking against the target directory with os.path.commonpath().
143 #
144 # Attention: Path.absolute() is not sufficient because it does not
145 # normalize, i.e. does not remove "..".
146 #
147 # We want to avoid Path.resolve() because it is significantly slower
148 # than os.path.abspath()!
149 target_dir = Path(os.path.abspath(self.scheme_dict[scheme])) # noqa: PTH100
150 file = Path(os.path.abspath(target_dir / path)) # noqa: PTH100
151
152 if not file.is_relative_to(target_dir):
153 raise ValueError(
154 f"Attempting to write {path} outside of the target directory"
155 )
156
157 if self.destdir is not None:
158 rel_path = file.relative_to(file.anchor)
159 return Path(self.destdir) / rel_path
160 return file
161
162 def write_to_fs(
163 self,
164 scheme: Scheme,
165 path: str,
166 stream: BinaryIO,
167 is_executable: bool,
168 ) -> RecordEntry:
169 """Write contents of ``stream`` to the correct location on the filesystem.
170
171 :param scheme: scheme to write the file in (like "purelib", "platlib" etc).
172 :param path: path within that scheme
173 :param stream: contents of the file
174 :param is_executable: whether the file should be made executable
175
176 - Ensures that an existing file is not being overwritten.
177 - Hashes the written content, to determine the entry in the ``RECORD`` file.
178 """
179 target_path = self._path_with_destdir(scheme, path)
180 if not self.overwrite_existing and target_path.exists():
181 message = f"File already exists: {target_path!s}"
182 raise FileExistsError(message)
183
184 parent_folder = target_path.parent
185 if not parent_folder.exists():
186 parent_folder.mkdir(parents=True)
187
188 with target_path.open("wb") as f:
189 hash_, size = copyfileobj_with_hashing(stream, f, self.hash_algorithm)
190
191 if is_executable:
192 make_file_executable(target_path)
193
194 return RecordEntry(path, Hash(self.hash_algorithm, hash_), size)
195
196 def write_file(
197 self,
198 scheme: Scheme,
199 path: Union[str, "os.PathLike[str]"],
200 stream: BinaryIO,
201 is_executable: bool,
202 ) -> RecordEntry:
203 """Write a file to correct ``path`` within the ``scheme``.
204
205 :param scheme: scheme to write the file in (like "purelib", "platlib" etc).
206 :param path: path within that scheme
207 :param stream: contents of the file
208 :param is_executable: whether the file should be made executable
209
210 - Changes the shebang for files in the "scripts" scheme.
211 - Uses :py:meth:`SchemeDictionaryDestination.write_to_fs` for the
212 filesystem interaction.
213 """
214 path_ = os.fspath(path)
215
216 if scheme == "scripts":
217 with fix_shebang(stream, self.interpreter) as stream_with_different_shebang:
218 return self.write_to_fs(
219 scheme, path_, stream_with_different_shebang, is_executable
220 )
221
222 return self.write_to_fs(scheme, path_, stream, is_executable)
223
224 def write_script(
225 self, name: str, module: str, attr: str, section: "ScriptSection"
226 ) -> RecordEntry:
227 """Write a script to invoke an entrypoint.
228
229 :param name: name of the script
230 :param module: module path, to load the entry point from
231 :param attr: final attribute access, for the entry point
232 :param section: Denotes the "entry point section" where this was specified.
233 Valid values are ``"gui"`` and ``"console"``.
234 :type section: str
235
236 - Generates a launcher using :any:`Script.generate`.
237 - Writes to the "scripts" scheme.
238 - Uses :py:meth:`SchemeDictionaryDestination.write_to_fs` for the
239 filesystem interaction.
240 """
241 script = Script(name, module, attr, section)
242 script_name, data = script.generate(self.interpreter, self.script_kind)
243
244 with io.BytesIO(data) as stream:
245 entry = self.write_to_fs(
246 Scheme("scripts"), script_name, stream, is_executable=True
247 )
248
249 path = self._path_with_destdir(Scheme("scripts"), script_name)
250 mode = path.stat().st_mode
251 mode |= (mode & 0o444) >> 2
252 path.chmod(mode)
253
254 return entry
255
256 def _compile_bytecode(self, scheme: Scheme, record: RecordEntry) -> None:
257 """Compile bytecode for a single .py file."""
258 if scheme not in ("purelib", "platlib"):
259 return
260
261 import compileall
262
263 target_path = self._path_with_destdir(scheme, record.path)
264 dir_path_to_embed = (Path(self.scheme_dict[scheme]) / record.path).parent
265
266 for level in self.bytecode_optimization_levels:
267 compileall.compile_file(
268 target_path, optimize=level, quiet=1, ddir=dir_path_to_embed
269 )
270
271 def finalize_installation(
272 self,
273 scheme: Scheme,
274 record_file_path: str,
275 records: Iterable[tuple[Scheme, RecordEntry]],
276 ) -> None:
277 """Finalize installation, by writing the ``RECORD`` file & compiling bytecode.
278
279 :param scheme: scheme to write the ``RECORD`` file in
280 :param record_file_path: path of the ``RECORD`` file with that scheme
281 :param records: entries to write to the ``RECORD`` file
282 """
283
284 def prefix_for_scheme(file_scheme: str) -> str | None:
285 if file_scheme == scheme:
286 return None
287 if _WINDOWS: # pragma: no cover
288 path = os.path.abspath(self.scheme_dict[file_scheme]) # noqa: PTH100
289 else: # pragma: no cover
290 path = os.path.relpath(
291 self.scheme_dict[file_scheme],
292 start=self.scheme_dict[scheme],
293 )
294 return path + "/"
295
296 record_list = list(records)
297 with construct_record_file(record_list, prefix_for_scheme) as record_stream:
298 self.write_to_fs(
299 scheme, record_file_path, record_stream, is_executable=False
300 )
301
302 for scheme, record in record_list:
303 self._compile_bytecode(scheme, record)