Files
semios-packages/lib/pkgcomposer.py
T
2026-08-15 12:47:13 +08:00

61 lines
2.0 KiB
Python

import json
import os
import shutil
import subprocess
import sys
class PkgComposer:
def __init__(self, pkgfile: str):
self.pkgfile = os.path.abspath(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):
subprocess.run(
[
"tar", "cpf", f"{self.pkgfile}.tar",
"-C", self.workdir,
"--numeric-owner",
".",
],
check=True,
)
subprocess.run(["zstd", "--rm", "-f", f"{self.pkgfile}.tar", "-o", self.pkgfile], check=True)
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}")