Debian Codegraph @

pybuild

raw symbols SCIP
1 #! /usr/bin/python3
2 # vim: et ts=4 sw=4
3 # Copyright © 2012-2013 Piotr Ożarowski <[email protected]g>
4 #
5 # Permission is hereby granted, free of charge, to any person obtaining a copy
6 # of this software and associated documentation files (the "Software"), to deal
7 # in the Software without restriction, including without limitation the rights
8 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 # copies of the Software, and to permit persons to whom the Software is
10 # furnished to do so, subject to the following conditions:
11 #
12 # The above copyright notice and this permission notice shall be included in
13 # all copies or substantial portions of the Software.
14 #
15 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 # THE SOFTWARE.
22
23 import logging
24 import re
25 import sys
26 from collections.abc import Callable
27 from enum import StrEnum, auto
28 from os import environ, makedirs, remove
29 from os.path import abspath, exists, isdir, join
30 from shutil import rmtree
31 from tempfile import mkdtemp
32 from typing import Literal, overload
33
34 from dhpython import build, PKG_PREFIX_MAP
35 from dhpython.build.options import (
36 DEFAULT_INSTALL_DIR,
37 PybuildOptions,
38 build_parser,
39 )
40 from dhpython.build.types import Args, Context
41 from dhpython.debhelper import DebHelper, build_options
42 from dhpython.version import Version, build_sorted, get_requested_versions
43 from dhpython.interpreter import Interpreter
44 from dhpython.tools import dpkg_architecture, execute, move_matching_files
45
46 INTERP_VERSION_RE = re.compile(r"^python(?P<version>3\.\d+)(?P<dbg>-dbg)?$")
47 logging.basicConfig(
48 format="%(levelname).1s: pybuild " "%(module)s:%(lineno)d: %(message)s"
49 )
50 log = logging.getLogger("dhpython")
51
52
53 def main(cfg: PybuildOptions) -> None:
54 log.debug("cfg: %s", cfg)
55
56 if cfg.list_systems:
57 for name, Plugin in sorted(build.plugins.items()):
58 print(name, "\t", Plugin.DESCRIPTION)
59 sys.exit(0)
60
61 nocheck = False
62 if "DEB_BUILD_OPTIONS" in environ:
63 nocheck = "nocheck" in environ["DEB_BUILD_OPTIONS"].split()
64 if not nocheck and "DEB_BUILD_PROFILES" in environ:
65 nocheck = "nocheck" in environ["DEB_BUILD_PROFILES"].split()
66
67 env = environ.copy()
68 # set some defaults in environ to make the build reproducible
69 env.setdefault("LC_ALL", "C.UTF-8")
70 env.setdefault("CCACHE_DIR", abspath(".pybuild/ccache"))
71 env.setdefault("no_proxy", "localhost")
72 if "http_proxy" not in env:
73 env["http_proxy"] = "http://127.0.0.1:9/"
74 elif not env["http_proxy"]:
75 del env["http_proxy"] # some tools don't like empty var.
76 if "https_proxy" not in env:
77 env["https_proxy"] = "https://127.0.0.1:9/"
78 elif not env["https_proxy"]:
79 del env["https_proxy"] # some tools don't like empty var.
80 if "DEB_PYTHON_INSTALL_LAYOUT" not in env:
81 env["DEB_PYTHON_INSTALL_LAYOUT"] = "deb"
82
83 arch_data = dpkg_architecture()
84 if arch_data:
85 # Set _PYTHON_HOST_PLATFORM to ensure debugging symbols on, f.e. i386
86 # emded a constant name regardless of the 32/64-bit kernel.
87 special_cases = {
88 "arm-linux-gnueabihf": "linux-armv7l",
89 "mips64el-linux-gnuabi64": "linux-mips64",
90 "mipsel-linux-gnu": "linux-mips",
91 "powerpc64-linux-gnu": "linux-ppc64",
92 "powerpc64le-linux-gnu": "linux-ppc64le",
93 }
94 host_platform = special_cases.get(
95 arch_data["DEB_HOST_MULTIARCH"],
96 "{DEB_HOST_ARCH_OS}-{DEB_HOST_GNU_CPU}".format(**arch_data),
97 )
98 env.setdefault("_PYTHON_HOST_PLATFORM", host_platform)
99
100 if arch_data["DEB_BUILD_ARCH"] != arch_data["DEB_HOST_ARCH"]:
101 # support cross compiling Python 3.X extensions, see #892931
102 env.setdefault(
103 "_PYTHON_SYSCONFIGDATA_NAME",
104 "_sysconfigdata__" + arch_data["DEB_HOST_MULTIARCH"],
105 )
106
107 # Selected on command line?
108 selected_plugin = cfg.system
109
110 # Selected by build_dep?
111 if not selected_plugin:
112 dh = DebHelper(build_options())
113 for build_dep in dh.build_depends:
114 if build_dep.startswith("pybuild-plugin-"):
115 selected_plugin = build_dep.split("-", 2)[2]
116 break
117
118 if selected_plugin:
119 certainty = 99
120 Plugin = build.plugins.get(selected_plugin)
121 if not Plugin:
122 log.error("unrecognized build system: %s", selected_plugin)
123 sys.exit(10)
124 plugin = Plugin(cfg)
125 context = Context(ENV=env, destdir="debian/tmp", dir=cfg.dir)
126 plugin.detect(context)
127 else:
128 plugin, certainty = None, 0
129 for Plugin in build.plugins.values():
130 try:
131 tmp_plugin = Plugin(cfg)
132 except Exception as err:
133 log.warning(
134 "cannot initialize %s plugin: %s",
135 Plugin.NAME,
136 err,
137 exc_info=cfg.verbose,
138 )
139 continue
140 tmp_context = Context(ENV=env, destdir="debian/tmp", dir=cfg.dir)
141 tmp_certainty = tmp_plugin.detect(tmp_context)
142 log.debug("Plugin %s: certainty %i", Plugin.NAME, tmp_certainty)
143 if tmp_certainty and tmp_certainty > certainty:
144 plugin, certainty, context = tmp_plugin, tmp_certainty, tmp_context
145 del Plugin
146 if not plugin:
147 log.error(
148 "cannot detect build system, please use --system option"
149 " or set PYBUILD_SYSTEM env. variable"
150 )
151 sys.exit(11)
152
153 if plugin.SUPPORTED_INTERPRETERS is not True:
154 # if versioned interpreter was requested and selected plugin lists
155 # versioned ones as supported: extend list of supported interpreters
156 # with this interpreter
157 tpls = {i for i in plugin.SUPPORTED_INTERPRETERS if "{version}" in i}
158 if tpls:
159 for interpreter in cfg.interpreter:
160 m = INTERP_VERSION_RE.match(interpreter)
161 if m:
162 ver = m.group("version")
163 updated = {tpl.format(version=ver) for tpl in tpls}
164 if updated:
165 plugin.SUPPORTED_INTERPRETERS.update(updated)
166
167 for interpreter in cfg.interpreter:
168 if (
169 plugin.SUPPORTED_INTERPRETERS is not True
170 and interpreter not in plugin.SUPPORTED_INTERPRETERS
171 ):
172 log.error("interpreter %s not supported by %s", interpreter, plugin)
173 sys.exit(12)
174 log.debug("detected build system: %s (certainty: %s%%)", plugin.NAME, certainty)
175
176 if cfg.detect_only:
177 if not cfg.really_quiet:
178 print(plugin.NAME)
179 sys.exit(0)
180
181 versions = cfg.versions
182 if not versions:
183 if len(cfg.interpreter) == 1:
184 i = cfg.interpreter[0]
185 m = INTERP_VERSION_RE.match(i)
186 if m:
187 log.debug("defaulting to version hardcoded in interpreter name")
188 versions = [Version(m.group("version"))]
189 else:
190 IMAP = {v: k for k, v in PKG_PREFIX_MAP.items()}
191 if i in IMAP:
192 versions = build_sorted(
193 get_requested_versions(IMAP[i], available=True), impl=IMAP[i]
194 )
195 if versions and "{version}" not in i:
196 versions = versions[-1:] # last one, the default one
197 if not versions: # still no luck
198 log.debug("defaulting to all supported Python 3.X versions")
199 versions = build_sorted(
200 get_requested_versions("cpython3", available=True), impl="cpython3"
201 )
202
203 @overload
204 def get_option(
205 name: str,
206 interpreter: str | None,
207 version: Version | None,
208 default: str,
209 ) -> str: ...
210
211 @overload
212 def get_option(
213 name: str,
214 interpreter: str | None = None,
215 version: Version | None = None,
216 default: None = None,
217 ) -> str | None: ...
218
219 def get_option(
220 name: str,
221 interpreter: str | None = None,
222 version: Version | None = None,
223 default: str | None = None,
224 ) -> str | None:
225 if interpreter:
226 # try PYBUILD_NAME_python3.3-dbg (or hardcoded interpreter)
227 i = interpreter.format(version=version or "")
228 opt = f"PYBUILD_{name.upper()}_{i}"
229 if opt in environ:
230 return environ[opt]
231 # try PYBUILD_NAME_python3-dbg (if not checked above)
232 if "{version}" in interpreter and version:
233 i = interpreter.format(version=version.major)
234 opt = f"PYBUILD_{name.upper()}_{i}"
235 if opt in environ:
236 return environ[opt]
237 # try PYBUILD_NAME
238 opt = f"PYBUILD_{name.upper()}"
239 if opt in environ:
240 return environ[opt]
241 # try command line args
242 return getattr(cfg, name, default) or default
243
244 class Step(StrEnum):
245 CLEAN = auto()
246 CONFIGURE = auto()
247 BUILD = auto()
248 INSTALL = auto()
249 TEST = auto()
250 AUTOPKGTEST = auto()
251 PRINT_ARGS = auto()
252
253 def get_args(
254 context: Context,
255 step: Step,
256 version: Version,
257 interpreter: str,
258 ) -> Args:
259 i = interpreter.format(version=version)
260 ipreter = Interpreter(i)
261
262 home_dirs = [ipreter.impl, str(version)]
263 if ipreter.debug:
264 home_dirs.append("dbg")
265 if cfg.name:
266 home_dirs.append(cfg.name)
267 if cfg.autopkgtest_only:
268 base_dir = environ.get("AUTOPKGTEST_TMP")
269 if not base_dir:
270 base_dir = mkdtemp(prefix="pybuild-autopkgtest-")
271 else:
272 base_dir = ".pybuild/{}"
273 home_dir = base_dir.format("_".join(home_dirs))
274
275 build_dir = get_option(
276 "build_dir", interpreter, version, default=join(home_dir, "build")
277 )
278
279 destdir = context.destdir.format(version=version, interpreter=i)
280 if cfg.name:
281 package = ipreter.suggest_pkg_name(cfg.name)
282 else:
283 package = "PYBUILD_NAME_not_set"
284 if cfg.name and get_option("destdir", interpreter, version) is None:
285 destdir = f"debian/{package}"
286 destdir = abspath(destdir)
287 parallel = cfg.parallel
288
289 args = Args(
290 ENV={},
291 autopkgtest=cfg.autopkgtest_only,
292 package=package,
293 interpreter=ipreter,
294 version=version,
295 args=get_option("%s_args" % step, interpreter, version, ""),
296 dir=abspath(context.dir.format(version=version, interpreter=i)),
297 destdir=destdir,
298 build_dir=abspath(build_dir.format(version=version, interpreter=i)),
299 # versioned dist-packages even for Python 3.X - dh_python3 will fix it later
300 # (and will have a chance to compare files)
301 install_dir=get_option(
302 "install_dir",
303 interpreter,
304 version,
305 DEFAULT_INSTALL_DIR,
306 ).format(version=version, interpreter=i),
307 home_dir=abspath(home_dir),
308 parallel=parallel,
309 )
310 for k, v in context.args.items():
311 setattr(args, k, v)
312 pp_str = args.ENV.get("PYTHONPATH", context.ENV.get("PYTHONPATH"))
313 pp = pp_str.split(":") if pp_str else []
314 if step in {"build", "test", "autopkgtest"}:
315 if step in {"test", "autopkgtest"}:
316 args.test_dir = join(args.destdir, args.install_dir.lstrip("/"))
317 if args.test_dir not in pp:
318 pp.append(args.test_dir)
319 if args.build_dir not in pp:
320 pp.append(args.build_dir)
321 # cross compilation support for Python 2.x
322 if version.major == 2 and arch_data.get("DEB_BUILD_ARCH") != arch_data.get(
323 "DEB_HOST_ARCH"
324 ):
325 pp.insert(
326 0,
327 ("/usr/lib/python{}/plat-{}").format(
328 version, arch_data["DEB_HOST_MULTIARCH"]
329 ),
330 )
331 args.ENV["PYTHONPATH"] = ":".join(pp)
332 # cross compilation support for Python <= 3.8 (see above)
333 if version.major == 3:
334 name = "_PYTHON_SYSCONFIGDATA_NAME"
335 value = args.ENV.get(name, context.ENV.get(name, ""))
336 if (
337 version << "3.8"
338 and value.startswith("_sysconfigdata_")
339 and not value.startswith("_sysconfigdata_m")
340 ):
341 value = args.ENV[name] = "_sysconfigdata_m%s" % value[15:]
342 # update default from main() for -dbg interpreter
343 if value and ipreter.debug and not value.startswith("_sysconfigdata_d"):
344 args.ENV[name] = "_sysconfigdata_d%s" % value[15:]
345
346 if not exists(args.build_dir):
347 makedirs(args.build_dir)
348
349 return args
350
351 def is_disabled(step: Step, interpreter: str, version: Version) -> bool:
352 i = interpreter
353 prefix = f"{step}/"
354 disabled = (get_option("disable", i, version) or "").split()
355 for item in disabled:
356 if item in (step, "1"):
357 log.debug("disabling %s step for %s %s", step, i, version)
358 return True
359 if item.startswith(prefix):
360 disabled.append(item[len(prefix) :])
361 if (
362 i in disabled
363 or str(version) in disabled
364 or i.format(version=version) in disabled
365 or i.format(version=version.major) in disabled
366 ):
367 log.debug("disabling %s step for %s %s", step, i, version)
368 return True
369 return False
370
371 def run(
372 func: Callable[[Context, Args], None],
373 interpreter: str,
374 version: Version,
375 context: Context,
376 ) -> None:
377 step = Step(func.__func__.__name__) # type: ignore
378 args = get_args(context, step, version, interpreter)
379 env = dict(context.ENV)
380 env.update(args.ENV)
381
382 before_cmd = get_option(f"before_{step}", interpreter, version)
383 if before_cmd:
384 log_file: str | Literal[False]
385 if cfg.quiet:
386 log_file = join(args.home_dir, f"before_{step}_cmd.log")
387 else:
388 log_file = False
389 command = args.format(before_cmd)
390 log.info(command)
391 output = execute(command, cwd=context.dir, env=env, log_output=log_file)
392 if output.returncode != 0:
393 msg = f"exit code={output.returncode}: {command}"
394 raise Exception(msg)
395
396 fpath = join(args.home_dir, "testfiles_to_rm_before_install")
397 if step == Step.INSTALL and exists(fpath):
398 with open(fpath, encoding="UTF-8") as fp:
399 for line in fp:
400 path = line.strip("\n")
401 if exists(path):
402 if isdir(path):
403 rmtree(path)
404 else:
405 remove(path)
406 remove(fpath)
407 func(context, args)
408
409 after_cmd = get_option(f"after_{step}", interpreter, version)
410 if after_cmd:
411 if cfg.quiet:
412 log_file = join(args.home_dir, f"after_{step}_cmd.log")
413 else:
414 log_file = False
415 command = args.format(after_cmd)
416 log.info(command)
417 output = execute(command, cwd=context.dir, env=env, log_output=log_file)
418 if output.returncode != 0:
419 msg = f"exit code={output.returncode}: {command}"
420 raise Exception(msg)
421
422 def move_to_ext_destdir(
423 i: str,
424 version: Version,
425 context: Context,
426 ) -> None:
427 """Move built C extensions from the general destdir to ext_destdir"""
428 args = get_args(context, Step.INSTALL, version, interpreter)
429 ext_destdir = get_option("ext_destdir", i, version)
430 ext_pattern = get_option("ext_pattern", i, version)
431 if ext_destdir:
432 assert ext_pattern
433 move_matching_files(
434 args.destdir,
435 ext_destdir,
436 ext_pattern,
437 get_option("ext_sub_pattern", i, version),
438 get_option("ext_sub_repl", i, version),
439 )
440
441 func = None
442 if cfg.clean_only:
443 func = plugin.clean
444 elif cfg.configure_only:
445 func = plugin.configure
446 elif cfg.build_only:
447 func = plugin.build
448 elif cfg.install_only:
449 func = plugin.install
450 elif cfg.test_only:
451 func = plugin.test
452 elif cfg.autopkgtest_only:
453 func = plugin.test
454 elif cfg.print_args:
455 func = plugin.print_args
456
457 # Default value for --dest-dir
458 default_destdir = environ.get("DESTDIR", "debian/tmp")
459
460 ### one function for each interpreter at a time mode ###
461 if func:
462 step = func.__func__.__name__
463 if step == "test" and nocheck:
464 sys.exit(0)
465 failure = False
466 for i in cfg.interpreter:
467 ipreter = Interpreter(i.format(version=versions[0]))
468 iversions = build_sorted(versions, impl=ipreter.impl)
469 if "{version}" not in i and len(versions) > 1:
470 log.info(
471 "limiting Python versions to %s due to missing {version}"
472 " in interpreter string",
473 str(versions[-1]),
474 )
475 iversions = versions[-1:] # just the default or closest to default
476 for version in iversions:
477 if is_disabled(step, i, version):
478 continue
479 c = context.copy()
480 c.dir = get_option("dir", i, version, cfg.dir)
481 c.destdir = get_option("destdir", i, version, default_destdir)
482 try:
483 run(func, i, version, c)
484 except Exception as err:
485 log.error(
486 "%s: plugin %s failed with: %s",
487 step,
488 plugin.NAME,
489 err,
490 exc_info=cfg.verbose,
491 )
492 # try to build/test other interpreters/versions even if
493 # one of them fails to make build logs more verbose:
494 failure = True
495 if step not in (Step.BUILD, Step.TEST, Step.AUTOPKGTEST):
496 sys.exit(13)
497 if step == Step.INSTALL:
498 move_to_ext_destdir(i, version, c)
499 if failure:
500 # exit with a non-zero return code if at least one build/test failed
501 sys.exit(13)
502 sys.exit(0)
503
504 ### all functions for interpreters in batches mode ###
505 try:
506 context_map: dict[tuple[str, Version], Context] = {}
507 for i in cfg.interpreter:
508 ipreter = Interpreter(i.format(version=versions[0]))
509 iversions = build_sorted(versions, impl=ipreter.impl)
510 if "{version}" not in i and len(versions) > 1:
511 log.info(
512 "limiting Python versions to %s due to missing {version}"
513 " in interpreter string",
514 str(versions[-1]),
515 )
516 iversions = versions[-1:] # just the default or closest to default
517 for version in iversions:
518 key = (i, version)
519 if key in context_map:
520 c = context_map[key]
521 else:
522 c = context.copy()
523 c.dir = get_option("dir", i, version, cfg.dir)
524 c.destdir = get_option("destdir", i, version, default_destdir)
525 context_map[key] = c
526
527 if not is_disabled(Step.CLEAN, i, version):
528 run(plugin.clean, i, version, c)
529 if not is_disabled(Step.CONFIGURE, i, version):
530 run(plugin.configure, i, version, c)
531 if not is_disabled(Step.BUILD, i, version):
532 run(plugin.build, i, version, c)
533 if not is_disabled(Step.INSTALL, i, version):
534 run(plugin.install, i, version, c)
535 move_to_ext_destdir(i, version, c)
536 if not nocheck and not is_disabled(Step.TEST, i, version):
537 run(plugin.test, i, version, c)
538 except Exception as err:
539 log.error("plugin %s failed: %s", plugin.NAME, err, exc_info=cfg.verbose)
540 sys.exit(14)
541
542
543 def parse_args(argv: list[str]) -> PybuildOptions:
544 parser = build_parser()
545 args = parser.parse_args(argv, PybuildOptions())
546 if not args.interpreter:
547 args.interpreter = environ.get(
548 "PYBUILD_INTERPRETERS", "python{version}"
549 ).split()
550 if not args.versions:
551 args.versions = [
552 Version(version) for version in environ.get("PYBUILD_VERSIONS", "").split()
553 ]
554
555 if (
556 args.test_nose
557 or args.test_nose2
558 or args.test_pytest
559 or args.test_tox
560 or args.test_stestr
561 or args.test_custom
562 or args.system == "custom"
563 ):
564 args.custom_tests = True
565 else:
566 args.custom_tests = False
567
568 return args
569
570
571 if __name__ == "__main__":
572 cfg = parse_args(sys.argv[1:])
573 if cfg.really_quiet:
574 cfg.quiet = True
575 log.setLevel(logging.CRITICAL)
576 elif cfg.verbose:
577 log.setLevel(logging.DEBUG)
578 else:
579 log.setLevel(logging.INFO)
580 log.debug("version: DEVELV")
581 log.debug(sys.argv)
582 main(cfg)
583 # let dh clean the .pybuild dir
584 # rmtree(join(cfg.dir, '.pybuild'))