ws-arch2-unix: archive/rpm (lead, signature + main headers, file list from dirnames / basenames, payload gzip / bzip2 / xz / lzma / zstd / none decompressed lazily via codecs/compress, cpio via containers/Cpio; meta.rpm), tests vs rpmbuild / rpm -qp / rpm2cpio; containers/Cpio.TYPE_OF

This commit is contained in:
4DBug committed 2026-10-31 14:14:56 -05:00
1 parent 07f70f70d5
commit 8b94584d0f
6 files changed
+549

No files matched your search

+1
View File
@@ -55,6 +55,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| archive | bz2 | .bz2 .tbz2 .tbz | yes | - | stream: true | `tests/archive/bz2.luau` |
| archive | cpio | .cpio | yes | yes | variants: "newc", "crc", "odc", "bin" | `tests/archive/cpio.luau` |
| archive | gzip | .gz .tgz .gzip | yes | yes | stream: true | `tests/archive/gzip.luau` |
| archive | rpm | .rpm | yes | - | compressors: "gzip", "bzip2", "xz", "lzma", "zstd" | `tests/archive/rpm.luau` |
| archive | tar | .tar | yes | yes | variants: "ustar", "pax", "gnu" | `tests/archive/tar.luau` |
| archive | xz | .xz .txz .lzma | yes | - | stream: true, filters: "lzma2", "lzma", "delta", "x86", "powerpc", "arm", "armthumb", "sparc", "arm64" | `tests/archive/xz.luau` |
| archive | zip | .zip .wsz | yes | yes | methods: "store", "deflate", zip64: true | `tests/archive/zip.luau` |
+12
View File
@@ -614,6 +614,18 @@ local list: { Entry } = {
return require("@formats/archive/gzip")
end,
},
{
name = "rpm",
category = "archive",
path = "archive/rpm",
extensions = { "rpm" },
mime = { "application/x-rpm" },
deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzma", "codecs/compress/Zstd", "codecs/compress/Bzip2", "containers/Archive", "containers/Cpio" },
caps = { decode = true, encode = false, compressors = { "gzip", "bzip2", "xz", "lzma", "zstd" } },
load = function()
return require("@formats/archive/rpm")
end,
},
{
name = "tar",
category = "archive",
+333
View File
@@ -0,0 +1,333 @@
--!strict
-- archive/rpm: RPM packages (format v3 / v4), read into the standard Archive value. The 96-byte lead, the signature
-- header (padded to 8 bytes) and the main header are parsed (every tag into meta.rpm.tags; the common ones by name in
-- meta.rpm); the file list comes from the header (dirnames / basenames / dirindexes, or the old filenames tag, with
-- sizes / long sizes, modes, mtimes, link targets, owners) and lists without touching the payload. The payload
-- (gzip / bzip2 / xz / lzma / zstd or none, through codecs/compress/*) is decompressed on the first read and parsed
-- as a cpio archive (containers/Cpio); entry names drop the leading "./" and "/". Ghost files (%ghost) are not
-- listed (they are not in the payload). Written from the RPM file format documentation (rpm.org, the LSB package
-- format chapter); no code ported. Not supported: writing, signature / digest verification, the "stripped cpio"
-- payload of packages with files over 4 GiB (Err.UNSUPPORTED on read), delta rpms.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Deflate = require("@formats/codecs/compress/Deflate")
local Lzma = require("@formats/codecs/compress/Lzma")
local Zstd = require("@formats/codecs/compress/Zstd")
local Bzip2 = require("@formats/codecs/compress/Bzip2")
local Archive = require("@formats/containers/Archive")
local Cpio = require("@formats/containers/Cpio")
-- ------------------------------------------------------------------------------------------------ contract
local Rpm = {
name = "rpm",
category = "archive",
extensions = { "rpm" },
mime = { "application/x-rpm" },
deps = { "core/Err", "core/Bytes", "codecs/compress/Deflate", "codecs/compress/Lzma", "codecs/compress/Zstd", "codecs/compress/Bzip2", "containers/Archive", "containers/Cpio" },
caps = { decode = true, encode = false, compressors = { "gzip", "bzip2", "xz", "lzma", "zstd" } },
}
export type DecodeOptions = {
maxBytes: number?, -- the largest decompressed payload (default 2^30)
maxEntries: number?, -- default 1e6
}
-- ------------------------------------------------------------------------------------------------ constants
local LEAD_MAGIC = "\237\171\238\219"
local HEADER_MAGIC = "\142\173\232\1"
local RPMFILE_GHOST = 64
-- the tags meta.rpm names
local NAMES: { [number]: string } = {
[1000] = "name",
[1001] = "version",
[1002] = "release",
[1003] = "epoch",
[1004] = "summary",
[1005] = "description",
[1006] = "buildtime",
[1007] = "buildhost",
[1009] = "size",
[1010] = "distribution",
[1011] = "vendor",
[1014] = "license",
[1015] = "packager",
[1016] = "group",
[1020] = "url",
[1021] = "os",
[1022] = "arch",
[1044] = "sourcerpm",
[1047] = "provides",
[1049] = "requires",
[1124] = "payloadFormat",
[1125] = "payloadCompressor",
[1126] = "payloadFlags",
[5009] = "longsize",
}
-- ------------------------------------------------------------------------------------------------ sniff
function Rpm.sniff(r: Bytes.Reader): number
return if r:peek(4) == LEAD_MAGIC then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
-- a header structure at p -> { [tag] = value }, end offset | nil, Err
local function header(b: buffer, p: number, e: number): (any, any)
if p + 16 > e then
return nil, Err.new(Err.TRUNCATED, "header past the end", p)
end
if buffer.readstring(b, p, 4) ~= HEADER_MAGIC then
return nil, Err.new(Err.CORRUPT, "bad header magic", p)
end
local n = bit32.byteswap(buffer.readu32(b, p + 8))
local hsize = bit32.byteswap(buffer.readu32(b, p + 12))
local index = p + 16
local store = index + n * 16
if n > 0x10000 or hsize > 0x10000000 then
return nil, Err.new(Err.LIMIT, "header too large", p)
end
if store + hsize > e then
return nil, Err.new(Err.TRUNCATED, "header data past the end", p)
end
local tags: { [number]: any } = {}
local se = store + hsize
for i = 0, n - 1 do
local q = index + i * 16
local tag = bit32.byteswap(buffer.readu32(b, q))
local typ = bit32.byteswap(buffer.readu32(b, q + 4))
local off = bit32.byteswap(buffer.readu32(b, q + 8))
local count = bit32.byteswap(buffer.readu32(b, q + 12))
local d = store + off
if off > hsize then
return nil, Err.new(Err.CORRUPT, "tag data outside the header", q)
end
local width = if typ == 2 or typ == 1 then 1 elseif typ == 3 then 2 elseif typ == 4 then 4 elseif typ == 5 then 8 else 0
if width > 0 then
if d + count * width > se then
return nil, Err.new(Err.CORRUPT, "tag data outside the header", q)
end
local v = table.create(count)
for k = 0, count - 1 do
local x = d + k * width
v[k + 1] = if width == 1 then buffer.readu8(b, x)
elseif width == 2 then bit32.bor(bit32.lshift(buffer.readu8(b, x), 8), buffer.readu8(b, x + 1))
elseif width == 4 then bit32.byteswap(buffer.readu32(b, x))
else bit32.byteswap(buffer.readu32(b, x)) * 4294967296 + bit32.byteswap(buffer.readu32(b, x + 4))
end
tags[tag] = v
elseif typ == 7 then
if d + count > se then
return nil, Err.new(Err.CORRUPT, "tag data outside the header", q)
end
tags[tag] = buffer.readstring(b, d, count)
elseif typ == 6 or typ == 8 or typ == 9 then
local v = {}
local s = d
local want = if typ == 6 then 1 else count
if want > hsize then
return nil, Err.new(Err.CORRUPT, "bad string count", q)
end
for _ = 1, want do
local z = s
while z < se and buffer.readu8(b, z) ~= 0 do
z += 1
end
if z >= se then
return nil, Err.new(Err.CORRUPT, "unterminated string", s)
end
table.insert(v, buffer.readstring(b, s, z - s))
s = z + 1
end
tags[tag] = if typ == 6 then v[1] else v
end
end
return tags, se
end
-- the file list of the header: { name, size, mode, mtime, link, user, group, flags }
local function files(tags: { [number]: any }): { any }
local names: { string } = {}
local bn, dn, di = tags[1117], tags[1118], tags[1116]
if type(bn) == "table" and type(dn) == "table" and type(di) == "table" then
for i, base in bn do
local d = dn[(di[i] or 0) + 1]
names[i] = (if type(d) == "string" then d else "") .. base
end
elseif type(tags[1027]) == "table" then
names = tags[1027]
end
local sizes = tags[5008] or tags[1028] or {}
local modes, mtimes, links = tags[1030] or {}, tags[1034] or {}, tags[1036] or {}
local users, groups, flags = tags[1039] or {}, tags[1040] or {}, tags[1037] or {}
local out = {}
for i, n in names do
table.insert(out, {
name = n,
size = sizes[i] or 0,
mode = modes[i] or 0,
mtime = mtimes[i] or 0,
link = if links[i] and links[i] ~= "" then links[i] else nil,
user = users[i],
group = groups[i],
flags = flags[i] or 0,
})
end
return out
end
local function strip(name: string): string
return (string.gsub(name, "^%.?/+", ""))
end
-- the payload: decompressed, then its cpio entries by stripped name
local function payload(b: buffer, p: number, e: number, compressor: string?, o: DecodeOptions): (any, Err.Err?)
local n = e - p
local opts: any = { maxBytes = o.maxBytes or 2 ^ 30 }
local raw: buffer?, err: any
local m = if n >= 6 then buffer.readstring(b, p, 6) else ""
if string.sub(m, 1, 2) == "\31\139" then
raw, err = Deflate.gunzip(b, p, n)
elseif m == "\253" .. "7zXZ\0" then
raw, err = Lzma.xz(b, p, n, opts)
elseif string.sub(m, 1, 3) == "BZh" then
raw, err = Bzip2.decompress(b, p, n, opts)
elseif string.sub(m, 1, 4) == "\40\181\47\253" then
raw, err = Zstd.decompress(b, p, n, opts)
elseif compressor == "lzma" then
raw, err = Lzma.alone(b, p, n, opts)
elseif string.sub(m, 1, 5) == "07070" then
raw = buffer.create(n)
buffer.copy(raw :: buffer, 0, b, p, n)
else
return nil, Err.new(Err.UNSUPPORTED, "payload compressor " .. tostring(compressor), p)
end
if not raw then
return nil, err
end
if buffer.len(raw) >= 6 and buffer.readstring(raw, 0, 6) == "07070X" then
return nil, Err.new(Err.UNSUPPORTED, "stripped cpio payload (files over 4 GiB)")
end
local list, cerr = Cpio.read(raw, 0, nil, { maxEntries = o.maxEntries })
if not list then
return nil, cerr
end
local by = {}
for _, ent in list do
by[strip(ent.name)] = ent
end
return { buf = raw, by = by }, nil
end
function Rpm.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local o: DecodeOptions = opts or {}
local b, base, e = r.buf, r.base, r.limit
if e - base < 96 then
return nil, Err.new(Err.TRUNCATED, "lead past the end", base)
end
if buffer.readstring(b, base, 4) ~= LEAD_MAGIC then
return nil, Err.new(Err.CORRUPT, "bad lead magic", base)
end
local major, minor = buffer.readu8(b, base + 4), buffer.readu8(b, base + 5)
local kind = bit32.bor(bit32.lshift(buffer.readu8(b, base + 6), 8), buffer.readu8(b, base + 7))
local leadName = buffer.readstring(b, base + 10, 66)
leadName = string.match(leadName, "^[^%z]*") :: string
if major < 3 then
return nil, Err.new(Err.UNSUPPORTED, "rpm format version " .. major, base + 4)
end
local sig, sigEnd = header(b, base + 96, e)
if not sig then
return nil, sigEnd
end
local hp = base + (sigEnd - base + 7) // 8 * 8
local tags, hEnd = header(b, hp, e)
if not tags then
return nil, hEnd
end
local a = Archive.new("rpm")
local info: { [string]: any } = { tags = tags, signature = sig, type = if kind == 1 then "source" else "binary", lead = { major = major, minor = minor, name = leadName } }
for tag, key in NAMES do
local v = tags[tag]
if type(v) == "table" and tag ~= 1047 and tag ~= 1049 then -- numbers and i18n strings: the first value
v = v[1]
end
info[key] = v
end
a.meta.rpm = info
a.meta.source = { format = "rpm", compressor = info.payloadCompressor }
if info.payloadFormat and info.payloadFormat ~= "cpio" then
return nil, Err.new(Err.UNSUPPORTED, "payload format " .. tostring(info.payloadFormat), hEnd)
end
local cache: any = nil
local cacheErr: Err.Err? = nil
local function entry(name: string): (any, Err.Err?)
if not cache and not cacheErr then
cache, cacheErr = payload(b, hEnd, e, info.payloadCompressor, o)
end
if not cache then
return nil, cacheErr
end
local ent = cache.by[name]
if not ent then
return nil, Err.new(Err.CORRUPT, "file " .. name .. " is not in the payload")
end
return ent, nil
end
local list = files(tags)
if #list > (o.maxEntries or 1e6) then
return nil, Err.new(Err.LIMIT, "too many files")
end
for _, f in list do
if bit32.band(f.flags, RPMFILE_GHOST) ~= 0 then
continue
end
local name = strip(f.name)
local typ = Cpio.TYPE_OF[bit32.band(f.mode, 0xF000)] or "0"
local data = typ == "0" and f.size > 0
Archive.put(a, {
name = name,
size = if data then f.size else 0,
dir = typ == "5",
mtime = f.mtime,
mode = bit32.band(f.mode, 0xFFF),
type = typ,
link = if typ == "2" then f.link else nil,
uname = f.user,
gname = f.group,
method = if info.payloadCompressor then info.payloadCompressor else "store",
load = if data
then function(): (buffer?, Err.Err?)
local ent, err = entry(name)
if not ent then
return nil, err
end
local out = buffer.create(ent.size)
buffer.copy(out, 0, cache.buf, ent.offset, ent.size)
return out, nil
end
else nil,
})
end
return a, nil
end
-- ------------------------------------------------------------------------------------------------ extras
-- cpio(r, opts?) -> the decompressed payload (a cpio archive, as rpm2cpio prints it) | nil, Err
function Rpm.cpio(r: Bytes.Reader, opts: DecodeOptions?): (buffer?, Err.Err?)
local a, err = Rpm.decode(r, opts)
if not a then
return nil, err
end
local p = r.base + 96
local _, sigEnd = header(r.buf, p, r.limit)
local hp = r.base + (sigEnd - r.base + 7) // 8 * 8
local _, hEnd = header(r.buf, hp, r.limit)
local pl, perr = payload(r.buf, hEnd, r.limit, a.meta.rpm.payloadCompressor, opts or {})
if not pl then
return nil, perr
end
return pl.buf, nil
end
return Rpm
+1
View File
@@ -58,6 +58,7 @@ for m, t in TYPES do
MODES[t] = m
end
Cpio.TYPE_MODE = MODES -- type letter -> S_IFMT bits
Cpio.TYPE_OF = TYPES -- S_IFMT bits -> type letter
local TRAILER = "TRAILER!!!"
+101
View File
@@ -0,0 +1,101 @@
-- archive/rpm tests: one package from rpmbuild with each payload compressor (gzip, bzip2, xz, lzma, zstd, none) gives
-- the header fields `rpm -qp --qf` prints, its file list (names, sizes, modes, mtimes, symlink targets; %ghost files
-- skipped), the file data rpm2cpio's stream holds (CRCs, hard links), and Rpm.cpio = rpm2cpio's bytes; errors; the
-- fuzz pass. Fixtures: tools/fixtures/rpm.py.
local T = require("@tests/T")
local F = require("@formats")
local Rpm = require("@formats/archive/rpm")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/rpm")
local t = T.suite("rpm")
t:eq(Rpm.name, "rpm", "name")
local TYPES = { [0x8000] = "0", [0x4000] = "5", [0xA000] = "2" }
for _, c in Fx.rpms do
local a, err = Rpm.decode(Bytes.reader(buffer.fromstring(c.data)))
t:check(a, c.name .. ": " .. tostring(err))
t:eq(F.detect(c.data), "rpm", c.name .. ": F.detect")
for k, v in c.fields do
t:eq(a.meta.rpm[k], v, c.name .. ": " .. k)
end
t:eq(a.meta.rpm.type, "binary", c.name .. ": binary package")
local by = {}
for _, e in a:list() do
by[e.name] = e
end
local n = 0
for _, w in c.files do
local e = by[w.name]
if w.flags % 128 >= 64 then
t:check(e == nil, c.name .. ": ghost " .. w.name .. " not listed")
continue
end
n += 1
t:check(e, c.name .. ": has " .. w.name)
t:eq(e.type, TYPES[w.type], c.name .. ": " .. w.name .. " type")
t:eq(e.mode, w.mode, c.name .. ": " .. w.name .. " mode")
t:eq(e.mtime, w.mtime, c.name .. ": " .. w.name .. " mtime")
t:eq(e.link, w.link, c.name .. ": " .. w.name .. " link")
if w.crc then
t:eq(e.size, w.size, c.name .. ": " .. w.name .. " size")
local b, rerr = a:read(w.name)
t:check(b, c.name .. ": read " .. w.name .. ": " .. tostring(rerr))
t:eq(Crc32.of(b), w.crc, c.name .. ": " .. w.name .. " data")
end
end
t:eq(#a:list(), n, c.name .. ": entry count")
-- hard links: both read the same bytes
t:eq(buffer.tostring(a:read("usr/bin/hello")), "#!/bin/sh\necho hello\n", c.name .. ": hard link (first)")
t:eq(buffer.tostring(a:read("usr/bin/hello2")), "#!/bin/sh\necho hello\n", c.name .. ": hard link (second)")
local raw = Rpm.cpio(Bytes.reader(buffer.fromstring(c.data)))
t:check(raw and buffer.len(raw) == c.cpioSize and Crc32.of(raw) == c.cpioCrc, c.name .. ": Rpm.cpio = rpm2cpio")
t:note("%-16s %s %d files", c.name, tostring(a.meta.rpm.payloadCompressor), n)
end
-- the api: an rpm loads as itself (no payload unwrap), converts to tar
do
local c = Fx.rpms[1]
local a = assert(F.load(c.data))
t:eq(a.format, "rpm", "F.load")
local tar = F.load(assert(F.save(a, nil, { format = "tar" })))
t:eq(buffer.tostring(tar:read("usr/bin/hello")), "#!/bin/sh\necho hello\n", "rpm -> tar")
local _, e = F.save(a)
t:check(e, "rpm is read-only")
end
-- errors
do
local good = Fx.rpms[1].data
local _, e1 = Rpm.decode(Bytes.reader(buffer.fromstring(string.sub(good, 1, 50))))
t:check(e1 and e1.code == Err.TRUNCATED, "short lead: " .. tostring(e1))
local b = buffer.fromstring(good)
buffer.writeu8(b, 96, 0)
local _, e2 = Rpm.decode(Bytes.reader(b))
t:check(e2 and e2.code == Err.CORRUPT, "bad signature magic: " .. tostring(e2))
local cut = Rpm.decode(Bytes.reader(buffer.fromstring(string.sub(good, 1, #good - 200))))
t:check(cut, "a cut payload still lists")
local _, e3 = cut:read("usr/share/doc/hello/README")
t:check(e3 ~= nil, "a cut payload fails on read: " .. tostring(e3))
end
local samples = {}
for _, c in Fx.rpms do
if #c.data < 40000 then
table.insert(samples, c.data)
end
end
t:fuzz("decode", function(b: buffer)
local a = Rpm.decode(Bytes.reader(b))
if a then
for _, e in a:list() do
a:read(e.name)
end
end
return a
end, samples, { mutations = 25, keepHeader = 4 })
t:done()
+101
View File
@@ -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})