Debian Codegraph @

src/auditwheel/tools.py

raw
1 from __future__ import annotations
2
3 import argparse
4 import logging
5 import os
6 import subprocess
7 import time
8 import zipfile
9 from datetime import datetime, timezone
10 from pathlib import Path
11 from typing import TYPE_CHECKING, Any, TypeVar
12
13 if TYPE_CHECKING:
14 from collections.abc import Generator, Iterable
15
16 _T = TypeVar("_T")
17
18 logger = logging.getLogger(__name__)
19
20
21 def unique_by_index(sequence: Iterable[_T]) -> list[_T]:
22 """Unique elements in `sequence` in the order in which they occur
23
24 Parameters
25 ----------
26 sequence : iterable
27
28 Returns
29 -------
30 uniques : list
31 unique elements of sequence, ordered by the order in which the element
32 occurs in `sequence`
33
34 """
35 uniques = []
36 for element in sequence:
37 if element not in uniques:
38 uniques.append(element)
39 return uniques
40
41
42 def walk(topdir: Path) -> Generator[tuple[Path, list[str], list[str]]]:
43 """Wrapper for `os.walk` with outputs in reproducible order
44
45 Parameters
46 ----------
47 topdir : Path
48 Root of the directory tree
49
50 Yields
51 ------
52 dirpath : Path
53 Path to a directory
54 dirnames : list[str]
55 List of subdirectory names in `dirpath`
56 filenames : list[str]
57 List of non-directory file names in `dirpath`
58
59 """
60 topdir = topdir.resolve(strict=True)
61 for dirpath_, dirnames, filenames in os.walk(topdir):
62 dirpath = Path(dirpath_)
63 # sort list of dirnames in-place such that `os.walk`
64 # will recurse into subdirectories in reproducible order
65 dirnames.sort()
66 # recurse into any top-level .dist-info subdirectory last
67 if dirpath == topdir:
68 subdirs = []
69 dist_info = []
70 for dir_ in dirnames:
71 if dir_.endswith(".dist-info"):
72 dist_info.append(dir_)
73 else:
74 subdirs.append(dir_)
75 dirnames[:] = subdirs
76 dirnames.extend(dist_info)
77 del dist_info
78 # sort list of filenames for iteration in reproducible order
79 filenames.sort()
80 # list any dist-info/RECORD file last
81 if (
82 dirpath.name.endswith(".dist-info")
83 and dirpath.parent == topdir
84 and "RECORD" in filenames
85 ):
86 filenames.remove("RECORD")
87 filenames.append("RECORD")
88 yield dirpath, dirnames, filenames
89
90
91 def zip2dir(zip_fname: Path, out_dir: Path) -> None:
92 """Extract `zip_fname` into output directory `out_dir`
93
94 Parameters
95 ----------
96 zip_fname : str
97 Filename of zip archive to write
98 out_dir : str
99 Directory path containing files to go in the zip archive
100
101 """
102 start = time.perf_counter()
103 with zipfile.ZipFile(zip_fname, "r") as z:
104 for name in z.namelist():
105 member = z.getinfo(name)
106 extracted_path = Path(z.extract(member, out_dir))
107 attr = member.external_attr >> 16
108 if member.is_dir():
109 # this is always rebuilt as 755 by dir2zip
110 extracted_path.chmod(0o755)
111 elif attr != 0:
112 attr &= 511 # only keep permission bits
113 attr |= 6 << 6 # at least read/write for current user
114 extracted_path.chmod(attr)
115 logger.debug(
116 "zip2dir from %s to %s takes %s",
117 zip_fname,
118 out_dir,
119 time.perf_counter() - start,
120 )
121
122
123 def dir2zip(
124 in_dir: Path,
125 zip_fname: Path,
126 zip_compression_level: int,
127 date_time: datetime | None,
128 ) -> None:
129 """Make a zip file `zip_fname` with contents of directory `in_dir`
130
131 The recorded filenames are relative to `in_dir`, so doing a standard zip
132 unpack of the resulting `zip_fname` in an empty directory will result in
133 the original directory contents.
134
135 Parameters
136 ----------
137 in_dir : Path
138 Directory path containing files to go in the zip archive
139 zip_fname : Path
140 Filename of zip archive to write
141 zip_compression_level: int
142 zlib.Z_DEFAULT_COMPRESSION (-1 aka. level 6) balances speed and size.
143 zlib.Z_NO_COMPRESSION (O) for some test builds that needs no compression at all
144 zlib.Z_BEST_COMPRESSION (9) for bandwidth-constrained or large amount of downloads
145 date_time : Optional[datetime]
146 Time stamp to set on each file in the archive
147
148 """
149 start = time.perf_counter()
150 in_dir = in_dir.resolve(strict=True)
151 if date_time is None:
152 st = in_dir.stat()
153 date_time = datetime.fromtimestamp(st.st_mtime, tz=timezone.utc)
154 date_time_args = date_time.timetuple()[:6]
155 if date_time_args < (1980, 1, 1, 0, 0, 0):
156 logger.warning("dir2zip, clipping timestamp to 1980-01-01")
157 date_time_args = (1980, 1, 1, 0, 0, 0)
158 compression = zipfile.ZIP_DEFLATED
159 with zipfile.ZipFile(zip_fname, "w", compression=compression) as z:
160 for dname, _, files in walk(in_dir):
161 if dname != in_dir:
162 out_dname = f"{dname.relative_to(in_dir)}/"
163 zinfo = zipfile.ZipInfo.from_file(dname, out_dname)
164 zinfo.date_time = date_time_args
165 z.writestr(zinfo, b"")
166 for file in files:
167 fname = dname / file
168 out_fname = fname.relative_to(in_dir)
169 zinfo = zipfile.ZipInfo.from_file(fname, out_fname)
170 zinfo.date_time = date_time_args
171 zinfo.compress_type = compression
172 with fname.open("rb") as fp:
173 z.writestr(zinfo, fp.read(), compresslevel=zip_compression_level)
174 logger.debug(
175 "dir2zip from %s to %s takes %s",
176 in_dir,
177 zip_fname,
178 time.perf_counter() - start,
179 )
180
181
182 def tarbz2todir(tarbz2_fname: Path, out_dir: Path) -> None:
183 """Extract `tarbz2_fname` into output directory `out_dir`"""
184 subprocess.check_output(["tar", "xjf", tarbz2_fname, "-C", out_dir])
185
186
187 class EnvironmentDefault(argparse.Action):
188 """Get values from environment variable."""
189
190 def __init__(
191 self,
192 *,
193 env: str,
194 required: bool = True,
195 default: str | None = None,
196 choices: Iterable[str] | None = None,
197 type: type | None = None, # noqa: A002
198 **kwargs: Any, # noqa: ANN401
199 ) -> None:
200 self.env_default = os.environ.get(env)
201 self.env = env
202 if self.env_default:
203 if type:
204 try:
205 self.env_default = type(self.env_default)
206 except Exception: # noqa: BLE001
207 self.option_strings = kwargs["option_strings"]
208 args = {
209 "value": self.env_default,
210 "type": type,
211 "env": self.env,
212 }
213 msg = (
214 "invalid type: %(value)r from environment variable "
215 "%(env)r cannot be converted to %(type)r"
216 )
217 raise argparse.ArgumentError(self, msg % args) from None
218 default = self.env_default
219 if self.env_default is not None and choices is not None and self.env_default not in choices:
220 self.option_strings = kwargs["option_strings"]
221 args = {
222 "value": self.env_default,
223 "choices": ", ".join(map(repr, choices)),
224 "env": self.env,
225 }
226 msg = (
227 "invalid choice: %(value)r from environment variable "
228 "%(env)r (choose from %(choices)s)"
229 )
230 raise argparse.ArgumentError(self, msg % args)
231
232 if default is not None:
233 required = False
234
235 super().__init__(
236 default=default,
237 required=required,
238 choices=choices,
239 type=type,
240 **kwargs,
241 )
242
243 def __call__(
244 self,
245 parser: argparse.ArgumentParser, # noqa: ARG002
246 namespace: argparse.Namespace,
247 values: Any, # noqa: ANN401
248 option_string: str | None = None, # noqa: ARG002
249 ) -> None:
250 setattr(namespace, self.dest, values)
251
252
253 def is_subdir(path: str | Path | None, root: str | Path) -> bool:
254 if path is None:
255 return False
256
257 path = Path(path).resolve()
258 root = Path(root).resolve()
259
260 return root == path or root in path.parents