import json import os import shutil import subprocess import sys if sys.version_info >= (3, 14): _archive_format = "zstdtar" _archive_suffix = ".tar.zst" else: _archive_format = "gztar" _archive_suffix = ".tar.gz" class PkgComposer: def __init__(self, pkgfile: str): self.pkgfile = pkgfile def setworkdir(self, workdir: str): self.workdir = workdir shutil.rmtree(workdir, ignore_errors=True) os.mkdir(workdir) os.mkdir(f"{workdir}/bundle") def write_manifest(self, manifest: dict): with open(self.workdir + "/PkgManifest.json", "w") as f: json.dump(manifest, f) def write_links(self, links: list[dict]): with open(self.workdir + "/_links", "w") as f: for link in links: json.dump(link, f) f.write("\n") def compose(self): shutil.make_archive(self.pkgfile, _archive_format, self.workdir) shutil.move(self.pkgfile + _archive_suffix, self.pkgfile) def makedir(self, name: str): os.mkdir(f"{self.workdir}/bundle/{name}") def makedirs(self, name: str): os.makedirs(f"{self.workdir}/bundle/{name}", exist_ok=True) def addfile(self, src: str, dst: str): shutil.copy2(src, f"{self.workdir}/bundle/{dst}", follow_symlinks=False) def add_dir(self, src: str, dst: str, merge: bool = False): target = f"{self.workdir}/bundle/{dst}" if not os.path.exists(src): raise FileNotFoundError(f"Source directory not found: {src}") os.makedirs(os.path.dirname(target), exist_ok=True) if merge and os.path.exists(target) and os.path.isdir(target): cmd = ["cp", "-a", f"{src}/.", target] else: cmd = ["cp", "-a", src, target] result = subprocess.run(cmd, capture_output=True, text=True) if result.returncode != 0: raise RuntimeError(f"cp command failed: {result.stderr}")