Debian Codegraph @

src/briefcase/integrations/file.py

raw
1 from __future__ import annotations
2
3 import itertools
4 import os
5 import shutil
6 import ssl
7 import sys
8 import tempfile
9 from collections.abc import Iterable, Sequence
10 from contextlib import suppress
11 from email.message import Message
12 from pathlib import Path
13
14 import httpx
15 import truststore
16
17 from briefcase.exceptions import (
18 BadNetworkResourceError,
19 MissingNetworkResourceError,
20 NetworkFailure,
21 )
22 from briefcase.integrations.base import Tool, ToolCache
23
24
25 class File(Tool):
26 name = "file"
27 full_name = "File"
28
29 @classmethod
30 def verify_install(cls, tools: ToolCache, **kwargs) -> File:
31 """Make File available in tool cache."""
32 # short circuit since already verified and available
33 if hasattr(tools, "file"):
34 return tools.file
35
36 tools.file = File(tools=tools)
37 return tools.file
38
39 @classmethod
40 def sorted_depth_first(cls, paths: Sequence[Path]) -> Iterable[Path]:
41 """Sort a list of paths, so that they appear in lexical order, with
42 subdirectories of a folder sorting before files in the same directory.
43
44 :param paths: The list of paths to sort.
45 :returns: The sorted list of paths
46 """
47 # The sort key for a path is a triple - the parent of the path; whether the path
48 # is a directory or not; and finally, the actual path. We then sort this in
49 # reverse order.
50 #
51 # Sorting by the parent of the path first (in reverse order) guarantees that
52 # long paths are sorted first; so a file in a folder will come *after* the
53 # folder it is in.
54 #
55 # The second term (parent.is_dir()) guarantees that subfolders in a folder are
56 # found before files in the same folder (because in reverse order, booleans sort
57 # True before False).
58 #
59 # Lastly, we sort on the actual path itself. This provide a guaranteed lexical
60 # ordering inside any given folder. This isn't strictly required, but it's
61 # helpful for testing and reproducibility that the sort order is reliable and
62 # repeatable.
63 return sorted(paths, key=lambda p: (p.parent, p.is_dir(), p), reverse=True)
64
65 @classmethod
66 def sorted_depth_first_groups(
67 cls,
68 paths: Sequence[Path],
69 ) -> Iterable[Iterable[Path]]:
70 """Convert a list of paths into a collection of groups that are all at the same
71 "level", grouped depth-first.
72
73 Subfolders in a folder will be in a separate group, returned *before* files in
74 the same folder.
75
76 :param paths: The list of paths return grouped.
77 :returns: A generator returning a iterable groups of paths that are all at the
78 same sorting level.
79 """
80 # The sort function guarantees depth first ordering, with folders before files
81 # at the same level.
82 #
83 # The grouping key is based on the parent of the path (so that all objects in
84 # the same folder group together), with an additional discriminator to ensure
85 # that subfolders are in a different group to files.
86 #
87 # itertools.groupby guarantees a new group whenever the key changes; and the
88 # input sort order guarantees that directories come before files, so we get
89 # our desired sort grouping and ordering.
90 return (
91 group_paths
92 for _, group_paths in itertools.groupby(
93 cls.sorted_depth_first(paths),
94 lambda path: (path.parent, path.is_dir()),
95 )
96 )
97
98 @property
99 def ssl_context(self):
100 """The SSL context to use for downloads."""
101 try:
102 return self._ssl_context
103 except AttributeError:
104 self._ssl_context = truststore.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
105
106 return self._ssl_context
107
108 def is_archive(self, filename: str | os.PathLike) -> bool:
109 """Can a file be unpacked via `shutil.unpack_archive()`?
110
111 The evaluation is based purely on the name of the file. A more robust
112 implementation may actually interrogate the file itself.
113
114 Notably, the types of archives that can be unpacked will vary based on the types
115 of compression the current Python supports. So, for example, if LZMA is not
116 available, then tar.xz archives cannot be unpacked.
117
118 :param filename: path to file to evaluate as an archive
119 """
120 filename = Path(filename)
121 file_extensions = {
122 # captures extensions like .tar.gz, .tar.bz2, etc.
123 "".join(filename.suffixes[-2:]),
124 # as well as .tar, .zip, etc.
125 filename.suffix,
126 }
127 return not file_extensions.isdisjoint(self.supported_archive_extensions)
128
129 @property
130 def supported_archive_extensions(self) -> set[str]:
131 return {
132 extension
133 for archive_format in shutil.get_unpack_formats()
134 for extension in archive_format[1]
135 }
136
137 def unpack_archive(
138 self,
139 filename: str | os.PathLike,
140 extract_dir: str | os.PathLike,
141 **kwargs,
142 ):
143 """Unpack an archive file in to a destination directory.
144
145 Additional protections for unpacking tar files were introduced in Python 3.12.
146 Since tarballs can contain anything valid in a UNIX file system, these
147 protections prevent unpacking potentially dangerous files. This behavior will be
148 the default in Python 3.14. However, the protections can only be enabled for tar
149 files...not zip files.
150
151 :param filename: File path for the archive
152 :param extract_dir: Target file path for where to unpack archive
153 :param kwargs: additional arguments for shutil.unpack_archive
154 """
155 is_zip = Path(filename).suffix == ".zip"
156 if sys.version_info >= (3, 12): # pragma: no-cover-if-lt-py312
157 unpack_kwargs = {"filter": "data"} if not is_zip else {}
158 else: # pragma: no-cover-if-gte-py312
159 unpack_kwargs = {}
160
161 self.tools.shutil.unpack_archive(
162 filename=filename,
163 extract_dir=extract_dir,
164 **{
165 **unpack_kwargs,
166 **kwargs,
167 },
168 )
169
170 def download(self, url: str, download_path: Path, role: str | None = None) -> Path:
171 """Download a given URL, caching it. If it has already been downloaded, return
172 the value that has been cached.
173
174 This is a utility method used to obtain assets used by the installation process.
175 The cached filename will be the filename portion of the URL, appended to the
176 download path.
177
178 :param url: The URL to download
179 :param download_path: The path to the download cache folder. This path will be
180 created if it doesn't exist.
181 :param role: A string describing the role played by the file being downloaded;
182 used to construct log and error messages. Should be able to fit into the
183 sentence "Error downloading {role}".
184 :returns: The filename of the downloaded (or cached) file.
185 """
186 download_path.mkdir(parents=True, exist_ok=True)
187 filename: Path | None = None
188 try:
189 with self.tools.httpx.stream(
190 "GET",
191 url,
192 follow_redirects=True,
193 verify=self.ssl_context,
194 ) as response:
195 if response.status_code == 404:
196 raise MissingNetworkResourceError(url=url)
197 elif response.status_code != 200:
198 raise BadNetworkResourceError(
199 url=url, status_code=response.status_code
200 )
201
202 # The initial URL might go through URL redirects, so we need the *final*
203 # response. We look at either the `Content-Disposition` header or the
204 # final URL to extract the cache filename.
205 cache_full_name = response.url.path
206 header_value = response.headers.get("Content-Disposition")
207 if header_value:
208 # Httpx does not provide a way to parse RFC6266 headers.
209 # The cgi module *did* have a way to parse these headers, but
210 # it was deprecated as part of PEP594. PEP594 recommends
211 # using the email.message module to parse these headers as they
212 # are near identical format.
213 # See also:
214 # * https://tools.ietf.org/html/rfc6266
215 # * https://peps.python.org/pep-0594/#cgi
216 msg = Message()
217 msg["Content-Disposition"] = header_value
218 filename = msg.get_filename()
219 if filename:
220 cache_full_name = filename
221 cache_name = cache_full_name.split("/")[-1]
222 filename = download_path / cache_name
223
224 if filename.exists():
225 self.tools.console.info(f"{cache_name} already downloaded")
226 else:
227 self.tools.console.info(f"Downloading {cache_name}...")
228 self._fetch_and_write_content(response, filename)
229 except httpx.RequestError as e:
230 if role:
231 description = role
232 else:
233 description = filename.name if filename else url
234
235 if isinstance(e, httpx.TooManyRedirects):
236 # httpx, unlike requests, will not follow redirects indefinitely and
237 # defaults to 20 redirects before calling it quits. If the download
238 # attempt exceeds 20 redirects, Briefcase probably needs to re-evaluate
239 # the URLs it is using for that download and ideally find a starting
240 # point that won't have so many redirects.
241 hint = (
242 "exceeded redirects when downloading the file.\n\n"
243 "Please report this as a bug to Briefcase."
244 )
245 elif isinstance(e, httpx.DecodingError):
246 hint = "the server sent a malformed response."
247 elif isinstance(e, httpx.ConnectError):
248 try:
249 # It's a little difficult to verify exactly what might cause httpx
250 # to raise a ConnectError, but `__context__.__context__` should be
251 # an SSLCertVerificationError if there's a certificate problem.
252 # Catch that case, and print the raw exception in other cases.
253 context = e.__context__.__context__
254 except AttributeError:
255 context = None
256
257 if isinstance(context, ssl.SSLCertVerificationError):
258 hint = (
259 "a connection to the server could not be established due to "
260 "a certificate verification problem.\n\n"
261 "This probably indicates an issue with a proxy configuration "
262 "on your computer."
263 )
264 else:
265 hint = (
266 "a connection to the server could not be established.\n\n"
267 f"The reported cause of the problem was {e}"
268 )
269 else:
270 # httpx.TransportError
271 # Use the default hint for generic network communication errors
272 hint = (
273 "is your computer offline?\n\n"
274 f"The reported cause of the problem was {e}"
275 )
276
277 raise NetworkFailure(
278 f"download {description}",
279 hint,
280 ) from e
281
282 return filename
283
284 def _fetch_and_write_content(self, response: httpx.Response, filename: Path):
285 """Write the content from the httpx Response to file.
286
287 The data is initially written in to a temporary file in the Briefcase
288 cache. This avoids partially downloaded files masquerading as complete
289 downloads in later Briefcase runs. The temporary file is only moved
290 to ``filename`` if the download is successful; otherwise, it is deleted.
291
292 :param response: ``httpx.Response``
293 :param filename: full filesystem path to save data
294 """
295 # `temp_file` is used in the `finally` block, so make sure it's assigned
296 # before the `try`.
297 temp_file = tempfile.NamedTemporaryFile( # noqa: SIM115 (use context manager)
298 dir=filename.parent,
299 prefix=f"{filename.name}.",
300 suffix=".download",
301 delete=False,
302 )
303 try:
304 with temp_file:
305 total = response.headers.get("content-length")
306 if total is None:
307 response.read()
308 temp_file.write(response.content)
309 else:
310 progress_bar = self.tools.console.progress_bar()
311 task_id = progress_bar.add_task("Downloader", total=int(total))
312 with progress_bar:
313 for data in response.iter_bytes(chunk_size=1024 * 1024):
314 temp_file.write(data)
315 progress_bar.update(task_id, advance=len(data))
316
317 # This file move short circuits to a file rename when the source and
318 # destination are on the same filesystem; therefore, it should complete
319 # quite quickly even for large files.
320 self.tools.shutil.move(temp_file.name, filename)
321 # Temporary files are created with only read/write permissions for the
322 # file's owner (i.e. 600); to match the behavior of file creation using
323 # ``open(..., "w")``, the downloaded file's permissions are updated for
324 # the group and world to have read/write permissions as well. Finally,
325 # (as with ``open()``) the system's umask is respected. The current
326 # umask is only available as the return value to updating the umask...
327 # Updating the umask affects the current process, including all threads.
328 # A umask value represents permissions that should be denied; so, 022
329 # denies write permissions to the group and world. A 022 umask is a
330 # common default among supporting systems.
331 os.umask(current_umask := os.umask(0o022))
332 # The umask is applied by inverting it and bitwise ANDing the default
333 # permissions...thus masking out permissions that should be denied.
334 self.tools.os.chmod(filename, 0o666 & ~current_umask)
335 finally:
336 # Ensure the temporary file is deleted; this file may still
337 # exist if the download fails or the user sends CTRL+C.
338 with suppress(FileNotFoundError):
339 self.tools.os.remove(temp_file.name)