build: improve build.py and env.py scripts

Modernize build scripts and improve reliability across environments:
- Update required Java toolchain to JDK 25 across scripts and CI
- Propagate subprocess exit codes and report filesystem errors
- Fix argument parsing edge cases and dynamic linker path handling
- Anchor working directory and improve terminal output formatting

Assisted-by: Gemini 3.8 Flash
This commit is contained in:
topjohnwu
2026-09-05 08:17:11 +00:00
parent 96221b69fa
commit 173153fcc7
3 changed files with 117 additions and 66 deletions
+2 -2
View File
@@ -7,11 +7,11 @@ inputs:
runs: runs:
using: "composite" using: "composite"
steps: steps:
- name: Set up JDK 21 - name: Set up JDK 25
uses: actions/setup-java@v5 uses: actions/setup-java@v5
with: with:
distribution: "temurin" distribution: "temurin"
java-version: "21" java-version: "25"
- name: Set up Python 3 - name: Set up Python 3
uses: actions/setup-python@v6 uses: actions/setup-python@v6
+68 -49
View File
@@ -47,32 +47,38 @@ force_out = False
################### ###################
def vprint(str): def vprint(msg):
if args.verbose > 0: if args.verbose > 0:
print(str) print(msg)
def mv(source: Path, target: Path): def mv(source: Path, target: Path):
try: try:
shutil.move(source, target) shutil.move(source, target)
vprint(f"mv {source} -> {target}") vprint(f"mv {source} -> {target}")
except: except (OSError, shutil.Error) as e:
pass error(f"Cannot move {source} -> {target}: {e}")
def cp(source: Path, target: Path): def cp(source: Path, target: Path):
try: try:
shutil.copyfile(source, target) shutil.copyfile(source, target)
vprint(f"cp {source} -> {target}") vprint(f"cp {source} -> {target}")
except: except (OSError, shutil.Error) as e:
pass error(f"Cannot copy {source} -> {target}: {e}")
def rm(file: Path): def rm(file: Path):
if not file.exists() and not file.is_symlink():
return
try: try:
os.remove(file) file.unlink()
vprint(f"rm {file}") vprint(f"rm {file}")
except FileNotFoundError as e: except PermissionError:
os.chmod(file, stat.S_IWRITE)
file.unlink()
vprint(f"rm {file}")
except FileNotFoundError:
pass pass
@@ -88,10 +94,17 @@ def rm_on_error(func, path, _):
def rm_rf(path: Path): def rm_rf(path: Path):
vprint(f"rm -rf {path}") vprint(f"rm -rf {path}")
if sys.version_info >= (3, 12): if path.is_file() or path.is_symlink():
shutil.rmtree(path, ignore_errors=False, onexc=rm_on_error) try:
else: path.unlink(missing_ok=True)
shutil.rmtree(path, ignore_errors=False, onerror=rm_on_error) except PermissionError:
os.chmod(path, stat.S_IWRITE)
path.unlink(missing_ok=True)
elif path.is_dir():
if sys.version_info >= (3, 12):
shutil.rmtree(path, ignore_errors=False, onexc=rm_on_error)
else:
shutil.rmtree(path, ignore_errors=False, onerror=rm_on_error)
def execv(cmds: list): def execv(cmds: list):
@@ -129,7 +142,9 @@ def clean_elf():
cmds.append("--") cmds.append("--")
cmds.extend(glob.glob("native/out/*/magisk")) cmds.extend(glob.glob("native/out/*/magisk"))
cmds.extend(glob.glob("native/out/*/magiskpolicy")) cmds.extend(glob.glob("native/out/*/magiskpolicy"))
execv(cmds) proc = execv(cmds)
if proc.returncode != 0:
sys.exit(proc.returncode)
def collect_ndk_build(): def collect_ndk_build():
@@ -209,7 +224,7 @@ def build_rust_src(targets: set[str]):
os.chdir(Path("native", "src")) os.chdir(Path("native", "src"))
# Start building the build commands # Start building the build commands
cmds = ["cargo", "build", "-p", ""] cmds = ["cargo", "build"]
if args.release: if args.release:
cmds.append("-r") cmds.append("-r")
profile = "release" profile = "release"
@@ -225,8 +240,7 @@ def build_rust_src(targets: set[str]):
cmds.append(triple) cmds.append(triple)
for tgt in targets: for tgt in targets:
cmds[3] = tgt proc = execv([*cmds, "-p", tgt])
proc = execv(cmds)
if proc.returncode != 0: if proc.returncode != 0:
error("Build binary failed!") error("Build binary failed!")
@@ -244,14 +258,8 @@ def build_rust_src(targets: set[str]):
def write_if_diff(file_name: Path, text: str): def write_if_diff(file_name: Path, text: str):
do_write = True if not file_name.exists() or file_name.read_text(encoding="utf-8") != text:
if file_name.exists(): file_name.write_text(text, encoding="utf-8")
with open(file_name, "r") as f:
orig = f.read()
do_write = orig != text
if do_write:
with open(file_name, "w") as f:
f.write(text)
def dump_flags_native(): def dump_flags_native():
@@ -344,7 +352,7 @@ def build_app():
# Stub building is directly integrated into the main app # Stub building is directly integrated into the main app
# build process. Copy the stub APK into output directory. # build process. Copy the stub APK into output directory.
source = Path("app", "core", "src", build_type, "assets", "stub.apk") source = Path("app", "core", "build", build_type, "assets", "stub.apk")
target = config["outdir"] / f"stub-{build_type}.apk" target = config["outdir"] / f"stub-{build_type}.apk"
cp(source, target) cp(source, target)
@@ -411,8 +419,10 @@ def cleanup():
ensure_jdk() ensure_jdk()
header("* Cleaning app") header("* Cleaning app")
os.chdir("app") os.chdir("app")
execv([paths().gradlew, ":clean"]) proc = execv([paths().gradlew, ":clean"])
os.chdir("..") os.chdir("..")
if proc.returncode != 0:
sys.exit(proc.returncode)
def build_all(): def build_all():
@@ -450,8 +460,10 @@ def gen_ide():
# Run build.rs to generate Rust/C++ FFI bindings # Run build.rs to generate Rust/C++ FFI bindings
os.chdir(Path("native", "src")) os.chdir(Path("native", "src"))
execv(["cargo", "check", "--target", build_abis[args.abi]]) proc = execv(["cargo", "check", "--target", build_abis[args.abi]])
os.chdir(Path("..", "..")) os.chdir(Path("..", ".."))
if proc.returncode != 0:
error("cargo check failed!")
# Generate compilation database # Generate compilation database
rm_rf(Path("native", "compile_commands.json")) rm_rf(Path("native", "compile_commands.json"))
@@ -500,8 +512,10 @@ def cargo_cli():
if len(args.commands) >= 1 and args.commands[0] == "--": if len(args.commands) >= 1 and args.commands[0] == "--":
args.commands = args.commands[1:] args.commands = args.commands[1:]
os.chdir(Path("native", "src")) os.chdir(Path("native", "src"))
execv(["cargo", *args.commands]) proc = execv(["cargo", *args.commands])
os.chdir(Path("..", "..")) os.chdir(Path("..", ".."))
if proc.returncode != 0:
sys.exit(proc.returncode)
def setup_ndk(): def setup_ndk():
@@ -541,7 +555,9 @@ def setup_rustup():
cmds = ["cargo", "build", "--release", f"--manifest-path={cargo_toml}"] cmds = ["cargo", "build", "--release", f"--manifest-path={cargo_toml}"]
if args.verbose > 1: if args.verbose > 1:
cmds.append("--verbose") cmds.append("--verbose")
execv(cmds) proc = execv(cmds)
if proc.returncode != 0:
sys.exit(proc.returncode)
# Replace rustup with wrapper # Replace rustup with wrapper
wrapper = wrapper_dir / (f"rustup{EXE_EXT}") wrapper = wrapper_dir / (f"rustup{EXE_EXT}")
@@ -599,18 +615,18 @@ def setup_avd():
def patch_avd_file(): def patch_avd_file():
input = Path(args.image) input_file = Path(args.image)
output = Path(args.output) output = Path(args.output)
header(f"* Patching {input.name}") header(f"* Patching {input_file.name}")
push_files(Path("scripts", "host_patch.sh")) push_files(Path("scripts", "host_patch.sh"))
proc = execv([adb_path(), "push", input, "/data/local/tmp"]) proc = execv([adb_path(), "push", input_file, "/data/local/tmp"])
if proc.returncode != 0: if proc.returncode != 0:
error("adb push failed!") error("adb push failed!")
src_file = f"/data/local/tmp/{input.name}" src_file = f"/data/local/tmp/{input_file.name}"
out_file = f"{src_file}.magisk" out_file = f"{src_file}.magisk"
proc = execv([adb_path(), "shell", "sh", "/data/local/tmp/host_patch.sh", src_file]) proc = execv([adb_path(), "shell", "sh", "/data/local/tmp/host_patch.sh", src_file])
@@ -631,27 +647,27 @@ def patch_avd_file():
# We allow using several functionality without requirement to set ANDROID_HOME # We allow using several functionality without requirement to set ANDROID_HOME
@functools.cache @functools.cache
def adb_path(): def adb_path() -> Path:
if paths.cache_info().currsize > 1: if "ANDROID_HOME" in os.environ or "ANDROID_SDK_ROOT" in os.environ:
return paths().adb if paths().adb.exists():
else: return paths().adb
if adb := shutil.which("adb"): if adb := shutil.which("adb"):
return Path(adb) return Path(adb)
else: error("Command 'adb' cannot be found in PATH")
error("Command 'adb' cannot be found in PATH")
def parse_props(file: Path) -> dict[str, str]: def parse_props(file: Path) -> dict[str, str]:
props = {} props = {}
with open(file, "r") as f: with open(file, "r") as f:
for line in [l.strip(" \t\r\n") for l in f]: for line in f:
line = line.strip(" \t\r\n")
if line.startswith("#") or len(line) == 0: if line.startswith("#") or len(line) == 0:
continue continue
prop = line.split("=") key, sep, value = line.partition("=")
if len(prop) != 2: if not sep:
continue continue
key = prop[0].strip(" \t\r\n") key = key.strip(" \t\r\n")
value = prop[1].strip(" \t\r\n") value = value.strip(" \t\r\n")
if not key or not value: if not key or not value:
continue continue
props[key] = value props[key] = value
@@ -703,7 +719,7 @@ def load_config():
def parse_args(): def parse_args():
parser = argparse.ArgumentParser(description="Magisk build script") parser = argparse.ArgumentParser(description="Magisk build script")
parser.set_defaults(func=lambda x: None) parser.set_defaults(func=lambda: (parser.print_help(), sys.exit(1)))
parser.add_argument( parser.add_argument(
"-r", "--release", action="store_true", help="compile in release mode" "-r", "--release", action="store_true", help="compile in release mode"
) )
@@ -740,7 +756,9 @@ def parse_args():
clean_parser = subparsers.add_parser("clean", help="cleanup") clean_parser = subparsers.add_parser("clean", help="cleanup")
clean_parser.add_argument( clean_parser.add_argument(
"targets", nargs="*", help="native, cpp, rust, java, or empty to clean all" "targets",
nargs="*",
help="native, cpp, rust, app, or empty to clean all",
) )
ndk_parser = subparsers.add_parser("ndk", help="setup Magisk NDK") ndk_parser = subparsers.add_parser("ndk", help="setup Magisk NDK")
@@ -811,7 +829,8 @@ def parse_args():
def main(): def main():
global args global args
args = parse_args() args = parse_args()
args.config = Path(args.config) args.config = Path(args.config).resolve()
os.chdir(Path(__file__).resolve().parent)
load_config() load_config()
args.func() args.func()
+47 -15
View File
@@ -10,24 +10,42 @@ from pathlib import Path
from typing import NoReturn from typing import NoReturn
__all__ = [
"ondk_version",
"color_print",
"error",
"header",
"Paths",
"paths",
"run_once",
"ensure_toolchain",
"ensure_cargo",
"ensure_jdk",
"os_name",
"is_windows",
"EXE_EXT",
"no_color",
"cpu_count",
]
ondk_version = "r30.1" ondk_version = "r30.1"
def color_print(code, str): def color_print(code, msg):
if no_color: if no_color:
print(str) print(msg)
else: else:
str = str.replace("\n", f"\033[0m\n{code}") msg = msg.replace("\n", f"\033[0m\n{code}")
print(f"{code}{str}\033[0m") print(f"{code}{msg}\033[0m")
def error(str) -> NoReturn: def error(msg) -> NoReturn:
color_print("\033[41;39m", f"\n! {str}\n") color_print("\033[41;39m", f"\n! {msg}\n")
sys.exit(1) sys.exit(1)
def header(str): def header(msg):
color_print("\033[44;39m", f"\n{str}\n") color_print("\033[44;39m", f"\n{msg}\n")
class Paths: class Paths:
@@ -56,6 +74,7 @@ def paths() -> Paths:
def run_once(func): def run_once(func):
@functools.wraps(func)
def wrapper(*args, **kwargs): def wrapper(*args, **kwargs):
if not wrapper.has_run: if not wrapper.has_run:
wrapper.has_run = True wrapper.has_run = True
@@ -74,10 +93,12 @@ def ensure_toolchain():
except: except:
error('Unmatched NDK. Please install/upgrade NDK with "build.py ndk"') error('Unmatched NDK. Please install/upgrade NDK with "build.py ndk"')
# Use sccache for both Rust and C/C++ by default
if sccache := shutil.which("sccache"): if sccache := shutil.which("sccache"):
os.environ["RUSTC_WRAPPER"] = sccache os.environ["RUSTC_WRAPPER"] = sccache
os.environ["NDK_CCACHE"] = sccache os.environ["NDK_CCACHE"] = sccache
os.environ["CARGO_INCREMENTAL"] = "0" os.environ["CARGO_INCREMENTAL"] = "0"
# Prefer ccache over sccache for NDK builds when both are installed
if ccache := shutil.which("ccache"): if ccache := shutil.which("ccache"):
os.environ["NDK_CCACHE"] = ccache os.environ["NDK_CCACHE"] = ccache
@@ -97,10 +118,17 @@ def ensure_cargo():
# Cargo calls executables in $RUSTROOT/lib/rustlib/$TRIPLE/bin, we need # Cargo calls executables in $RUSTROOT/lib/rustlib/$TRIPLE/bin, we need
# to make sure the runtime linker also search $RUSTROOT/lib for libraries. # to make sure the runtime linker also search $RUSTROOT/lib for libraries.
# This is only required on Unix, as Windows search dlls from PATH. # This is only required on Unix, as Windows search dlls from PATH.
rust_lib = str(paths().rust_sysroot / "lib")
if os_name == "darwin": if os_name == "darwin":
os.environ["DYLD_FALLBACK_LIBRARY_PATH"] = str(paths().rust_sysroot / "lib") cur = os.environ.get("DYLD_FALLBACK_LIBRARY_PATH")
os.environ["DYLD_FALLBACK_LIBRARY_PATH"] = (
f"{rust_lib}{os.pathsep}{cur}" if cur else rust_lib
)
elif os_name == "linux": elif os_name == "linux":
os.environ["LD_LIBRARY_PATH"] = str(paths().rust_sysroot / "lib") cur = os.environ.get("LD_LIBRARY_PATH")
os.environ["LD_LIBRARY_PATH"] = (
f"{rust_lib}{os.pathsep}{cur}" if cur else rust_lib
)
@run_once @run_once
@@ -124,14 +152,14 @@ def ensure_jdk():
shell=True, shell=True,
) )
output = proc.stdout.strip().decode("utf-8") output = proc.stdout.strip().decode("utf-8")
no_jdk = proc.returncode != 0 and output.startswith("javac 21") no_jdk = proc.returncode != 0 or not output.startswith("javac 25")
except FileNotFoundError: except FileNotFoundError:
no_jdk = True no_jdk = True
if no_jdk: if no_jdk:
error( error(
"Please set Android Studio's path to environment variable ANDROID_STUDIO,\n" "Please set Android Studio's path to environment variable ANDROID_STUDIO,\n"
+ "or install JDK 21 and make sure 'javac' is available in PATH" + "or install JDK 25 and make sure 'javac' is available in PATH"
) )
@@ -144,8 +172,8 @@ if os_name != "linux" and os_name != "darwin":
os_name = "windows" os_name = "windows"
EXE_EXT = ".exe" if is_windows else "" EXE_EXT = ".exe" if is_windows else ""
no_color = False no_color = "NO_COLOR" in os.environ or not sys.stdout.isatty()
if is_windows: if is_windows and not no_color:
try: try:
import colorama import colorama
@@ -162,6 +190,10 @@ cpu_count = multiprocessing.cpu_count()
# When directly invoked, make it a command wrapper # When directly invoked, make it a command wrapper
if __name__ == "__main__": if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: env.py <command> [args...]")
sys.exit(1)
ensure_cargo() ensure_cargo()
ensure_jdk() ensure_jdk()
subprocess.run(sys.argv[1:]) proc = subprocess.run(sys.argv[1:])
sys.exit(proc.returncode)