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lew ile APK üretir.
|
| 5 |
+
|
| 6 |
+
Neden Space'te: derleme ~10-20 dakika sürüyor ve arka plan thread'inde
|
| 7 |
+
çalıştığı için kullanıcı tarayıcıyı kapatabiliyor. Sonuç diske yazılıyor,
|
| 8 |
+
geri dönüldüğünde indirilebilir halde duruyor.
|
| 9 |
+
|
| 10 |
+
Winlator kaynağı FORK'LANMIYOR: pin'li commit'ten çekilip üstüne overlay
|
| 11 |
+
seriliyor ve yalnızca patches.json'daki cerrahi yamalar uygulanıyor.
|
| 12 |
+
"""
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import json
|
| 16 |
+
import os
|
| 17 |
+
import shutil
|
| 18 |
+
|
| 19 |
+
from .bus import EventBus
|
| 20 |
+
from .config import WINLATOR_APP_PIN, WINLATOR_APP_REPO
|
| 21 |
+
from .util import CommandError, human, rm_rf, run
|
| 22 |
+
|
| 23 |
+
# Bu modülün bulunduğu paketin bir üstü = Space kökü
|
| 24 |
+
SPACE_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 25 |
+
OVERLAY_DIR = os.path.join(SPACE_ROOT, "android", "overlay")
|
| 26 |
+
PATCHES_FILE = os.path.join(SPACE_ROOT, "android", "patches.json")
|
| 27 |
+
|
| 28 |
+
# Dockerfile bu sürümleri kuruyor; değiştirirsen orayı da güncelle.
|
| 29 |
+
REQUIRED_NDK = "24.0.8215888"
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class AndroidBuildError(RuntimeError):
|
| 33 |
+
pass
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _sdk_root() -> str:
|
| 37 |
+
return (
|
| 38 |
+
os.environ.get("ANDROID_HOME")
|
| 39 |
+
or os.environ.get("ANDROID_SDK_ROOT")
|
| 40 |
+
or "/opt/android-sdk"
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def preflight(bus: EventBus) -> None:
|
| 45 |
+
"""Derleme ortamının gerçekten hazır olduğunu, build'e girmeden doğrular.
|
| 46 |
+
|
| 47 |
+
20 dakikalık bir gradle çalıştırmasının ortasında 'NDK yok' demek yerine
|
| 48 |
+
en baştan net bir hata vermek istiyoruz.
|
| 49 |
+
"""
|
| 50 |
+
sdk = _sdk_root()
|
| 51 |
+
problems: list[str] = []
|
| 52 |
+
|
| 53 |
+
if not os.path.isdir(sdk):
|
| 54 |
+
problems.append(f"Android SDK bulunamadı: {sdk}")
|
| 55 |
+
else:
|
| 56 |
+
ndk_dir = os.path.join(sdk, "ndk", REQUIRED_NDK)
|
| 57 |
+
if not os.path.isdir(ndk_dir):
|
| 58 |
+
available = []
|
| 59 |
+
ndk_root = os.path.join(sdk, "ndk")
|
| 60 |
+
if os.path.isdir(ndk_root):
|
| 61 |
+
available = sorted(os.listdir(ndk_root))
|
| 62 |
+
problems.append(
|
| 63 |
+
f"NDK {REQUIRED_NDK} bulunamadı ({ndk_dir}). "
|
| 64 |
+
f"Kurulu olanlar: {', '.join(available) or 'yok'}"
|
| 65 |
+
)
|
| 66 |
+
if not os.path.isdir(os.path.join(sdk, "platforms", "android-35")):
|
| 67 |
+
problems.append("platforms;android-35 kurulu değil.")
|
| 68 |
+
|
| 69 |
+
if not os.path.isdir(OVERLAY_DIR):
|
| 70 |
+
problems.append(f"Overlay klasörü yok: {OVERLAY_DIR}")
|
| 71 |
+
if not os.path.isfile(PATCHES_FILE):
|
| 72 |
+
problems.append(f"patches.json yok: {PATCHES_FILE}")
|
| 73 |
+
|
| 74 |
+
if not shutil.which("java"):
|
| 75 |
+
problems.append("java bulunamadı (JDK 17 gerekli).")
|
| 76 |
+
|
| 77 |
+
if problems:
|
| 78 |
+
raise AndroidBuildError(
|
| 79 |
+
"APK derleme ortamı hazır değil:\n - " + "\n - ".join(problems)
|
| 80 |
+
)
|
| 81 |
+
bus.ok(f"Derleme ortamı hazır (SDK: {sdk}, NDK {REQUIRED_NDK}).")
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def _ensure_full_source(cache_root: str, bus: EventBus) -> str:
|
| 85 |
+
"""winlator-app'in TAM kaynağını pin'li commit'te hazırlar.
|
| 86 |
+
|
| 87 |
+
AŞAMA A aynı depoyu sparse (sadece assets) çekiyor. APK için tüm kaynak
|
| 88 |
+
lazım; sparse'ı kapatıyoruz. Partial clone olduğu için git eksik blob'ları
|
| 89 |
+
bu noktada tembel olarak indiriyor. Bir sorun çıkarsa sıfırdan tam klona
|
| 90 |
+
düşüyoruz — yarım bir çalışma ağacıyla derlemeye girmek istemiyoruz.
|
| 91 |
+
"""
|
| 92 |
+
repo = os.path.join(cache_root, "winlator-app")
|
| 93 |
+
|
| 94 |
+
if os.path.isdir(os.path.join(repo, ".git")):
|
| 95 |
+
try:
|
| 96 |
+
bus.info("Mevcut klon tam kaynağa genişletiliyor…")
|
| 97 |
+
run(["git", "-C", repo, "sparse-checkout", "disable"], bus, quiet=True)
|
| 98 |
+
run(["git", "-C", repo, "checkout", "--force", WINLATOR_APP_PIN], bus, quiet=True)
|
| 99 |
+
except (CommandError, OSError) as exc:
|
| 100 |
+
bus.warn(f"Genişletme başarısız ({exc}); sıfırdan tam klon alınıyor.")
|
| 101 |
+
rm_rf(repo)
|
| 102 |
+
|
| 103 |
+
if not os.path.isdir(os.path.join(repo, ".git")):
|
| 104 |
+
bus.info(f"winlator-app tam klonu alınıyor (pin {WINLATOR_APP_PIN[:10]})…")
|
| 105 |
+
os.makedirs(cache_root, exist_ok=True)
|
| 106 |
+
run(["git", "clone", WINLATOR_APP_REPO, repo], bus, quiet=True)
|
| 107 |
+
run(["git", "-C", repo, "checkout", "--force", WINLATOR_APP_PIN], bus, quiet=True)
|
| 108 |
+
|
| 109 |
+
gradle_file = os.path.join(repo, "app", "build.gradle")
|
| 110 |
+
if not os.path.isfile(gradle_file):
|
| 111 |
+
raise AndroidBuildError(
|
| 112 |
+
f"Kaynak eksik görünüyor: {gradle_file} yok. Klon bozulmuş olabilir."
|
| 113 |
+
)
|
| 114 |
+
bus.ok("Winlator kaynağı hazır.")
|
| 115 |
+
return repo
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def _prepare_project(repo: str, project: str, bus: EventBus) -> None:
|
| 119 |
+
"""Pin'li kaynağın temiz bir kopyasını çıkarır (cache'i kirletmeden)."""
|
| 120 |
+
rm_rf(project)
|
| 121 |
+
bus.info("Çalışma kopyası hazırlanıyor…")
|
| 122 |
+
shutil.copytree(
|
| 123 |
+
repo, project, symlinks=True,
|
| 124 |
+
ignore=shutil.ignore_patterns(".git", "build", ".gradle", "local.properties"),
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def _apply_overlay(project: str, bus: EventBus) -> None:
|
| 129 |
+
for name in os.listdir(OVERLAY_DIR):
|
| 130 |
+
src = os.path.join(OVERLAY_DIR, name)
|
| 131 |
+
dst = os.path.join(project, name)
|
| 132 |
+
if os.path.isdir(src):
|
| 133 |
+
shutil.copytree(src, dst, dirs_exist_ok=True, symlinks=True)
|
| 134 |
+
else:
|
| 135 |
+
shutil.copy2(src, dst)
|
| 136 |
+
# Upstream deposunda gradlew'in çalıştırma biti yok.
|
| 137 |
+
gradlew = os.path.join(project, "gradlew")
|
| 138 |
+
if os.path.isfile(gradlew):
|
| 139 |
+
os.chmod(gradlew, 0o755)
|
| 140 |
+
bus.ok("Tek-oyun katmanı serildi.")
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def _apply_patches(project: str, bus: EventBus) -> None:
|
| 144 |
+
"""patches.json'daki cerrahi yamaları uygular.
|
| 145 |
+
|
| 146 |
+
Çapa bulunamazsa DURUYORUZ: upstream pin'i değişmiş demektir ve sessizce
|
| 147 |
+
yanlış yere yazmaktansa build'i düşürmek doğru olan.
|
| 148 |
+
"""
|
| 149 |
+
with open(PATCHES_FILE, encoding="utf-8") as fh:
|
| 150 |
+
patches = json.load(fh)["patches"]
|
| 151 |
+
|
| 152 |
+
for patch in patches:
|
| 153 |
+
path = os.path.join(project, patch["file"])
|
| 154 |
+
if not os.path.isfile(path):
|
| 155 |
+
raise AndroidBuildError(f"Yamalanacak dosya yok: {patch['file']}")
|
| 156 |
+
with open(path, encoding="utf-8") as fh:
|
| 157 |
+
text = fh.read()
|
| 158 |
+
|
| 159 |
+
if patch["marker"] in text:
|
| 160 |
+
bus.info(f" {patch['id']}: zaten yamalı, atlandı")
|
| 161 |
+
continue
|
| 162 |
+
if patch["anchor"] not in text:
|
| 163 |
+
raise AndroidBuildError(
|
| 164 |
+
f"YAMA ÇAPASI BULUNAMADI: {patch['id']} ({patch['file']}).\n"
|
| 165 |
+
f"Aranan: {patch['anchor'][:120]}\n"
|
| 166 |
+
"Upstream pin'i değişmiş olabilir; patches.json güncellenmeli."
|
| 167 |
+
)
|
| 168 |
+
with open(path, "w", encoding="utf-8") as fh:
|
| 169 |
+
fh.write(text.replace(patch["anchor"], patch["replacement"], 1))
|
| 170 |
+
bus.ok(f" {patch['id']}: yamalandı")
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def _place_artifacts(project: str, artifacts: dict[str, str], config_path: str,
|
| 174 |
+
bus: EventBus) -> None:
|
| 175 |
+
assets = os.path.join(project, "app", "src", "main", "assets")
|
| 176 |
+
gameport = os.path.join(assets, "gameport")
|
| 177 |
+
os.makedirs(gameport, exist_ok=True)
|
| 178 |
+
|
| 179 |
+
shutil.copy2(config_path, os.path.join(gameport, "game_config.json"))
|
| 180 |
+
shutil.copy2(artifacts["payload"], os.path.join(gameport, "game_payload.tzst"))
|
| 181 |
+
|
| 182 |
+
if artifacts.get("rootfs"):
|
| 183 |
+
shutil.copy2(artifacts["rootfs"], os.path.join(assets, "rootfs.tzst"))
|
| 184 |
+
bus.info(" yamalanmış rootfs.tzst yerleştirildi")
|
| 185 |
+
else:
|
| 186 |
+
bus.info(" upstream rootfs.tzst korunuyor (applicationId=com.winlator)")
|
| 187 |
+
|
| 188 |
+
if artifacts.get("controls"):
|
| 189 |
+
profiles = os.path.join(assets, "inputcontrols", "profiles")
|
| 190 |
+
os.makedirs(profiles, exist_ok=True)
|
| 191 |
+
shutil.copy2(artifacts["controls"], os.path.join(profiles, "controls-1.icp"))
|
| 192 |
+
bus.info(" özel input profili yerleştirildi")
|
| 193 |
+
|
| 194 |
+
total = sum(
|
| 195 |
+
os.path.getsize(os.path.join(dp, f))
|
| 196 |
+
for dp, _d, fs in os.walk(assets) for f in fs
|
| 197 |
+
)
|
| 198 |
+
bus.ok(f"Asset'ler yerleşti (toplam {human(total)}).")
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def _write_port_properties(project: str, config_path: str, bus: EventBus) -> None:
|
| 202 |
+
with open(config_path, encoding="utf-8") as fh:
|
| 203 |
+
config = json.load(fh)
|
| 204 |
+
|
| 205 |
+
lines = [
|
| 206 |
+
"# Space tarafindan game_config.json'dan uretildi.",
|
| 207 |
+
f"gameport.applicationId={config['appId']}",
|
| 208 |
+
f"gameport.appLabel={config.get('appLabel') or config['game']['name']}",
|
| 209 |
+
f"gameport.versionName={config.get('versionName', '1.0')}",
|
| 210 |
+
f"gameport.versionCode={config.get('versionCode', 1)}",
|
| 211 |
+
]
|
| 212 |
+
with open(os.path.join(project, "port.properties"), "w", encoding="utf-8") as fh:
|
| 213 |
+
fh.write("\n".join(lines) + "\n")
|
| 214 |
+
for line in lines[1:]:
|
| 215 |
+
bus.info(f" {line}")
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def _write_local_properties(project: str) -> None:
|
| 219 |
+
with open(os.path.join(project, "local.properties"), "w", encoding="utf-8") as fh:
|
| 220 |
+
fh.write(f"sdk.dir={_sdk_root()}\n")
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def _gradle_env(gradle_home: str) -> dict[str, str]:
|
| 224 |
+
sdk = _sdk_root()
|
| 225 |
+
return {
|
| 226 |
+
"ANDROID_HOME": sdk,
|
| 227 |
+
"ANDROID_SDK_ROOT": sdk,
|
| 228 |
+
"GRADLE_USER_HOME": gradle_home,
|
| 229 |
+
# Space'te 32GB RAM var; Gradle ve Kotlin derleyicisine yeterli alan
|
| 230 |
+
# verilmezse büyük Java kaynağında OOM'a düşebiliyor.
|
| 231 |
+
"GRADLE_OPTS": "-Xmx6g -XX:MaxMetaspaceSize=1g -Dfile.encoding=UTF-8",
|
| 232 |
+
"JAVA_TOOL_OPTIONS": "",
|
| 233 |
+
"TERM": "dumb",
|
| 234 |
+
}
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def build(
|
| 238 |
+
cfg,
|
| 239 |
+
artifacts: dict[str, str],
|
| 240 |
+
config_path: str,
|
| 241 |
+
cache_root: str,
|
| 242 |
+
work_root: str,
|
| 243 |
+
out_root: str,
|
| 244 |
+
bus: EventBus,
|
| 245 |
+
) -> dict:
|
| 246 |
+
"""APK üretir. Dönüş: {'apk': yol, 'size': bayt, 'variant': 'debug'}"""
|
| 247 |
+
preflight(bus)
|
| 248 |
+
|
| 249 |
+
repo = _ensure_full_source(cache_root, bus)
|
| 250 |
+
project = os.path.join(work_root, "android-project")
|
| 251 |
+
_prepare_project(repo, project, bus)
|
| 252 |
+
|
| 253 |
+
bus.info("Cerrahi yamalar uygulanıyor…")
|
| 254 |
+
_apply_overlay(project, bus)
|
| 255 |
+
_apply_patches(project, bus)
|
| 256 |
+
|
| 257 |
+
bus.info("AŞAMA A çıktıları assets'e yerleştiriliyor…")
|
| 258 |
+
_place_artifacts(project, artifacts, config_path, bus)
|
| 259 |
+
_write_port_properties(project, config_path, bus)
|
| 260 |
+
_write_local_properties(project)
|
| 261 |
+
|
| 262 |
+
variant = "debug"
|
| 263 |
+
task = "assembleDebug"
|
| 264 |
+
gradle_home = os.path.join(cache_root, "gradle-home")
|
| 265 |
+
os.makedirs(gradle_home, exist_ok=True)
|
| 266 |
+
|
| 267 |
+
bus.info(
|
| 268 |
+
"Gradle başlatılıyor. İlk çalıştırma Gradle dağıtımını ve bağımlılıkları "
|
| 269 |
+
"indirir (5-15 dk); sonraki derlemeler 2-5 dk sürer. Native CMake/NDK "
|
| 270 |
+
"derlemesi de bu adıma dahil."
|
| 271 |
+
)
|
| 272 |
+
run(
|
| 273 |
+
[
|
| 274 |
+
"./gradlew", task,
|
| 275 |
+
"--no-daemon", "--console=plain", "--stacktrace",
|
| 276 |
+
],
|
| 277 |
+
bus,
|
| 278 |
+
cwd=project,
|
| 279 |
+
env=_gradle_env(gradle_home),
|
| 280 |
+
timeout=5400,
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
apk = _find_apk(project, variant)
|
| 284 |
+
if not apk:
|
| 285 |
+
raise AndroidBuildError(
|
| 286 |
+
"Gradle başarıyla bitti ama APK bulunamadı. "
|
| 287 |
+
f"Aranan yer: app/build/outputs/apk/{variant}/"
|
| 288 |
+
)
|
| 289 |
+
|
| 290 |
+
safe = "".join(c for c in cfg.game_name if c.isalnum() or c in "_-") or "game"
|
| 291 |
+
os.makedirs(out_root, exist_ok=True)
|
| 292 |
+
dest = os.path.join(out_root, f"{safe}-{variant}.apk")
|
| 293 |
+
rm_rf(dest)
|
| 294 |
+
shutil.copy2(apk, dest)
|
| 295 |
+
|
| 296 |
+
size = os.path.getsize(dest)
|
| 297 |
+
bus.ok(f"APK hazır: {os.path.basename(dest)} ({human(size)})")
|
| 298 |
+
return {"apk": dest, "size": size, "variant": variant}
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
def _find_apk(project: str, variant: str) -> str | None:
|
| 302 |
+
outputs = os.path.join(project, "app", "build", "outputs", "apk", variant)
|
| 303 |
+
if not os.path.isdir(outputs):
|
| 304 |
+
return None
|
| 305 |
+
for name in sorted(os.listdir(outputs)):
|
| 306 |
+
if name.endswith(".apk"):
|
| 307 |
+
return os.path.join(outputs, name)
|
| 308 |
+
return None
|