Debian Codegraph @

src/auditwheel/main_repair.py

raw
1 from __future__ import annotations
2
3 import argparse
4 import logging
5 import shutil
6 import zlib
7 from pathlib import Path
8 from typing import Any
9
10 from auditwheel import options
11 from auditwheel.architecture import Architecture
12 from auditwheel.error import NonPlatformWheelError, WheelToolsError
13 from auditwheel.libc import Libc
14 from auditwheel.patcher import Patchelf
15 from auditwheel.policy import WheelPolicies
16 from auditwheel.tools import EnvironmentDefault
17 from auditwheel.wheeltools import get_wheel_architecture, get_wheel_libc
18
19 logger = logging.getLogger(__name__)
20
21
22 def configure_parser(sub_parsers: Any) -> None: # noqa: ANN401
23 policies = WheelPolicies(libc=Libc.detect(), arch=Architecture.detect())
24 policy_names = [p.name for p in policies if p != policies.linux]
25 policy_names += [alias for p in policies for alias in p.aliases]
26 policy_names += ["auto"]
27 epilog = """PLATFORMS:
28 These are the possible platform tags for this machine, as specified by PEP 600.
29 Note that old, pre-PEP 600 tags are still usable and are listed as aliases
30 below.
31 """
32 for p in policies:
33 epilog += f"- {p.name}"
34 if len(p.aliases) > 0:
35 epilog += f" (aliased by {', '.join(p.aliases)})"
36 epilog += "\n"
37 help_ = """Vendor in external shared library dependencies of a wheel.
38 If multiple wheels are specified, an error processing one
39 wheel will abort processing of subsequent wheels.
40 """
41 parser = sub_parsers.add_parser(
42 "repair",
43 help=help_,
44 description=help_,
45 epilog=epilog,
46 formatter_class=argparse.RawDescriptionHelpFormatter,
47 )
48 parser.add_argument("WHEEL_FILE", type=Path, help="Path to wheel file.", nargs="+")
49 parser.add_argument(
50 "-z",
51 "--zip-compression-level",
52 action=EnvironmentDefault,
53 metavar="ZIP_COMPRESSION_LEVEL",
54 env="AUDITWHEEL_ZIP_COMPRESSION_LEVEL",
55 dest="ZIP_COMPRESSION_LEVEL",
56 type=int,
57 help="Compress level to be used to create zip file.",
58 choices=list(range(zlib.Z_NO_COMPRESSION, zlib.Z_BEST_COMPRESSION + 1)),
59 default=zlib.Z_DEFAULT_COMPRESSION,
60 )
61 parser.add_argument(
62 "--plat",
63 action=EnvironmentDefault,
64 metavar="PLATFORM",
65 env="AUDITWHEEL_PLAT",
66 dest="PLAT",
67 help="Desired target platform. See the available platforms under the "
68 'PLATFORMS section below. (default: "auto")',
69 choices=policy_names,
70 default="auto",
71 )
72 parser.add_argument(
73 "-L",
74 "--lib-sdir",
75 dest="LIB_SDIR",
76 help=('Subdirectory in packages to store copied libraries. (default: ".libs")'),
77 default=".libs",
78 )
79 parser.add_argument(
80 "-w",
81 "--wheel-dir",
82 dest="WHEEL_DIR",
83 type=Path,
84 help=('Directory to store delocated wheels (default: "wheelhouse/")'),
85 default="wheelhouse/",
86 )
87 parser.add_argument(
88 "--no-update-tags",
89 dest="UPDATE_TAGS",
90 action="store_false",
91 help=(
92 "Do not update the wheel filename tags and WHEEL info"
93 " to match the repaired platform tag."
94 ),
95 default=True,
96 )
97 parser.add_argument(
98 "--strip",
99 dest="STRIP",
100 action="store_true",
101 help="Strip symbols in the resulting wheel",
102 default=False,
103 )
104 parser.add_argument(
105 "--exclude",
106 dest="EXCLUDE",
107 help="Exclude SONAME from grafting into the resulting wheel "
108 "Please make sure wheel metadata reflects your dependencies. "
109 "See https://github.com/pypa/auditwheel/pull/411#issuecomment-1500826281 "
110 "(can be specified multiple times) "
111 "(can contain wildcards, for example libfoo.so.*)",
112 action="append",
113 default=[],
114 )
115 parser.add_argument(
116 "--only-plat",
117 dest="ONLY_PLAT",
118 action="store_true",
119 help="Do not check for higher policy compatibility",
120 default=False,
121 )
122 options.disable_isa_check(parser)
123 options.allow_pure_python_wheel(parser)
124 options.ldpaths(parser)
125
126 parser.set_defaults(func=execute)
127
128
129 def execute(args: argparse.Namespace, parser: argparse.ArgumentParser) -> int:
130 from auditwheel.repair import repair_wheel
131 from auditwheel.wheel_abi import analyze_wheel_abi
132
133 exclude: frozenset[str] = frozenset(args.EXCLUDE)
134 wheel_dir: Path = args.WHEEL_DIR.absolute()
135 wheel_files: list[Path] = args.WHEEL_FILE
136
137 requested_architecture: Architecture | None = None
138
139 plat_base: str = args.PLAT
140 for a in Architecture:
141 suffix = f"_{a.value}"
142 if plat_base.endswith(suffix):
143 plat_base = plat_base[: -len(suffix)]
144 requested_architecture = a
145 break
146
147 for wheel_file in wheel_files:
148 if not wheel_file.is_file():
149 parser.error(f"cannot access {wheel_file}. No such file")
150
151 wheel_filename = wheel_file.name
152 arch = requested_architecture
153 is_pure_python = False
154 try:
155 arch = get_wheel_architecture(wheel_filename)
156 if requested_architecture is not None and requested_architecture != arch:
157 msg = (
158 f"can't repair wheel {wheel_filename} with {arch.value} architecture to a "
159 f"wheel targeting {requested_architecture.value}"
160 )
161 parser.error(msg)
162 except (WheelToolsError, NonPlatformWheelError) as e:
163 logger.warning(
164 "The architecture could not be deduced from the wheel filename",
165 )
166 is_pure_python = isinstance(e, NonPlatformWheelError)
167
168 try:
169 libc = get_wheel_libc(wheel_filename)
170 except WheelToolsError:
171 logger.debug("The libc could not be deduced from the wheel filename")
172 libc = None
173
174 for lc in Libc:
175 if plat_base.startswith(lc.tag_prefix):
176 if libc is None:
177 libc = lc
178 if libc != lc:
179 msg = (
180 f"can't repair wheel {wheel_filename} with {libc.name} libc to a wheel "
181 f"targeting {lc.name}"
182 )
183 parser.error(msg)
184
185 logger.info("Repairing %s", wheel_filename)
186
187 if not wheel_dir.exists():
188 wheel_dir.mkdir(parents=True)
189
190 try:
191 wheel_abi = analyze_wheel_abi(
192 libc,
193 arch,
194 wheel_file,
195 exclude,
196 disable_isa_ext_check=args.DISABLE_ISA_EXT_CHECK,
197 allow_graft=True,
198 requested_policy_base_name=plat_base,
199 args_ldpaths=args.LDPATHS,
200 )
201 except NonPlatformWheelError as e:
202 logger.info(e.message)
203 if is_pure_python and args.ALLOW_PURE_PY_WHEEL:
204 dest_fname = wheel_dir / wheel_file.name
205 if not dest_fname.is_file() or not dest_fname.samefile(wheel_file):
206 shutil.copy2(wheel_file, dest_fname)
207 # process next wheel
208 continue
209 return 1
210
211 policies = wheel_abi.policies
212 if plat_base == "auto":
213 if wheel_abi.overall_policy == policies.linux:
214 # we're getting 'linux', override
215 plat = policies.lowest.name
216 else:
217 plat = wheel_abi.overall_policy.name
218 else:
219 plat = f"{plat_base}_{policies.architecture.value}"
220 requested_policy = policies.get_policy_by_name(plat)
221
222 if requested_policy > wheel_abi.sym_policy:
223 msg = (
224 f'cannot repair "{wheel_file}" to "{plat}" ABI because of the '
225 "presence of too-recent versioned symbols. You'll need to compile "
226 "the wheel on an older toolchain."
227 )
228 parser.error(msg)
229
230 if requested_policy > wheel_abi.ucs_policy:
231 msg = (
232 f'cannot repair "{wheel_file}" to "{plat}" ABI because it was '
233 "compiled against a UCS2 build of Python. You'll need to compile "
234 "the wheel against a wide-unicode build of Python."
235 )
236 parser.error(msg)
237
238 if requested_policy > wheel_abi.blacklist_policy:
239 msg = (
240 f'cannot repair "{wheel_file}" to "{plat}" ABI because it '
241 "depends on black-listed symbols."
242 )
243 parser.error(msg)
244
245 if requested_policy > wheel_abi.machine_policy:
246 msg = (
247 f'cannot repair "{wheel_file}" to "{plat}" ABI because it '
248 "depends on unsupported ISA extensions."
249 )
250 parser.error(msg)
251
252 abis = [requested_policy.name, *requested_policy.aliases]
253 if (not args.ONLY_PLAT) and requested_policy < wheel_abi.overall_policy:
254 logger.info(
255 (
256 "Wheel is eligible for a higher priority tag. "
257 "You requested %s but I have found this wheel is "
258 "eligible for %s."
259 ),
260 plat,
261 wheel_abi.overall_policy.name,
262 )
263 abis = [
264 wheel_abi.overall_policy.name,
265 *wheel_abi.overall_policy.aliases,
266 *abis,
267 ]
268
269 patcher = Patchelf(requested_policy.name)
270 out_wheel = repair_wheel(
271 wheel_abi,
272 wheel_file,
273 abis=abis,
274 lib_sdir=args.LIB_SDIR,
275 out_dir=wheel_dir,
276 update_tags=args.UPDATE_TAGS,
277 patcher=patcher,
278 strip=args.STRIP,
279 zip_compression_level=args.ZIP_COMPRESSION_LEVEL,
280 )
281
282 if out_wheel is not None:
283 logger.info("\nFixed-up wheel written to %s", out_wheel)
284 return 0