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:
using: "composite"
steps:
- name: Set up JDK 21
- name: Set up JDK 25
uses: actions/setup-java@v5
with:
distribution: "temurin"
java-version: "21"
java-version: "25"
- name: Set up Python 3
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:
print(str)
print(msg)
def mv(source: Path, target: Path):
try:
shutil.move(source, target)
vprint(f"mv {source} -> {target}")
except:
pass
except (OSError, shutil.Error) as e:
error(f"Cannot move {source} -> {target}: {e}")
def cp(source: Path, target: Path):
try:
shutil.copyfile(source, target)
vprint(f"cp {source} -> {target}")
except:
pass
except (OSError, shutil.Error) as e:
error(f"Cannot copy {source} -> {target}: {e}")
def rm(file: Path):
if not file.exists() and not file.is_symlink():
return
try:
os.remove(file)
file.unlink()
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
@@ -88,10 +94,17 @@ def rm_on_error(func, path, _):
def rm_rf(path: Path):
vprint(f"rm -rf {path}")
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)
if path.is_file() or path.is_symlink():
try:
path.unlink(missing_ok=True)
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):
@@ -129,7 +142,9 @@ def clean_elf():
cmds.append("--")
cmds.extend(glob.glob("native/out/*/magisk"))
cmds.extend(glob.glob("native/out/*/magiskpolicy"))
execv(cmds)
proc = execv(cmds)
if proc.returncode != 0:
sys.exit(proc.returncode)
def collect_ndk_build():
@@ -209,7 +224,7 @@ def build_rust_src(targets: set[str]):
os.chdir(Path("native", "src"))
# Start building the build commands
cmds = ["cargo", "build", "-p", ""]
cmds = ["cargo", "build"]
if args.release:
cmds.append("-r")
profile = "release"
@@ -225,8 +240,7 @@ def build_rust_src(targets: set[str]):
cmds.append(triple)
for tgt in targets:
cmds[3] = tgt
proc = execv(cmds)
proc = execv([*cmds, "-p", tgt])
if proc.returncode != 0:
error("Build binary failed!")
@@ -244,14 +258,8 @@ def build_rust_src(targets: set[str]):
def write_if_diff(file_name: Path, text: str):
do_write = True
if file_name.exists():
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)
if not file_name.exists() or file_name.read_text(encoding="utf-8") != text:
file_name.write_text(text, encoding="utf-8")
def dump_flags_native():
@@ -344,7 +352,7 @@ def build_app():
# Stub building is directly integrated into the main app
# 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"
cp(source, target)
@@ -411,8 +419,10 @@ def cleanup():
ensure_jdk()
header("* Cleaning app")
os.chdir("app")
execv([paths().gradlew, ":clean"])
proc = execv([paths().gradlew, ":clean"])
os.chdir("..")
if proc.returncode != 0:
sys.exit(proc.returncode)
def build_all():
@@ -450,8 +460,10 @@ def gen_ide():
# Run build.rs to generate Rust/C++ FFI bindings
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("..", ".."))
if proc.returncode != 0:
error("cargo check failed!")
# Generate compilation database
rm_rf(Path("native", "compile_commands.json"))
@@ -500,8 +512,10 @@ def cargo_cli():
if len(args.commands) >= 1 and args.commands[0] == "--":
args.commands = args.commands[1:]
os.chdir(Path("native", "src"))
execv(["cargo", *args.commands])
proc = execv(["cargo", *args.commands])
os.chdir(Path("..", ".."))
if proc.returncode != 0:
sys.exit(proc.returncode)
def setup_ndk():
@@ -541,7 +555,9 @@ def setup_rustup():
cmds = ["cargo", "build", "--release", f"--manifest-path={cargo_toml}"]
if args.verbose > 1:
cmds.append("--verbose")
execv(cmds)
proc = execv(cmds)
if proc.returncode != 0:
sys.exit(proc.returncode)
# Replace rustup with wrapper
wrapper = wrapper_dir / (f"rustup{EXE_EXT}")
@@ -599,18 +615,18 @@ def setup_avd():
def patch_avd_file():
input = Path(args.image)
input_file = Path(args.image)
output = Path(args.output)
header(f"* Patching {input.name}")
header(f"* Patching {input_file.name}")
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:
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"
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
@functools.cache
def adb_path():
if paths.cache_info().currsize > 1:
return paths().adb
else:
if adb := shutil.which("adb"):
return Path(adb)
else:
error("Command 'adb' cannot be found in PATH")
def adb_path() -> Path:
if "ANDROID_HOME" in os.environ or "ANDROID_SDK_ROOT" in os.environ:
if paths().adb.exists():
return paths().adb
if adb := shutil.which("adb"):
return Path(adb)
error("Command 'adb' cannot be found in PATH")
def parse_props(file: Path) -> dict[str, str]:
props = {}
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:
continue
prop = line.split("=")
if len(prop) != 2:
key, sep, value = line.partition("=")
if not sep:
continue
key = prop[0].strip(" \t\r\n")
value = prop[1].strip(" \t\r\n")
key = key.strip(" \t\r\n")
value = value.strip(" \t\r\n")
if not key or not value:
continue
props[key] = value
@@ -703,7 +719,7 @@ def load_config():
def parse_args():
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(
"-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.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")
@@ -811,7 +829,8 @@ def parse_args():
def main():
global args
args = parse_args()
args.config = Path(args.config)
args.config = Path(args.config).resolve()
os.chdir(Path(__file__).resolve().parent)
load_config()
args.func()
+47 -15
View File
@@ -10,24 +10,42 @@ from pathlib import Path
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"
def color_print(code, str):
def color_print(code, msg):
if no_color:
print(str)
print(msg)
else:
str = str.replace("\n", f"\033[0m\n{code}")
print(f"{code}{str}\033[0m")
msg = msg.replace("\n", f"\033[0m\n{code}")
print(f"{code}{msg}\033[0m")
def error(str) -> NoReturn:
color_print("\033[41;39m", f"\n! {str}\n")
def error(msg) -> NoReturn:
color_print("\033[41;39m", f"\n! {msg}\n")
sys.exit(1)
def header(str):
color_print("\033[44;39m", f"\n{str}\n")
def header(msg):
color_print("\033[44;39m", f"\n{msg}\n")
class Paths:
@@ -56,6 +74,7 @@ def paths() -> Paths:
def run_once(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
if not wrapper.has_run:
wrapper.has_run = True
@@ -74,10 +93,12 @@ def ensure_toolchain():
except:
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"):
os.environ["RUSTC_WRAPPER"] = sccache
os.environ["NDK_CCACHE"] = sccache
os.environ["CARGO_INCREMENTAL"] = "0"
# Prefer ccache over sccache for NDK builds when both are installed
if ccache := shutil.which("ccache"):
os.environ["NDK_CCACHE"] = ccache
@@ -97,10 +118,17 @@ def ensure_cargo():
# Cargo calls executables in $RUSTROOT/lib/rustlib/$TRIPLE/bin, we need
# to make sure the runtime linker also search $RUSTROOT/lib for libraries.
# This is only required on Unix, as Windows search dlls from PATH.
rust_lib = str(paths().rust_sysroot / "lib")
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":
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
@@ -124,14 +152,14 @@ def ensure_jdk():
shell=True,
)
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:
no_jdk = True
if no_jdk:
error(
"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"
EXE_EXT = ".exe" if is_windows else ""
no_color = False
if is_windows:
no_color = "NO_COLOR" in os.environ or not sys.stdout.isatty()
if is_windows and not no_color:
try:
import colorama
@@ -162,6 +190,10 @@ cpu_count = multiprocessing.cpu_count()
# When directly invoked, make it a command wrapper
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: env.py <command> [args...]")
sys.exit(1)
ensure_cargo()
ensure_jdk()
subprocess.run(sys.argv[1:])
proc = subprocess.run(sys.argv[1:])
sys.exit(proc.returncode)