ws-arch2: archive/uu (uuencode / xxencode / base64 blocks, read + write), core/Crc16 (ccitt / arc), Archive.files helper, shared fixture helpers (_arch2.py / _arch2_ours.luau) and tests/archive/_entries.luau
core/Crc16 is new (CRC-16/XMODEM for BinHex / MacBinary, CRC-16/ARC for LHA / Zoo). containers/Archive gains Archive.files(value, name?) (additive).
This commit is contained in:
1 parent
51117f9732
commit
8cdb65367a
10 files changed
+679
No files matched your search
@@ -54,6 +54,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 | gzip | .gz .tgz .gzip | yes | yes | stream: true | `tests/archive/gzip.luau` |
|
||||
| archive | tar | .tar | yes | yes | variants: "ustar", "pax", "gnu" | `tests/archive/tar.luau` |
|
||||
| archive | uu | .uu .uue .xxe .b64 | yes | yes | variants: "uu", "xx", "base64" | `tests/archive/uu.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` |
|
||||
| archive | zst | .zst .tzst | yes | - | stream: true | `tests/archive/zst.luau` |
|
||||
|
||||
@@ -602,6 +602,18 @@ local list: { Entry } = {
|
||||
return require("@formats/archive/tar")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "uu",
|
||||
category = "archive",
|
||||
path = "archive/uu",
|
||||
extensions = { "uu", "uue", "xxe", "b64" },
|
||||
mime = { "text/x-uuencode" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Base64", "containers/Archive" },
|
||||
caps = { decode = true, encode = true, variants = { "uu", "xx", "base64" } },
|
||||
load = function()
|
||||
return require("@formats/archive/uu")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "xz",
|
||||
category = "archive",
|
||||
|
||||
@@ -0,0 +1,276 @@
|
||||
--!strict
|
||||
-- archive/uu: uuencoded, xxencoded and GNU "begin-base64" text as an Archive: every "begin <mode> <name>" block of a
|
||||
-- text (mail, news, shar parts: the text around the blocks is ignored) is one entry (entry.mode = the octal mode);
|
||||
-- one block makes a single-stream archive (meta.stream: the api unwraps a uuencoded .tar.gz). The variant of each
|
||||
-- block (uu / xx / base64) is detected from its characters and line lengths and kept in entry.variant and
|
||||
-- meta.source.variant. Written from the POSIX uuencode description and the xxencode alphabet; written as GNU sharutils
|
||||
-- does (45 bytes a line, "`" for zero, base64 lines of 60 characters + "===="). Not supported: multi-part postings
|
||||
-- split over several files (concatenate the parts first), yEnc (archive/yenc), BinHex (archive/binhex).
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Base64 = require("@formats/core/Base64")
|
||||
local Archive = require("@formats/containers/Archive")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Uu = {
|
||||
name = "uu",
|
||||
category = "archive",
|
||||
extensions = { "uu", "uue", "xxe", "b64" },
|
||||
mime = { "text/x-uuencode" },
|
||||
deps = { "core/Err", "core/Bytes", "core/Base64", "containers/Archive" },
|
||||
caps = { decode = true, encode = true, variants = { "uu", "xx", "base64" } },
|
||||
}
|
||||
|
||||
export type DecodeOptions = { maxBytes: number?, name: string? } -- maxBytes: default 2^30
|
||||
export type EncodeOptions = {
|
||||
variant: ("uu" | "xx" | "base64")?, -- default "uu"
|
||||
mode: number?, -- file mode when the entry has none (default 0o644)
|
||||
name: string?, -- the name of a buffer / string value (default "data")
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local XX = "+-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
|
||||
local XX_VALUE: { [number]: number } = {}
|
||||
for i = 1, 64 do
|
||||
XX_VALUE[string.byte(XX, i)] = i - 1
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Uu.sniff(r: Bytes.Reader): number
|
||||
local head = r:peek(4096)
|
||||
if string.match(head, "^begin%-base64 [0-7]+ [^\r\n]") or string.match(head, "^begin [0-7]+ [^\r\n]") then
|
||||
return 0.9
|
||||
end
|
||||
if string.match(head, "\nbegin%-base64 [0-7]+ [^\r\n]") or string.match(head, "\nbegin [0-7][0-7][0-7]+ [^\r\n]") then
|
||||
return 0.5
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
-- the value of character c in a variant, or nil
|
||||
local function value(c: number, xx: boolean): number?
|
||||
if xx then
|
||||
return XX_VALUE[c]
|
||||
end
|
||||
if c >= 32 and c <= 96 then
|
||||
return bit32.band(c - 32, 63)
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
-- does a data line fit the variant: every character valid and the length matching the count character
|
||||
local function fits(line: string, xx: boolean): boolean
|
||||
local n = value(string.byte(line, 1) or 0, xx)
|
||||
if not n then
|
||||
return false
|
||||
end
|
||||
local need = math.ceil(n / 3) * 4
|
||||
if #line - 1 < need or #line - 1 > need + 2 then
|
||||
return false
|
||||
end
|
||||
for i = 2, need + 1 do
|
||||
if not value(string.byte(line, i), xx) then
|
||||
return false
|
||||
end
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
-- decode the uu / xx lines of a block into a buffer (nil, message on a bad line)
|
||||
local function decodeLines(lines: { string }, xx: boolean, maxBytes: number): (buffer?, string?)
|
||||
local total = 0
|
||||
for _, l in lines do
|
||||
total += value(string.byte(l, 1) or 0, xx) or 0
|
||||
end
|
||||
if total > maxBytes then
|
||||
return nil, "limit: data larger than maxBytes"
|
||||
end
|
||||
local out = buffer.create(total)
|
||||
local o = 0
|
||||
for li, l in lines do
|
||||
local n = value(string.byte(l, 1) or 0, xx) or 0
|
||||
local p = 2
|
||||
local left = n
|
||||
while left > 0 do
|
||||
local a = value(string.byte(l, p) or 0, xx)
|
||||
local b = value(string.byte(l, p + 1) or 0, xx)
|
||||
local c = value(string.byte(l, p + 2) or 0, xx) or 0
|
||||
local d = value(string.byte(l, p + 3) or 0, xx) or 0
|
||||
if not a or not b then
|
||||
return nil, "bad character in line " .. li
|
||||
end
|
||||
local v = a * 262144 + b * 4096 + c * 64 + d
|
||||
for k = 2, 0, -1 do
|
||||
if left > 0 then
|
||||
buffer.writeu8(out, o, bit32.band(bit32.rshift(v, k * 8), 255))
|
||||
o += 1
|
||||
left -= 1
|
||||
end
|
||||
end
|
||||
p += 4
|
||||
end
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
|
||||
type Block = { name: string, mode: number, variant: string, data: buffer }
|
||||
|
||||
local function parse(text: string, maxBytes: number): ({ Block }?, string?)
|
||||
local lines = string.split(text, "\n")
|
||||
local blocks: { Block } = {}
|
||||
local i = 1
|
||||
while i <= #lines do
|
||||
local line = string.gsub(lines[i], "\r$", "")
|
||||
local b64, mode, name = string.match(line, "^begin(%-base64) ([0-7]+) (.+)$")
|
||||
if not b64 then
|
||||
mode, name = string.match(line, "^begin ([0-7]+) (.+)$")
|
||||
end
|
||||
if mode and name then
|
||||
local body: { string } = {}
|
||||
local closed = false
|
||||
i += 1
|
||||
while i <= #lines do
|
||||
local l = string.gsub(lines[i], "\r$", "")
|
||||
if (b64 and l == "====") or (not b64 and l == "end") then
|
||||
closed = true
|
||||
break
|
||||
end
|
||||
table.insert(body, l)
|
||||
i += 1
|
||||
end
|
||||
if not closed then
|
||||
return nil, "truncated: block " .. name .. " has no end line"
|
||||
end
|
||||
local data, variant
|
||||
if b64 then
|
||||
local d, err = Base64.decode(table.concat(body))
|
||||
if not d then
|
||||
return nil, "block " .. name .. ": " .. tostring(err)
|
||||
end
|
||||
data, variant = d, "base64"
|
||||
else
|
||||
-- drop the empty-line terminator ("`" / " " in uu, "+" in xx) and blank lines
|
||||
local data_lines: { string } = {}
|
||||
for _, l in body do
|
||||
if l ~= "" then
|
||||
table.insert(data_lines, l)
|
||||
end
|
||||
end
|
||||
local uuOk, xxOk = true, true
|
||||
for _, l in data_lines do
|
||||
uuOk = uuOk and fits(l, false)
|
||||
xxOk = xxOk and fits(l, true)
|
||||
end
|
||||
local xx = xxOk and not uuOk
|
||||
if not uuOk and not xxOk then
|
||||
return nil, "block " .. name .. ": lines are neither uuencode nor xxencode"
|
||||
end
|
||||
local d, err = decodeLines(data_lines, xx, maxBytes)
|
||||
if not d then
|
||||
return nil, err
|
||||
end
|
||||
data, variant = d, if xx then "xx" else "uu"
|
||||
end
|
||||
table.insert(blocks, { name = name, mode = tonumber(mode, 8) or 0, variant = variant, data = data })
|
||||
end
|
||||
i += 1
|
||||
end
|
||||
if #blocks == 0 then
|
||||
return nil, "no begin line"
|
||||
end
|
||||
return blocks, nil
|
||||
end
|
||||
|
||||
local function encoder(a: any, o: any?): (buffer?, Err.Err?)
|
||||
return Uu.encode(a, o)
|
||||
end
|
||||
|
||||
function Uu.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local o: DecodeOptions = opts or {}
|
||||
local blocks, err = parse(buffer.readstring(r.buf, r.base, r.limit - r.base), o.maxBytes or 2 ^ 30)
|
||||
if not blocks then
|
||||
return nil, Err.from(err)
|
||||
end
|
||||
local a = Archive.new("uu", encoder)
|
||||
for _, b in blocks do
|
||||
Archive.put(a, { name = b.name, size = buffer.len(b.data), dir = false, mode = b.mode, variant = b.variant, method = b.variant, data = b.data })
|
||||
end
|
||||
a.meta.stream = #a:list() == 1
|
||||
a.meta.source = { format = "uu", variant = blocks[1].variant }
|
||||
return a, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
local function encodeLines(data: buffer, xx: boolean, out: { string })
|
||||
local n = buffer.len(data)
|
||||
local function ch(v: number): string
|
||||
if xx then
|
||||
return string.sub(XX, v + 1, v + 1)
|
||||
end
|
||||
return if v == 0 then "`" else string.char(v + 32)
|
||||
end
|
||||
local p = 0
|
||||
while p < n do
|
||||
local len = math.min(45, n - p)
|
||||
local parts = { ch(len) }
|
||||
for q = p, p + len - 1, 3 do
|
||||
local b0 = buffer.readu8(data, q)
|
||||
local b1 = if q + 1 < p + len then buffer.readu8(data, q + 1) else 0
|
||||
local b2 = if q + 2 < p + len then buffer.readu8(data, q + 2) else 0
|
||||
local v = b0 * 65536 + b1 * 256 + b2
|
||||
table.insert(parts, ch(bit32.rshift(v, 18)) .. ch(bit32.band(bit32.rshift(v, 12), 63)) .. ch(bit32.band(bit32.rshift(v, 6), 63)) .. ch(bit32.band(v, 63)))
|
||||
end
|
||||
table.insert(out, table.concat(parts))
|
||||
p += len
|
||||
end
|
||||
table.insert(out, ch(0))
|
||||
end
|
||||
|
||||
function Uu.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local o: EncodeOptions = opts or {}
|
||||
local variant = o.variant or "uu"
|
||||
if variant ~= "uu" and variant ~= "xx" and variant ~= "base64" then
|
||||
return nil, Err.new(Err.ARG, "variant must be uu, xx or base64")
|
||||
end
|
||||
local files, err = Archive.files(value, o.name)
|
||||
if not files then
|
||||
return nil, err
|
||||
end
|
||||
if #files == 0 then
|
||||
return nil, Err.new(Err.ARG, "nothing to encode")
|
||||
end
|
||||
local out: { string } = {}
|
||||
for _, f in files do
|
||||
if string.find(f.name, "[\r\n]") then
|
||||
return nil, Err.new(Err.ARG, "file names may not contain line breaks")
|
||||
end
|
||||
local mode = if type(f.entry.mode) == "number" then f.entry.mode else (o.mode or 0x1A4)
|
||||
local m = string.format("%o", bit32.band(mode, 0xFFF))
|
||||
if variant == "base64" then
|
||||
table.insert(out, "begin-base64 " .. m .. " " .. f.name)
|
||||
local s = Base64.encode(f.data)
|
||||
for p = 1, #s, 60 do
|
||||
table.insert(out, string.sub(s, p, p + 59))
|
||||
end
|
||||
table.insert(out, "====")
|
||||
else
|
||||
table.insert(out, "begin " .. m .. " " .. f.name)
|
||||
encodeLines(f.data, variant == "xx", out)
|
||||
table.insert(out, "end")
|
||||
end
|
||||
end
|
||||
return buffer.fromstring(table.concat(out, "\n") .. "\n"), nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
-- new() -> an empty uu Archive: a:add(name, data, { mode }); a:write({ variant })
|
||||
function Uu.new(): any
|
||||
local a = Archive.new("uu", encoder)
|
||||
a.meta.source = { format = "uu" }
|
||||
return a
|
||||
end
|
||||
|
||||
return Uu
|
||||
@@ -152,6 +152,30 @@ function Archive.entries(value: any): { { entry: Types.ArchiveEntry, read: () ->
|
||||
return out
|
||||
end
|
||||
|
||||
-- files(value, name?) -> { { name, data, entry } } | nil, Err: the files (directories skipped) of any Archive value,
|
||||
-- read; a buffer or a string is one file named name (default "data"). What single-file and encoding writers take.
|
||||
function Archive.files(value: any, name: string?): ({ { name: string, data: buffer, entry: any } }?, Err.Err?)
|
||||
if type(value) == "buffer" or type(value) == "string" then
|
||||
local b = if type(value) == "string" then buffer.fromstring(value) else value
|
||||
return { { name = name or "data", data = b, entry = { name = name or "data", size = buffer.len(b), dir = false } } }, nil
|
||||
end
|
||||
local items = Archive.entries(value)
|
||||
if not items then
|
||||
return nil, Err.new(Err.ARG, "expected an Archive, a buffer or a string")
|
||||
end
|
||||
local out = {}
|
||||
for _, it in items do
|
||||
if not it.entry.dir then
|
||||
local b, err = it.read()
|
||||
if not b then
|
||||
return nil, err
|
||||
end
|
||||
table.insert(out, { name = it.entry.name, data = b, entry = it.entry })
|
||||
end
|
||||
end
|
||||
return out, nil
|
||||
end
|
||||
|
||||
-- streamName(opts, ext) -> the entry name for a single-stream archive: opts.name without its compression extension
|
||||
-- (".tgz" -> ".tar"), else "data"
|
||||
function Archive.streamName(opts: any?, exts: { string }): string
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
--!strict
|
||||
--!native
|
||||
-- core/Crc16: the two 16-bit CRCs old archive and encoding formats use, table driven. New code.
|
||||
-- Crc16.ccitt(buf, off, len, crc?) CRC-16/XMODEM: polynomial 0x1021, MSB first, init 0, no final XOR (BinHex 4.0,
|
||||
-- MacBinary II / III headers)
|
||||
-- Crc16.arc(buf, off, len, crc?) CRC-16/ARC: polynomial 0x8005 reflected (0xA001), init 0 (LHA, Zoo, ARC)
|
||||
-- Pass a previous result as crc to continue it. Never throws: the range is clamped to the buffer.
|
||||
local band, bxor, rshift, lshift = bit32.band, bit32.bxor, bit32.rshift, bit32.lshift
|
||||
local readu8 = buffer.readu8
|
||||
|
||||
local MSB = table.create(256, 0)
|
||||
local ARC = table.create(256, 0)
|
||||
for n = 0, 255 do
|
||||
local c = lshift(n, 8)
|
||||
for _ = 1, 8 do
|
||||
c = if band(c, 0x8000) ~= 0 then bxor(band(lshift(c, 1), 0xFFFF), 0x1021) else band(lshift(c, 1), 0xFFFF)
|
||||
end
|
||||
MSB[n + 1] = c
|
||||
local r = n
|
||||
for _ = 1, 8 do
|
||||
r = if band(r, 1) ~= 0 then bxor(rshift(r, 1), 0xA001) else rshift(r, 1)
|
||||
end
|
||||
ARC[n + 1] = r
|
||||
end
|
||||
|
||||
local Crc16 = {}
|
||||
|
||||
local function clamp(buf: buffer, off: number, len: number): (number, number)
|
||||
local n = buffer.len(buf)
|
||||
local o = math.clamp(math.floor(off), 0, n)
|
||||
return o, math.clamp(math.floor(len), 0, n - o)
|
||||
end
|
||||
|
||||
function Crc16.ccitt(buf: buffer, off: number, len: number, crc: number?): number
|
||||
local o, l = clamp(buf, off, len)
|
||||
local c = crc or 0
|
||||
for i = o, o + l - 1 do
|
||||
c = bxor(band(lshift(c, 8), 0xFFFF), MSB[bxor(rshift(c, 8), readu8(buf, i)) + 1])
|
||||
end
|
||||
return c
|
||||
end
|
||||
|
||||
function Crc16.arc(buf: buffer, off: number, len: number, crc: number?): number
|
||||
local o, l = clamp(buf, off, len)
|
||||
local c = crc or 0
|
||||
for i = o, o + l - 1 do
|
||||
c = bxor(rshift(c, 8), ARC[bxor(band(c, 0xFF), readu8(buf, i)) + 1])
|
||||
end
|
||||
return c
|
||||
end
|
||||
|
||||
return Crc16
|
||||
@@ -0,0 +1,78 @@
|
||||
-- shared by the archive tests: check(t, archive, want, label) compares an Archive's entries with the reference listing
|
||||
-- want = { { name, size?, crc?, mode?, mtime?, dir?, link? } } (only the fields present are compared; every wanted
|
||||
-- entry must exist; crc is the CRC-32 of the data read back), and the files written by _arch2_ours.luau.
|
||||
local Crc32 = require("@formats/core/Crc32")
|
||||
|
||||
local E = {}
|
||||
|
||||
function E.check(t: any, a: any, want: { any }, label: string, exact: boolean?)
|
||||
local list = a:list()
|
||||
if exact ~= false then
|
||||
t:eq(#list, #want, label .. ": entry count")
|
||||
end
|
||||
local by = {}
|
||||
for _, e in list do
|
||||
by[e.name] = e
|
||||
end
|
||||
for _, w in want do
|
||||
local e = by[w.name]
|
||||
t:check(e, label .. ": has " .. tostring(w.name))
|
||||
if e then
|
||||
for _, k in { "size", "mode", "mtime", "dir", "link" } do
|
||||
if w[k] ~= nil then
|
||||
t:eq(e[k], w[k], label .. ": " .. w.name .. " " .. k)
|
||||
end
|
||||
end
|
||||
if w.crc then
|
||||
local b, err = a:read(w.name)
|
||||
t:check(b, label .. ": read " .. w.name .. ": " .. tostring(err))
|
||||
if b then
|
||||
t:eq(Crc32.of(b), w.crc, label .. ": " .. w.name .. " data")
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- the standard file set of tools/fixtures/_arch2_ours.luau / _arch2.py
|
||||
local function content(n: number, seed: number): buffer
|
||||
local b = buffer.create(n)
|
||||
local s = seed
|
||||
for i = 0, n - 1 do
|
||||
s = (s * 75 + 74) % 65537
|
||||
buffer.writeu8(b, i, if (i // 64) % 3 == 0 then (i // 7) % 256 else s % 256)
|
||||
end
|
||||
return b
|
||||
end
|
||||
E.content = content
|
||||
E.FILES = {
|
||||
{ name = "hello.txt", data = buffer.fromstring("hello, archive\n") },
|
||||
{ name = "data.bin", data = content(5000, 7) },
|
||||
{ name = "empty.txt", data = buffer.create(0) },
|
||||
}
|
||||
|
||||
-- roundTrip(t, mod, opts, label): add the standard files to mod.new(), write with opts, decode, compare
|
||||
function E.roundTrip(t: any, mod: any, opts: any?, label: string): buffer?
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local a = mod.new()
|
||||
for _, f in E.FILES do
|
||||
a:add(f.name, f.data, { mtime = 1700000000, mode = 0x1A4 })
|
||||
end
|
||||
local out, err = a:write(opts)
|
||||
t:check(out, label .. ": write: " .. tostring(err))
|
||||
if not out then
|
||||
return nil
|
||||
end
|
||||
local back, berr = mod.decode(Bytes.reader(out), {})
|
||||
t:check(back, label .. ": decode: " .. tostring(berr))
|
||||
if back then
|
||||
local want = {}
|
||||
for _, f in E.FILES do
|
||||
table.insert(want, { name = f.name, size = buffer.len(f.data), crc = Crc32.of(f.data) })
|
||||
end
|
||||
E.check(t, back, want, label, false)
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
return E
|
||||
@@ -0,0 +1,70 @@
|
||||
-- archive/uu tests: blocks by GNU uuencode (classic / -m) and uuenview (-u / -x) decode to the right names, sizes,
|
||||
-- modes and data; several blocks in a mail; CRLF lines; our uu / xx / base64 output decodes with uudecode / uudeview
|
||||
-- (fixture step) and is byte-identical to GNU uuencode for one file; round trips; errors; the fuzz pass.
|
||||
-- Fixtures: tools/fixtures/uu.py.
|
||||
local T = require("@tests/T")
|
||||
local F = require("@formats")
|
||||
local Uu = require("@formats/archive/uu")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local E = require("@tests/archive/_entries")
|
||||
local Fx = require("@tests/gen/uu")
|
||||
|
||||
local t = T.suite("uu")
|
||||
t:eq(Uu.name, "uu", "name")
|
||||
|
||||
local samples = {}
|
||||
for _, c in Fx.cases do
|
||||
local a, err = Uu.decode(Bytes.reader(buffer.fromstring(c.data)))
|
||||
t:check(a, c.name .. ": " .. tostring(err))
|
||||
if a then
|
||||
E.check(t, a, c.entries, c.name)
|
||||
end
|
||||
t:eq(F.detect(c.data), "uu", c.name .. ": detect")
|
||||
table.insert(samples, c.data)
|
||||
end
|
||||
|
||||
-- byte-identical to GNU uuencode (mode 644) for each single file
|
||||
for _, g in Fx.gnu do
|
||||
local data = buffer.create(0)
|
||||
for _, f in E.FILES do
|
||||
if f.name == g.name then
|
||||
data = f.data
|
||||
end
|
||||
end
|
||||
local a = Uu.new()
|
||||
a:add(g.name, data, { mode = 0x1A4 })
|
||||
t:eq(buffer.tostring(a:write() :: buffer), g.uu, g.name .. ": same bytes as uuencode")
|
||||
t:eq(buffer.tostring(a:write({ variant = "base64" }) :: buffer), g.base64, g.name .. ": same bytes as uuencode -m")
|
||||
end
|
||||
for _, o in Fx.ours do
|
||||
t:check(o.ok, "our " .. o.variant .. " output decodes with the reference tool")
|
||||
end
|
||||
for _, v in { "uu", "xx", "base64" } do
|
||||
local out = E.roundTrip(t, Uu, { variant = v }, "round trip " .. v)
|
||||
if out then
|
||||
local back = Uu.decode(Bytes.reader(out)) :: any
|
||||
t:eq(back:list()[1].variant, v, v .. ": variant detected")
|
||||
end
|
||||
end
|
||||
-- a single block is a stream: the api unwraps what is inside (here: a uuencoded uuencoded file)
|
||||
local inner = Uu.encode("abc", { name = "x.uu" }) :: buffer
|
||||
local outer = Uu.encode(inner, { name = "x.uu" }) :: buffer
|
||||
local v = F.load(outer) :: any
|
||||
t:check(v and v.format == "uu" and v.meta.compression == "uu" and buffer.tostring((v:read("x.uu"))) == "abc", "api unwraps a single block")
|
||||
|
||||
-- errors
|
||||
local function code(s: string): string?
|
||||
local _, e = Uu.decode(Bytes.reader(buffer.fromstring(s)))
|
||||
return e and e.code
|
||||
end
|
||||
t:eq(code("no blocks here\n"), Err.CORRUPT, "no begin line")
|
||||
t:eq(code("begin 644 x\n#86)C\n"), Err.TRUNCATED, "no end line")
|
||||
t:eq(code("begin 644 x\n#8~~~\n`\nend\n"), Err.CORRUPT, "bad characters")
|
||||
t:eq(select(2, Uu.encode({})) and (select(2, Uu.encode({})) :: any).code, Err.ARG, "encode a non-archive")
|
||||
t:eq((select(2, Uu.encode("x", { variant = "zz" :: any })) :: any).code, Err.ARG, "bad variant")
|
||||
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return Uu.decode(Bytes.reader(b))
|
||||
end, samples)
|
||||
t:done()
|
||||
@@ -0,0 +1,62 @@
|
||||
# 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")
|
||||
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-")
|
||||
@@ -0,0 +1,43 @@
|
||||
-- tools/fixtures/_arch2_ours.luau: our archive writers' output for the reference tools to read (run by the ws-arch2
|
||||
-- fixture generators through `luau tools/fixtures/_arch2_ours.luau -a <format> [<options as k=v,k=v>]`). Writes the
|
||||
-- standard file set (the same names and bytes as _arch2.FILES) with the format's encoder and prints the file as hex.
|
||||
local F = require("@formats")
|
||||
|
||||
local which, optstr = ...
|
||||
local function content(n: number, seed: number): buffer
|
||||
local b = buffer.create(n)
|
||||
local s = seed
|
||||
for i = 0, n - 1 do
|
||||
s = (s * 75 + 74) % 65537
|
||||
-- runs and noise, so compressors have something to find
|
||||
buffer.writeu8(b, i, if (i // 64) % 3 == 0 then (i // 7) % 256 else s % 256)
|
||||
end
|
||||
return b
|
||||
end
|
||||
|
||||
local opts: { [string]: any } = {}
|
||||
for k, v in string.gmatch(optstr or "", "([%w_]+)=([^,]*)") do
|
||||
opts[k] = tonumber(v) or (if v == "true" then true elseif v == "false" then false else v)
|
||||
end
|
||||
local mod = F.format(which) :: any
|
||||
local a = if mod.new then mod.new() else nil
|
||||
local files = {
|
||||
{ "hello.txt", buffer.fromstring("hello, archive\n") },
|
||||
{ "data.bin", content(5000, 7) },
|
||||
{ "empty.txt", buffer.create(0) },
|
||||
}
|
||||
if opts.single then
|
||||
files = { files[2] }
|
||||
end
|
||||
for _, f in files do
|
||||
a:add(f[1], f[2], { mtime = 1700000000, mode = 0x1A4 })
|
||||
end
|
||||
local out, err = a:write(opts)
|
||||
if not out then
|
||||
error(tostring(err))
|
||||
end
|
||||
local t = table.create(buffer.len(out))
|
||||
for i = 0, buffer.len(out) - 1 do
|
||||
t[i + 1] = string.format("%02x", buffer.readu8(out, i))
|
||||
end
|
||||
print(table.concat(t))
|
||||
@@ -0,0 +1,61 @@
|
||||
# uuencode / xxencode / base64 fixtures (tools/fixtures.py): blocks made by GNU sharutils `uuencode` (classic and -m)
|
||||
# and uudeview's `uuenview` (-u, -x), alone and several in one text with mail-like text around them; our writer's uu /
|
||||
# xx / base64 output (tools/fixtures/_arch2_ours.luau) decoded by `uudecode` / `uudeview`.
|
||||
# tests/gen/uu.luau { cases = { { name, data, entries = { { name, size, crc, mode } } } }, gnu = { { name, data } },
|
||||
# ours = { { variant, ok } } }
|
||||
import importlib.util, os, shutil, zlib
|
||||
|
||||
_s = importlib.util.spec_from_file_location("_arch2", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_arch2.py"))
|
||||
A = importlib.util.module_from_spec(_s)
|
||||
_s.loader.exec_module(A)
|
||||
|
||||
INPUTS = ["tools/fixtures/_arch2.py", "tools/fixtures/_arch2_ours.luau", "src/Formats/archive/uu"]
|
||||
PKGS = ["sharutils", "uudeview"]
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
tmp = A.tmpdir()
|
||||
try:
|
||||
A.tree(A.FILES, tmp)
|
||||
for name, _ in A.FILES:
|
||||
os.chmod(os.path.join(tmp, name), 0o644)
|
||||
ents = {n: {"name": n, "size": len(d), "crc": zlib.crc32(d), "mode": 0o644} for n, d in A.FILES}
|
||||
cases, gnu = [], []
|
||||
for name, _ in A.FILES:
|
||||
uu = A.tool(PKGS, ["uuencode", name, name], cwd=tmp)
|
||||
b64 = A.tool(PKGS, ["uuencode", "-m", name, name], cwd=tmp)
|
||||
gnu.append({"name": name, "uu": uu, "base64": b64})
|
||||
cases.append({"name": "uuencode " + name, "data": uu, "entries": [ents[name]]})
|
||||
cases.append({"name": "uuencode -m " + name, "data": b64, "entries": [ents[name]]})
|
||||
for flag in ("-u", "-x"):
|
||||
out = A.tool(PKGS, ["uuenview", flag, name], cwd=tmp)
|
||||
cases.append({"name": "uuenview %s %s" % (flag, name), "data": out, "entries": [{"name": name, "size": ents[name]["size"], "crc": ents[name]["crc"]}]})
|
||||
# several blocks in one mail-like text
|
||||
text = b"From: someone\nSubject: files\n\nHere they are:\n\n" + gnu[0]["uu"] + b"\nand the other one\n" + gnu[1]["base64"] + b"\n-- \nsig\n"
|
||||
cases.append({"name": "mail with two blocks", "data": text, "entries": [ents["hello.txt"], ents["data.bin"]]})
|
||||
crlf = gnu[1]["uu"].replace(b"\n", b"\r\n")
|
||||
cases.append({"name": "crlf lines", "data": crlf, "entries": [ents["data.bin"]]})
|
||||
ours = []
|
||||
for variant in ("uu", "xx", "base64"):
|
||||
data = A.ours(ctx, "uu", "variant=" + variant)
|
||||
d = A.tmpdir()
|
||||
try:
|
||||
# one block per file: uudecode reads the first block only
|
||||
end = b"====\n" if variant == "base64" else b"end\n"
|
||||
for k, block in enumerate(data.split(end)[:-1]):
|
||||
p = os.path.join(d, "in%d.txt" % k)
|
||||
open(p, "wb").write(block + end)
|
||||
if variant != "xx":
|
||||
A.tool(PKGS, ["uudecode", p], cwd=d)
|
||||
if variant == "xx":
|
||||
p = os.path.join(d, "all.txt")
|
||||
open(p, "wb").write(data)
|
||||
A.tool(PKGS, ["uudeview", "-i", "-p", d + "/", p], cwd=d)
|
||||
got = A.read_tree(d)
|
||||
ok = all(got.get(n) == zlib.crc32(b) for n, b in A.FILES)
|
||||
ours.append({"variant": variant, "ok": ok})
|
||||
finally:
|
||||
shutil.rmtree(d)
|
||||
ctx.emit("uu", {"cases": cases, "gnu": gnu, "ours": ours})
|
||||
finally:
|
||||
shutil.rmtree(tmp)
|
||||
Reference in new issue
Block a user