#!/usr/bin/env python3 """Safely install Forge's portable testtask entry point in an existing repository.""" import argparse import hashlib import json import shutil import subprocess import sys from pathlib import Path SOURCE = Path(__file__).resolve().parents[1] / "distribution/testtask" FILES = ("testtask.sh", "testtask_runner.py") def digest(path): return hashlib.sha256(path.read_bytes()).hexdigest() def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("repository", type=Path) parser.add_argument("--update", action="store_true", help="update an unmodified prior Forge installation") parser.add_argument("--dry-run", action="store_true") args = parser.parse_args() root = args.repository.resolve() probe = subprocess.run(["git", "-C", str(root), "rev-parse", "--show-toplevel"], capture_output=True, text=True) if not root.is_dir() or probe.returncode or Path(probe.stdout.strip()).resolve() != root: parser.error("repository must be an existing Git checkout") target = root / "scripts" if target.is_symlink(): parser.error("scripts directory is a symlink; reconcile manually") manifest = target / ".forge-testtask-install.json" previous = None if manifest.exists(): try: previous = json.loads(manifest.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError): parser.error("invalid installation manifest; reconcile manually") if args.update and previous is None: parser.error("no prior Forge installation; reconcile existing scripts manually") if not args.update and previous is not None: parser.error("Forge testtask already installed; use --update") for name in FILES: dest = target / name if args.update: if dest.is_symlink() or not dest.is_file() or previous.get(name) != digest(dest): parser.error(f"modified or missing installed file: {dest}; reconcile manually") elif dest.exists() or dest.is_symlink(): parser.error(f"installation conflict: {dest}; reconcile manually") if not args.update and manifest.exists(): parser.error(f"installation conflict: {manifest}") print(f"{'Update' if args.update else 'Install'} testtask in {root}") for name in FILES: print(f" {target / name}") if args.dry_run: return 0 target.mkdir(parents=True, exist_ok=True) for name in FILES: shutil.copy2(SOURCE / name, target / name) manifest.write_text(json.dumps({name: digest(target / name) for name in FILES}, indent=2) + "\n", encoding="utf-8") return 0 if __name__ == "__main__": sys.exit(main())