Files

74 lines
2.8 KiB
Python

# Shared helpers for the ws-arch2 fixture generators (archives, encodings, disk images): reference tools through nix,
# our writers' output through tools/fixtures/_arch2_ours.luau, and the standard file set those writers produce.
import os, shutil, subprocess, tempfile, zlib
def content(n, seed):
"""the bytes of _arch2_ours.luau's content(n, seed)"""
out = bytearray(n)
s = seed
for i in range(n):
s = (s * 75 + 74) % 65537
out[i] = (i // 7) % 256 if (i // 64) % 3 == 0 else s % 256
return bytes(out)
FILES = [("hello.txt", b"hello, archive\n"), ("data.bin", content(5000, 7)), ("empty.txt", b"")]
MTIME = 1700000000
def tool(pkgs, argv, cwd=None, input=None, check=True):
"""run argv with the nix packages pkgs on PATH (the host's tool when argv[0] is installed and pkgs is empty)"""
if isinstance(pkgs, str):
pkgs = [pkgs]
cmd = (["nix", "shell"] + ["nixpkgs#" + p for p in pkgs] + ["-c"] if pkgs else []) + list(argv)
r = subprocess.run(cmd, cwd=cwd, input=input, capture_output=True)
if check and r.returncode != 0:
raise RuntimeError("%s failed (%d): %s" % (" ".join(argv), r.returncode, r.stderr.decode(errors="replace")))
return r.stdout
def ours(ctx, fmt, opts=""):
"""our writer's output for the standard file set (bytes)"""
script = os.path.join(ctx.root, "tools", "fixtures", "_arch2_ours.luau")
subprocess.run(["python3", "-I", os.path.join(ctx.root, "tools", "gen_registry.py")], check=True, capture_output=True)
exe = shutil.which("luau")
argv = ([exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"]) + [script, "-a", fmt, opts]
out = subprocess.run(argv, check=True, capture_output=True, cwd=ctx.root).stdout
return bytes.fromhex(out.decode().strip())
def tree(files, root):
"""write [(name, bytes)] under root (with MTIME)"""
for name, data in files:
p = os.path.join(root, name)
os.makedirs(os.path.dirname(p), exist_ok=True)
with open(p, "wb") as f:
f.write(data)
os.utime(p, (MTIME, MTIME))
def read_tree(root):
"""{relative name: crc32} of the files under root"""
out = {}
for d, _, fs in os.walk(root):
for f in fs:
p = os.path.join(d, f)
if os.path.isfile(p) and not os.path.islink(p):
out[os.path.relpath(p, root)] = zlib.crc32(open(p, "rb").read())
return out
def tmpdir():
return tempfile.mkdtemp(prefix="arch2-")
def rmtree(root):
"""shutil.rmtree that first makes extracted directories writable (archives store read-only modes)"""
for d, ds, _ in os.walk(root):
for x in ds:
p = os.path.join(d, x)
if not os.path.islink(p):
os.chmod(p, 0o755)
shutil.rmtree(root, ignore_errors=True)