Debian Codegraph @

src/pbs_installer/_install.py

raw
1 from __future__ import annotations
2
3 import hashlib
4 import logging
5 import os
6 import tempfile
7 from typing import TYPE_CHECKING, Optional, Tuple, cast
8 from urllib.parse import unquote
9
10 from ._utils import PythonVersion, get_arch_platform
11
12 if TYPE_CHECKING:
13 from typing import Literal
14
15 import httpx
16 from _typeshed import StrPath
17
18 PythonImplementation = Literal["cpython", "pypy"]
19
20 logger = logging.getLogger(__name__)
21 THIS_ARCH, THIS_PLATFORM = get_arch_platform()
22 PythonFile = Tuple[str, Optional[str]]
23
24
25 def _get_headers() -> dict[str, str] | None:
26 TOKEN = os.getenv("GITHUB_TOKEN")
27 if TOKEN is None:
28 return None
29 return {
30 "X-GitHub-Api-Version": "2022-11-28",
31 "Authorization": f"Bearer {TOKEN}",
32 }
33
34
35 def get_download_link(
36 request: str,
37 arch: str = THIS_ARCH,
38 platform: str = THIS_PLATFORM,
39 implementation: PythonImplementation = "cpython",
40 build_dir: bool = False,
41 free_threaded: bool = False,
42 ) -> tuple[PythonVersion, PythonFile]:
43 """Get the download URL matching the given requested version.
44
45 Parameters:
46 request: The version of Python to install, e.g. 3.14, 3.10.4, [email protected]
47 arch: The architecture to install, e.g. x86_64, arm64
48 platform: The platform to install, e.g. linux, macos
49 implementation: The implementation of Python to install, allowed values are 'cpython' and 'pypy'
50 build_dir: Whether to include the `build/` directory from indygreg builds
51 free_threaded: Whether to install the freethreaded version of Python
52
53 Returns:
54 A tuple of the PythonVersion and the download URL
55
56 Examples:
57 >>> get_download_link("3.10", "x86_64", "linux")
58 (PythonVersion(kind='cpython', major=3, minor=10, micro=13),
59 'https://github.com/indygreg/python-build-standalone/releases/download/20240224/cpython-3.10.13%2B20240224-x86_64-unknown-linux-gnu-pgo%2Blto-full.tar.zst')
60 """
61 from ._versions import PYTHON_VERSIONS
62
63 if free_threaded and not request.endswith("t"):
64 request += "t"
65
66 for py_ver, urls in PYTHON_VERSIONS.items():
67 if not py_ver.matches(request, implementation):
68 continue
69
70 matched = urls.get((platform, arch, not build_dir))
71 if matched is not None:
72 return py_ver, matched
73 if not build_dir and (matched := urls.get((platform, arch, False))) is not None:
74 return py_ver, matched
75 raise ValueError(
76 f"Could not find a version matching version={request!r}, implementation={implementation}"
77 )
78
79
80 def download(
81 python_file: PythonFile, destination: StrPath, client: httpx.Client | None = None
82 ) -> str:
83 """Download the given url to the destination.
84
85 Note: Extras required
86 `pbs-installer[download]` must be installed to use this function.
87
88 Parameters:
89 python_file: The (url, checksum) tuple to download
90 destination: The file path to download to
91 client: A http.Client to use for downloading, or None to create a new one
92
93 Returns:
94 The original filename of the downloaded file
95 """
96 url, checksum = python_file
97 logger.debug("Downloading url %s to %s", url, destination)
98 try:
99 import httpx
100 except ModuleNotFoundError:
101 raise RuntimeError("You must install httpx to use this function") from None
102
103 if client is None:
104 client = httpx.Client(trust_env=True, follow_redirects=True)
105
106 filename = unquote(url.rsplit("/")[-1])
107 hasher = hashlib.sha256()
108 if not checksum:
109 logger.warning("No checksum found for %s, this would be insecure", url)
110
111 with open(destination, "wb") as f:
112 with client.stream("GET", url, headers=_get_headers()) as resp:
113 resp.raise_for_status()
114 for chunk in resp.iter_bytes(chunk_size=8192):
115 if checksum:
116 hasher.update(chunk)
117 f.write(chunk)
118
119 if checksum and hasher.hexdigest() != checksum:
120 raise RuntimeError(f"Checksum mismatch. Expected {checksum}, got {hasher.hexdigest()}")
121 return filename
122
123
124 def install_file(
125 filename: StrPath,
126 destination: StrPath,
127 original_filename: str | None = None,
128 build_dir: bool = False,
129 ) -> None:
130 """Unpack the downloaded file to the destination.
131
132 Note: Extras required
133 `pbs-installer[install]` must be installed to use this function.
134
135 Parameters:
136 filename: The file to unpack
137 destination: The directory to unpack to
138 original_filename: The original filename of the file, if it was renamed
139 build_dir: Whether to include the `build/` directory from indygreg builds
140 """
141
142 from ._utils import unpack_tar, unpack_zip
143
144 if original_filename is None:
145 original_filename = str(filename)
146 logger.debug(
147 "Extracting file %s to %s with original filename %s",
148 filename,
149 destination,
150 original_filename,
151 )
152 filename = cast(str, filename)
153 if original_filename.endswith(".zip"):
154 unpack_zip(filename, destination)
155 else:
156 unpack_tar(filename, destination, original_filename)
157
158
159 def install(
160 request: str,
161 destination: StrPath,
162 version_dir: bool = False,
163 client: httpx.Client | None = None,
164 arch: str | None = None,
165 platform: str | None = None,
166 implementation: PythonImplementation = "cpython",
167 build_dir: bool = False,
168 free_threaded: bool = False,
169 ) -> None:
170 """Download and install the requested python version.
171
172 Note: Extras required
173 `pbs-installer[all]` must be installed to use this function.
174
175 Parameters:
176 request: The version of Python to install, e.g. 3.8,3.10.4
177 destination: The directory to install to
178 version_dir: Whether to install to a subdirectory named with the python version
179 client: A httpx.Client to use for downloading
180 arch: The architecture to install, e.g. x86_64, arm64
181 platform: The platform to install, e.g. linux, macos
182 implementation: The implementation of Python to install, allowed values are 'cpython' and 'pypy'
183 build_dir: Whether to include the `build/` directory from indygreg builds
184 free_threaded: Whether to install the freethreaded version of Python
185 Examples:
186 >>> install("3.10", "./python")
187 Installing [email protected] to ./python
188 >>> install("3.10", "./python", version_dir=True)
189 Installing [email protected] to ./python/[email protected]
190 """
191 if platform is None:
192 platform = THIS_PLATFORM
193 if arch is None:
194 arch = THIS_ARCH
195
196 ver, python_file = get_download_link(
197 request,
198 arch=arch,
199 platform=platform,
200 implementation=implementation,
201 build_dir=build_dir,
202 free_threaded=free_threaded,
203 )
204 if version_dir:
205 destination = os.path.join(destination, str(ver))
206 logger.debug("Installing %s to %s", ver, destination)
207 os.makedirs(destination, exist_ok=True)
208 with tempfile.NamedTemporaryFile() as tf:
209 tf.close()
210 original_filename = download(python_file, tf.name, client)
211 install_file(tf.name, destination, original_filename, build_dir)