Pin the standalone Horizon fork as a submodule (#104)

Replace patch-stack reconstruction with safe pinned initialization and legacy checkout migration; use an engine-local packer and write artifact identities.

Co-Authored-By: Codex <noreply@openai.com>
This commit is contained in:
2026-11-02 01:09:21 +03:00
parent afe320786d
commit 4761ae7d70
57 changed files with 194 additions and 47435 deletions
+63 -66
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env python3
"""AirDef: сборка, установка и запуск на Windows, macOS и Linux. Только стандартная библиотека Python.
python3 tools/airdef.py fork # скачать Horizon нужной версии и наложить патчи форка (horizon/)
python3 tools/airdef.py fork # инициализировать закреплённый сабмодуль Horizon (horizon/)
python3 tools/airdef.py game # собрать игру (форк) — нужен Rust
python3 tools/airdef.py mod # собрать мод airdef.hmod — нужен Rust с wasm32
python3 tools/airdef.py install # положить мод в папку игры и включить
@@ -26,7 +26,6 @@ from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
FORK = ROOT / "horizon"
UPSTREAM = "https://github.com/ludovic111/horizon.git"
EXE = ".exe" if os.name == "nt" else ""
@@ -56,51 +55,46 @@ def cargo() -> str:
return found
def fork_stamp(commit: str, patches) -> str:
"""Что должно стоять в horizon/: коммит апстрима и содержимое патчей."""
h = hashlib.sha256(commit.encode())
for p in patches:
h.update(p.name.encode())
h.update(p.read_bytes())
return h.hexdigest()
def engine_commit() -> str:
"""The index pins the engine, including a deliberate not-yet-committed gitlink update."""
row = subprocess.check_output(["git", "ls-files", "--stage", "--", "horizon"], cwd=ROOT, text=True).strip().split()
if len(row) < 2 or row[0] != "160000":
sys.exit("Нет закреплённого сабмодуля horizon/: проверьте checkout AirDef")
return row[1]
def engine_identity() -> str:
commit = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=FORK, text=True).strip()
diff = subprocess.check_output(["git", "diff", "--binary", "HEAD"], cwd=FORK)
return commit + ("-" + hashlib.sha256(diff).hexdigest()[:16] if diff else "")
def fork():
"""horizon/ = апстрим на коммите HORIZON_COMMIT + патчи horizon-patches/.
Ветка airdef пересобирается, когда коммит или патчи изменились (после обновления репозитория);
прежняя остаётся в ветке airdef-prev."""
commit = (ROOT / "HORIZON_COMMIT").read_text().strip()
patches = sorted((ROOT / "horizon-patches").glob("*.patch"))
stamp = fork_stamp(commit, patches)
stamp_file = FORK / ".git" / "airdef-stamp"
if not (FORK / ".git").exists():
# Без CRLF на Windows: патчи накладываются на файлы как в апстриме.
run(["git", "clone", "-c", "core.autocrlf=false", "--filter=blob:none", UPSTREAM, FORK])
branch = subprocess.run(["git", "-C", FORK, "branch", "--show-current"], capture_output=True, text=True).stdout.strip()
if branch == "airdef" and stamp_file.exists() and stamp_file.read_text().strip() == stamp:
print("horizon/: ветка airdef на нужных коммите и патчах")
return
dirty = subprocess.run(["git", "-C", FORK, "status", "--porcelain", "--untracked-files=no"],
capture_output=True, text=True).stdout.strip()
if dirty:
sys.exit("horizon/: есть незакоммиченные изменения, а движок надо обновить. Закоммить или убери их и запусти снова.")
exists = subprocess.run(["git", "-C", FORK, "rev-parse", "--verify", "-q", "refs/heads/airdef"],
capture_output=True).returncode == 0
if exists:
print("horizon/: коммит или патчи изменились, ветка airdef пересобирается (прежняя: airdef-prev)")
run(["git", "-C", FORK, "branch", "-f", "airdef-prev", "airdef"])
run(["git", "-C", FORK, "fetch", "--quiet", "origin", commit])
run(["git", "-C", FORK, "checkout", "-B", "airdef", commit])
if patches:
run(["git", "-C", FORK, "-c", "user.name=airdef", "-c", "user.email=airdef@localhost",
"am", "--3way", *patches])
stamp_file.write_text(stamp + "\n")
"""Initialize the exact gitlink; never replace a modified developer checkout."""
expected = engine_commit()
if (FORK / ".git").exists():
current = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=FORK, text=True).strip()
if current == expected:
print(f"horizon/: закреплённый коммит {expected}")
return
dirty = subprocess.check_output(["git", "status", "--porcelain"], cwd=FORK, text=True).strip()
if dirty:
sys.exit("horizon/: есть изменения при другом закреплённом SHA; сохраните их перед обновлением сабмодуля")
if (FORK / ".git").is_dir():
# Migrate the old standalone clone without deleting it or any local branches.
run(["git", "submodule", "absorbgitdirs", "--", "horizon"], cwd=ROOT)
url = subprocess.check_output(["git", "config", "-f", ".gitmodules", "--get", "submodule.horizon.url"], cwd=ROOT, text=True).strip()
run(["git", "remote", "set-url", "origin", url], cwd=FORK)
elif FORK.exists() and any(FORK.iterdir()):
sys.exit("horizon/: непустой каталог без Git; сохраните его перед инициализацией сабмодуля")
run(["git", "submodule", "update", "--init", "--recursive", "--", "horizon"], cwd=ROOT)
current = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=FORK, text=True).strip()
if current != expected:
sys.exit(f"horizon/: ожидался {expected}, получен {current}")
def game():
if not (FORK / "Cargo.toml").exists():
fork()
fork()
run([cargo(), "build", "--profile", "fast", "-p", "horizon-client", "--features", "mods"], cwd=FORK)
@@ -113,19 +107,28 @@ def built_game() -> Path:
sys.exit("Нет собранной игры: python3 tools/airdef.py game (или AIRDEF_GAME=путь к horizon-client)")
def packer_path() -> Path:
return ROOT / ".horizon-cache" / "packer" / engine_identity() / "bin" / ("cargo-horizon-mod" + EXE)
def mod():
tool = shutil.which("cargo-horizon-mod") or Path.home() / ".cargo" / "bin" / ("cargo-horizon-mod" + EXE)
if not (FORK / "Cargo.toml").exists():
fork()
# Упаковщик должен быть от этого форка: старый не знает новых уровней API.
stamp_file = FORK / ".git" / "airdef-packer-stamp"
commit = (ROOT / "HORIZON_COMMIT").read_text().strip()
stamp = fork_stamp(commit, sorted((ROOT / "horizon-patches").glob("*.patch")))
if not Path(tool).exists() or not stamp_file.exists() or stamp_file.read_text().strip() != stamp:
# Without trial runs (wasmtime): building a mod needs only packing, a fraction of the compile.
run([cargo(), "install", "--locked", "--force", "--no-default-features", "--path", FORK / "crates" / "cargo-horizon-mod"])
stamp_file.write_text(stamp + "\n")
run([cargo(), "horizon-mod", "build"], cwd=ROOT / "airdef-mod")
fork()
tool = packer_path()
if not tool.exists():
run([cargo(), "install", "--locked", "--no-default-features", "--root", tool.parent.parent,
"--path", FORK / "crates" / "cargo-horizon-mod"])
# Invoke the pinned executable directly; PATH may contain an unrelated old packer.
build_env = dict(os.environ)
build_env["PATH"] = str(Path(cargo()).parent) + os.pathsep + build_env.get("PATH", "")
run([tool, "horizon-mod", "build"], cwd=ROOT / "airdef-mod", env=build_env)
artifact = hmod()
identity = {"airdef": subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=ROOT, text=True).strip(),
"engine": engine_identity(), "engine_pin": engine_commit(),
"wit_sha256": hashlib.sha256((FORK / "crates/horizon-mod-sdk/wit/horizon.wit").read_bytes()).hexdigest(),
"artifact_sha256": hashlib.sha256(artifact.read_bytes()).hexdigest(),
"airdef_dirty": bool(subprocess.check_output(["git", "status", "--porcelain", "--untracked-files=no"], cwd=ROOT)),
"airdef_diff_sha256": hashlib.sha256(subprocess.check_output(["git", "diff", "--binary", "HEAD"], cwd=ROOT)).hexdigest()}
artifact.with_name("build-identity.json").write_text(json.dumps(identity, indent=2) + "\n")
def hmod() -> Path:
@@ -211,9 +214,7 @@ def game_level():
def check():
"""Говорит прямо, совпадают ли форк, упаковщик, уровень API мода с игрой и ресурсы. Код 0 — да, 1 — нет."""
commit = (ROOT / "HORIZON_COMMIT").read_text().strip()
patches = sorted((ROOT / "horizon-patches").glob("*.patch"))
stamp = fork_stamp(commit, patches)
commit = engine_commit()
problems = []
def line(name, ok, text):
@@ -221,16 +222,12 @@ def check():
if not ok:
problems.append(name)
stamp_file = FORK / ".git" / "airdef-stamp"
fork_ok = stamp_file.exists() and stamp_file.read_text().strip() == stamp
line("форк", fork_ok, f"коммит {commit[:12]}, патчей {len(patches)}" if fork_ok else
"horizon/ не собран из HORIZON_COMMIT и horizon-patches/: python3 tools/airdef.py fork")
tool = shutil.which("cargo-horizon-mod") or str(Path.home() / ".cargo" / "bin" / ("cargo-horizon-mod" + EXE))
packer_stamp = FORK / ".git" / "airdef-packer-stamp"
packer_ok = Path(tool).exists() and packer_stamp.exists() and packer_stamp.read_text().strip() == stamp
line("упаковщик", packer_ok, "собран из этого форка" if packer_ok else
"не установлен или собран из другого форка: python3 tools/airdef.py mod")
current = subprocess.run(["git", "rev-parse", "HEAD"], cwd=FORK, capture_output=True, text=True).stdout.strip() if (FORK / ".git").exists() else ""
fork_ok = current == commit
line("форк", fork_ok, f"gitlink {commit}, checkout {current or 'не инициализирован'}")
packer_ok = fork_ok and packer_path().exists()
line("упаковщик", packer_ok, "repo-local, соответствует engine identity" if packer_ok else
"нет упаковщика этого форка: python3 tools/airdef.py mod")
api = fork_api()
try:
+76
View File
@@ -0,0 +1,76 @@
"""Real-Git checks for pinned initialization and safe legacy migration; no network."""
import importlib.util
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
from unittest.mock import patch
spec = importlib.util.spec_from_file_location('airdef_tool', Path(__file__).with_name('airdef.py'))
tool = importlib.util.module_from_spec(spec)
spec.loader.exec_module(tool)
def git(where, *args):
return subprocess.check_output(['git', '-C', str(where), *args], stderr=subprocess.STDOUT, text=True).strip()
class CheckoutTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.base = Path(self.tmp.name)
self.engine = self.base / 'engine'
self.engine.mkdir()
git(self.engine, 'init', '-q')
git(self.engine, 'config', 'user.name', 'Fixture')
git(self.engine, 'config', 'user.email', 'fixture@example.invalid')
(self.engine / 'marker').write_text('old')
git(self.engine, 'add', 'marker')
git(self.engine, 'commit', '-qm', 'old')
self.old = git(self.engine, 'rev-parse', 'HEAD')
(self.engine / 'marker').write_text('new')
git(self.engine, 'commit', '-qam', 'new')
self.new = git(self.engine, 'rev-parse', 'HEAD')
self.parent = self.base / 'airdef'
self.parent.mkdir()
git(self.parent, 'init', '-q')
(self.parent / '.gitmodules').write_text('[submodule "horizon"]\n path = horizon\n url = ' + str(self.engine) + '\n')
git(self.parent, 'add', '.gitmodules')
self.pin(self.old)
self.addCleanup(patch.stopall)
patch.object(tool, 'ROOT', self.parent).start()
patch.object(tool, 'FORK', self.parent / 'horizon').start()
patch.dict(os.environ, {'GIT_ALLOW_PROTOCOL': 'file'}).start()
def pin(self, sha):
git(self.parent, 'update-index', '--add', '--cacheinfo', '160000,' + sha + ',horizon')
def test_initialization_uses_pin_instead_of_newer_tip(self):
tool.fork()
self.assertEqual(git(tool.FORK, 'rev-parse', 'HEAD'), self.old)
self.assertEqual((tool.FORK / 'marker').read_text(), 'old')
tool.fork() # idempotent
def test_dirty_checkout_is_preserved_when_pin_changes(self):
tool.fork()
(tool.FORK / 'marker').write_text('user changes')
self.pin(self.new)
with self.assertRaises(SystemExit):
tool.fork()
self.assertEqual((tool.FORK / 'marker').read_text(), 'user changes')
self.assertEqual(git(tool.FORK, 'rev-parse', 'HEAD'), self.old)
def test_old_standalone_clone_is_absorbed_without_losing_branches(self):
git(self.parent, 'clone', str(self.engine), 'horizon')
git(tool.FORK, 'checkout', '-qb', 'my-work', self.old)
self.pin(self.new)
tool.fork()
self.assertTrue((tool.FORK / '.git').is_file())
self.assertEqual(git(tool.FORK, 'rev-parse', 'HEAD'), self.new)
self.assertEqual(git(tool.FORK, 'rev-parse', 'my-work'), self.old)
if __name__ == '__main__':
unittest.main()