Files
asteria-qt/scripts/download-mingw-arm64-qt.py
T
2026-11-13 10:56:08 +01:00

304 lines
9.9 KiB
Python
Executable File

#!/usr/bin/env python3
"""
Downloads and extracts MSYS2 MinGW-w64 (clang64 / clangarm64) Qt6 packages,
third-party libraries (libarchive, libiconv, minizip, uchardet, zlib), and all
transitive runtime dependencies into the destination sysroot directory.
Usage:
download-mingw-arm64-qt.py --dest /path/to/sysroot [--arch {x86_64,arm64}] [--dry-run]
"""
import argparse
import glob
import io
import os
import re
import shutil
import subprocess
import sys
import tarfile
import urllib.error
import urllib.request
ARCH_CONFIG = {
"x86_64": {
"repo": "clang64",
"pkg_prefix": "mingw-w64-clang-x86_64",
},
"arm64": {
"repo": "clangarm64",
"pkg_prefix": "mingw-w64-clang-aarch64",
},
}
MIRROR_BASES = [
"https://mirror.msys2.org/mingw",
"https://repo.msys2.org/mingw",
]
SEED_PACKAGES = [
"qt6-base",
"qt6-declarative",
"qt6-svg",
"qt6-imageformats",
"libarchive",
"libiconv",
"minizip",
"uchardet",
"zlib",
]
# Non-runtime / scripting packages not required by Qt6 C++ / QML applications
SKIP_SUBSTRINGS = (
"python",
"tcl",
"tk",
"mpdecimal",
)
EXPECTED_DLLS = [
"Qt6Core.dll",
"Qt6Gui.dll",
"Qt6Qml.dll",
"Qt6Quick.dll",
"Qt6Svg.dll",
"Qt6Widgets.dll",
"Qt6Network.dll",
"libarchive-13.dll",
"libiconv-2.dll",
"libminizip-1.dll",
"libuchardet.dll",
"zlib1.dll",
"libzstd.dll",
"libmd4c.dll",
"libb2-1.dll",
"libfreetype-6.dll",
"libharfbuzz-0.dll",
"libpng16-16.dll",
"libglib-2.0-0.dll",
"libc++.dll",
"libunwind.dll",
]
EXPECTED_PC_FILES = [
"minizip.pc",
"libarchive.pc",
"uchardet.pc",
]
def fetch_url(url, timeout=60):
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0 (Asteria-CI)"})
with urllib.request.urlopen(req, timeout=timeout) as resp:
return resp.read()
def download_db(repo):
for base in MIRROR_BASES:
db_url = f"{base}/{repo}/{repo}.db.tar.zst"
print(f"==> Downloading package database from {db_url}...")
try:
data = fetch_url(db_url, timeout=30)
print(f"==> Downloaded database ({len(data)} bytes)")
return data, f"{base}/{repo}"
except Exception as e:
print(f" Failed ({e}), trying next mirror...", file=sys.stderr)
raise RuntimeError(f"Failed to download {repo}.db.tar.zst from all mirrors")
def parse_database(db_bytes):
res = subprocess.run(["zstd", "-d", "-c"], input=db_bytes, capture_output=True)
if res.returncode != 0:
raise RuntimeError(f"zstd decompression failed: {res.stderr.decode('utf-8', errors='replace')}")
tar = tarfile.open(fileobj=io.BytesIO(res.stdout))
packages = {}
provides_map = {}
for member in tar.getmembers():
if member.isfile() and member.name.endswith("/desc"):
content = tar.extractfile(member).read().decode("utf-8", errors="replace")
current_section = None
pkg_name = None
filename = None
depends = []
provides = []
for line in content.splitlines():
line = line.strip()
if line.startswith("%") and line.endswith("%"):
current_section = line[1:-1]
elif current_section == "NAME" and line:
pkg_name = line
elif current_section == "FILENAME" and line:
filename = line
elif current_section == "DEPENDS" and line:
dep = re.split(r"[<>=]", line)[0]
depends.append(dep)
elif current_section == "PROVIDES" and line:
prov = re.split(r"[<>=]", line)[0]
provides.append(prov)
if pkg_name:
packages[pkg_name] = {"filename": filename, "depends": depends}
provides_map[pkg_name] = pkg_name
for prov in provides:
if prov not in packages:
provides_map[prov] = pkg_name
return packages, provides_map
def resolve_dependencies(packages, provides_map, pkg_prefix):
seeds = [f"{pkg_prefix}-{name}" for name in SEED_PACKAGES]
queue = list(seeds)
visited = set(seeds)
resolved = []
while queue:
curr = queue.pop(0)
real_pkg = provides_map.get(curr, curr)
if any(skip in real_pkg for skip in SKIP_SUBSTRINGS):
continue
if real_pkg in packages:
visited.add(real_pkg)
resolved.append((real_pkg, packages[real_pkg]["filename"]))
for dep in packages[real_pkg]["depends"]:
dep_real = provides_map.get(dep, dep)
if any(skip in dep_real for skip in SKIP_SUBSTRINGS):
continue
if dep_real not in visited:
visited.add(dep_real)
queue.append(dep_real)
else:
print(f"Warning: dependency '{curr}' not found in database", file=sys.stderr)
return sorted(resolved)
def download_and_extract_packages(resolved, repo, dest_dir):
os.makedirs(dest_dir, exist_ok=True)
temp_pkg = f"/tmp/msys2_{repo}_pkg.tar.zst"
for i, (pkg_name, filename) in enumerate(resolved, 1):
print(f"[{i}/{len(resolved)}] Downloading {filename}...")
downloaded = False
last_err = None
for base in MIRROR_BASES:
pkg_url = f"{base}/{repo}/{filename}"
try:
data = fetch_url(pkg_url, timeout=60)
with open(temp_pkg, "wb") as f:
f.write(data)
downloaded = True
break
except Exception as e:
last_err = e
print(f" Failed from {base}/{repo} ({e}), trying next mirror...", file=sys.stderr)
if not downloaded:
raise RuntimeError(f"Failed to download {filename}: {last_err}")
tar_res = subprocess.run(
["tar", "-I", "zstd", "-xf", temp_pkg, "--strip-components=1", "-C", dest_dir],
capture_output=True,
)
if os.path.exists(temp_pkg):
os.remove(temp_pkg)
if tar_res.returncode != 0:
err = tar_res.stderr.decode("utf-8", errors="replace")
raise RuntimeError(f"Failed to extract {filename}: {err}")
def configure_sysroot(dest_dir, repo):
abs_dest = os.path.abspath(dest_dir)
# Rewrite hardcoded /clang64 or /clangarm64 prefixes in pkg-config files
pc_files = glob.glob(os.path.join(abs_dest, "lib", "pkgconfig", "*.pc")) + glob.glob(
os.path.join(abs_dest, "share", "pkgconfig", "*.pc")
)
for pc_path in pc_files:
with open(pc_path, "r", encoding="utf-8", errors="replace") as f:
content = f.read()
updated = content.replace(f"/{repo}", abs_dest)
if updated != content:
with open(pc_path, "w", encoding="utf-8") as f:
f.write(updated)
# Copy any share/pkgconfig/*.pc (e.g. zlib.pc) into lib/pkgconfig so a single PKG_CONFIG_PATH works
lib_pc_dir = os.path.join(abs_dest, "lib", "pkgconfig")
os.makedirs(lib_pc_dir, exist_ok=True)
for pc_path in glob.glob(os.path.join(abs_dest, "share", "pkgconfig", "*.pc")):
target_pc = os.path.join(lib_pc_dir, os.path.basename(pc_path))
if not os.path.exists(target_pc):
shutil.copy2(pc_path, target_pc)
# Remove target Windows Qt6*Tools CMake packages so CMake cross-compilation
# always uses host Linux tools (moc, rcc, qmlcachegen, qmlimportscanner) from QT_HOST_PATH.
for tools_dir in glob.glob(os.path.join(abs_dest, "lib", "cmake", "Qt6*Tools")):
if os.path.isdir(tools_dir):
shutil.rmtree(tools_dir)
def verify_installation(dest_dir):
bin_dir = os.path.join(dest_dir, "bin")
if not os.path.isdir(bin_dir):
raise RuntimeError(f"Expected bin directory missing: {bin_dir}")
missing_dlls = [dll for dll in EXPECTED_DLLS if not os.path.isfile(os.path.join(bin_dir, dll))]
if missing_dlls:
raise RuntimeError(f"Missing expected DLLs in {bin_dir}: {', '.join(missing_dlls)}")
pc_dir = os.path.join(dest_dir, "lib", "pkgconfig")
missing_pcs = [pc for pc in EXPECTED_PC_FILES if not os.path.isfile(os.path.join(pc_dir, pc))]
if missing_pcs:
raise RuntimeError(f"Missing expected pkg-config files in {pc_dir}: {', '.join(missing_pcs)}")
print(
f"==> Verification passed: all {len(EXPECTED_DLLS)} core DLLs and "
f"{len(EXPECTED_PC_FILES)} pkg-config files present in {dest_dir}"
)
def main():
parser = argparse.ArgumentParser(
description="Download MSYS2 Windows (x86_64 / arm64) Qt6 and third-party packages"
)
parser.add_argument("--dest", required=True, help="Destination directory to extract packages into")
parser.add_argument(
"--arch",
choices=["x86_64", "arm64"],
default="arm64",
help="Target Windows architecture (default: arm64)",
)
parser.add_argument("--dry-run", action="store_true", help="Resolve packages without downloading or extracting")
args = parser.parse_args()
cfg = ARCH_CONFIG[args.arch]
repo = cfg["repo"]
pkg_prefix = cfg["pkg_prefix"]
db_bytes, _ = download_db(repo)
packages, provides_map = parse_database(db_bytes)
print(f"==> Parsed {len(packages)} packages from MSYS2 {repo} database")
resolved = resolve_dependencies(packages, provides_map, pkg_prefix)
print(f"==> Resolved {len(resolved)} packages to install for Windows {args.arch} ({repo}):")
for pkg_name, filename in resolved:
print(f" - {pkg_name} ({filename})")
if args.dry_run:
print("==> Dry run complete.")
return
download_and_extract_packages(resolved, repo, args.dest)
configure_sysroot(args.dest, repo)
verify_installation(args.dest)
print(f"==> Successfully installed Windows {args.arch} sysroot into {args.dest}")
if __name__ == "__main__":
main()