| 1 |
"""General tools for working with wheels |
| 2 |
|
| 3 |
Tools that aren't specific to delocation |
| 4 |
""" |
| 5 |
|
| 6 |
from __future__ import annotations |
| 7 |
|
| 8 |
import csv |
| 9 |
import hashlib |
| 10 |
import logging |
| 11 |
import os |
| 12 |
import re |
| 13 |
import zlib |
| 14 |
from base64 import urlsafe_b64encode |
| 15 |
from datetime import datetime, timezone |
| 16 |
from itertools import product |
| 17 |
from pathlib import Path |
| 18 |
from typing import TYPE_CHECKING |
| 19 |
|
| 20 |
from packaging.utils import parse_wheel_filename |
| 21 |
|
| 22 |
from auditwheel._vendor.wheel.pkginfo import read_pkg_info, write_pkg_info |
| 23 |
from auditwheel.architecture import Architecture |
| 24 |
from auditwheel.error import NonPlatformWheelError, WheelToolsError |
| 25 |
from auditwheel.libc import Libc |
| 26 |
from auditwheel.tmpdirs import InTemporaryDirectory |
| 27 |
from auditwheel.tools import dir2zip, unique_by_index, walk, zip2dir |
| 28 |
|
| 29 |
if TYPE_CHECKING: |
| 30 |
from collections.abc import Generator, Iterable |
| 31 |
from types import TracebackType |
| 32 |
|
| 33 |
logger = logging.getLogger(__name__) |
| 34 |
|
| 35 |
|
| 36 |
# Copied from wheel 0.31.1 |
| 37 |
WHEEL_INFO_RE = re.compile( |
| 38 |
r"""^(?P<namever>(?P<name>.+?)-(?P<ver>\d.*?))(-(?P<build>\d.*?))? |
| 39 |
-(?P<pyver>[a-z].+?)-(?P<abi>.+?)-(?P<plat>.+?)(\.whl|\.dist-info)$""", |
| 40 |
re.VERBOSE, |
| 41 |
).match |
| 42 |
|
| 43 |
|
| 44 |
def _dist_info_dir(bdist_dir: Path) -> Path: |
| 45 |
"""Get the .dist-info directory from an unpacked wheel |
| 46 |
|
| 47 |
Parameters |
| 48 |
---------- |
| 49 |
bdist_dir : Path |
| 50 |
Path of unpacked wheel file |
| 51 |
""" |
| 52 |
|
| 53 |
info_dirs = list(bdist_dir.glob("*.dist-info")) |
| 54 |
if len(info_dirs) != 1: |
| 55 |
msg = "Should be exactly one `*.dist_info` directory" |
| 56 |
raise WheelToolsError(msg) |
| 57 |
return info_dirs[0] |
| 58 |
|
| 59 |
|
| 60 |
def rewrite_record(bdist_dir: Path) -> None: |
| 61 |
"""Rewrite RECORD file with hashes for all files in `wheel_sdir` |
| 62 |
|
| 63 |
Copied from :method:`wheel.bdist_wheel.bdist_wheel.write_record` |
| 64 |
|
| 65 |
Will also unsign wheel |
| 66 |
|
| 67 |
Parameters |
| 68 |
---------- |
| 69 |
bdist_dir : Path |
| 70 |
Path of unpacked wheel file |
| 71 |
""" |
| 72 |
info_dir = _dist_info_dir(bdist_dir) |
| 73 |
record_path = info_dir / "RECORD" |
| 74 |
record_relpath = record_path.relative_to(bdist_dir) |
| 75 |
# Unsign wheel - because we're invalidating the record hash |
| 76 |
sig_path = info_dir / "RECORD.jws" |
| 77 |
if sig_path.exists(): |
| 78 |
sig_path.unlink() |
| 79 |
|
| 80 |
def files() -> Generator[Path]: |
| 81 |
for dir_, _, files in walk(bdist_dir): |
| 82 |
for file in files: |
| 83 |
yield dir_ / file |
| 84 |
|
| 85 |
def skip(path: Path) -> bool: |
| 86 |
"""Wheel hashes every possible file.""" |
| 87 |
return path == record_relpath |
| 88 |
|
| 89 |
with record_path.open("w+", newline="", encoding="utf-8") as record_file: |
| 90 |
writer = csv.writer(record_file) |
| 91 |
for path in files(): |
| 92 |
relative_path = path.relative_to(bdist_dir) |
| 93 |
if skip(relative_path): |
| 94 |
hash_ = "" |
| 95 |
size = "" |
| 96 |
else: |
| 97 |
data = path.read_bytes() |
| 98 |
digest = hashlib.sha256(data).digest() |
| 99 |
sha256 = urlsafe_b64encode(digest).rstrip(b"=").decode("ascii") |
| 100 |
hash_ = f"sha256={sha256}" |
| 101 |
size = f"{len(data)}" |
| 102 |
record_path_ = path.relative_to(bdist_dir).as_posix() |
| 103 |
writer.writerow((record_path_, hash_, size)) |
| 104 |
|
| 105 |
|
| 106 |
class InWheel(InTemporaryDirectory): |
| 107 |
"""Context manager for doing things inside wheels |
| 108 |
|
| 109 |
On entering, you'll find yourself in the root tree of the wheel. If you've |
| 110 |
asked for an output wheel, then on exit we'll rewrite the wheel record and |
| 111 |
pack stuff up for you. |
| 112 |
""" |
| 113 |
|
| 114 |
def __init__(self, in_wheel: Path, out_wheel: Path | None = None) -> None: |
| 115 |
"""Initialize in-wheel context manager |
| 116 |
|
| 117 |
Parameters |
| 118 |
---------- |
| 119 |
in_wheel : Path |
| 120 |
filename of wheel to unpack and work inside |
| 121 |
out_wheel : None or Path: |
| 122 |
filename of wheel to write after exiting. If None, don't write and |
| 123 |
discard |
| 124 |
""" |
| 125 |
self.in_wheel = in_wheel.absolute() |
| 126 |
self.out_wheel = None if out_wheel is None else out_wheel.absolute() |
| 127 |
self.zip_compression_level = zlib.Z_DEFAULT_COMPRESSION |
| 128 |
super().__init__() |
| 129 |
|
| 130 |
def __enter__(self) -> Path: |
| 131 |
zip2dir(self.in_wheel, self.name) |
| 132 |
return super().__enter__() |
| 133 |
|
| 134 |
def __exit__( |
| 135 |
self, |
| 136 |
exc: type[BaseException] | None, |
| 137 |
value: BaseException | None, |
| 138 |
tb: TracebackType | None, |
| 139 |
) -> None: |
| 140 |
if self.out_wheel is not None: |
| 141 |
rewrite_record(self.name) |
| 142 |
date_time = None |
| 143 |
timestamp = os.environ.get("SOURCE_DATE_EPOCH") |
| 144 |
if timestamp: |
| 145 |
date_time = datetime.fromtimestamp(int(timestamp), tz=timezone.utc) |
| 146 |
dir2zip(self.name, self.out_wheel, self.zip_compression_level, date_time) |
| 147 |
return super().__exit__(exc, value, tb) |
| 148 |
|
| 149 |
|
| 150 |
class InWheelCtx(InWheel): |
| 151 |
"""Context manager for doing things inside wheels |
| 152 |
|
| 153 |
On entering, you'll find yourself in the root tree of the wheel. If you've |
| 154 |
asked for an output wheel, then on exit we'll rewrite the wheel record and |
| 155 |
pack stuff up for you. |
| 156 |
|
| 157 |
The context manager returns itself from the __enter__ method, so you can |
| 158 |
set things like ``out_wheel``. This is useful when processing in the wheel |
| 159 |
will dicate what the output wheel name is, or whether you want to save at |
| 160 |
all. |
| 161 |
|
| 162 |
The current path of the wheel contents is set in the attribute |
| 163 |
``wheel_path``. |
| 164 |
""" |
| 165 |
|
| 166 |
def __init__(self, in_wheel: Path, out_wheel: Path | None = None) -> None: |
| 167 |
"""Init in-wheel context manager returning self from enter |
| 168 |
|
| 169 |
Parameters |
| 170 |
---------- |
| 171 |
in_wheel : Path |
| 172 |
filename of wheel to unpack and work inside |
| 173 |
out_wheel : None or Path: |
| 174 |
filename of wheel to write after exiting. If None, don't write and |
| 175 |
discard |
| 176 |
""" |
| 177 |
super().__init__(in_wheel, out_wheel) |
| 178 |
self.path: Path | None = None |
| 179 |
|
| 180 |
def __enter__(self): # type: ignore[no-untyped-def] |
| 181 |
self.path = super().__enter__() |
| 182 |
return self |
| 183 |
|
| 184 |
def iter_files(self) -> Generator[Path]: |
| 185 |
if self.path is None: |
| 186 |
msg = "This function should be called from context manager" |
| 187 |
raise ValueError(msg) |
| 188 |
record_name = _dist_info_dir(self.path) / "RECORD" |
| 189 |
record = record_name.read_text() |
| 190 |
reader = csv.reader(r for r in record.splitlines()) |
| 191 |
for row in reader: |
| 192 |
filename = row[0] |
| 193 |
yield Path(filename) |
| 194 |
|
| 195 |
|
| 196 |
def add_platforms( |
| 197 |
wheel_ctx: InWheelCtx, |
| 198 |
platforms: list[str], |
| 199 |
remove_platforms: Iterable[str] = (), |
| 200 |
) -> Path: |
| 201 |
"""Add platform tags `platforms` to a wheel |
| 202 |
|
| 203 |
Add any platform tags in `platforms` that are missing |
| 204 |
to wheel_ctx's filename and ``WHEEL`` file. |
| 205 |
|
| 206 |
Parameters |
| 207 |
---------- |
| 208 |
wheel_ctx : InWheelCtx |
| 209 |
An open wheel context |
| 210 |
platforms : list |
| 211 |
platform tags to add to wheel filename and WHEEL tags - e.g. |
| 212 |
``('macosx_10_9_intel', 'macosx_10_9_x86_64') |
| 213 |
remove_platforms : iterable |
| 214 |
platform tags to remove to the wheel filename and WHEEL tags, e.g. |
| 215 |
``('linux_x86_64',)`` when ``('manylinux_x86_64')`` is added |
| 216 |
""" |
| 217 |
if wheel_ctx.path is None: |
| 218 |
msg = "This function should be called from wheel_ctx context manager" |
| 219 |
raise ValueError(msg) |
| 220 |
|
| 221 |
to_remove = list(remove_platforms) # we might want to modify this, make a copy |
| 222 |
|
| 223 |
definitely_not_purelib = False |
| 224 |
|
| 225 |
info_fname = _dist_info_dir(wheel_ctx.path) / "WHEEL" |
| 226 |
info = read_pkg_info(info_fname) |
| 227 |
# Check what tags we have |
| 228 |
if wheel_ctx.out_wheel is not None: |
| 229 |
out_dir = wheel_ctx.out_wheel.parent |
| 230 |
wheel_fname = wheel_ctx.out_wheel.name |
| 231 |
else: |
| 232 |
out_dir = Path.cwd() |
| 233 |
wheel_fname = wheel_ctx.in_wheel.name |
| 234 |
|
| 235 |
original_fname_tags = get_wheel_platforms(wheel_fname) |
| 236 |
logger.info("Previous filename tags: %s", ", ".join(original_fname_tags)) |
| 237 |
fname_tags = [tag for tag in original_fname_tags if tag not in to_remove] |
| 238 |
fname_tags = unique_by_index(fname_tags + platforms) |
| 239 |
|
| 240 |
# Can't be 'any' and another platform |
| 241 |
if "any" in fname_tags and len(fname_tags) > 1: |
| 242 |
fname_tags.remove("any") |
| 243 |
to_remove.append("any") |
| 244 |
definitely_not_purelib = True |
| 245 |
|
| 246 |
if fname_tags != original_fname_tags: |
| 247 |
logger.info("New filename tags: %s", ", ".join(fname_tags)) |
| 248 |
else: |
| 249 |
logger.info("No filename tags change needed.") |
| 250 |
|
| 251 |
fparts = { |
| 252 |
"prefix": wheel_fname.rsplit("-", maxsplit=1)[0], |
| 253 |
"plat": ".".join(sorted(fname_tags)), |
| 254 |
"ext": Path(wheel_fname).suffix, |
| 255 |
} |
| 256 |
out_wheel_fname = "{prefix}-{plat}{ext}".format(**fparts) |
| 257 |
out_wheel = out_dir / out_wheel_fname |
| 258 |
|
| 259 |
in_info_tags = [tag for name, tag in info.items() if name == "Tag"] |
| 260 |
logger.info("Previous WHEEL info tags: %s", ", ".join(in_info_tags)) |
| 261 |
# Python version, C-API version combinations |
| 262 |
pyc_apis = ["-".join(tag.split("-")[:2]) for tag in in_info_tags] |
| 263 |
# unique Python version, C-API version combinations |
| 264 |
pyc_apis = unique_by_index(pyc_apis) |
| 265 |
# Add new platform tags for each Python version, C-API combination |
| 266 |
wanted_tags = ["-".join(tup) for tup in product(pyc_apis, platforms)] |
| 267 |
new_tags = [tag for tag in wanted_tags if tag not in in_info_tags] |
| 268 |
unwanted_tags = ["-".join(tup) for tup in product(pyc_apis, to_remove)] |
| 269 |
updated_tags = [tag for tag in in_info_tags if tag not in unwanted_tags] |
| 270 |
updated_tags += new_tags |
| 271 |
if updated_tags != in_info_tags: |
| 272 |
del info["Tag"] |
| 273 |
for tag in updated_tags: |
| 274 |
info.add_header("Tag", tag) |
| 275 |
|
| 276 |
if definitely_not_purelib: |
| 277 |
del info["Root-Is-Purelib"] |
| 278 |
info["Root-Is-Purelib"] = "False" |
| 279 |
logger.info("Changed wheel type to Platlib") |
| 280 |
|
| 281 |
logger.info("New WHEEL info tags: %s", ", ".join(info.get_all("Tag"))) |
| 282 |
write_pkg_info(info_fname, info) |
| 283 |
else: |
| 284 |
logger.info("No WHEEL info change needed.") |
| 285 |
wheel_ctx.out_wheel = out_wheel |
| 286 |
return out_wheel |
| 287 |
|
| 288 |
|
| 289 |
def get_wheel_architecture(filename: str) -> Architecture: |
| 290 |
result: set[Architecture] = set() |
| 291 |
missed = False |
| 292 |
pure = True |
| 293 |
for platform in get_wheel_platforms(filename): |
| 294 |
found = False |
| 295 |
pure_ = platform == "any" |
| 296 |
pure = pure and pure_ |
| 297 |
missed = missed or pure_ |
| 298 |
if not pure_: |
| 299 |
for arch in Architecture: |
| 300 |
if platform.endswith(f"_{arch.value}"): |
| 301 |
result.add(arch.baseline) |
| 302 |
found = True |
| 303 |
if not found: |
| 304 |
logger.warning( |
| 305 |
"couldn't guess architecture for platform tag '%s'", |
| 306 |
platform, |
| 307 |
) |
| 308 |
missed = True |
| 309 |
if len(result) == 0: |
| 310 |
if pure: |
| 311 |
raise NonPlatformWheelError(None, None) |
| 312 |
msg = "unknown architecture" |
| 313 |
raise WheelToolsError(msg) |
| 314 |
if missed or len(result) > 1: |
| 315 |
if len(result) == 1: |
| 316 |
msg = "wheels with multiple architectures are not supported" |
| 317 |
else: |
| 318 |
msg = f"wheels with multiple architectures are not supported, got {result}" |
| 319 |
raise WheelToolsError(msg) |
| 320 |
return result.pop() |
| 321 |
|
| 322 |
|
| 323 |
def get_wheel_libc(filename: str) -> Libc: |
| 324 |
result: set[Libc] = set() |
| 325 |
for platform in get_wheel_platforms(filename): |
| 326 |
for libc in Libc: |
| 327 |
if platform.startswith(libc.tag_prefix): |
| 328 |
result.add(libc) |
| 329 |
if len(result) == 0: |
| 330 |
msg = "unknown libc used" |
| 331 |
raise WheelToolsError(msg) |
| 332 |
if len(result) > 1: |
| 333 |
msg = f"wheels with multiple libc are not supported, got {result}" |
| 334 |
raise WheelToolsError(msg) |
| 335 |
return result.pop() |
| 336 |
|
| 337 |
|
| 338 |
def get_wheel_platforms(filename: str) -> list[str]: |
| 339 |
_, _, _, in_tags = parse_wheel_filename(filename) |
| 340 |
return sorted({tag.platform for tag in in_tags}) |
| 341 |
|
| 342 |
|
| 343 |
def android_api_level(tag: str) -> int: |
| 344 |
match = re.match(r"android_(\d+)", tag) |
| 345 |
if match is None: |
| 346 |
msg = f"invalid tag: {tag}" |
| 347 |
raise ValueError(msg) |
| 348 |
return int(match[1]) |