#! /usr/bin/python3 # vim: et ts=4 sw=4 # Copyright © 2012-2013 Piotr Ożarowski # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import logging import re import sys from collections.abc import Callable from enum import StrEnum, auto from os import environ, makedirs, remove from os.path import abspath, exists, isdir, join from shutil import rmtree from tempfile import mkdtemp from typing import Literal, overload from dhpython import build, PKG_PREFIX_MAP from dhpython.build.options import ( DEFAULT_INSTALL_DIR, PybuildOptions, build_parser, ) from dhpython.build.types import Args, Context from dhpython.debhelper import DebHelper, build_options from dhpython.version import Version, build_sorted, get_requested_versions from dhpython.interpreter import Interpreter from dhpython.tools import dpkg_architecture, execute, move_matching_files INTERP_VERSION_RE = re.compile(r"^python(?P3\.\d+)(?P-dbg)?$") logging.basicConfig( format="%(levelname).1s: pybuild " "%(module)s:%(lineno)d: %(message)s" ) log = logging.getLogger("dhpython") def main(cfg: PybuildOptions) -> None: log.debug("cfg: %s", cfg) if cfg.list_systems: for name, Plugin in sorted(build.plugins.items()): print(name, "\t", Plugin.DESCRIPTION) sys.exit(0) nocheck = False if "DEB_BUILD_OPTIONS" in environ: nocheck = "nocheck" in environ["DEB_BUILD_OPTIONS"].split() if not nocheck and "DEB_BUILD_PROFILES" in environ: nocheck = "nocheck" in environ["DEB_BUILD_PROFILES"].split() env = environ.copy() # set some defaults in environ to make the build reproducible env.setdefault("LC_ALL", "C.UTF-8") env.setdefault("CCACHE_DIR", abspath(".pybuild/ccache")) env.setdefault("no_proxy", "localhost") if "http_proxy" not in env: env["http_proxy"] = "http://127.0.0.1:9/" elif not env["http_proxy"]: del env["http_proxy"] # some tools don't like empty var. if "https_proxy" not in env: env["https_proxy"] = "https://127.0.0.1:9/" elif not env["https_proxy"]: del env["https_proxy"] # some tools don't like empty var. if "DEB_PYTHON_INSTALL_LAYOUT" not in env: env["DEB_PYTHON_INSTALL_LAYOUT"] = "deb" arch_data = dpkg_architecture() if arch_data: # Set _PYTHON_HOST_PLATFORM to ensure debugging symbols on, f.e. i386 # emded a constant name regardless of the 32/64-bit kernel. special_cases = { "arm-linux-gnueabihf": "linux-armv7l", "mips64el-linux-gnuabi64": "linux-mips64", "mipsel-linux-gnu": "linux-mips", "powerpc64-linux-gnu": "linux-ppc64", "powerpc64le-linux-gnu": "linux-ppc64le", } host_platform = special_cases.get( arch_data["DEB_HOST_MULTIARCH"], "{DEB_HOST_ARCH_OS}-{DEB_HOST_GNU_CPU}".format(**arch_data), ) env.setdefault("_PYTHON_HOST_PLATFORM", host_platform) if arch_data["DEB_BUILD_ARCH"] != arch_data["DEB_HOST_ARCH"]: # support cross compiling Python 3.X extensions, see #892931 env.setdefault( "_PYTHON_SYSCONFIGDATA_NAME", "_sysconfigdata__" + arch_data["DEB_HOST_MULTIARCH"], ) # Selected on command line? selected_plugin = cfg.system # Selected by build_dep? if not selected_plugin: dh = DebHelper(build_options()) for build_dep in dh.build_depends: if build_dep.startswith("pybuild-plugin-"): selected_plugin = build_dep.split("-", 2)[2] break if selected_plugin: certainty = 99 Plugin = build.plugins.get(selected_plugin) if not Plugin: log.error("unrecognized build system: %s", selected_plugin) sys.exit(10) plugin = Plugin(cfg) context = Context(ENV=env, destdir="debian/tmp", dir=cfg.dir) plugin.detect(context) else: plugin, certainty = None, 0 for Plugin in build.plugins.values(): try: tmp_plugin = Plugin(cfg) except Exception as err: log.warning( "cannot initialize %s plugin: %s", Plugin.NAME, err, exc_info=cfg.verbose, ) continue tmp_context = Context(ENV=env, destdir="debian/tmp", dir=cfg.dir) tmp_certainty = tmp_plugin.detect(tmp_context) log.debug("Plugin %s: certainty %i", Plugin.NAME, tmp_certainty) if tmp_certainty and tmp_certainty > certainty: plugin, certainty, context = tmp_plugin, tmp_certainty, tmp_context del Plugin if not plugin: log.error( "cannot detect build system, please use --system option" " or set PYBUILD_SYSTEM env. variable" ) sys.exit(11) if plugin.SUPPORTED_INTERPRETERS is not True: # if versioned interpreter was requested and selected plugin lists # versioned ones as supported: extend list of supported interpreters # with this interpreter tpls = {i for i in plugin.SUPPORTED_INTERPRETERS if "{version}" in i} if tpls: for interpreter in cfg.interpreter: m = INTERP_VERSION_RE.match(interpreter) if m: ver = m.group("version") updated = {tpl.format(version=ver) for tpl in tpls} if updated: plugin.SUPPORTED_INTERPRETERS.update(updated) for interpreter in cfg.interpreter: if ( plugin.SUPPORTED_INTERPRETERS is not True and interpreter not in plugin.SUPPORTED_INTERPRETERS ): log.error("interpreter %s not supported by %s", interpreter, plugin) sys.exit(12) log.debug("detected build system: %s (certainty: %s%%)", plugin.NAME, certainty) if cfg.detect_only: if not cfg.really_quiet: print(plugin.NAME) sys.exit(0) versions = cfg.versions if not versions: if len(cfg.interpreter) == 1: i = cfg.interpreter[0] m = INTERP_VERSION_RE.match(i) if m: log.debug("defaulting to version hardcoded in interpreter name") versions = [Version(m.group("version"))] else: IMAP = {v: k for k, v in PKG_PREFIX_MAP.items()} if i in IMAP: versions = build_sorted( get_requested_versions(IMAP[i], available=True), impl=IMAP[i] ) if versions and "{version}" not in i: versions = versions[-1:] # last one, the default one if not versions: # still no luck log.debug("defaulting to all supported Python 3.X versions") versions = build_sorted( get_requested_versions("cpython3", available=True), impl="cpython3" ) @overload def get_option( name: str, interpreter: str | None, version: Version | None, default: str, ) -> str: ... @overload def get_option( name: str, interpreter: str | None = None, version: Version | None = None, default: None = None, ) -> str | None: ... def get_option( name: str, interpreter: str | None = None, version: Version | None = None, default: str | None = None, ) -> str | None: if interpreter: # try PYBUILD_NAME_python3.3-dbg (or hardcoded interpreter) i = interpreter.format(version=version or "") opt = f"PYBUILD_{name.upper()}_{i}" if opt in environ: return environ[opt] # try PYBUILD_NAME_python3-dbg (if not checked above) if "{version}" in interpreter and version: i = interpreter.format(version=version.major) opt = f"PYBUILD_{name.upper()}_{i}" if opt in environ: return environ[opt] # try PYBUILD_NAME opt = f"PYBUILD_{name.upper()}" if opt in environ: return environ[opt] # try command line args return getattr(cfg, name, default) or default class Step(StrEnum): CLEAN = auto() CONFIGURE = auto() BUILD = auto() INSTALL = auto() TEST = auto() AUTOPKGTEST = auto() PRINT_ARGS = auto() def get_args( context: Context, step: Step, version: Version, interpreter: str, ) -> Args: i = interpreter.format(version=version) ipreter = Interpreter(i) home_dirs = [ipreter.impl, str(version)] if ipreter.debug: home_dirs.append("dbg") if cfg.name: home_dirs.append(cfg.name) if cfg.autopkgtest_only: base_dir = environ.get("AUTOPKGTEST_TMP") if not base_dir: base_dir = mkdtemp(prefix="pybuild-autopkgtest-") else: base_dir = ".pybuild/{}" home_dir = base_dir.format("_".join(home_dirs)) build_dir = get_option( "build_dir", interpreter, version, default=join(home_dir, "build") ) destdir = context.destdir.format(version=version, interpreter=i) if cfg.name: package = ipreter.suggest_pkg_name(cfg.name) else: package = "PYBUILD_NAME_not_set" if cfg.name and get_option("destdir", interpreter, version) is None: destdir = f"debian/{package}" destdir = abspath(destdir) parallel = cfg.parallel args = Args( ENV={}, autopkgtest=cfg.autopkgtest_only, package=package, interpreter=ipreter, version=version, args=get_option("%s_args" % step, interpreter, version, ""), dir=abspath(context.dir.format(version=version, interpreter=i)), destdir=destdir, build_dir=abspath(build_dir.format(version=version, interpreter=i)), # versioned dist-packages even for Python 3.X - dh_python3 will fix it later # (and will have a chance to compare files) install_dir=get_option( "install_dir", interpreter, version, DEFAULT_INSTALL_DIR, ).format(version=version, interpreter=i), home_dir=abspath(home_dir), parallel=parallel, ) for k, v in context.args.items(): setattr(args, k, v) pp_str = args.ENV.get("PYTHONPATH", context.ENV.get("PYTHONPATH")) pp = pp_str.split(":") if pp_str else [] if step in {"build", "test", "autopkgtest"}: if step in {"test", "autopkgtest"}: args.test_dir = join(args.destdir, args.install_dir.lstrip("/")) if args.test_dir not in pp: pp.append(args.test_dir) if args.build_dir not in pp: pp.append(args.build_dir) # cross compilation support for Python 2.x if version.major == 2 and arch_data.get("DEB_BUILD_ARCH") != arch_data.get( "DEB_HOST_ARCH" ): pp.insert( 0, ("/usr/lib/python{}/plat-{}").format( version, arch_data["DEB_HOST_MULTIARCH"] ), ) args.ENV["PYTHONPATH"] = ":".join(pp) # cross compilation support for Python <= 3.8 (see above) if version.major == 3: name = "_PYTHON_SYSCONFIGDATA_NAME" value = args.ENV.get(name, context.ENV.get(name, "")) if ( version << "3.8" and value.startswith("_sysconfigdata_") and not value.startswith("_sysconfigdata_m") ): value = args.ENV[name] = "_sysconfigdata_m%s" % value[15:] # update default from main() for -dbg interpreter if value and ipreter.debug and not value.startswith("_sysconfigdata_d"): args.ENV[name] = "_sysconfigdata_d%s" % value[15:] if not exists(args.build_dir): makedirs(args.build_dir) return args def is_disabled(step: Step, interpreter: str, version: Version) -> bool: i = interpreter prefix = f"{step}/" disabled = (get_option("disable", i, version) or "").split() for item in disabled: if item in (step, "1"): log.debug("disabling %s step for %s %s", step, i, version) return True if item.startswith(prefix): disabled.append(item[len(prefix) :]) if ( i in disabled or str(version) in disabled or i.format(version=version) in disabled or i.format(version=version.major) in disabled ): log.debug("disabling %s step for %s %s", step, i, version) return True return False def run( func: Callable[[Context, Args], None], interpreter: str, version: Version, context: Context, ) -> None: step = Step(func.__func__.__name__) # type: ignore args = get_args(context, step, version, interpreter) env = dict(context.ENV) env.update(args.ENV) before_cmd = get_option(f"before_{step}", interpreter, version) if before_cmd: log_file: str | Literal[False] if cfg.quiet: log_file = join(args.home_dir, f"before_{step}_cmd.log") else: log_file = False command = args.format(before_cmd) log.info(command) output = execute(command, cwd=context.dir, env=env, log_output=log_file) if output.returncode != 0: msg = f"exit code={output.returncode}: {command}" raise Exception(msg) fpath = join(args.home_dir, "testfiles_to_rm_before_install") if step == Step.INSTALL and exists(fpath): with open(fpath, encoding="UTF-8") as fp: for line in fp: path = line.strip("\n") if exists(path): if isdir(path): rmtree(path) else: remove(path) remove(fpath) func(context, args) after_cmd = get_option(f"after_{step}", interpreter, version) if after_cmd: if cfg.quiet: log_file = join(args.home_dir, f"after_{step}_cmd.log") else: log_file = False command = args.format(after_cmd) log.info(command) output = execute(command, cwd=context.dir, env=env, log_output=log_file) if output.returncode != 0: msg = f"exit code={output.returncode}: {command}" raise Exception(msg) def move_to_ext_destdir( i: str, version: Version, context: Context, ) -> None: """Move built C extensions from the general destdir to ext_destdir""" args = get_args(context, Step.INSTALL, version, interpreter) ext_destdir = get_option("ext_destdir", i, version) ext_pattern = get_option("ext_pattern", i, version) if ext_destdir: assert ext_pattern move_matching_files( args.destdir, ext_destdir, ext_pattern, get_option("ext_sub_pattern", i, version), get_option("ext_sub_repl", i, version), ) func = None if cfg.clean_only: func = plugin.clean elif cfg.configure_only: func = plugin.configure elif cfg.build_only: func = plugin.build elif cfg.install_only: func = plugin.install elif cfg.test_only: func = plugin.test elif cfg.autopkgtest_only: func = plugin.test elif cfg.print_args: func = plugin.print_args # Default value for --dest-dir default_destdir = environ.get("DESTDIR", "debian/tmp") ### one function for each interpreter at a time mode ### if func: step = func.__func__.__name__ if step == "test" and nocheck: sys.exit(0) failure = False for i in cfg.interpreter: ipreter = Interpreter(i.format(version=versions[0])) iversions = build_sorted(versions, impl=ipreter.impl) if "{version}" not in i and len(versions) > 1: log.info( "limiting Python versions to %s due to missing {version}" " in interpreter string", str(versions[-1]), ) iversions = versions[-1:] # just the default or closest to default for version in iversions: if is_disabled(step, i, version): continue c = context.copy() c.dir = get_option("dir", i, version, cfg.dir) c.destdir = get_option("destdir", i, version, default_destdir) try: run(func, i, version, c) except Exception as err: log.error( "%s: plugin %s failed with: %s", step, plugin.NAME, err, exc_info=cfg.verbose, ) # try to build/test other interpreters/versions even if # one of them fails to make build logs more verbose: failure = True if step not in (Step.BUILD, Step.TEST, Step.AUTOPKGTEST): sys.exit(13) if step == Step.INSTALL: move_to_ext_destdir(i, version, c) if failure: # exit with a non-zero return code if at least one build/test failed sys.exit(13) sys.exit(0) ### all functions for interpreters in batches mode ### try: context_map: dict[tuple[str, Version], Context] = {} for i in cfg.interpreter: ipreter = Interpreter(i.format(version=versions[0])) iversions = build_sorted(versions, impl=ipreter.impl) if "{version}" not in i and len(versions) > 1: log.info( "limiting Python versions to %s due to missing {version}" " in interpreter string", str(versions[-1]), ) iversions = versions[-1:] # just the default or closest to default for version in iversions: key = (i, version) if key in context_map: c = context_map[key] else: c = context.copy() c.dir = get_option("dir", i, version, cfg.dir) c.destdir = get_option("destdir", i, version, default_destdir) context_map[key] = c if not is_disabled(Step.CLEAN, i, version): run(plugin.clean, i, version, c) if not is_disabled(Step.CONFIGURE, i, version): run(plugin.configure, i, version, c) if not is_disabled(Step.BUILD, i, version): run(plugin.build, i, version, c) if not is_disabled(Step.INSTALL, i, version): run(plugin.install, i, version, c) move_to_ext_destdir(i, version, c) if not nocheck and not is_disabled(Step.TEST, i, version): run(plugin.test, i, version, c) except Exception as err: log.error("plugin %s failed: %s", plugin.NAME, err, exc_info=cfg.verbose) sys.exit(14) def parse_args(argv: list[str]) -> PybuildOptions: parser = build_parser() args = parser.parse_args(argv, PybuildOptions()) if not args.interpreter: args.interpreter = environ.get( "PYBUILD_INTERPRETERS", "python{version}" ).split() if not args.versions: args.versions = [ Version(version) for version in environ.get("PYBUILD_VERSIONS", "").split() ] if ( args.test_nose or args.test_nose2 or args.test_pytest or args.test_tox or args.test_stestr or args.test_custom or args.system == "custom" ): args.custom_tests = True else: args.custom_tests = False return args if __name__ == "__main__": cfg = parse_args(sys.argv[1:]) if cfg.really_quiet: cfg.quiet = True log.setLevel(logging.CRITICAL) elif cfg.verbose: log.setLevel(logging.DEBUG) else: log.setLevel(logging.INFO) log.debug("version: DEVELV") log.debug(sys.argv) main(cfg) # let dh clean the .pybuild dir # rmtree(join(cfg.dir, '.pybuild'))