merge ws/arch2-unix (cpio, ar/deb, rpm, z, iso, lz4; containers/Cpio, Iso9660; codecs UnixCompress, Xxh32, Lz4 from ws/roblox)
This commit is contained in:
commit
242e38c4fe
36 files changed
+5171
-7
No files matched your search
+44
-1
@@ -1,7 +1,7 @@
|
||||
-- Throughput (bash tools/bench.sh): codec MB/s under both runtimes. MB/s are of decompressed output, best of n runs.
|
||||
-- Fixtures: tools/fixtures/deflate.py (a 6 MB corpus), tools/fixtures/png.py (1024 x 768 images), tools/fixtures/mp3.py,
|
||||
-- tools/fixtures/opus.py (3 s stereo files; MB/s of f32 output, 48 kHz stereo f32 is 0.384 MB/s of real time),
|
||||
-- tools/fixtures/flac.py; wav encodes / decodes a generated tone; zstd / brotli / bzip2 / lzma (*_bench corpora), fonts
|
||||
-- tools/fixtures/flac.py; wav encodes / decodes a generated tone; zstd / brotli / bzip2 / lzma / lz4 (*_bench corpora), .Z (tools/fixtures/z.py), fonts
|
||||
-- (glyphs per second), json / xml / yaml, jpeg / gif / tiff / qoi / tga / pnm / hdr and ImageOps.
|
||||
local Deflate = require("@formats/codecs/compress/Deflate")
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
@@ -236,6 +236,19 @@ do
|
||||
Zstd.decompress(z19, nil, nil, { verify = false })
|
||||
end)
|
||||
end
|
||||
do
|
||||
local Lz4 = require("@formats/codecs/compress/Lz4")
|
||||
local LB = require("@tests/gen/lz4_bench")
|
||||
local lz = buffer.fromstring(LB.data)
|
||||
local raw = assert(Lz4.decompress(lz, nil, nil, LB.size))
|
||||
assert(Crc32.of(raw) == LB.crc, "lz4 bench corpus mismatch")
|
||||
bench("lz4 block decompress (hc9)", 5, LB.size, function()
|
||||
Lz4.decompress(lz, nil, nil, LB.size)
|
||||
end)
|
||||
bench("lz4 block compress", 3, LB.size, function()
|
||||
Lz4.compress(raw)
|
||||
end)
|
||||
end
|
||||
do
|
||||
local Brotli = require("@formats/codecs/compress/Brotli")
|
||||
local BB = require("@tests/gen/brotli_bench")
|
||||
@@ -254,6 +267,36 @@ do
|
||||
Bzip2.decompress(bz)
|
||||
end)
|
||||
end
|
||||
do
|
||||
local Lz4F = require("@formats/archive/lz4")
|
||||
local LF = require("@tests/gen/lz4frame")
|
||||
local LC = require("@tests/gen/lz4frame_corpora")
|
||||
local frameData
|
||||
for _, c in LF.cases do
|
||||
if c.name == "text/BX" then
|
||||
frameData = buffer.fromstring(c.data)
|
||||
end
|
||||
end
|
||||
bench("lz4 frame decode (64K, xxh32)", 5, #LC.text, function()
|
||||
Lz4F.decompress(frameData)
|
||||
end)
|
||||
local tb = buffer.fromstring(LC.text)
|
||||
bench("lz4 frame encode (xxh32)", 5, #LC.text, function()
|
||||
Lz4F.compress(tb)
|
||||
end)
|
||||
end
|
||||
do
|
||||
local UnixCompress = require("@formats/codecs/compress/UnixCompress")
|
||||
local ZC = require("@tests/gen/z")
|
||||
local zc = ZC.cases[5] -- the 700 KB corpus, -b 16
|
||||
local zb, zi = buffer.fromstring(zc.z), buffer.fromstring(zc.input)
|
||||
bench(".Z decompress (lzw -b16)", 5, #zc.input, function()
|
||||
UnixCompress.decompress(zb)
|
||||
end)
|
||||
bench(".Z compress (lzw -b16)", 3, #zc.input, function()
|
||||
UnixCompress.compress(zi)
|
||||
end)
|
||||
end
|
||||
do
|
||||
local Lzma = require("@formats/codecs/compress/Lzma")
|
||||
local LB = require("@tests/gen/lzma_bench")
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
-- tools/fixtures/_lz4_encode.luau: run by tools/fixtures/lz4.py under the luau CLI: compresses every corpus of
|
||||
-- tests/gen/lz4_corpora with codecs/compress/Lz4 and prints "<name> <hex>" lines for the reference to decompress.
|
||||
local Lz4 = require("@formats/codecs/compress/Lz4")
|
||||
local C = require("@tests/gen/lz4_corpora")
|
||||
|
||||
for name, data in C do
|
||||
local b = assert(Lz4.compress(data))
|
||||
local t = table.create(buffer.len(b))
|
||||
for i = 0, buffer.len(b) - 1 do
|
||||
t[i + 1] = string.format("%02x", buffer.readu8(b, i))
|
||||
end
|
||||
print(name .. " " .. table.concat(t))
|
||||
end
|
||||
@@ -0,0 +1,21 @@
|
||||
-- tools/fixtures/_lz4frame_encode.luau: run by tools/fixtures/lz4frame.py under the luau CLI: writes every corpus of
|
||||
-- tests/gen/lz4frame_corpora as LZ4 frames with archive/lz4 (several option sets) and prints "<name> <hex>" lines for
|
||||
-- the lz4 tool to decompress.
|
||||
local Lz4F = require("@formats/archive/lz4")
|
||||
local C = require("@tests/gen/lz4frame_corpora")
|
||||
|
||||
local sets = {
|
||||
default = {},
|
||||
b64k = { blockSize = 65536, blockChecksum = true, contentSize = true },
|
||||
nocrc = { contentChecksum = false, blockSize = 262144 },
|
||||
}
|
||||
for name, data in C do
|
||||
for sname, o in sets do
|
||||
local b = assert(Lz4F.compress(data, o :: any))
|
||||
local t = table.create(buffer.len(b))
|
||||
for i = 0, buffer.len(b) - 1 do
|
||||
t[i + 1] = string.format("%02x", buffer.readu8(b, i))
|
||||
end
|
||||
print(name .. "/" .. sname .. " " .. table.concat(t))
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,139 @@
|
||||
# ar / deb fixtures (tools/fixtures.py): GNU ar (binutils: deterministic `rcSD`, real times `rcSU`, a library of two
|
||||
# `as`-assembled objects with its "/" symbol table), llvm-ar --format=bsd (#1/ names, __.SYMDEF), bsdtar arbsd, and
|
||||
# Debian packages from dpkg-deb --build (-Zxz / gzip / zstd / none) plus two built here (bzip2 and lzma members, as
|
||||
# older dpkg wrote them). The expected entries are the input files; the .deb data entries come from Python's tarfile.
|
||||
# tests/gen/ar.luau { files = { { name, data } }, gnuD = data (GNU ar rcSD of files), archives = { { name, data,
|
||||
# variant, entries = { { name, size, mtime?, crc } }, symbols? = { { name, member } }, roundtrip? } },
|
||||
# debs = { { name, data, control = { [field] = value }, payload, entries = { { name, type, size, crc? } } } } }
|
||||
import bz2, gzip, io, lzma, os, shutil, subprocess, tarfile, tempfile, time, zlib
|
||||
|
||||
MTIME = 1700000000
|
||||
|
||||
|
||||
def sh(pkgs, script, cwd, env=None):
|
||||
argv = ["nix", "shell"] + ["nixpkgs#" + p for p in pkgs] + ["-c", "sh", "-c", script]
|
||||
return subprocess.run(argv, cwd=cwd, capture_output=True, check=True, env=env).stdout
|
||||
|
||||
|
||||
def ar_member(name, data, mtime=MTIME):
|
||||
h = b"%-16s%-12d%-6d%-6d%-8s%-10d`\n" % (name, mtime, 0, 0, b"100644", len(data))
|
||||
return h + data + (b"\n" if len(data) % 2 else b"")
|
||||
|
||||
|
||||
def unpack(z, m):
|
||||
if z == "xz":
|
||||
return lzma.decompress(m)
|
||||
if z == "gzip":
|
||||
return gzip.decompress(m)
|
||||
if z == "zstd":
|
||||
return subprocess.run(["nix", "shell", "nixpkgs#zstd", "-c", "zstd", "-d", "-c"], input=m, capture_output=True, check=True).stdout
|
||||
return m
|
||||
|
||||
|
||||
def tar_entries(raw):
|
||||
out = []
|
||||
with tarfile.open(fileobj=io.BytesIO(raw)) as t:
|
||||
for m in t.getmembers():
|
||||
e = {"name": m.name + ("/" if m.isdir() and not m.name.endswith("/") else ""), "type": m.type.decode() if m.type != b"\0" else "0",
|
||||
"size": m.size if m.isfile() else 0}
|
||||
if m.isfile():
|
||||
e["crc"] = zlib.crc32(t.extractfile(m).read())
|
||||
out.append(e)
|
||||
return out
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = ctx.rng(17)
|
||||
files = [
|
||||
("a.txt", b"hello, ar\n"),
|
||||
("odd", b"x" * 7),
|
||||
("empty", b""),
|
||||
("exactly15chars_", b"fifteen"),
|
||||
("sixteen_chars_16", b"sixteen"),
|
||||
("a_very_long_member_name.txt", rng.randbytes(1001)),
|
||||
("another-long-member-name.bin", b"long name two\n"),
|
||||
]
|
||||
tmp = tempfile.mkdtemp()
|
||||
try:
|
||||
names = [n for n, _ in files]
|
||||
for n, d in files:
|
||||
with open(os.path.join(tmp, n), "wb") as f:
|
||||
f.write(d)
|
||||
os.utime(os.path.join(tmp, n), (MTIME, MTIME))
|
||||
q = " ".join(names)
|
||||
archives = []
|
||||
gnuD = sh(["binutils"], "ar rcSD out.a %s && cat out.a && rm out.a" % q, tmp)
|
||||
ents = [{"name": n, "size": len(d), "crc": zlib.crc32(d)} for n, d in files]
|
||||
timed = [dict(e, mtime=MTIME) for e in ents]
|
||||
archives.append({"name": "gnu-D", "data": gnuD, "variant": "gnu", "entries": ents})
|
||||
archives.append({"name": "gnu-U", "data": sh(["binutils"], "ar rcSU out.a %s && cat out.a && rm out.a" % q, tmp),
|
||||
"variant": "gnu", "entries": timed})
|
||||
# a library: two objects, with a symbol table
|
||||
with open(os.path.join(tmp, "s1.s"), "w") as f:
|
||||
f.write(".globl foo\nfoo:\n.data\n.globl bar\nbar: .long 1\n")
|
||||
with open(os.path.join(tmp, "s2.s"), "w") as f:
|
||||
f.write(".globl baz_with_a_long_symbol_name\nbaz_with_a_long_symbol_name:\n")
|
||||
sh(["binutils"], "as -o one.o s1.s && as -o second_object_long_name.o s2.s", tmp)
|
||||
objs = []
|
||||
for n in ("one.o", "second_object_long_name.o"):
|
||||
with open(os.path.join(tmp, n), "rb") as f:
|
||||
d = f.read()
|
||||
objs.append({"name": n, "size": len(d), "crc": zlib.crc32(d)})
|
||||
syms = [{"name": "foo", "member": "one.o"}, {"name": "bar", "member": "one.o"},
|
||||
{"name": "baz_with_a_long_symbol_name", "member": "second_object_long_name.o"}]
|
||||
lib = "one.o second_object_long_name.o a.txt"
|
||||
archives.append({"name": "gnu-lib", "data": sh(["binutils"], "ar rcsD out.a %s && cat out.a && rm out.a" % lib, tmp),
|
||||
"variant": "gnu", "entries": objs + ents[:1], "symbols": syms})
|
||||
archives.append({"name": "llvm-bsd", "data": sh(["llvm"], "llvm-ar rcSD --format=bsd out.a %s && cat out.a && rm out.a" % q, tmp),
|
||||
"variant": "bsd", "entries": ents})
|
||||
archives.append({"name": "llvm-bsd-lib", "data": sh(["llvm"], "llvm-ar rcsD --format=bsd out.a %s && cat out.a && rm out.a" % lib, tmp),
|
||||
"variant": "bsd", "entries": objs + ents[:1], "symbols": syms})
|
||||
archives.append({"name": "bsdtar-arbsd", "data": sh(["libarchive"], "bsdtar --format=arbsd -cf - %s" % q, tmp),
|
||||
"variant": "bsd", "entries": timed, "roundtrip": True})
|
||||
# Debian packages
|
||||
pkg = os.path.join(tmp, "pkg")
|
||||
os.makedirs(os.path.join(pkg, "DEBIAN"))
|
||||
os.makedirs(os.path.join(pkg, "usr", "share", "doc", "hello"))
|
||||
os.makedirs(os.path.join(pkg, "usr", "bin"))
|
||||
control = ("Package: hello\nVersion: 1.0-1\nArchitecture: all\nMaintainer: Ada <[email protected]>\n"
|
||||
"Depends: libc6 (>= 2.31)\nDescription: a greeting\n prints a greeting\n .\n and exits\n")
|
||||
with open(os.path.join(pkg, "DEBIAN", "control"), "w") as f:
|
||||
f.write(control)
|
||||
with open(os.path.join(pkg, "usr", "bin", "hello"), "wb") as f:
|
||||
f.write(b"#!/bin/sh\necho hello\n")
|
||||
os.chmod(os.path.join(pkg, "usr", "bin", "hello"), 0o755)
|
||||
with open(os.path.join(pkg, "usr", "share", "doc", "hello", "README"), "wb") as f:
|
||||
f.write(rng.randbytes(2000))
|
||||
fields = {"Package": "hello", "Version": "1.0-1", "Architecture": "all", "Maintainer": "Ada <[email protected]>",
|
||||
"Depends": "libc6 (>= 2.31)", "Description": "a greeting\nprints a greeting\n.\nand exits"}
|
||||
env = dict(os.environ, SOURCE_DATE_EPOCH=str(MTIME))
|
||||
debs = []
|
||||
for z, ext in (("xz", ".xz"), ("gzip", ".gz"), ("zstd", ".zst"), ("none", "")):
|
||||
data = sh(["dpkg"], "dpkg-deb --root-owner-group -Z%s --build pkg out.deb >/dev/null && cat out.deb && rm out.deb" % z, tmp, env)
|
||||
raw = None
|
||||
p = 8
|
||||
while p < len(data):
|
||||
n = int(data[p + 48:p + 58])
|
||||
if data[p:p + 8] == b"data.tar":
|
||||
m = data[p + 60:p + 60 + n]
|
||||
raw = unpack(z, m)
|
||||
p += 60 + n + (n & 1)
|
||||
debs.append({"name": "dpkg-" + z, "data": data, "control": fields, "payload": "data.tar" + ext, "entries": tar_entries(raw)})
|
||||
# older compressors, assembled here: control.tar.bz2 + data.tar.bz2, control.tar.lzma + data.tar.lzma
|
||||
def tar_of(root, prefix):
|
||||
b = io.BytesIO()
|
||||
with tarfile.open(fileobj=b, mode="w", format=tarfile.GNU_FORMAT) as t:
|
||||
t.add(root, arcname=prefix, filter=lambda ti: setattr(ti, "mtime", MTIME) or ti)
|
||||
return b.getvalue()
|
||||
ctl = tar_of(os.path.join(pkg, "DEBIAN"), ".")
|
||||
dat_dir = os.path.join(tmp, "datatree")
|
||||
shutil.copytree(pkg, dat_dir, ignore=shutil.ignore_patterns("DEBIAN"))
|
||||
dat = tar_of(dat_dir, ".")
|
||||
alone = lambda b: lzma.compress(b, format=lzma.FORMAT_ALONE)
|
||||
for name, comp, ext in (("py-bzip2", bz2.compress, ".bz2"), ("py-lzma", alone, ".lzma")):
|
||||
data = b"!<arch>\n" + ar_member(b"debian-binary", b"2.0\n") + ar_member(b"control.tar" + ext.encode(), comp(ctl)) + \
|
||||
ar_member(b"data.tar" + ext.encode(), comp(dat))
|
||||
debs.append({"name": name, "data": data, "control": fields, "payload": "data.tar" + ext, "entries": tar_entries(dat)})
|
||||
finally:
|
||||
shutil.rmtree(tmp)
|
||||
ctx.emit("ar", {"files": [{"name": n, "data": d} for n, d in files], "gnuD": gnuD, "archives": archives, "debs": debs})
|
||||
@@ -0,0 +1,110 @@
|
||||
# cpio fixtures (tools/fixtures.py): GNU cpio (nixpkgs#cpio, --reproducible) archives of one tree in newc / crc / odc /
|
||||
# bin, the bin one byte-swapped into the big-endian old binary format, bsdtar (libarchive) newc / odc archives, a crafted
|
||||
# newc archive with device nodes and a bad crc sum, and a .cpio.gz. The expected entries come from os.lstat of the tree.
|
||||
# tests/gen/cpio.luau { archives = { { name, data, format, gnu?, entries = { { name, type, mode, size, mtime, nlink,
|
||||
# link?, crc? } } } }, devices = data, badcrc = data, gz = data }
|
||||
import gzip, os, shutil, stat, struct, subprocess, tempfile, zlib
|
||||
|
||||
TYPES = {stat.S_IFREG: "0", stat.S_IFDIR: "5", stat.S_IFLNK: "2", stat.S_IFIFO: "6", stat.S_IFCHR: "3", stat.S_IFBLK: "4"}
|
||||
|
||||
|
||||
def run(ctx, pkg, script, cwd):
|
||||
return subprocess.run(["nix", "shell", "nixpkgs#" + pkg, "-c", "sh", "-c", script], cwd=cwd, capture_output=True, check=True).stdout
|
||||
|
||||
|
||||
def swap_bin(data):
|
||||
"""the little-endian old binary archive -> the big-endian one (every u16 header field swapped)"""
|
||||
out, p = bytearray(), 0
|
||||
while True:
|
||||
f = struct.unpack("<13H", data[p:p + 26])
|
||||
ns, fs = f[10], f[11] << 16 | f[12]
|
||||
name = data[p + 26:p + 26 + ns - 1]
|
||||
out += struct.pack(">13H", *f)
|
||||
q = p + 26 + ns + (ns & 1)
|
||||
e = q + fs + (fs & 1)
|
||||
out += data[p + 26:e]
|
||||
p = e
|
||||
if name == b"TRAILER!!!":
|
||||
return bytes(out + data[p:])
|
||||
|
||||
|
||||
def newc(name, mode, size=0, data=b"", nlink=1, rdev=(0, 0), check=0, ino=1, crc=False):
|
||||
ns = len(name) + 1
|
||||
h = b"070701" + b"".join(b"%08X" % v for v in (ino, mode, 0, 0, nlink, 1600000000, size, 0, 0, rdev[0], rdev[1], ns, check))
|
||||
if crc:
|
||||
h = b"070702" + h[6:]
|
||||
b = h + name + b"\0"
|
||||
b += b"\0" * (-len(b) % 4) + data + b"\0" * (-len(data) % 4)
|
||||
return b
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = ctx.rng(11)
|
||||
files = [
|
||||
("hello.txt", b"hello, cpio\n"),
|
||||
("empty", b""),
|
||||
("dir/sub/data.bin", rng.randbytes(3000)),
|
||||
("exact4", b"four"),
|
||||
("odd", b"x" * 7),
|
||||
("d" * 60 + "/" + "e" * 80 + "/a-name-longer-than-a-hundred-bytes.txt", b"long " * 40),
|
||||
("unicodé/naïve.txt", "ünïcödé".encode()),
|
||||
]
|
||||
tmp = tempfile.mkdtemp()
|
||||
try:
|
||||
root = os.path.join(tmp, "tree")
|
||||
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.chmod(os.path.join(root, "odd"), 0o755)
|
||||
os.makedirs(os.path.join(root, "emptydir"))
|
||||
os.symlink("hello.txt", os.path.join(root, "sym"))
|
||||
os.symlink("dir/sub/data.bin", os.path.join(root, "dir/sublink"))
|
||||
os.link(os.path.join(root, "hello.txt"), os.path.join(root, "hard"))
|
||||
os.link(os.path.join(root, "hello.txt"), os.path.join(root, "dir/hard2"))
|
||||
os.mkfifo(os.path.join(root, "fifo"))
|
||||
for dirpath, dirs, fs in os.walk(root):
|
||||
for n in dirs + fs:
|
||||
os.utime(os.path.join(dirpath, n), (1650000000, 1650000000), follow_symlinks=False)
|
||||
os.utime(root, (1650000000, 1650000000))
|
||||
names = sorted(subprocess.run(["find", "."], cwd=root, capture_output=True, check=True).stdout.decode().split("\n")[:-1])
|
||||
names = [n[2:] if n.startswith("./") else n for n in names]
|
||||
|
||||
def expected():
|
||||
out = []
|
||||
for n in names:
|
||||
st = os.lstat(os.path.join(root, n))
|
||||
t = TYPES[stat.S_IFMT(st.st_mode)]
|
||||
e = {"name": n, "type": t, "mode": stat.S_IMODE(st.st_mode), "mtime": int(st.st_mtime), "nlink": st.st_nlink,
|
||||
"size": st.st_size if t == "0" else 0}
|
||||
if t == "2":
|
||||
e["link"] = os.readlink(os.path.join(root, n))
|
||||
if t == "0":
|
||||
with open(os.path.join(root, n), "rb") as f:
|
||||
e["crc"] = zlib.crc32(f.read())
|
||||
out.append(e)
|
||||
return out
|
||||
|
||||
want = expected()
|
||||
listing = "find . | LC_ALL=C sort | "
|
||||
archives = []
|
||||
for fmt in ("newc", "crc", "odc", "bin"):
|
||||
data = run(ctx, "cpio", listing + "cpio -o -H %s --reproducible 2>/dev/null" % fmt, root)
|
||||
archives.append({"name": "gnu-" + fmt, "data": data, "format": fmt, "gnu": True, "entries": want})
|
||||
archives.append({"name": "gnu-binbe", "data": swap_bin(archives[3]["data"]), "format": "binbe", "entries": want})
|
||||
for fmt in ("newc", "odc"):
|
||||
data = run(ctx, "libarchive", listing + "sed 's|^\\./||' | bsdtar --format=%s -n -cf - -T -" % fmt, root)
|
||||
archives.append({"name": "bsdtar-" + fmt, "data": data, "format": fmt, "entries": want})
|
||||
gz = gzip.compress(archives[0]["data"], mtime=0)
|
||||
finally:
|
||||
shutil.rmtree(tmp)
|
||||
devices = b"".join([
|
||||
newc(b"dev", 0o040755, nlink=2, ino=1),
|
||||
newc(b"dev/null", 0o020666, rdev=(1, 3), ino=2),
|
||||
newc(b"dev/sda", 0o060660, rdev=(8, 0), ino=3),
|
||||
newc(b"dev/sock", 0o140755, ino=4),
|
||||
newc(b"TRAILER!!!", 0, ino=0),
|
||||
])
|
||||
badcrc = newc(b"f", 0o100644, 3, b"abc", check=1, crc=True) + newc(b"TRAILER!!!", 0, ino=0, crc=True)
|
||||
ctx.emit("cpio", {"archives": archives, "devices": devices, "badcrc": badcrc, "gz": gz})
|
||||
@@ -0,0 +1,81 @@
|
||||
# Docs inputs for the archive page's Unix / package sections (tools/fixtures.py; tools/docs_check.py explains the
|
||||
# inputs): a newc cpio by GNU cpio, a .deb by dpkg-deb, an .rpm by rpmbuild, a .tar.Z by ncompress, an ISO image by
|
||||
# xorriso (-J -R, with an El Torito boot image) and an .lz4 by the lz4 tool, all of one small tree.
|
||||
# tests/gen/docs_arch_unix.luau { files = { [name] = bytes }, vars = { cpioBytes = "tree.cpio", ... } }
|
||||
import importlib.util, io, os, subprocess, tarfile, tempfile
|
||||
|
||||
INPUTS = ["tools/docs_check.py"]
|
||||
|
||||
MTIME = 1767225600 # 2026-01-01T00:00:00Z
|
||||
SPEC = """Name: hello
|
||||
Version: 1.0
|
||||
Release: 1
|
||||
Summary: a greeting
|
||||
License: MIT
|
||||
BuildArch: noarch
|
||||
%description
|
||||
prints a greeting
|
||||
%install
|
||||
mkdir -p %{buildroot}/usr/bin
|
||||
printf '#!/bin/sh\\necho hello\\n' > %{buildroot}/usr/bin/hello
|
||||
chmod 755 %{buildroot}/usr/bin/hello
|
||||
%files
|
||||
/usr/bin/hello
|
||||
"""
|
||||
|
||||
|
||||
def docs_check(ctx):
|
||||
spec = importlib.util.spec_from_file_location("docs_check", os.path.join(ctx.root, "tools", "docs_check.py"))
|
||||
m = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(m)
|
||||
return m
|
||||
|
||||
|
||||
def sh(pkgs, script, cwd, env=None):
|
||||
argv = ["nix", "shell"] + ["nixpkgs#" + p for p in pkgs] + ["-c", "sh", "-c", script]
|
||||
return subprocess.run(argv, cwd=cwd, capture_output=True, check=True, env=env).stdout
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
dc = docs_check(ctx)
|
||||
files = {}
|
||||
env = dict(os.environ, SOURCE_DATE_EPOCH=str(MTIME))
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
tree = os.path.join(d, "tree")
|
||||
os.makedirs(os.path.join(tree, "bin"))
|
||||
with open(os.path.join(tree, "readme.txt"), "wb") as f:
|
||||
f.write(b"formats-luau unix archives\n")
|
||||
with open(os.path.join(tree, "bin", "run.sh"), "wb") as f:
|
||||
f.write(b"#!/bin/sh\necho hi\n")
|
||||
os.chmod(os.path.join(tree, "bin", "run.sh"), 0o755)
|
||||
os.symlink("bin/run.sh", os.path.join(tree, "run"))
|
||||
with open(os.path.join(tree, "boot.img"), "wb") as f:
|
||||
f.write(b"\xfa\xeb\xfe" + bytes(2045))
|
||||
for dirpath, dirs, fs in os.walk(tree):
|
||||
for n in dirs + fs:
|
||||
os.utime(os.path.join(dirpath, n), (MTIME, MTIME), follow_symlinks=False)
|
||||
files["tree.cpio"] = sh(["cpio", "findutils"], "find readme.txt bin run | LC_ALL=C sort | cpio -o -H newc --reproducible 2>/dev/null", tree)
|
||||
files["disc.iso"] = sh(["xorriso"], "xorriso -as mkisofs -quiet -no-pad -J -R -V DOCS -b boot.img -no-emul-boot -boot-load-size 4 -o - .", tree)
|
||||
b = io.BytesIO()
|
||||
with tarfile.open(fileobj=b, mode="w", format=tarfile.PAX_FORMAT) as t:
|
||||
for n in ("readme.txt", "bin/run.sh"):
|
||||
t.add(os.path.join(tree, n), arcname=n)
|
||||
files["src.tar.Z"] = subprocess.run(["nix", "shell", "nixpkgs#ncompress", "-c", "compress", "-c", "-f"], input=b.getvalue(),
|
||||
capture_output=True, check=True).stdout
|
||||
files["notes.txt.lz4"] = subprocess.run(["nix", "shell", "nixpkgs#lz4", "-c", "lz4", "-c"], input=b"formats-luau unix archives\n" * 8,
|
||||
capture_output=True, check=True).stdout
|
||||
pkg = os.path.join(d, "pkg")
|
||||
os.makedirs(os.path.join(pkg, "DEBIAN"))
|
||||
os.makedirs(os.path.join(pkg, "usr", "bin"))
|
||||
with open(os.path.join(pkg, "DEBIAN", "control"), "w") as f:
|
||||
f.write("Package: hello\nVersion: 1.0-1\nArchitecture: all\nMaintainer: Ada <[email protected]>\nDescription: a greeting\n")
|
||||
with open(os.path.join(pkg, "usr", "bin", "hello"), "wb") as f:
|
||||
f.write(b"#!/bin/sh\necho hello\n")
|
||||
os.chmod(os.path.join(pkg, "usr", "bin", "hello"), 0o755)
|
||||
files["hello.deb"] = sh(["dpkg"], "dpkg-deb --root-owner-group -Zxz --build pkg out.deb >/dev/null && cat out.deb", d, env)
|
||||
with open(os.path.join(d, "hello.spec"), "w") as f:
|
||||
f.write(SPEC)
|
||||
sh(["rpm"], "rpmbuild --define '_topdir %s/top' --define '__os_install_post %%{nil}' --define '_build_id_links none' -bb hello.spec >/dev/null 2>&1" % d, d, env)
|
||||
files["hello.rpm"] = open(os.path.join(d, "top", "RPMS", "noarch", "hello-1.0-1.noarch.rpm"), "rb").read()
|
||||
dc.emit_inputs(ctx, files, {"cpioBytes": "tree.cpio", "isoBytes": "disc.iso", "tarZBytes": "src.tar.Z", "lz4Bytes": "notes.txt.lz4",
|
||||
"debBytes": "hello.deb", "rpmBytes": "hello.rpm"})
|
||||
@@ -0,0 +1,195 @@
|
||||
# iso fixtures (tools/fixtures.py): ISO 9660 images of one tree built by xorriso (nixpkgs#xorriso: plain and Joliet
|
||||
# with -rockridge off, then the mkisofs emulation -R, -J -R, an El Torito no-emulation boot image) and genisoimage (nixpkgs#cdrkit, -J -R: deep directories
|
||||
# relocated to rr_moved, long names and symlink targets in CE continuation areas), plus a multi-extent file and an
|
||||
# interleaved file crafted here by splitting / editing a directory record. Expected listings: the source tree (os.lstat)
|
||||
# for Rock Ridge images, pycdlib (a second reader, run through nix python) for the plain and Joliet name sets.
|
||||
# tests/gen/iso.luau { images = { { name, data (or same = the index of the image with the same data), tree, entries = { { name, dir, size?, crc?, mode?, link?, mtime? } } } },
|
||||
# boot = { data, lba, sectors, catalog }, multi = { data, name, size, crc }, interleaved = data }
|
||||
import json, os, shutil, stat, struct, subprocess, tempfile, zlib
|
||||
|
||||
MTIME = 1650000000
|
||||
DUMP = r"""
|
||||
import json, sys, io, zlib, pycdlib
|
||||
path, kind = sys.argv[1], sys.argv[2]
|
||||
iso = pycdlib.PyCdlib()
|
||||
iso.open(path)
|
||||
out = []
|
||||
key = {"joliet": "joliet_path", "iso9660": "iso_path"}[kind]
|
||||
for d, dirs, files in iso.walk(**{key: "/"}):
|
||||
base = d.rstrip("/")
|
||||
for n in dirs:
|
||||
out.append({"name": (base + "/" + n).lstrip("/"), "dir": True})
|
||||
for n in files:
|
||||
p = base + "/" + n
|
||||
b = io.BytesIO()
|
||||
iso.get_file_from_iso_fp(b, **{key: p})
|
||||
name = p.lstrip("/")
|
||||
if ";" in name:
|
||||
name = name[:name.rindex(";")]
|
||||
if kind == "iso9660" and name.endswith("."):
|
||||
name = name[:-1]
|
||||
out.append({"name": name, "dir": False, "size": len(b.getvalue()), "crc": zlib.crc32(b.getvalue())})
|
||||
iso.close()
|
||||
sys.stdout.write(json.dumps(out))
|
||||
"""
|
||||
|
||||
|
||||
def sh(pkg, argv, cwd):
|
||||
return subprocess.run(["nix", "shell", "nixpkgs#" + pkg, "-c"] + argv, cwd=cwd, capture_output=True, check=True).stdout
|
||||
|
||||
|
||||
def tree_entries(root, skip_deep=False):
|
||||
out = []
|
||||
for dirpath, dirs, files in os.walk(root):
|
||||
dirs.sort()
|
||||
for n in sorted(dirs + files):
|
||||
p = os.path.join(dirpath, n)
|
||||
rel = os.path.relpath(p, root)
|
||||
st = os.lstat(p)
|
||||
e = {"name": rel, "dir": stat.S_ISDIR(st.st_mode), "mode": stat.S_IMODE(st.st_mode), "mtime": MTIME}
|
||||
if stat.S_ISLNK(st.st_mode):
|
||||
e["link"] = os.readlink(p)
|
||||
elif stat.S_ISREG(st.st_mode):
|
||||
with open(p, "rb") as f:
|
||||
d = f.read()
|
||||
e["size"], e["crc"] = len(d), zlib.crc32(d)
|
||||
out.append(e)
|
||||
return out
|
||||
|
||||
|
||||
def split_record(data, name, at_bytes):
|
||||
"""a multi-extent copy: the directory record of name split into two records (the first flagged 0x80)"""
|
||||
img = bytearray(data)
|
||||
root_lba = struct.unpack_from("<I", img, 16 * 2048 + 156 + 2)[0]
|
||||
root_len = struct.unpack_from("<I", img, 16 * 2048 + 156 + 10)[0]
|
||||
p, e = root_lba * 2048, root_lba * 2048 + root_len
|
||||
while p < e:
|
||||
ln = img[p]
|
||||
if ln == 0:
|
||||
p = (p // 2048 + 1) * 2048
|
||||
continue
|
||||
nl = img[p + 32]
|
||||
if bytes(img[p + 33:p + 33 + nl]) == name:
|
||||
rec = bytearray(img[p:p + ln])
|
||||
size = struct.unpack_from("<I", rec, 10)[0]
|
||||
lba = struct.unpack_from("<I", rec, 2)[0]
|
||||
a, b2 = bytearray(rec), bytearray(rec)
|
||||
struct.pack_into("<I", a, 10, at_bytes)
|
||||
struct.pack_into(">I", a, 14, at_bytes)
|
||||
a[25] |= 0x80
|
||||
struct.pack_into("<I", b2, 2, lba + at_bytes // 2048)
|
||||
struct.pack_into(">I", b2, 6, lba + at_bytes // 2048)
|
||||
struct.pack_into("<I", b2, 10, size - at_bytes)
|
||||
struct.pack_into(">I", b2, 14, size - at_bytes)
|
||||
sector_end = (p // 2048 + 1) * 2048
|
||||
used = sector_end
|
||||
q = p + ln
|
||||
while q < sector_end and img[q] != 0:
|
||||
q += img[q]
|
||||
assert q + ln <= sector_end, "no room in the directory sector"
|
||||
img[p:q + ln] = a + b2 + img[p + ln:q]
|
||||
return bytes(img), size
|
||||
p += ln
|
||||
raise Exception("record not found")
|
||||
|
||||
|
||||
def set_interleave(data, name):
|
||||
img = bytearray(data)
|
||||
root_lba = struct.unpack_from("<I", img, 16 * 2048 + 156 + 2)[0]
|
||||
p = root_lba * 2048
|
||||
while img[p]:
|
||||
nl = img[p + 32]
|
||||
if bytes(img[p + 33:p + 33 + nl]) == name:
|
||||
img[p + 26], img[p + 27] = 1, 1
|
||||
return bytes(img)
|
||||
p += img[p]
|
||||
raise Exception("record not found")
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = ctx.rng(29)
|
||||
tmp = tempfile.mkdtemp()
|
||||
try:
|
||||
root = os.path.join(tmp, "tree")
|
||||
files = [
|
||||
("hello.txt", b"hello, iso\n"),
|
||||
("empty", b""),
|
||||
("dir/sub/data.bin", rng.randbytes(5000)),
|
||||
("big.bin", rng.randbytes(40000)),
|
||||
("A File With Spaces And A Name Longer Than Sixty-Four Characters For Joliet.txt", b"long joliet\n"),
|
||||
("unicodé/naïve.txt", "ünïcödé".encode()),
|
||||
("run.sh", b"#!/bin/sh\necho hi\n"),
|
||||
]
|
||||
for n, d in files:
|
||||
p = os.path.join(root, n)
|
||||
os.makedirs(os.path.dirname(p), exist_ok=True)
|
||||
with open(p, "wb") as f:
|
||||
f.write(d)
|
||||
os.chmod(os.path.join(root, "run.sh"), 0o755)
|
||||
os.symlink("hello.txt", os.path.join(root, "link"))
|
||||
os.makedirs(os.path.join(root, "emptydir"))
|
||||
for dirpath, dirs, fs in os.walk(root):
|
||||
for n in dirs + fs:
|
||||
os.utime(os.path.join(dirpath, n), (MTIME, MTIME), follow_symlinks=False)
|
||||
base_entries = tree_entries(root)
|
||||
# a second tree with what only Rock Ridge holds: deep directories, a 200-byte name, a long symlink target
|
||||
root2 = os.path.join(tmp, "tree2")
|
||||
shutil.copytree(root, root2, symlinks=True)
|
||||
deep = os.path.join(root2, *["d%d" % i for i in range(1, 11)])
|
||||
os.makedirs(deep)
|
||||
with open(os.path.join(deep, "deep.txt"), "wb") as f:
|
||||
f.write(b"ten levels down\n")
|
||||
with open(os.path.join(root2, "n" * 200), "wb") as f:
|
||||
f.write(b"a 200-byte name\n")
|
||||
os.symlink("/" + "/".join(["target-component-%02d" % i for i in range(16)]), os.path.join(root2, "longlink"))
|
||||
for dirpath, dirs, fs in os.walk(root2):
|
||||
for n in dirs + fs:
|
||||
os.utime(os.path.join(dirpath, n), (MTIME, MTIME), follow_symlinks=False)
|
||||
rr_entries = tree_entries(root2)
|
||||
images = []
|
||||
|
||||
def dump(path, kind):
|
||||
return json.loads(ctx.python(["pycdlib"], DUMP.replace("sys.argv[1], sys.argv[2]", repr(path) + ", " + repr(kind))))
|
||||
|
||||
def xorriso(name, args, src, tree, entries=None):
|
||||
out = os.path.join(tmp, name + ".iso")
|
||||
if args and args[0] == "native": # xorriso's own commands (mkisofs emulation always writes Rock Ridge)
|
||||
sh("xorriso", ["xorriso", "-outdev", out, "-padding", "0"] + args[1:] + ["-map", src, "/"], tmp)
|
||||
else:
|
||||
sh("xorriso", ["xorriso", "-as", "mkisofs", "-quiet", "-no-pad", "-o", out] + args + [src], tmp)
|
||||
if entries is None:
|
||||
entries = dump(out, tree)
|
||||
images.append({"name": name, "data": open(out, "rb").read(), "tree": tree, "entries": entries})
|
||||
return out
|
||||
|
||||
plain = xorriso("xorriso-plain", ["native", "-rockridge", "off"], root, "iso9660")
|
||||
xorriso("xorriso-J", ["native", "-rockridge", "off", "-joliet", "on"], root, "joliet")
|
||||
xorriso("xorriso-R", ["-R"], root, "rockridge", base_entries)
|
||||
xorriso("xorriso-JR", ["-J", "-R"], root2, "rockridge", rr_entries)
|
||||
out = os.path.join(tmp, "geniso.iso")
|
||||
sh("cdrkit", ["genisoimage", "-quiet", "-no-pad", "-J", "-R", "-o", out, root2], tmp)
|
||||
images.append({"name": "genisoimage-JR", "data": open(out, "rb").read(), "tree": "rockridge", "entries": rr_entries})
|
||||
# Joliet from the -J -R image too (prefer = "joliet")
|
||||
images.append({"name": "genisoimage-JR-joliet", "same": len(images), "tree": "joliet", "entries": dump(out, "joliet")})
|
||||
# El Torito
|
||||
bootdir = os.path.join(tmp, "boot")
|
||||
shutil.copytree(root, bootdir, symlinks=True)
|
||||
with open(os.path.join(bootdir, "boot.img"), "wb") as f:
|
||||
f.write(b"\xfa\xeb\xfe" + bytes(2045))
|
||||
out = os.path.join(tmp, "boot.iso")
|
||||
sh("xorriso", ["xorriso", "-as", "mkisofs", "-quiet", "-no-pad", "-R", "-o", out, "-b", "boot.img", "-c", "boot.cat", "-no-emul-boot",
|
||||
"-boot-load-size", "4", bootdir], tmp)
|
||||
bdata = open(out, "rb").read()
|
||||
info = subprocess.run(["nix", "shell", "nixpkgs#xorriso", "-c", "xorriso", "-indev", out, "-report_el_torito", "plain"],
|
||||
capture_output=True, text=True).stdout
|
||||
# "El Torito boot img : 1 BIOS y none 0x0000 0x00 4 LBA"
|
||||
row = [l for l in info.split("\n") if l.startswith("El Torito boot img")][0].split()
|
||||
cat = [l for l in info.split("\n") if l.startswith("El Torito catalog")][0].split()
|
||||
boot = {"data": bdata, "sectors": int(row[-2]), "lba": int(row[-1]), "bootable": row[7] == "y", "catalog": int(cat[4])}
|
||||
multi, msize = split_record(open(plain, "rb").read(), b"BIG.BIN;1", 2048 * 8)
|
||||
mcrc = zlib.crc32(dict(files)["big.bin"])
|
||||
interleaved = set_interleave(open(plain, "rb").read(), b"HELLO.TXT;1")
|
||||
finally:
|
||||
shutil.rmtree(tmp)
|
||||
ctx.emit("iso", {"images": images, "boot": boot, "multi": {"data": multi, "name": "BIG.BIN", "size": msize, "crc": mcrc},
|
||||
"interleaved": interleaved})
|
||||
@@ -0,0 +1,90 @@
|
||||
# LZ4 block fixtures (tools/fixtures.py): deterministic corpora compressed by the reference (python-lz4, the lz4
|
||||
# library: fast mode at several accelerations, and HC at levels 4 / 9 / 12), plus our own encoder's blocks
|
||||
# (tools/fixtures/_lz4_encode.luau under the luau CLI) decompressed by the reference, as verdicts.
|
||||
# tests/gen/lz4.luau { corpora = { [name] = bytes }, cases = { { name, corpus, data } }, ours = { { name, ok } } }
|
||||
# tests/gen/lz4_bench.luau { size, crc, data (lz4 HC 9 block), raw }
|
||||
import json, os, random, shutil, subprocess, zlib
|
||||
|
||||
INPUTS = ["src/Formats/codecs/compress/Lz4.luau", "tools/fixtures/_lz4_encode.luau"]
|
||||
|
||||
REF = r"""
|
||||
import json, sys, lz4.block
|
||||
req = json.load(sys.stdin)
|
||||
out = {}
|
||||
if req["op"] == "compress":
|
||||
for name, hexdata in req["corpora"].items():
|
||||
data = bytes.fromhex(hexdata)
|
||||
res = {}
|
||||
for acc in (1, 4, 16):
|
||||
res["fast%d" % acc] = lz4.block.compress(data, mode="fast", acceleration=acc, store_size=False).hex()
|
||||
for lv in (4, 9, 12):
|
||||
res["hc%d" % lv] = lz4.block.compress(data, mode="high_compression", compression=lv, store_size=False).hex()
|
||||
out[name] = res
|
||||
else:
|
||||
for name, item in req["blocks"].items():
|
||||
try:
|
||||
got = lz4.block.decompress(bytes.fromhex(item["data"]), uncompressed_size=item["size"])
|
||||
out[name] = got.hex() == item["want"]
|
||||
except Exception as e:
|
||||
out[name] = False
|
||||
print(json.dumps(out))
|
||||
"""
|
||||
|
||||
|
||||
def corpora(rng):
|
||||
base = os.path.dirname(os.__file__)
|
||||
text = bytearray()
|
||||
for name in sorted(os.listdir(base)):
|
||||
if name.endswith(".py"):
|
||||
with open(os.path.join(base, name), "rb") as f:
|
||||
text += f.read()
|
||||
if len(text) >= 300000:
|
||||
break
|
||||
text = bytes(text[:300000])
|
||||
far = rng.randbytes(9000)
|
||||
return {
|
||||
"empty": b"",
|
||||
"one": b"a",
|
||||
"twelve": b"abcabcabcabc",
|
||||
"thirteen": b"abcabcabcabca",
|
||||
"short": b"hello, hello, hello lz4 world\n",
|
||||
"text": text[:150000],
|
||||
"random": rng.randbytes(20000),
|
||||
"runs": b"abc" * 4000 + b"\0" * 70000 + bytes(range(256)) * 40 + b"z" * 300,
|
||||
"zeros": b"\0" * 100000,
|
||||
"far": far + rng.randbytes(60000) + far,
|
||||
"binary": bytes(rng.choice(b"\0\0\0\x01\x02\xff ABC") for _ in range(60000)),
|
||||
"longlit": rng.randbytes(1000) + b"q" * 1000 + rng.randbytes(300),
|
||||
}
|
||||
|
||||
|
||||
def luau_cmd():
|
||||
exe = shutil.which("luau")
|
||||
return [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"]
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = random.Random(41)
|
||||
cs = corpora(rng)
|
||||
ref = json.loads(ctx.python(["lz4"], REF, input=json.dumps({"op": "compress", "corpora": {k: v.hex() for k, v in cs.items()}}).encode()))
|
||||
cases = []
|
||||
for name, res in ref.items():
|
||||
for mode, hexdata in res.items():
|
||||
cases.append({"name": "%s/%s" % (name, mode), "corpus": name, "data": bytes.fromhex(hexdata)})
|
||||
# our encoder's blocks, read back by the reference
|
||||
ctx.emit("lz4_corpora", cs)
|
||||
enc = subprocess.run(luau_cmd() + [os.path.join(ctx.root, "tools", "fixtures", "_lz4_encode.luau")], capture_output=True, check=True, cwd=ctx.root).stdout.decode()
|
||||
blocks = {}
|
||||
for line in enc.split("\n"):
|
||||
if line.strip():
|
||||
name, hexdata = line.split(" ", 1)
|
||||
blocks[name] = {"data": hexdata.strip(), "size": len(cs[name]), "want": cs[name].hex()}
|
||||
verdict = json.loads(ctx.python(["lz4"], REF, input=json.dumps({"op": "decompress", "blocks": blocks}).encode()))
|
||||
ours = [{"name": n, "ok": bool(verdict.get(n)), "size": len(bytes.fromhex(blocks[n]["data"]))} for n in sorted(blocks)]
|
||||
ctx.emit("lz4", {"cases": cases, "ours": ours})
|
||||
bench = bytearray()
|
||||
while len(bench) < 6_000_000:
|
||||
bench += cs["text"] + bytes(rng.choice(b"\0\0\0\x01\x02\xff ABC") for _ in range(100000)) + rng.randbytes(20000)
|
||||
bench = bytes(bench[:6_000_000])
|
||||
code = "import sys, lz4.block; sys.stdout.buffer.write(lz4.block.compress(sys.stdin.buffer.read(), mode='high_compression', compression=9, store_size=False))"
|
||||
ctx.emit("lz4_bench", {"size": len(bench), "crc": zlib.crc32(bench), "data": ctx.python(["lz4"], code, input=bench)})
|
||||
@@ -0,0 +1,72 @@
|
||||
# LZ4 frame fixtures (tools/fixtures.py): corpora compressed by the lz4 tool 1.10 (nixpkgs#lz4) with its frame options
|
||||
# (default, linked blocks -BD, 64 KB blocks -B4 with and without -BD, block checksums -BX, --content-size,
|
||||
# --no-frame-crc, -9, the legacy format -l), concatenated frames and a skippable frame; and our writer's frames
|
||||
# (tools/fixtures/_lz4frame_encode.luau under the luau CLI) decompressed by `lz4 -d`, as verdicts.
|
||||
# tests/gen/lz4frame.luau { cases = { { name, corpus, data } }, ours = { { name, ok } } }
|
||||
# tests/gen/lz4frame_corpora.luau { [name] = bytes }
|
||||
import os, shutil, struct, subprocess, tempfile
|
||||
|
||||
INPUTS = ["src/Formats/archive/lz4/init.luau", "src/Formats/codecs/compress/Lz4.luau", "src/Formats/codecs/compress/Xxh32.luau",
|
||||
"tools/fixtures/_lz4frame_encode.luau"]
|
||||
|
||||
|
||||
def lz4(args, data=None, path=None):
|
||||
argv = ["nix", "shell", "nixpkgs#lz4", "-c", "lz4"] + args + ([path] if path else [])
|
||||
return subprocess.run(argv, input=data, capture_output=True, check=True).stdout
|
||||
|
||||
|
||||
def corpora(rng):
|
||||
base = os.path.dirname(os.__file__)
|
||||
text = bytearray()
|
||||
for name in sorted(os.listdir(base)):
|
||||
if name.endswith(".py"):
|
||||
with open(os.path.join(base, name), "rb") as f:
|
||||
text += f.read()
|
||||
if len(text) >= 160000:
|
||||
break
|
||||
return {"empty": b"", "short": b"hello, lz4 frames\n", "text": bytes(text[:160000]), "random": rng.randbytes(20000),
|
||||
"zeros": b"\0" * 300000}
|
||||
|
||||
|
||||
def luau_cmd():
|
||||
exe = shutil.which("luau")
|
||||
return [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"]
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
cs = corpora(ctx.rng(43))
|
||||
cases = []
|
||||
tmp = tempfile.mkdtemp()
|
||||
try:
|
||||
for name, data in cs.items():
|
||||
path = os.path.join(tmp, name)
|
||||
with open(path, "wb") as f:
|
||||
f.write(data)
|
||||
variants = [("default", ["-c"])]
|
||||
if name in ("text", "zeros", "short"):
|
||||
variants += [("BD", ["-c", "-BD"]), ("B4", ["-c", "-B4"]), ("B4BD", ["-c", "-B4", "-BD"]), ("BX", ["-c", "-B4", "-BX"]),
|
||||
("size", ["-c", "--content-size"]), ("nocrc", ["-c", "--no-frame-crc"]), ("hc9", ["-c", "-9", "-B4", "-BD"]),
|
||||
("legacy", ["-c", "-l"])]
|
||||
for vname, args in variants:
|
||||
cases.append({"name": name + "/" + vname, "corpus": name, "data": lz4(args, path=path)})
|
||||
finally:
|
||||
shutil.rmtree(tmp)
|
||||
# two frames, and a skippable frame in front
|
||||
two = lz4(["-c"], data=cs["short"]) + lz4(["-c", "-B4"], data=cs["text"])
|
||||
cases.append({"name": "concat", "corpus": "short+text", "data": two})
|
||||
skip = struct.pack("<II", 0x184D2A53, 5) + b"skip!" + lz4(["-c"], data=cs["short"])
|
||||
cases.append({"name": "skippable", "corpus": "short", "data": skip})
|
||||
ctx.emit("lz4frame_corpora", cs)
|
||||
enc = subprocess.run(luau_cmd() + [os.path.join(ctx.root, "tools", "fixtures", "_lz4frame_encode.luau")], capture_output=True,
|
||||
check=True, cwd=ctx.root).stdout.decode()
|
||||
ours = []
|
||||
for line in enc.split("\n"):
|
||||
if line.strip():
|
||||
name, hexdata = line.split(" ", 1)
|
||||
try:
|
||||
got = lz4(["-d", "-c"], data=bytes.fromhex(hexdata.strip()))
|
||||
ok = got == cs[name.split("/")[0]]
|
||||
except subprocess.CalledProcessError:
|
||||
ok = False
|
||||
ours.append({"name": name, "ok": ok})
|
||||
ctx.emit("lz4frame", {"cases": cases, "ours": sorted(ours, key=lambda o: o["name"])})
|
||||
@@ -0,0 +1,101 @@
|
||||
# rpm fixtures (tools/fixtures.py): one package built by rpmbuild (nixpkgs#rpm) with each payload compressor (gzip,
|
||||
# bzip2, xz, lzma, zstd, none), holding files, a symlink, a hard link pair, a directory and a %ghost file. The expected
|
||||
# header fields and file list come from `rpm -qp --qf`, the file data from rpm2cpio's cpio stream (parsed here).
|
||||
# tests/gen/rpm.luau { rpms = { { name, data, compressor, fields = { name, version, ... }, files = { { name, size,
|
||||
# mode, mtime, link?, crc? } }, cpioCrc } } }
|
||||
import os, shutil, subprocess, tempfile, zlib
|
||||
|
||||
SPEC = r"""
|
||||
Name: hello
|
||||
Version: 1.0
|
||||
Release: 3
|
||||
Epoch: 2
|
||||
Summary: a greeting
|
||||
License: MIT
|
||||
URL: https://example.org/hello
|
||||
Group: Applications/Text
|
||||
BuildArch: noarch
|
||||
%description
|
||||
prints a greeting
|
||||
and exits
|
||||
%install
|
||||
mkdir -p %{buildroot}/usr/bin %{buildroot}/usr/share/doc/hello %{buildroot}/var/log
|
||||
printf '#!/bin/sh\necho hello\n' > %{buildroot}/usr/bin/hello
|
||||
chmod 755 %{buildroot}/usr/bin/hello
|
||||
python3 -c "import random; open('%{buildroot}/usr/share/doc/hello/README', 'wb').write(random.Random(3).randbytes(20000))"
|
||||
printf 'a long name' > "%{buildroot}/usr/share/doc/hello/a file name with spaces and more than one hundred characters, to pass every old limit of the cpio or tar headers.txt"
|
||||
ln -s hello %{buildroot}/usr/bin/hi
|
||||
ln %{buildroot}/usr/bin/hello %{buildroot}/usr/bin/hello2
|
||||
touch %{buildroot}/var/log/hello.log
|
||||
%files
|
||||
/usr/bin/hello
|
||||
/usr/bin/hello2
|
||||
/usr/bin/hi
|
||||
%dir /usr/share/doc/hello
|
||||
/usr/share/doc/hello/README
|
||||
"/usr/share/doc/hello/a file name with spaces and more than one hundred characters, to pass every old limit of the cpio or tar headers.txt"
|
||||
%ghost /var/log/hello.log
|
||||
"""
|
||||
|
||||
QF = "%{NAME}\\n%{VERSION}\\n%{RELEASE}\\n%{EPOCH}\\n%{ARCH}\\n%{OS}\\n%{LICENSE}\\n%{URL}\\n%{PAYLOADCOMPRESSOR}\\n%{PAYLOADFORMAT}\\n%{SUMMARY}\\n"
|
||||
FQF = "[%{FILENAMES}\\t%{FILESIZES}\\t%{FILEMODES}\\t%{FILEMTIMES}\\t%{FILELINKTOS}\\t%{FILEFLAGS}\\n]"
|
||||
|
||||
|
||||
def cpio_files(d):
|
||||
out, ino, p = {}, {}, 0
|
||||
while p < len(d):
|
||||
h = d[p:p + 110]
|
||||
f = [int(h[6 + 8 * i:14 + 8 * i], 16) for i in range(13)]
|
||||
ns, fs = f[11], f[6]
|
||||
name = d[p + 110:p + 110 + ns - 1].decode()
|
||||
p = (p + 110 + ns + 3) & ~3
|
||||
if name == "TRAILER!!!":
|
||||
out[None] = p # the archive's end (rpm2cpio pads its output with zeros)
|
||||
break
|
||||
out[name[2:] if name.startswith("./") else name] = f[0]
|
||||
if fs:
|
||||
ino[f[0]] = d[p:p + fs]
|
||||
p = (p + fs + 3) & ~3
|
||||
return {n: (i if n is None else ino.get(i, b"")) for n, i in out.items()} # hard links: the data of their inode
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
tmp = tempfile.mkdtemp()
|
||||
rpms = []
|
||||
try:
|
||||
with open(os.path.join(tmp, "hello.spec"), "w") as f:
|
||||
f.write(SPEC)
|
||||
env = dict(os.environ, SOURCE_DATE_EPOCH="1700000000")
|
||||
for comp, io in (("gzip", "w9.gzdio"), ("bzip2", "w9.bzdio"), ("xz", "w6.xzdio"), ("lzma", "w6.lzdio"), ("zstd", "w19.zstdio"), ("none", "w0.ufdio")):
|
||||
top = os.path.join(tmp, "top-" + comp)
|
||||
subprocess.run(["nix", "shell", "nixpkgs#rpm", "nixpkgs#python3", "-c", "rpmbuild", "--define", "_topdir " + top,
|
||||
"--define", "_binary_payload " + io, "--define", "__os_install_post %{nil}",
|
||||
"--define", "_build_id_links none", "--define", "use_source_date_epoch_as_buildtime 1",
|
||||
"--define", "clamp_mtime_to_source_date_epoch 1", "-bb", "hello.spec"],
|
||||
cwd=tmp, capture_output=True, check=True, env=env)
|
||||
path = os.path.join(top, "RPMS", "noarch", "hello-1.0-3.noarch.rpm")
|
||||
data = open(path, "rb").read()
|
||||
q = lambda fmt: subprocess.run(["nix", "shell", "nixpkgs#rpm", "-c", "rpm", "--dbpath", os.path.join(tmp, "db"), "-qp", "--qf", fmt, path],
|
||||
capture_output=True, check=True).stdout.decode()
|
||||
v = q(QF).split("\n")
|
||||
fields = dict(zip(["name", "version", "release", "epoch", "arch", "os", "license", "url", "payloadCompressor", "payloadFormat", "summary"], v))
|
||||
fields["epoch"] = int(fields["epoch"])
|
||||
if comp == "none":
|
||||
del fields["payloadCompressor"] # whatever rpm stores for "no compression" is checked by the test itself
|
||||
raw = subprocess.run(["nix", "shell", "nixpkgs#rpm", "-c", "rpm2cpio", path], capture_output=True, check=True).stdout
|
||||
content = cpio_files(raw)
|
||||
files = []
|
||||
for line in q(FQF).split("\n")[:-1]:
|
||||
name, size, mode, mtime, link, flags = line.split("\t")
|
||||
e = {"name": name.lstrip("/"), "size": int(size), "mode": int(mode) & 0xFFF, "type": int(mode) & 0xF000,
|
||||
"mtime": int(mtime), "flags": int(flags)}
|
||||
if link:
|
||||
e["link"] = link
|
||||
if e["name"] in content and e["type"] == 0x8000:
|
||||
e["crc"] = zlib.crc32(content[e["name"]])
|
||||
files.append(e)
|
||||
rpms.append({"name": "rpmbuild-" + comp, "data": data, "compressor": comp, "fields": fields, "files": files,
|
||||
"cpioCrc": zlib.crc32(raw[:content[None]]), "cpioSize": content[None]})
|
||||
finally:
|
||||
shutil.rmtree(tmp)
|
||||
ctx.emit("rpm", {"rpms": rpms})
|
||||
@@ -0,0 +1,45 @@
|
||||
# .Z fixtures (tools/fixtures.py): Unix compress files written by ncompress 5.0 (nixpkgs#ncompress, `compress -c -f
|
||||
# -b N`) from a few inputs: empty, one byte, short text, a 700 KB word corpus with incompressible stretches (the 16-bit
|
||||
# table fills, the ratio check emits CLEAR codes), random bytes, and every width 10..16; a .tar.Z for the api's unwrap.
|
||||
# gzip -d reads each file too (its output must be the input: a second decoder agreeing on what ncompress wrote).
|
||||
# tests/gen/z.luau { cases = { { name, input, bits, z } }, tarZ = data, tarNames = { ... } }
|
||||
import io, subprocess, tarfile
|
||||
|
||||
|
||||
def compress(data, bits):
|
||||
return subprocess.run(["nix", "shell", "nixpkgs#ncompress", "-c", "compress", "-c", "-f", "-b", str(bits)], input=data,
|
||||
capture_output=True, check=True).stdout
|
||||
|
||||
|
||||
def corpus(rng, size):
|
||||
words = ["".join(rng.choice("abcdefghijklmnopqrstuvwxyz") for _ in range(rng.randint(2, 9))) for _ in range(3000)]
|
||||
out = bytearray()
|
||||
while len(out) < size:
|
||||
if rng.random() < 0.002:
|
||||
out += rng.randbytes(rng.randint(500, 4000)) # incompressible stretches: the ratio drops, CLEAR follows
|
||||
else:
|
||||
out += (" ".join(rng.choice(words) for _ in range(12)) + ".\n").encode()
|
||||
return bytes(out[:size])
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = ctx.rng(23)
|
||||
big = corpus(rng, 700000)
|
||||
inputs = [("empty", b"", 16), ("one", b"A", 16), ("text", b"TOBEORNOTTOBEORTOBEORNOT#" * 40, 16),
|
||||
("random", rng.randbytes(30000), 16), ("corpus16", big, 16)]
|
||||
mid = big[:120000]
|
||||
for bits in range(10, 16): # (-b 9 output does not round-trip through ncompress or gzip: not a valid file)
|
||||
inputs.append(("corpus-b%d" % bits, mid, bits))
|
||||
cases = []
|
||||
for name, data, bits in inputs:
|
||||
z = compress(data, bits)
|
||||
back = subprocess.run(["nix", "shell", "nixpkgs#gzip", "-c", "gzip", "-d", "-c"], input=z, capture_output=True, check=True).stdout
|
||||
assert back == data, "gzip -d disagrees on " + name
|
||||
cases.append({"name": name, "input": data, "bits": bits, "z": z})
|
||||
b = io.BytesIO()
|
||||
with tarfile.open(fileobj=b, mode="w", format=tarfile.PAX_FORMAT) as t:
|
||||
for n, d in (("a.txt", b"alpha\n"), ("b/c.txt", b"gamma " * 100)):
|
||||
ti = tarfile.TarInfo(n)
|
||||
ti.size, ti.mtime = len(d), 1700000000
|
||||
t.addfile(ti, io.BytesIO(d))
|
||||
ctx.emit("z", {"cases": cases, "tarZ": compress(b.getvalue(), 16), "tarNames": ["a.txt", "b/c.txt"]})
|
||||
Reference in new issue
Block a user