| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818 |
- import argparse
- import hashlib
- import json
- import os
- import re
- import shutil
- import subprocess
- import sys
- import tarfile
- import tempfile
- from pathlib import Path, PurePosixPath
- import yaml
- from validate_desired_state import validate_state
- ROOT = Path(__file__).resolve().parents[1]
- STATE_PATH = Path.home() / ".local" / "state" / "rigforge" / "deployment.json"
- NAM_RELEASE_ASSET = re.compile(
- r"^https://github\.com/mikeoliphant/neural-amp-modeler-lv2/releases/download/"
- r"(?P<tag>[A-Za-z0-9._-]+)/neural_amp_modeler_lv2_rpi5\.tgz$"
- )
- PLUGIN_ARCHIVES = {
- "lsp": "7z",
- "dragonfly_reverb": "tar.xz",
- }
- def load_deployment():
- with (ROOT / "config" / "desired-state.yaml").open(encoding="utf-8") as stream:
- state = yaml.safe_load(stream)
- errors = validate_state(state)
- deployment = state.get("deployment") if isinstance(state, dict) else None
- if not isinstance(deployment, dict):
- raise ValueError("deployment must be a mapping")
- namlv2 = deployment.get("namlv2")
- pipewire = deployment.get("pipewire")
- if not isinstance(namlv2, dict) or not isinstance(pipewire, dict):
- raise ValueError("deployment.namlv2 and deployment.pipewire must be mappings")
- for component, archive_format in PLUGIN_ARCHIVES.items():
- plugin = deployment.get(component)
- if not isinstance(plugin, dict):
- raise ValueError(f"deployment.{component} must be a mapping")
- if plugin.get("archive_format") != archive_format:
- errors.append(f"{component} archive format is invalid")
- if not isinstance(plugin.get("bundle_paths"), dict) or not plugin["bundle_paths"]:
- errors.append(f"{component} bundle paths are invalid")
- tag = namlv2.get("tag")
- match = NAM_RELEASE_ASSET.fullmatch(namlv2.get("archive_url", ""))
- if not isinstance(tag, str) or not re.fullmatch(r"[A-Za-z0-9._-]+", tag):
- errors.append("NAM LV2 tag is invalid")
- if match is None or match.group("tag") != tag:
- errors.append("NAM LV2 URL must be the approved release asset for the declared tag")
- if namlv2.get("bundle_directory") != "neural_amp_modeler.lv2":
- errors.append("NAM LV2 bundle directory is invalid")
- source = pipewire.get("fragment_source")
- if source != "config/pipewire/filter-chain.conf.d/rigforge-direct-mix.conf":
- errors.append("PipeWire fragment source is invalid")
- if pipewire.get("fragment_destination") != ".config/pipewire/filter-chain.conf.d/rigforge-direct-mix.conf":
- errors.append("PipeWire fragment destination is invalid")
- if pipewire.get("user_service") != "filter-chain.service":
- errors.append("PipeWire user service is invalid")
- if errors:
- raise ValueError("; ".join(errors))
- return deployment
- def read_registry():
- if not STATE_PATH.exists():
- return {}
- with STATE_PATH.open(encoding="utf-8") as stream:
- registry = json.load(stream)
- if not isinstance(registry, dict):
- raise ValueError(f"deployment registry is not a mapping: {STATE_PATH}")
- return registry
- def write_registry(registry):
- STATE_PATH.parent.mkdir(parents=True, exist_ok=True)
- fd, temporary_name = tempfile.mkstemp(prefix="deployment.", dir=STATE_PATH.parent)
- try:
- with os.fdopen(fd, "w", encoding="utf-8") as stream:
- json.dump(registry, stream, indent=2, sort_keys=True)
- stream.write("\n")
- os.replace(temporary_name, STATE_PATH)
- finally:
- if os.path.exists(temporary_name):
- os.unlink(temporary_name)
- def run(command):
- subprocess.run(command, check=True)
- def tree_sha256(path):
- digest = hashlib.sha256()
- for item in sorted(path.rglob("*")):
- relative = item.relative_to(path).as_posix().encode()
- digest.update(relative + b"\\0")
- if item.is_symlink():
- digest.update(b"link\\0" + os.readlink(item).encode())
- elif item.is_file():
- digest.update(b"file\\0" + item.read_bytes())
- elif item.is_dir():
- digest.update(b"directory\\0")
- else:
- raise RuntimeError(f"unsupported file type in managed bundle: {item}")
- return digest.hexdigest()
- def validate_user_destination(destination):
- home = Path.home().resolve()
- parent = destination.parent.resolve()
- if not parent.is_relative_to(home):
- raise RuntimeError(f"deployment path escapes the user home directory: {destination}")
- if destination.is_symlink():
- raise RuntimeError(f"refusing to manage a symlink destination: {destination}")
- def validate_backup_path(backup, destination, is_directory=False):
- if backup is None:
- return None
- backup_path = Path(backup)
- expected = destination.with_name(destination.name + ".rigforge-backup")
- if backup_path != expected:
- raise RuntimeError(f"recorded backup path is outside its approved location: {backup_path}")
- if backup_path.is_symlink():
- raise RuntimeError(f"recorded backup must not be a symlink: {backup_path}")
- if backup_path.exists() and backup_path.is_dir() != is_directory:
- raise RuntimeError(f"recorded backup has the wrong type: {backup_path}")
- return backup_path
- def atomic_install(source, destination):
- destination.parent.mkdir(parents=True, exist_ok=True)
- fd, temporary_name = tempfile.mkstemp(prefix=f".{destination.name}.", dir=destination.parent)
- os.close(fd)
- try:
- shutil.copyfile(source, temporary_name)
- shutil.copymode(source, temporary_name)
- os.replace(temporary_name, destination)
- finally:
- if os.path.exists(temporary_name):
- os.unlink(temporary_name)
- def apply_quantum(frames):
- run(["pw-metadata", "-n", "settings", "0", "clock.force-quantum", str(frames)])
- def restart_filter_service(service):
- run(["systemctl", "--user", "restart", service])
- run(["systemctl", "--user", "is-active", "--quiet", service])
- def deploy_pipewire(action, config, registry, quantum_frames):
- destination = Path.home() / config["fragment_destination"]
- validate_user_destination(destination)
- source = ROOT / config["fragment_source"]
- managed = registry.get("pipewire")
- pending_reload = registry.get("pipewire_pending_reload")
- if pending_reload is not None:
- apply_quantum(pending_reload["quantum_frames"])
- restart_filter_service(config["user_service"])
- registry.pop("pipewire_pending_reload")
- write_registry(registry)
- managed = registry.get("pipewire")
- if action == "reload":
- if not source.is_file() or not destination.is_file():
- raise RuntimeError("PipeWire reload requires both the repository fragment and installed fragment")
- apply_quantum(quantum_frames)
- restart_filter_service(config["user_service"])
- print("PipeWire runtime quantum applied; filter-chain user service restarted.")
- return
- if action == "install":
- if managed is not None and managed.get("pending_uninstall"):
- raise RuntimeError("PipeWire uninstall is incomplete; retry uninstall pipewire first")
- if managed is not None:
- validate_backup_path(managed.get("backup"), destination)
- if not destination.exists():
- raise RuntimeError(f"managed PipeWire fragment is missing: {destination}")
- if managed is not None and destination.exists():
- current_digest = hashlib.sha256(destination.read_bytes()).hexdigest()
- if current_digest != managed["installed_sha256"]:
- raise RuntimeError(f"managed file changed locally; refusing overwrite: {destination}")
- was_unmanaged = managed is None
- changed = not destination.exists() or destination.read_bytes() != source.read_bytes()
- if managed is None:
- backup_path = None
- backup_sha256 = None
- if destination.exists():
- backup_path = str(destination.with_name(destination.name + ".rigforge-backup"))
- if Path(backup_path).exists():
- raise RuntimeError(f"backup path already exists: {backup_path}")
- shutil.copy2(destination, backup_path)
- backup_sha256 = hashlib.sha256(Path(backup_path).read_bytes()).hexdigest()
- managed = {
- "installed_sha256": "",
- "backup": backup_path,
- "backup_sha256": backup_sha256,
- }
- registry["pipewire"] = managed
- if changed:
- atomic_install(source, destination)
- managed["installed_sha256"] = hashlib.sha256(source.read_bytes()).hexdigest()
- managed["pending_reload"] = changed or was_unmanaged or managed.get("pending_reload", False)
- registry["pipewire"] = managed
- write_registry(registry)
- apply_quantum(quantum_frames)
- if managed["pending_reload"]:
- restart_filter_service(config["user_service"])
- managed.pop("pending_reload", None)
- registry["pipewire"] = managed
- write_registry(registry)
- print(f"PipeWire fragment {'updated' if changed else 'already current'} at {destination}.")
- return
- if action == "uninstall":
- if managed is None:
- print("No managed PipeWire fragment to uninstall.")
- return
- if managed.get("pending_uninstall"):
- backup_path = validate_backup_path(managed.get("backup"), destination)
- backup_exists = backup_path is not None and backup_path.is_file()
- if backup_path is not None and backup_path.exists():
- if not backup_exists:
- raise RuntimeError(f"recorded backup has the wrong type: {backup_path}")
- backup_digest = hashlib.sha256(backup_path.read_bytes()).hexdigest()
- if backup_digest != managed.get("backup_sha256"):
- raise RuntimeError(f"recorded backup changed locally: {backup_path}")
- if destination.exists():
- current_digest = hashlib.sha256(destination.read_bytes()).hexdigest()
- if backup_exists and current_digest == managed.get("backup_sha256"):
- backup_path.unlink()
- elif backup_path is not None and not backup_exists and current_digest == managed.get("backup_sha256"):
- pass
- elif current_digest == managed.get("installed_sha256"):
- destination.unlink()
- if backup_exists:
- os.replace(backup_path, destination)
- elif backup_path is not None:
- raise RuntimeError(f"recorded backup is missing: {backup_path}")
- else:
- raise RuntimeError(f"unexpected file blocks pending uninstall: {destination}")
- elif backup_exists:
- os.replace(backup_path, destination)
- elif backup_path is not None:
- raise RuntimeError(f"recorded backup is missing: {backup_path}")
- registry.pop("pipewire")
- write_registry(registry)
- apply_quantum(0)
- restart_filter_service(config["user_service"])
- print("Completed interrupted PipeWire uninstall and restored prior state.")
- return
- if not destination.exists():
- raise RuntimeError(f"managed PipeWire fragment is missing: {destination}")
- current_digest = hashlib.sha256(destination.read_bytes()).hexdigest()
- if current_digest != managed["installed_sha256"]:
- raise RuntimeError(f"managed file changed locally; refusing to remove: {destination}")
- backup_path = validate_backup_path(managed.get("backup"), destination)
- if backup_path is not None and not backup_path.is_file():
- raise RuntimeError(f"recorded backup is missing: {backup_path}")
- if backup_path is not None:
- backup_digest = hashlib.sha256(backup_path.read_bytes()).hexdigest()
- if backup_digest != managed.get("backup_sha256"):
- raise RuntimeError(f"recorded backup changed locally: {backup_path}")
- managed["pending_uninstall"] = True
- registry["pipewire"] = managed
- write_registry(registry)
- destination.unlink()
- if backup_path is not None:
- atomic_install(backup_path, destination)
- backup_path.unlink()
- registry.pop("pipewire")
- registry["pipewire_pending_reload"] = {"quantum_frames": 0}
- write_registry(registry)
- apply_quantum(0)
- restart_filter_service(config["user_service"])
- registry.pop("pipewire_pending_reload")
- write_registry(registry)
- print("Rigforge PipeWire fragment removed or prior file restored; quantum reset to automatic.")
- return
- def inspect_archive(archive_path, bundle_name):
- with tarfile.open(archive_path, "r:gz") as archive:
- members = archive.getmembers()
- bundle_prefix = PurePosixPath(bundle_name)
- matching = []
- for member in members:
- member_path = PurePosixPath(member.name)
- if member_path.is_absolute() or ".." in member_path.parts:
- raise RuntimeError(f"unsafe archive path: {member.name}")
- if member_path.parts and member_path.parts[0] == bundle_prefix.name:
- if not member_path.is_relative_to(bundle_prefix):
- raise RuntimeError(f"unexpected bundle path: {member.name}")
- if not (member.isdir() or member.isfile()):
- raise RuntimeError(f"unsupported archive member type: {member.name}")
- matching.append(member)
- else:
- raise RuntimeError(f"unexpected archive path: {member.name}")
- if not matching or not any(member.name == bundle_name and member.isdir() for member in matching):
- raise RuntimeError(f"archive does not contain expected bundle directory {bundle_name}")
- return members
- def extract_bundle(archive_path, destination, bundle_name):
- with tarfile.open(archive_path, "r:gz") as archive:
- members = inspect_archive(archive_path, bundle_name)
- for member in members:
- member_path = PurePosixPath(member.name)
- relative_parts = member_path.parts[1:]
- output_path = destination.joinpath(*relative_parts) if relative_parts else destination
- if member.isdir():
- output_path.mkdir(parents=True, exist_ok=True)
- output_path.chmod(0o755)
- continue
- output_path.parent.mkdir(parents=True, exist_ok=True)
- extracted = archive.extractfile(member)
- if extracted is None:
- raise RuntimeError(f"unable to read archive member: {member.name}")
- with extracted, output_path.open("wb") as output:
- shutil.copyfileobj(extracted, output)
- output_path.chmod(0o755 if member.mode & 0o111 else 0o644)
- def download_archive(url, destination):
- run(["curl", "--fail", "--location", "--silent", "--show-error", "--output", str(destination), url])
- def inspect_tar_archive(archive_path, bundle_paths):
- expected_roots = {PurePosixPath(path) for path in bundle_paths.values()}
- with tarfile.open(archive_path, "r:xz") as archive:
- members = archive.getmembers()
- for member in members:
- member_path = PurePosixPath(member.name)
- if member_path.is_absolute() or ".." in member_path.parts:
- raise RuntimeError(f"unsafe archive path: {member.name}")
- if not member.isfile() and not member.isdir():
- raise RuntimeError(f"unsupported archive member type: {member.name}")
- for bundle_root in expected_roots:
- if not any(member.name.rstrip("/") == str(bundle_root) and member.isdir() for member in members):
- raise RuntimeError(f"archive does not contain expected bundle directory {bundle_root}")
- if not any(member.name == f"{bundle_root}/manifest.ttl" and member.isfile() for member in members):
- raise RuntimeError(f"archive bundle is missing manifest.ttl: {bundle_root}")
- return expected_roots
- def extract_tar_bundles(archive_path, bundle_paths, extraction_root):
- expected_roots = inspect_tar_archive(archive_path, bundle_paths)
- extracted = {bundle_name: extraction_root / bundle_name for bundle_name in bundle_paths}
- with tarfile.open(archive_path, "r:xz") as archive:
- for member in archive.getmembers():
- member_path = PurePosixPath(member.name)
- bundle_root = next(
- (root for root in expected_roots if member_path == root or member_path.is_relative_to(root)),
- None,
- )
- if bundle_root is None:
- continue
- bundle_name = next(name for name, path in bundle_paths.items() if PurePosixPath(path) == bundle_root)
- output_path = extracted[bundle_name].joinpath(*member_path.parts[len(bundle_root.parts):])
- if member.isdir():
- output_path.mkdir(parents=True, exist_ok=True)
- output_path.chmod(0o755)
- continue
- output_path.parent.mkdir(parents=True, exist_ok=True)
- source = archive.extractfile(member)
- if source is None:
- raise RuntimeError(f"unable to read archive member: {member.name}")
- with source, output_path.open("wb") as destination:
- shutil.copyfileobj(source, destination)
- output_path.chmod(0o755 if member.mode & 0o111 else 0o644)
- return extracted
- def inspect_7z_archive(bundle_paths, listing):
- paths = []
- current = {}
- for line in listing.splitlines() + [""]:
- if not line and current:
- path = current.get("Path")
- attributes = current.get("Attributes", "")
- if path and attributes:
- member_path = PurePosixPath(path)
- if member_path.is_absolute() or ".." in member_path.parts:
- raise RuntimeError(f"unsafe archive path: {path}")
- if "L" in attributes or "H" in attributes:
- raise RuntimeError(f"unsupported archive member type: {path}")
- paths.append((member_path, "D" in attributes))
- current = {}
- elif " = " in line:
- key, value = line.split(" = ", 1)
- current[key] = value
- expected_roots = {PurePosixPath(path) for path in bundle_paths.values()}
- present_roots = {path for path, is_directory in paths if is_directory and path in expected_roots}
- if present_roots != expected_roots:
- raise RuntimeError(f"7z archive is missing expected LV2 bundles: {sorted(map(str, expected_roots - present_roots))}")
- for root in expected_roots:
- if not any(path == root / "manifest.ttl" and not is_directory for path, is_directory in paths):
- raise RuntimeError(f"7z archive bundle is missing manifest.ttl: {root}")
- return expected_roots, paths
- def extract_7z_bundles(archive_path, bundle_paths, extraction_root):
- executable = shutil.which("7z") or shutil.which("7zz") or shutil.which("7za")
- if executable is None:
- raise RuntimeError("installing LSP plugins requires 7z, 7zz, or 7za on PATH")
- listing = subprocess.run(
- [executable, "l", "-slt", str(archive_path)],
- check=True,
- capture_output=True,
- text=True,
- ).stdout
- expected_roots, paths = inspect_7z_archive(bundle_paths, listing)
- temporary_output = extraction_root / "7z-output"
- temporary_output.mkdir()
- result = subprocess.run(
- [executable, "x", "-y", f"-o{temporary_output}", str(archive_path)],
- check=False,
- capture_output=True,
- text=True,
- )
- if result.returncode != 0:
- missing_files = [
- path
- for path, is_directory in paths
- if not is_directory
- and any(path.is_relative_to(root) for root in expected_roots)
- and not temporary_output.joinpath(*path.parts).is_file()
- ]
- if missing_files:
- raise subprocess.CalledProcessError(
- result.returncode,
- result.args,
- output=result.stdout,
- stderr=result.stderr,
- )
- extracted = {}
- for bundle_name, path in bundle_paths.items():
- bundle_root = PurePosixPath(path)
- source = temporary_output.joinpath(*bundle_root.parts)
- if not source.is_dir():
- raise RuntimeError(f"expected LV2 bundle missing after extraction: {source}")
- target = extraction_root / bundle_name
- shutil.copytree(source, target, symlinks=False)
- extracted[bundle_name] = target
- return extracted
- def deploy_lv2_archives(action, component, config, registry):
- bundle_paths = config["bundle_paths"]
- bundle_names = list(bundle_paths)
- destinations = {name: Path.home() / ".lv2" / name for name in bundle_names}
- for destination in destinations.values():
- validate_user_destination(destination)
- managed = registry.get(component)
- if action == "reload":
- print(f"Nothing to reload for {component}; restart its LV2 host after installation.")
- return
- if action == "uninstall":
- if managed is None:
- print(f"No managed {component} bundles to uninstall.")
- return
- recorded = managed.get("bundles")
- if not isinstance(recorded, dict) or set(recorded) != set(bundle_names):
- raise RuntimeError(f"managed {component} bundle declaration changed")
- if managed.get("pending_uninstall"):
- for name, destination in destinations.items():
- record = recorded[name]
- backup = validate_backup_path(record.get("backup"), destination, is_directory=True)
- backup_exists = backup is not None and backup.is_dir()
- if backup is not None and backup.exists() and not backup_exists:
- raise RuntimeError(f"recorded backup has the wrong type: {backup}")
- if backup_exists and tree_sha256(backup) != record.get("backup_sha256"):
- raise RuntimeError(f"recorded backup bundle changed locally: {backup}")
- if destination.exists():
- current = tree_sha256(destination)
- if backup_exists and current == record.get("backup_sha256"):
- continue
- if backup is None and record.get("backup_sha256") is None:
- if current == record.get("installed_sha256"):
- continue
- raise RuntimeError(f"unexpected bundle blocks pending uninstall: {destination}")
- if not backup_exists and current == record.get("backup_sha256"):
- continue
- if current != record.get("installed_sha256"):
- raise RuntimeError(f"unexpected bundle blocks pending uninstall: {destination}")
- elif backup is not None and not backup_exists:
- raise RuntimeError(f"recorded backup bundle is missing: {backup}")
- for name, destination in destinations.items():
- record = recorded[name]
- backup = validate_backup_path(record.get("backup"), destination, is_directory=True)
- backup_exists = backup is not None and backup.is_dir()
- if destination.exists() and tree_sha256(destination) == record.get("installed_sha256"):
- shutil.rmtree(destination)
- if backup_exists:
- os.replace(backup, destination)
- registry.pop(component)
- write_registry(registry)
- print(f"Completed interrupted {component} uninstall at {Path.home() / '.lv2'}.")
- return
- for name, destination in destinations.items():
- record = recorded[name]
- backup = validate_backup_path(record.get("backup"), destination, is_directory=True)
- if not destination.is_dir():
- raise RuntimeError(f"managed {component} bundle is missing: {destination}")
- if record.get("installed_path") != str(destination):
- raise RuntimeError(f"managed {component} path changed: {destination}")
- if tree_sha256(destination) != record.get("installed_sha256"):
- raise RuntimeError(f"managed {component} bundle changed locally; refusing to remove: {destination}")
- if backup is not None:
- if not backup.is_dir():
- raise RuntimeError(f"recorded backup bundle is missing: {backup}")
- if tree_sha256(backup) != record.get("backup_sha256"):
- raise RuntimeError(f"recorded backup bundle changed locally: {backup}")
- managed["pending_uninstall"] = True
- registry[component] = managed
- write_registry(registry)
- for name, destination in destinations.items():
- record = recorded[name]
- shutil.rmtree(destination)
- backup = validate_backup_path(record.get("backup"), destination, is_directory=True)
- if backup is not None:
- os.replace(backup, destination)
- registry.pop(component)
- write_registry(registry)
- print(f"Removed managed {component} bundles from {Path.home() / '.lv2'}.")
- return
- if managed is not None:
- if managed.get("pending_uninstall"):
- raise RuntimeError(f"{component} uninstall is incomplete; retry uninstall {component} first")
- recorded = managed.get("bundles")
- if not isinstance(recorded, dict) or set(recorded) != set(bundle_names):
- raise RuntimeError(f"managed {component} bundle declaration changed")
- for name, destination in destinations.items():
- record = recorded[name]
- backup = validate_backup_path(record.get("backup"), destination, is_directory=True)
- if backup is not None:
- if not backup.is_dir() or tree_sha256(backup) != record.get("backup_sha256"):
- raise RuntimeError(f"recorded backup bundle changed locally: {backup}")
- if not destination.is_dir():
- raise RuntimeError(f"managed {component} bundle is missing: {destination}")
- if tree_sha256(destination) != record.get("installed_sha256"):
- raise RuntimeError(f"managed {component} bundle changed locally; refusing overwrite: {destination}")
- if managed.get("tag") == config["tag"]:
- print(f"{component} tag {config['tag']} is already installed and unchanged.")
- return
- for name, destination in destinations.items():
- previous = managed.get("bundles", {}).get(name) if managed else None
- if previous is not None:
- backup = validate_backup_path(previous.get("backup"), destination, is_directory=True)
- if backup is not None:
- if not backup.is_dir():
- raise RuntimeError(f"recorded backup bundle is missing: {backup}")
- if tree_sha256(backup) != previous.get("backup_sha256"):
- raise RuntimeError(f"recorded backup bundle changed locally: {backup}")
- if previous is None and destination.exists():
- backup = destination.with_name(destination.name + ".rigforge-backup")
- if backup.exists():
- raise RuntimeError(f"backup path already exists: {backup}")
- staged = destination.with_name(destination.name + ".rigforge-new")
- previous_path = destination.with_name(destination.name + ".rigforge-old")
- if staged.exists() or previous_path.exists():
- raise RuntimeError(f"{component} staging or recovery path already exists: {destination}")
- with tempfile.TemporaryDirectory(prefix=f"rigforge-{component}-") as temporary_dir:
- temporary = Path(temporary_dir)
- archive_path = temporary / (
- "plugin.tar.xz" if config["archive_format"] == "tar.xz" else "plugin.7z"
- )
- download_archive(config["archive_url"], archive_path)
- archive_digest = hashlib.sha256(archive_path.read_bytes()).hexdigest()
- extraction_root = temporary / "extract"
- extraction_root.mkdir()
- if config["archive_format"] == "tar.xz":
- extracted = extract_tar_bundles(archive_path, config["bundle_paths"], extraction_root)
- else:
- extracted = extract_7z_bundles(archive_path, config["bundle_paths"], extraction_root)
- records = {}
- created_backups = []
- installed_destinations = []
- try:
- for name, destination in destinations.items():
- previous = managed.get("bundles", {}).get(name) if managed else None
- backup = (
- validate_backup_path(previous.get("backup"), destination, is_directory=True)
- if previous is not None
- else destination.with_name(destination.name + ".rigforge-backup")
- if destination.exists()
- else None
- )
- backup_digest = previous.get("backup_sha256") if previous is not None else None
- if backup is not None and previous is None:
- shutil.copytree(destination, backup, symlinks=True)
- created_backups.append(backup)
- backup_digest = tree_sha256(backup)
- destination.parent.mkdir(parents=True, exist_ok=True)
- staged = destination.with_name(destination.name + ".rigforge-new")
- previous_path = destination.with_name(destination.name + ".rigforge-old")
- shutil.copytree(extracted[name], staged, symlinks=False)
- try:
- if destination.exists():
- os.replace(destination, previous_path)
- os.replace(staged, destination)
- installed_destinations.append((destination, previous_path))
- except OSError:
- if previous_path.exists() and not destination.exists():
- os.replace(previous_path, destination)
- if staged.exists():
- shutil.rmtree(staged)
- raise
- records[name] = {
- "installed_path": str(destination),
- "backup": str(backup) if backup is not None else None,
- "backup_sha256": backup_digest,
- "installed_sha256": tree_sha256(destination),
- }
- for _, previous_path in installed_destinations:
- if previous_path.exists():
- shutil.rmtree(previous_path)
- except (OSError, shutil.Error):
- for destination, previous_path in reversed(installed_destinations):
- if destination.exists():
- shutil.rmtree(destination)
- if previous_path.exists():
- os.replace(previous_path, destination)
- for destination in destinations.values():
- staged = destination.with_name(destination.name + ".rigforge-new")
- if staged.exists():
- shutil.rmtree(staged)
- for backup in created_backups:
- if backup.exists():
- shutil.rmtree(backup)
- raise
- registry[component] = {
- "tag": config["tag"],
- "archive_sha256": archive_digest,
- "bundles": records,
- }
- write_registry(registry)
- print(f"Installed {component} tag {config['tag']} under {Path.home() / '.lv2'}.")
- print(f"Downloaded archive SHA-256 (identity only, no publisher checksum): {archive_digest}")
- def deploy_namlv2(action, config, registry):
- bundle_name = config["bundle_directory"]
- destination = Path.home() / ".lv2" / bundle_name
- validate_user_destination(destination)
- managed = registry.get("namlv2")
- if action == "reload":
- print("Nothing to reload for the NAM LV2 plugin; restart its LV2 host after installation.")
- return
- if action == "uninstall":
- if managed is None:
- print("No managed NAM LV2 bundle to uninstall.")
- return
- if managed.get("pending_uninstall"):
- backup_path = validate_backup_path(managed.get("backup"), destination, is_directory=True)
- backup_exists = backup_path is not None and backup_path.is_dir()
- if backup_path is not None and backup_path.exists() and not backup_exists:
- raise RuntimeError(f"recorded backup has the wrong type: {backup_path}")
- if backup_exists and tree_sha256(backup_path) != managed.get("backup_sha256"):
- raise RuntimeError(f"recorded backup bundle changed locally: {backup_path}")
- if destination.exists():
- destination_digest = tree_sha256(destination)
- if backup_exists and destination_digest == managed.get("backup_sha256"):
- shutil.rmtree(backup_path)
- elif destination_digest == managed.get("installed_sha256"):
- shutil.rmtree(destination)
- if backup_exists:
- os.replace(backup_path, destination)
- else:
- raise RuntimeError(f"unexpected bundle blocks pending uninstall: {destination}")
- elif backup_exists:
- os.replace(backup_path, destination)
- elif backup_path is not None:
- raise RuntimeError(f"recorded backup bundle is missing: {backup_path}")
- registry.pop("namlv2")
- write_registry(registry)
- print(f"Completed interrupted NAM LV2 uninstall at {destination}.")
- return
- if not destination.exists():
- raise RuntimeError(f"managed NAM LV2 bundle is missing: {destination}")
- if managed.get("installed_path") != str(destination):
- raise RuntimeError(f"managed NAM LV2 path changed: {destination}")
- if tree_sha256(destination) != managed.get("installed_sha256"):
- raise RuntimeError(f"managed NAM LV2 bundle changed locally; refusing to remove: {destination}")
- backup_path = validate_backup_path(managed.get("backup"), destination, is_directory=True)
- if backup_path is not None and not backup_path.is_dir():
- raise RuntimeError(f"recorded backup bundle is missing: {backup_path}")
- if backup_path is not None and tree_sha256(backup_path) != managed.get("backup_sha256"):
- raise RuntimeError(f"recorded backup bundle changed locally: {backup_path}")
- managed["pending_uninstall"] = True
- registry["namlv2"] = managed
- write_registry(registry)
- shutil.rmtree(destination)
- if backup_path is not None:
- os.replace(backup_path, destination)
- registry.pop("namlv2")
- write_registry(registry)
- print(f"Removed managed NAM LV2 bundle from {destination}.")
- return
- if managed is not None:
- if managed.get("pending_uninstall"):
- raise RuntimeError("NAM LV2 uninstall is incomplete; retry uninstall namlv2 first")
- if not destination.is_dir():
- raise RuntimeError(f"managed NAM LV2 bundle is missing: {destination}")
- if tree_sha256(destination) != managed.get("installed_sha256"):
- raise RuntimeError(f"managed NAM LV2 bundle changed locally; refusing overwrite: {destination}")
- if managed.get("tag") == config["tag"]:
- print(f"NAM LV2 tag {config['tag']} is already installed and unchanged.")
- return
- backup = validate_backup_path(managed.get("backup"), destination, is_directory=True)
- backup_sha256 = managed.get("backup_sha256")
- elif destination.exists():
- backup = destination.with_name(destination.name + ".rigforge-backup")
- if backup.exists():
- raise RuntimeError(f"backup path already exists: {backup}")
- backup_sha256 = None
- else:
- backup = None
- backup_sha256 = None
- with tempfile.TemporaryDirectory(prefix="rigforge-namlv2-") as temporary_dir:
- temporary = Path(temporary_dir)
- archive_path = temporary / "namlv2.tgz"
- download_archive(config["archive_url"], archive_path)
- archive_digest = hashlib.sha256(archive_path.read_bytes()).hexdigest()
- inspect_archive(archive_path, bundle_name)
- extraction_root = temporary / "extract"
- extraction_root.mkdir()
- extracted_bundle = extraction_root / bundle_name
- extracted_bundle.mkdir()
- extract_bundle(archive_path, extracted_bundle, bundle_name)
- if not extracted_bundle.is_dir():
- raise RuntimeError(f"expected bundle missing after extraction: {extracted_bundle}")
- destination.parent.mkdir(parents=True, exist_ok=True)
- staged_bundle = destination.with_name(destination.name + ".rigforge-new")
- previous_bundle = destination.with_name(destination.name + ".rigforge-old")
- if staged_bundle.exists() or previous_bundle.exists():
- raise RuntimeError("NAM LV2 staging or recovery path already exists")
- backup_created = False
- moved_previous = False
- try:
- shutil.copytree(extracted_bundle, staged_bundle)
- if managed is None and backup is not None:
- shutil.copytree(destination, backup)
- backup_created = True
- backup_sha256 = tree_sha256(backup)
- if destination.exists():
- os.replace(destination, previous_bundle)
- moved_previous = True
- os.replace(staged_bundle, destination)
- except (OSError, shutil.Error):
- if moved_previous and previous_bundle.exists() and not destination.exists():
- os.replace(previous_bundle, destination)
- if backup_created and backup.exists():
- shutil.rmtree(backup)
- raise
- finally:
- if staged_bundle.exists():
- shutil.rmtree(staged_bundle)
- if previous_bundle.exists():
- shutil.rmtree(previous_bundle)
- registry["namlv2"] = {
- "tag": config["tag"],
- "archive_sha256": archive_digest,
- "installed_path": str(destination),
- "backup": str(backup) if backup is not None else None,
- "backup_sha256": backup_sha256,
- "installed_sha256": tree_sha256(destination),
- }
- write_registry(registry)
- print(f"Installed NAM LV2 tag {config['tag']} at {destination}.")
- print(f"Downloaded archive SHA-256 (identity only, no publisher checksum): {archive_digest}")
- def main(argv=None):
- parser = argparse.ArgumentParser()
- parser.add_argument("action", choices=("install", "uninstall", "reload"))
- parser.add_argument("target", choices=("namlv2", "lsp", "dragonfly-reverb", "pipewire"))
- args = parser.parse_args(argv)
- try:
- state = yaml.safe_load((ROOT / "config" / "desired-state.yaml").read_text(encoding="utf-8"))
- deployment = load_deployment()
- quantum_frames = state["parameters"]["quantum_frames"]
- if not isinstance(quantum_frames, int) or isinstance(quantum_frames, bool) or quantum_frames < 1:
- raise ValueError("parameters.quantum_frames must be a positive integer")
- registry = read_registry()
- if args.target == "namlv2":
- deploy_namlv2(args.action, deployment["namlv2"], registry)
- elif args.target == "pipewire":
- deploy_pipewire(args.action, deployment["pipewire"], registry, quantum_frames)
- else:
- component = "dragonfly_reverb" if args.target == "dragonfly-reverb" else args.target
- deploy_lv2_archives(args.action, component, deployment[component], registry)
- except (OSError, ValueError, RuntimeError, KeyError, TypeError, subprocess.CalledProcessError, tarfile.TarError, yaml.YAMLError) as error:
- print(f"ERROR: {error}", file=sys.stderr)
- return 1
- return 0
- if __name__ == "__main__":
- raise SystemExit(main())
|