|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +import argparse |
| 4 | +import os |
| 5 | +import re |
| 6 | +import shutil |
| 7 | +import subprocess |
| 8 | +import sys |
| 9 | +import sysconfig |
| 10 | +from os.path import relpath |
| 11 | +from pathlib import Path |
| 12 | + |
| 13 | +SCRIPT_NAME = Path(__file__).name |
| 14 | +CHECKOUT = Path(__file__).resolve().parent.parent |
| 15 | +CROSS_BUILD_DIR = CHECKOUT / "cross-build" |
| 16 | + |
| 17 | + |
| 18 | +def delete_if_exists(path): |
| 19 | + if path.exists(): |
| 20 | + print(f"Deleting {path} ...") |
| 21 | + shutil.rmtree(path) |
| 22 | + |
| 23 | + |
| 24 | +def subdir(name, *, clean=None): |
| 25 | + path = CROSS_BUILD_DIR / name |
| 26 | + if clean: |
| 27 | + delete_if_exists(path) |
| 28 | + if not path.exists(): |
| 29 | + if clean is None: |
| 30 | + sys.exit( |
| 31 | + f"{path} does not exist. Create it by running the appropriate " |
| 32 | + f"`configure` subcommand of {SCRIPT_NAME}.") |
| 33 | + else: |
| 34 | + path.mkdir(parents=True) |
| 35 | + return path |
| 36 | + |
| 37 | + |
| 38 | +def run(command, *, host=None, **kwargs): |
| 39 | + env = os.environ.copy() |
| 40 | + if host: |
| 41 | + env_script = CHECKOUT / "Android/android-env.sh" |
| 42 | + env_output = subprocess.run( |
| 43 | + f"set -eu; " |
| 44 | + f"HOST={host}; " |
| 45 | + f"PREFIX={subdir(host)}/prefix; " |
| 46 | + f". {env_script}; " |
| 47 | + f"export", |
| 48 | + check=True, shell=True, text=True, stdout=subprocess.PIPE |
| 49 | + ).stdout |
| 50 | + |
| 51 | + for line in env_output.splitlines(): |
| 52 | + # We don't require every line to match, as there may be some other |
| 53 | + # output from installing the NDK. |
| 54 | + if match := re.search( |
| 55 | + "^(declare -x |export )?(\\w+)=['\"]?(.*?)['\"]?$", line |
| 56 | + ): |
| 57 | + key, value = match[2], match[3] |
| 58 | + if env.get(key) != value: |
| 59 | + print(line) |
| 60 | + env[key] = value |
| 61 | + |
| 62 | + if env == os.environ: |
| 63 | + raise ValueError(f"Found no variables in {env_script.name} output:\n" |
| 64 | + + env_output) |
| 65 | + |
| 66 | + print(">", " ".join(map(str, command))) |
| 67 | + try: |
| 68 | + subprocess.run(command, check=True, env=env, **kwargs) |
| 69 | + except subprocess.CalledProcessError as e: |
| 70 | + sys.exit(e) |
| 71 | + |
| 72 | + |
| 73 | +def build_python_path(): |
| 74 | + """The path to the build Python binary.""" |
| 75 | + build_dir = subdir("build") |
| 76 | + binary = build_dir / "python" |
| 77 | + if not binary.is_file(): |
| 78 | + binary = binary.with_suffix(".exe") |
| 79 | + if not binary.is_file(): |
| 80 | + raise FileNotFoundError("Unable to find `python(.exe)` in " |
| 81 | + f"{build_dir}") |
| 82 | + |
| 83 | + return binary |
| 84 | + |
| 85 | + |
| 86 | +def configure_build_python(context): |
| 87 | + os.chdir(subdir("build", clean=context.clean)) |
| 88 | + |
| 89 | + command = [relpath(CHECKOUT / "configure")] |
| 90 | + if context.args: |
| 91 | + command.extend(context.args) |
| 92 | + run(command) |
| 93 | + |
| 94 | + |
| 95 | +def make_build_python(context): |
| 96 | + os.chdir(subdir("build")) |
| 97 | + run(["make", "-j", str(os.cpu_count())]) |
| 98 | + |
| 99 | + |
| 100 | +def unpack_deps(host): |
| 101 | + deps_url = "https://github.com/beeware/cpython-android-source-deps/releases/download" |
| 102 | + for name_ver in ["bzip2-1.0.8-1", "libffi-3.4.4-2", "openssl-3.0.13-1", |
| 103 | + "sqlite-3.45.1-0", "xz-5.4.6-0"]: |
| 104 | + filename = f"{name_ver}-{host}.tar.gz" |
| 105 | + run(["wget", f"{deps_url}/{name_ver}/{filename}"]) |
| 106 | + run(["tar", "-xf", filename]) |
| 107 | + os.remove(filename) |
| 108 | + |
| 109 | + |
| 110 | +def configure_host_python(context): |
| 111 | + host_dir = subdir(context.host, clean=context.clean) |
| 112 | + |
| 113 | + prefix_dir = host_dir / "prefix" |
| 114 | + if not prefix_dir.exists(): |
| 115 | + prefix_dir.mkdir() |
| 116 | + os.chdir(prefix_dir) |
| 117 | + unpack_deps(context.host) |
| 118 | + |
| 119 | + build_dir = host_dir / "build" |
| 120 | + build_dir.mkdir(exist_ok=True) |
| 121 | + os.chdir(build_dir) |
| 122 | + |
| 123 | + command = [ |
| 124 | + # Basic cross-compiling configuration |
| 125 | + relpath(CHECKOUT / "configure"), |
| 126 | + f"--host={context.host}", |
| 127 | + f"--build={sysconfig.get_config_var('BUILD_GNU_TYPE')}", |
| 128 | + f"--with-build-python={build_python_path()}", |
| 129 | + "--without-ensurepip", |
| 130 | + |
| 131 | + # Android always uses a shared libpython. |
| 132 | + "--enable-shared", |
| 133 | + "--without-static-libpython", |
| 134 | + |
| 135 | + # Dependent libraries. The others are found using pkg-config: see |
| 136 | + # android-env.sh. |
| 137 | + f"--with-openssl={prefix_dir}", |
| 138 | + ] |
| 139 | + |
| 140 | + if context.args: |
| 141 | + command.extend(context.args) |
| 142 | + run(command, host=context.host) |
| 143 | + |
| 144 | + |
| 145 | +def make_host_python(context): |
| 146 | + host_dir = subdir(context.host) |
| 147 | + os.chdir(host_dir / "build") |
| 148 | + run(["make", "-j", str(os.cpu_count())], host=context.host) |
| 149 | + run(["make", "install", f"prefix={host_dir}/prefix"], host=context.host) |
| 150 | + |
| 151 | + |
| 152 | +def build_all(context): |
| 153 | + steps = [configure_build_python, make_build_python, configure_host_python, |
| 154 | + make_host_python] |
| 155 | + for step in steps: |
| 156 | + step(context) |
| 157 | + |
| 158 | + |
| 159 | +def clean_all(context): |
| 160 | + delete_if_exists(CROSS_BUILD_DIR) |
| 161 | + |
| 162 | + |
| 163 | +def main(): |
| 164 | + parser = argparse.ArgumentParser() |
| 165 | + subcommands = parser.add_subparsers(dest="subcommand") |
| 166 | + build = subcommands.add_parser("build", help="Build everything") |
| 167 | + configure_build = subcommands.add_parser("configure-build", |
| 168 | + help="Run `configure` for the " |
| 169 | + "build Python") |
| 170 | + make_build = subcommands.add_parser("make-build", |
| 171 | + help="Run `make` for the build Python") |
| 172 | + configure_host = subcommands.add_parser("configure-host", |
| 173 | + help="Run `configure` for Android") |
| 174 | + make_host = subcommands.add_parser("make-host", |
| 175 | + help="Run `make` for Android") |
| 176 | + clean = subcommands.add_parser("clean", help="Delete files and directories " |
| 177 | + "created by this script") |
| 178 | + for subcommand in build, configure_build, configure_host: |
| 179 | + subcommand.add_argument( |
| 180 | + "--clean", action="store_true", default=False, dest="clean", |
| 181 | + help="Delete any relevant directories before building") |
| 182 | + for subcommand in build, configure_host, make_host: |
| 183 | + subcommand.add_argument( |
| 184 | + "host", metavar="HOST", |
| 185 | + choices=["aarch64-linux-android", "x86_64-linux-android"], |
| 186 | + help="Host triplet: choices=[%(choices)s]") |
| 187 | + for subcommand in build, configure_build, configure_host: |
| 188 | + subcommand.add_argument("args", nargs="*", |
| 189 | + help="Extra arguments to pass to `configure`") |
| 190 | + |
| 191 | + context = parser.parse_args() |
| 192 | + dispatch = {"configure-build": configure_build_python, |
| 193 | + "make-build": make_build_python, |
| 194 | + "configure-host": configure_host_python, |
| 195 | + "make-host": make_host_python, |
| 196 | + "build": build_all, |
| 197 | + "clean": clean_all} |
| 198 | + dispatch[context.subcommand](context) |
| 199 | + |
| 200 | + |
| 201 | +if __name__ == "__main__": |
| 202 | + main() |
0 commit comments