Debian Codegraph @

src/installer/_core.py

raw symbols SCIP
1 """Core wheel installation logic."""
2
3 import posixpath
4 import warnings
5 from io import BytesIO
6 from pathlib import Path
7 from typing import cast
8
9 from installer.destinations import WheelDestination
10 from installer.exceptions import InvalidWheelSource
11 from installer.records import RecordEntry
12 from installer.sources import WheelSource
13 from installer.utils import SCHEME_NAMES, Scheme, parse_entrypoints, parse_metadata_file
14
15 __all__ = ["install"]
16
17
18 def _process_WHEEL_file(source: WheelSource) -> Scheme: # noqa: N802
19 """Process the WHEEL file, from ``source``.
20
21 Returns the scheme that the archive root should go in.
22 """
23 stream = source.read_dist_info("WHEEL")
24 metadata = parse_metadata_file(stream)
25
26 # Ensure compatibility with this wheel version.
27 if not (metadata["Wheel-Version"] and metadata["Wheel-Version"].startswith("1.")):
28 message = "Incompatible Wheel-Version {}, only support version 1.x wheels."
29 raise InvalidWheelSource(source, message.format(metadata["Wheel-Version"]))
30
31 # Determine where archive root should go.
32 if metadata["Root-Is-Purelib"] == "true":
33 return cast("Scheme", "purelib")
34 else:
35 return cast("Scheme", "platlib")
36
37
38 def _determine_scheme(
39 path: str, source: WheelSource, root_scheme: Scheme
40 ) -> tuple[Scheme, str]:
41 """Determine which scheme to place given path in, from source."""
42 data_dir = source.data_dir
43
44 # If it's in not `{distribution}-{version}.data`, then it's in root_scheme.
45 if posixpath.commonprefix([data_dir, path]) != data_dir:
46 return root_scheme, path
47
48 # Figure out which scheme this goes to.
49 parts = []
50 scheme_name = None
51 left = path
52 while True:
53 left, right = posixpath.split(left)
54 parts.append(right)
55 if left == source.data_dir:
56 scheme_name = right
57 break
58
59 if scheme_name not in SCHEME_NAMES:
60 msg_fmt = "{path} is not contained in a valid .data subdirectory."
61 raise InvalidWheelSource(source, msg_fmt.format(path=path))
62
63 return cast("Scheme", scheme_name), posixpath.join(*reversed(parts[:-1]))
64
65
66 def install(
67 source: WheelSource,
68 destination: WheelDestination,
69 additional_metadata: dict[str, bytes],
70 ) -> None:
71 """Install wheel described by ``source`` into ``destination``.
72
73 :param source: wheel to install.
74 :param destination: where to write the wheel.
75 :param additional_metadata: additional metadata files to generate, usually
76 generated by the caller.
77
78 """
79 root_scheme = _process_WHEEL_file(source)
80
81 # RECORD handling
82 record_file_path = posixpath.join(source.dist_info_dir, "RECORD")
83 written_records = []
84
85 # Write the entry_points based scripts.
86 if "entry_points.txt" in source.dist_info_filenames:
87 entrypoints_text = source.read_dist_info("entry_points.txt")
88 for name, module, attr, section in parse_entrypoints(entrypoints_text):
89 record = destination.write_script(
90 name=name,
91 module=module,
92 attr=attr,
93 section=section,
94 )
95 written_records.append((Scheme("scripts"), record))
96
97 # Write all the files from the wheel.
98 for record_elements, stream, is_executable in source.get_contents():
99 source_record = RecordEntry.from_elements(*record_elements)
100 path = source_record.path
101 # Skip the RECORD, which is written at the end, based on this info.
102 if path == record_file_path:
103 continue
104
105 if "__pycache__" in Path(path).parts[:-1]:
106 warnings.warn(
107 (
108 f"Skip installing {path} from {source.distribution}."
109 " Installing files in a __pycache__ directory poses a security risk."
110 " __pycache__ directories should not be included in wheels."
111 f" This is probably an issue in the build process of '{source.distribution}'."
112 ),
113 RuntimeWarning,
114 stacklevel=2,
115 )
116 continue
117
118 # Figure out where to write this file.
119 scheme, destination_path = _determine_scheme(
120 path=path,
121 source=source,
122 root_scheme=root_scheme,
123 )
124 record = destination.write_file(
125 scheme=scheme,
126 path=destination_path,
127 stream=stream,
128 is_executable=is_executable,
129 )
130 written_records.append((scheme, record))
131
132 # Write all the installation-specific metadata
133 for filename, contents in additional_metadata.items():
134 path = posixpath.join(source.dist_info_dir, filename)
135
136 with BytesIO(contents) as other_stream:
137 record = destination.write_file(
138 scheme=root_scheme,
139 path=path,
140 stream=other_stream,
141 is_executable=False,
142 )
143 written_records.append((root_scheme, record))
144
145 written_records.append((root_scheme, RecordEntry(record_file_path, None, None)))
146 destination.finalize_installation(
147 scheme=root_scheme,
148 record_file_path=record_file_path,
149 records=written_records,
150 )