| 1 |
g> |
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
import logging |
| 22 |
from collections.abc import Callable |
| 23 |
from functools import wraps |
| 24 |
from glob import glob1 |
| 25 |
from os import environ, remove, walk, makedirs |
| 26 |
from os.path import exists, isdir, join |
| 27 |
from pathlib import Path |
| 28 |
from shutil import rmtree, copyfile, copytree, which |
| 29 |
from typing import ( |
| 30 |
TYPE_CHECKING, |
| 31 |
ClassVar, |
| 32 |
Concatenate, |
| 33 |
Literal, |
| 34 |
ParamSpec, |
| 35 |
TypeVar, |
| 36 |
cast, |
| 37 |
overload, |
| 38 |
) |
| 39 |
|
| 40 |
from dhpython import CACHE_DIRECTORIES |
| 41 |
from dhpython.debhelper import DebHelper, build_options |
| 42 |
from dhpython.exceptions import RequiredCommandMissingException |
| 43 |
from dhpython.tools import execute, ExecutionResult, ExecutionResultWithOutput |
| 44 |
from dhpython.build.options import PybuildOptions |
| 45 |
from dhpython.build.types import Args, Context |
| 46 |
|
| 47 |
if TYPE_CHECKING: |
| 48 |
from functools import _Wrapped |
| 49 |
|
| 50 |
log = logging.getLogger('dhpython') |
| 51 |
|
| 52 |
P = ParamSpec('P') |
| 53 |
T = TypeVar('T') |
| 54 |
BC = TypeVar('BC', bound="Base") |
| 55 |
|
| 56 |
def copy_test_files( |
| 57 |
dest: str = '{build_dir}', |
| 58 |
filelist: str = '{home_dir}/testfiles_to_rm_before_install', |
| 59 |
add_to_args: tuple[str, ...] = ('test', 'tests') |
| 60 |
) -> Callable[ |
| 61 |
[Callable[Concatenate[BC, Context, Args, P], T]], |
| 62 |
Callable[Concatenate[BC, Context, Args, P], T], |
| 63 |
]: |
| 64 |
|
| 65 |
def _copy_test_files( |
| 66 |
func: Callable[Concatenate[BC, Context, Args, P], T], / |
| 67 |
) -> "_Wrapped[Concatenate[BC, Context, Args, P], T, Concatenate[BC, Context, Args, P], T]": |
| 68 |
|
| 69 |
@wraps(func) |
| 70 |
def __copy_test_files( |
| 71 |
self: BC, |
| 72 |
context: Context, |
| 73 |
args: Args, |
| 74 |
*oargs: P.args, |
| 75 |
**kwargs: P.kwargs |
| 76 |
) -> T: |
| 77 |
files_to_copy = {'pyproject.toml', 'pytest.ini', 'test', 'tests'} |
| 78 |
|
| 79 |
for tpl in ('_{i}{v}', '_{i}{m}', ''): |
| 80 |
tpl = tpl.format(i=args.interpreter.name, |
| 81 |
v=args.version, |
| 82 |
m=args.version.major) |
| 83 |
fpath = join(args.dir, f'debian/pybuild{tpl}.testfiles') |
| 84 |
if exists(fpath): |
| 85 |
with open(fpath, encoding='utf-8') as fp: |
| 86 |
|
| 87 |
files_to_copy = set() |
| 88 |
for line in fp.readlines(): |
| 89 |
line = line.strip() |
| 90 |
if line.startswith('#'): |
| 91 |
continue |
| 92 |
if not line: |
| 93 |
continue |
| 94 |
files_to_copy.add(line) |
| 95 |
break |
| 96 |
|
| 97 |
files_to_remove = set() |
| 98 |
for entry in files_to_copy: |
| 99 |
name, *rest = entry.split(maxsplit=1) |
| 100 |
dest_suffix = rest[0] if rest else "" |
| 101 |
if not dest_suffix or dest_suffix.endswith('/'): |
| 102 |
dest_suffix = join(dest_suffix, name.rsplit('/', 1)[-1]) |
| 103 |
|
| 104 |
src_dpath = join(args.dir, name) |
| 105 |
dst_dpath = join(args.format(dest), dest_suffix) |
| 106 |
if exists(src_dpath): |
| 107 |
if not exists(dst_dpath): |
| 108 |
log.debug("Copying %s to %s for tests", src_dpath, dst_dpath) |
| 109 |
makedirs(dst_dpath.rsplit('/', 1)[0], exist_ok=True) |
| 110 |
if isdir(src_dpath): |
| 111 |
copytree(src_dpath, dst_dpath) |
| 112 |
else: |
| 113 |
copyfile(src_dpath, dst_dpath) |
| 114 |
files_to_remove.add(dst_dpath + '\n') |
| 115 |
if not args.args and 'PYBUILD_TEST_ARGS' not in context.ENV\ |
| 116 |
and (self.cfg.test_pytest or self.cfg.test_nose) \ |
| 117 |
and name in add_to_args: |
| 118 |
args.args = name |
| 119 |
if files_to_remove and filelist: |
| 120 |
with open(args.format(filelist), 'a', encoding="UTF-8") as fp: |
| 121 |
fp.writelines(files_to_remove) |
| 122 |
|
| 123 |
return func(self, context, args, *oargs, **kwargs) |
| 124 |
return __copy_test_files |
| 125 |
return _copy_test_files |
| 126 |
|
| 127 |
|
| 128 |
class Base: |
| 129 |
"""Base class for build system plugins |
| 130 |
|
| 131 |
:attr REQUIRED_COMMANDS: list of command checked by default in :meth:is_usable, |
| 132 |
if one of them is missing, plugin cannot be used. |
| 133 |
:type REQUIRED_COMMANDS: list of strings |
| 134 |
:attr REQUIRED_FILES: list of files (or glob templates) required by given |
| 135 |
build system |
| 136 |
:attr OPTIONAL_FILES: dictionary of glob templates (key) and score (value) |
| 137 |
used to detect if given plugin is the best one for the job |
| 138 |
:type OPTIONAL_FILES: dict (key is a string, value is an int) |
| 139 |
:attr SUPPORTED_INTERPRETERS: set of interpreter templates (with or without |
| 140 |
{version}) supported by given plugin |
| 141 |
""" |
| 142 |
cfg: PybuildOptions |
| 143 |
NAME: ClassVar[str] |
| 144 |
DESCRIPTION = '' |
| 145 |
REQUIRED_COMMANDS: list[str] = [] |
| 146 |
REQUIRED_FILES: list[str] = [] |
| 147 |
DETECTED_REQUIRED_FILES: dict[str, list[str]] |
| 148 |
OPTIONAL_FILES: dict[str, int] = {} |
| 149 |
DETECTED_OPTIONAL_FILES: dict[str, list[str]] |
| 150 |
SUPPORTED_INTERPRETERS: Literal[True] | set[str] = { |
| 151 |
'python', 'python3', 'python-dbg', 'python3-dbg', |
| 152 |
'python{version}', 'python{version}-dbg' |
| 153 |
} |
| 154 |
|
| 155 |
CLEAN_FILES = CACHE_DIRECTORIES |
| 156 |
|
| 157 |
def __init__(self, cfg: PybuildOptions) -> None: |
| 158 |
self.cfg = cfg |
| 159 |
|
| 160 |
def __repr__(self) -> str: |
| 161 |
return "BuildSystem(%s)" % self.NAME |
| 162 |
|
| 163 |
@classmethod |
| 164 |
def is_usable(cls) -> None: |
| 165 |
for command in cls.REQUIRED_COMMANDS: |
| 166 |
pth = which(command) |
| 167 |
if not pth: |
| 168 |
raise RequiredCommandMissingException(command) |
| 169 |
|
| 170 |
def detect(self, context: Context) -> int: |
| 171 |
"""Return certainty level that this plugin describes the right build system |
| 172 |
|
| 173 |
This method is using cls.{REQUIRED,OPTIONAL}_FILES only by default, |
| 174 |
please extend it in the plugin if more sofisticated methods can be used |
| 175 |
for given build system. |
| 176 |
|
| 177 |
:return: 0 <= certainty <= 100 |
| 178 |
:rtype: int |
| 179 |
""" |
| 180 |
result = 0 |
| 181 |
|
| 182 |
required_files_num = 0 |
| 183 |
self.DETECTED_REQUIRED_FILES = {} |
| 184 |
for tpl in self.REQUIRED_FILES: |
| 185 |
found = False |
| 186 |
for ftpl in tpl.split('|'): |
| 187 |
res = glob1(context.dir, ftpl) |
| 188 |
if res: |
| 189 |
found = True |
| 190 |
self.DETECTED_REQUIRED_FILES.setdefault(tpl, []).extend(res) |
| 191 |
if found: |
| 192 |
required_files_num += 1 |
| 193 |
|
| 194 |
if self.REQUIRED_FILES: |
| 195 |
result += int(required_files_num / len(self.REQUIRED_FILES) * 50) |
| 196 |
|
| 197 |
self.DETECTED_OPTIONAL_FILES = {} |
| 198 |
for ftpl, score in self.OPTIONAL_FILES.items(): |
| 199 |
res = glob1(context.dir, ftpl) |
| 200 |
if res: |
| 201 |
result += score |
| 202 |
self.DETECTED_OPTIONAL_FILES.setdefault(ftpl, []).extend(res) |
| 203 |
if result > 100: |
| 204 |
return 100 |
| 205 |
return result |
| 206 |
|
| 207 |
def clean(self, context: Context, args: Args) -> None: |
| 208 |
tox_dir = join(args.dir, '.tox') |
| 209 |
if isdir(tox_dir): |
| 210 |
try: |
| 211 |
rmtree(tox_dir) |
| 212 |
except Exception: |
| 213 |
log.debug('cannot remove %s', tox_dir) |
| 214 |
|
| 215 |
for fn in self.CLEAN_FILES: |
| 216 |
path = join(context.dir, fn) |
| 217 |
if isdir(path): |
| 218 |
try: |
| 219 |
rmtree(path) |
| 220 |
except Exception: |
| 221 |
log.debug('cannot remove %s', path) |
| 222 |
elif exists(path): |
| 223 |
try: |
| 224 |
remove(path) |
| 225 |
except Exception: |
| 226 |
log.debug('cannot remove %s', path) |
| 227 |
|
| 228 |
dh = DebHelper(build_options()) |
| 229 |
|
| 230 |
clean_sources_txt = not { |
| 231 |
'python3-setuptools-scm', 'python3-setuptools-git' |
| 232 |
}.intersection(set(dh.build_depends)) |
| 233 |
|
| 234 |
for root, dirs, file_names in walk(context.dir): |
| 235 |
for name in dirs[:]: |
| 236 |
if name == '__pycache__' or ( |
| 237 |
clean_sources_txt and name.endswith('.egg-info')): |
| 238 |
dpath = join(root, name) |
| 239 |
log.debug('removing dir: %s', dpath) |
| 240 |
try: |
| 241 |
rmtree(dpath) |
| 242 |
except Exception: |
| 243 |
log.debug('cannot remove %s', dpath) |
| 244 |
else: |
| 245 |
dirs.remove(name) |
| 246 |
for fn in file_names: |
| 247 |
if fn.endswith(('.pyc', '.pyo')): |
| 248 |
fpath = join(root, fn) |
| 249 |
log.debug('removing: %s', fpath) |
| 250 |
try: |
| 251 |
remove(fpath) |
| 252 |
except Exception: |
| 253 |
log.debug('cannot remove %s', fpath) |
| 254 |
if root.endswith('.egg-info'): |
| 255 |
for fn in file_names: |
| 256 |
if fn != 'SOURCES.txt': |
| 257 |
fpath = join(root, fn) |
| 258 |
log.debug('removing: %s', fpath) |
| 259 |
try: |
| 260 |
remove(fpath) |
| 261 |
except Exception: |
| 262 |
log.debug('cannot remove %s', fpath) |
| 263 |
|
| 264 |
def configure(self, context: Context, args: Args) -> None: |
| 265 |
raise NotImplementedError("configure method not implemented in %s" % self.NAME) |
| 266 |
|
| 267 |
def install(self, context: Context, args: Args) -> None: |
| 268 |
raise NotImplementedError("install method not implemented in %s" % self.NAME) |
| 269 |
|
| 270 |
def build(self, context: Context, args: Args) -> None: |
| 271 |
raise NotImplementedError("build method not implemented in %s" % self.NAME) |
| 272 |
|
| 273 |
def test(self, context: Context, args: Args) -> None: |
| 274 |
raise NotImplementedError("test method not implemented in %s" % self.NAME) |
| 275 |
|
| 276 |
@copy_test_files() |
| 277 |
def test_cmd(self, context: Context, args: Args) -> str: |
| 278 |
if self.cfg.test_nose2: |
| 279 |
return 'cd {build_dir}; {interpreter} -m nose2 -v {args}' |
| 280 |
elif self.cfg.test_nose: |
| 281 |
return 'cd {build_dir}; {interpreter} -m nose -v {args}' |
| 282 |
elif self.cfg.test_pytest: |
| 283 |
return 'cd {build_dir}; {interpreter} -m pytest {args}' |
| 284 |
elif self.cfg.test_tox: |
| 285 |
tox_config = None |
| 286 |
if exists(join(args.dir, 'tox.ini')): |
| 287 |
tox_config = '{dir}/tox.ini' |
| 288 |
elif exists(join(args.dir, 'pyproject.toml')): |
| 289 |
tox_config = '{dir}/pyproject.toml' |
| 290 |
elif exists(join(args.dir, 'setup.cfg')): |
| 291 |
tox_config = '{dir}/setup.cfg' |
| 292 |
else: |
| 293 |
raise Exception("tox config not found. " |
| 294 |
"Expected to find tox.ini, pyproject.toml, or setup.cfg") |
| 295 |
|
| 296 |
tox_cmd = ['cd {build_dir};', |
| 297 |
'tox', |
| 298 |
'-c', tox_config, |
| 299 |
'--sitepackages', |
| 300 |
'-e', 'py{version.major}{version.minor}', |
| 301 |
'-x', 'testenv.passenv+=_PYTHON_HOST_PLATFORM', |
| 302 |
] |
| 303 |
if args.autopkgtest: |
| 304 |
tox_cmd += ['--skip-pkg-install'] |
| 305 |
|
| 306 |
if not args.autopkgtest: |
| 307 |
wheel = self.built_wheel(context, args) |
| 308 |
if not wheel: |
| 309 |
self.build_wheel(context, args) |
| 310 |
wheel = self.built_wheel(context, args) |
| 311 |
assert wheel |
| 312 |
args.wheel = wheel |
| 313 |
tox_cmd += ['--installpkg', '{wheel}'] |
| 314 |
|
| 315 |
tox_cmd.append('{args}') |
| 316 |
return ' '.join(tox_cmd) |
| 317 |
elif self.cfg.test_stestr: |
| 318 |
return ( |
| 319 |
'cd {build_dir};' |
| 320 |
'stestr --config {dir}/.stestr.conf init;' |
| 321 |
'PYTHON=python{version} stestr --config {dir}/.stestr.conf run' |
| 322 |
) |
| 323 |
elif self.cfg.test_unittest: |
| 324 |
return 'cd {build_dir}; {interpreter} -m unittest discover -v {args}' |
| 325 |
elif self.cfg.test_custom: |
| 326 |
return 'cd {build_dir}; {args}' |
| 327 |
else: |
| 328 |
log.warning( |
| 329 |
"No test runner selected, defaulting to unittest, ignoring " |
| 330 |
"test discovery problems.\nUse --test-unittest to explicitly " |
| 331 |
"select the unittest runner.") |
| 332 |
|
| 333 |
args.ignore_no_tests = True |
| 334 |
return 'cd {build_dir}; {interpreter} -m unittest discover -v {args}' |
| 335 |
|
| 336 |
def build_wheel(self, context: Context, args: Args) -> None: |
| 337 |
raise NotImplementedError("build_wheel method not implemented in %s" % self.NAME) |
| 338 |
|
| 339 |
def built_wheel(self, context: Context, args: Args) -> str | None: |
| 340 |
"""Return the path to any built wheels we can find""" |
| 341 |
|
| 342 |
wheels = list(Path(args.home_dir).glob('*.whl')) |
| 343 |
n_wheels = len(wheels) |
| 344 |
if n_wheels > 1: |
| 345 |
raise Exception(f"Expecting to have built exactly 1 wheel, but found {n_wheels}") |
| 346 |
if n_wheels == 1: |
| 347 |
return str(wheels[0]) |
| 348 |
return None |
| 349 |
|
| 350 |
@overload |
| 351 |
def execute( |
| 352 |
self, |
| 353 |
context: Context, |
| 354 |
args: Args, |
| 355 |
command: str, |
| 356 |
*, |
| 357 |
log_file: None = None, |
| 358 |
) -> ExecutionResultWithOutput: |
| 359 |
... |
| 360 |
|
| 361 |
@overload |
| 362 |
def execute( |
| 363 |
self, |
| 364 |
context: Context, |
| 365 |
args: Args, |
| 366 |
command: str, |
| 367 |
*, |
| 368 |
log_file: str | Literal[False], |
| 369 |
) -> ExecutionResult: |
| 370 |
... |
| 371 |
|
| 372 |
def execute( |
| 373 |
self, |
| 374 |
context: Context, |
| 375 |
args: Args, |
| 376 |
command: str, |
| 377 |
*, |
| 378 |
log_file: str | Literal[False] | None = None |
| 379 |
) -> ExecutionResult | ExecutionResultWithOutput: |
| 380 |
if log_file is False and self.cfg.really_quiet: |
| 381 |
log_file = None |
| 382 |
command = args.format(command) |
| 383 |
env = dict(context.ENV) |
| 384 |
env.update(args.ENV) |
| 385 |
log.info(command) |
| 386 |
return execute(command, cwd=context.dir, env=env, log_output=log_file) |
| 387 |
|
| 388 |
def print_args(self, context: Context, args: Args) -> None: |
| 389 |
|
| 390 |
cfg = self.cfg |
| 391 |
if len(cfg.print_args) == 1 and len(cfg.interpreter) == 1 and '{version}' not in cfg.interpreter[0]: |
| 392 |
i = cfg.print_args[0] |
| 393 |
if '{' in i: |
| 394 |
print(args.format(i)) |
| 395 |
else: |
| 396 |
print(args.as_dict().get(i, '')) |
| 397 |
else: |
| 398 |
for i in cfg.print_args: |
| 399 |
if '{' in i: |
| 400 |
print(args.format(i)) |
| 401 |
else: |
| 402 |
print('{} {}: {}'.format(args.interpreter, i, args.as_dict().get(i, ''))) |
| 403 |
|
| 404 |
|
| 405 |
def shell_command( |
| 406 |
func: Callable[Concatenate[BC, Context, Args, P], str | Literal[0]], / |
| 407 |
) -> Callable[Concatenate[BC, Context, Args, P], None]: |
| 408 |
|
| 409 |
@wraps(func) |
| 410 |
def wrapped_func( |
| 411 |
self: BC, |
| 412 |
context: Context, |
| 413 |
args: Args, |
| 414 |
*oargs: P.args, |
| 415 |
**kwargs: P.kwargs, |
| 416 |
) -> None: |
| 417 |
command = kwargs.pop('command', None) |
| 418 |
if not command: |
| 419 |
command = func(self, context, args, *oargs, **kwargs) |
| 420 |
if isinstance(command, int): |
| 421 |
return |
| 422 |
assert isinstance(command, str) |
| 423 |
if not command: |
| 424 |
log.warning('missing command ' |
| 425 |
'(plugin=%s, method=%s, interpreter=%s, version=%s)', |
| 426 |
self.NAME, func.__name__, |
| 427 |
args.interpreter, args.version) |
| 428 |
return |
| 429 |
|
| 430 |
log_file: str | Literal[False] |
| 431 |
if self.cfg.quiet: |
| 432 |
log_file = join(args.home_dir, f'{func.__name__}_cmd.log') |
| 433 |
else: |
| 434 |
log_file = False |
| 435 |
|
| 436 |
command = args.format_quoted(command) |
| 437 |
|
| 438 |
output = self.execute(context, args, command=command, log_file=log_file) |
| 439 |
if output.returncode == 5 and args.ignore_no_tests: |
| 440 |
|
| 441 |
pass |
| 442 |
elif output.returncode != 0: |
| 443 |
msg = f'exit code={output.returncode}: {command}' |
| 444 |
if log_file: |
| 445 |
msg += f'\nfull command log is available in {log_file}' |
| 446 |
raise Exception(msg) |
| 447 |
|
| 448 |
|
| 449 |
return cast(Callable[Concatenate[BC, Context, Args, P], None], wrapped_func) |
| 450 |
|
| 451 |
|
| 452 |
def create_setuptools_parallel_cfg( |
| 453 |
backend: Callable[[], str | None] | None = None |
| 454 |
) -> Callable[ |
| 455 |
[Callable[Concatenate[BC, Context, Args, P], T]], |
| 456 |
Callable[Concatenate[BC, Context, Args, P], T], |
| 457 |
]: |
| 458 |
"""Enable parallel building of extensions |
| 459 |
|
| 460 |
An adaption of Michał Górny's technique described in |
| 461 |
https://blogs.gentoo.org/mgorny/2024/03/15/optimizing-parallel-extension-builds-in-pep517-builds |
| 462 |
|
| 463 |
This function is not part of :pyfunc:`create_pydistutils_cfg` as that |
| 464 |
function is not used for `build_wheel`, which is our target. |
| 465 |
|
| 466 |
For PEP-517 (pyproject) builds we can not yet use PEP-517 Config Settings |
| 467 |
as we need to pass the parallel building option to `build_ext` and |
| 468 |
setuptools (as of version 80.9.0) does not have a way to redirect PEP-517 |
| 469 |
Config Settings to specific commands. Setuptools only passes PEP-517 Config |
| 470 |
Settings to all commands via `--global-option` and to `build_wheel` with |
| 471 |
`--build-option`. |
| 472 |
See https://github.com/pypa/setuptools/blob/d198e86f57231e83de87975c5c82bc40c196da79/setuptools/build_meta.py |
| 473 |
and https://github.com/pypa/setuptools/discussions/4083 |
| 474 |
""" |
| 475 |
def decorator( |
| 476 |
func: Callable[Concatenate[BC, Context, Args, P], T], / |
| 477 |
) -> Callable[Concatenate[BC, Context, Args, P], T]: |
| 478 |
@wraps(func) |
| 479 |
def wrapped_func( |
| 480 |
self: BC, |
| 481 |
context: Context, |
| 482 |
args: Args, |
| 483 |
*oargs: P.args, |
| 484 |
**kwargs: P.kwargs, |
| 485 |
) -> T: |
| 486 |
fpath = join(args.home_dir, 'setuptools-build_ext-parallel.cfg') |
| 487 |
if not exists(fpath): |
| 488 |
with open(fpath, 'w', encoding='utf-8') as fp: |
| 489 |
lines = ['[build_ext]\n', |
| 490 |
f'parallel={args.parallel}\n'] |
| 491 |
log.debug('parallel build extension config file:\n%s', ''.join(lines)) |
| 492 |
fp.writelines(lines) |
| 493 |
context.ENV['DIST_EXTRA_CONFIG'] = fpath |
| 494 |
return func(self, context, args, *oargs, **kwargs) |
| 495 |
|
| 496 |
if 'DIST_EXTRA_CONFIG' in environ: |
| 497 |
return func |
| 498 |
|
| 499 |
if backend is not None: |
| 500 |
pyproject_backend = backend() |
| 501 |
if pyproject_backend is not None and pyproject_backend != "setuptools.build_meta": |
| 502 |
return func |
| 503 |
|
| 504 |
return cast(Callable[Concatenate[BC, Context, Args, P], T], wrapped_func) |
| 505 |
return decorator |