Files
ai-engineering/scripts/activate-native-package.py
T

73 lines
2.6 KiB
Python

#!/usr/bin/env python3
"""Installer activation helper. Tests run a copied helper with fake tools and destinations."""
import argparse
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import uuid
parser = argparse.ArgumentParser()
parser.add_argument("package", type=Path)
parser.add_argument("--bin-dir", type=Path, required=True)
parser.add_argument("--lib-dir", type=Path, required=True)
args = parser.parse_args()
bin_dir = args.bin_dir.absolute()
lib_dir = args.lib_dir.absolute()
bin_dir.mkdir(parents=True, exist_ok=True)
lib_dir.mkdir(parents=True, exist_ok=True)
current = lib_dir / "current"
if current.exists() and not current.is_symlink():
raise SystemExit("Package current target must be a symlink")
names = {"ai-engineering": str(current / "ai-engineering"), "aie": "ai-engineering",
"aie-sqlite3": str(current / "sqlite3")}
for name in names:
if (bin_dir / name).is_dir():
raise SystemExit("Installation target is a directory: " + str(bin_dir / name))
release = lib_dir / "releases" / str(uuid.uuid4())
release.parent.mkdir(parents=True, exist_ok=True)
shutil.copytree(args.package, release)
try:
subprocess.run([sys.executable, str(Path(__file__).with_name("verify-native-package.py")), str(release)], check=True)
except BaseException:
shutil.rmtree(release)
raise
backup = Path(tempfile.mkdtemp(prefix=".aie-install.", dir=bin_dir))
previous_current = os.readlink(current) if current.is_symlink() else None
changed = []
safe_to_cleanup = False
try:
for name, target in names.items():
path = bin_dir / name
if path.is_symlink() or path.exists():
shutil.copy2(path, backup / name, follow_symlinks=False)
(backup / (name + ".new")).symlink_to(target)
switch = lib_dir / (".current-" + str(uuid.uuid4()))
switch.symlink_to(str(release.relative_to(lib_dir)))
os.replace(switch, current)
for name in names:
os.replace(backup / (name + ".new"), bin_dir / name)
changed.append(name)
safe_to_cleanup = True
except BaseException:
for name in reversed(changed):
saved = backup / name
if saved.is_symlink() or saved.exists():
os.replace(saved, bin_dir / name)
else:
(bin_dir / name).unlink()
if previous_current is None:
current.unlink(missing_ok=True)
else:
restored = lib_dir / (".restore-" + str(uuid.uuid4())); restored.symlink_to(previous_current)
os.replace(restored, current)
shutil.rmtree(release)
safe_to_cleanup = True
raise
finally:
if safe_to_cleanup:
shutil.rmtree(backup)
print("Activated native package:", current)