ws-arch: containers/Tar + archive/tar (ustar / pax / GNU read + write, byte-identical to Python's tarfile) and archive/gzip (read + write, .tar.gz writing); tests incl. .tar.gz/.tgz/.tar.bz2/.tar.xz/.tar.zst/.tar.br unwrap through the api

This commit is contained in:
4DBug committed 2026-10-31 08:54:37 -05:00
1 parent 74f4c47c12
commit e6f077ba54
9 files changed
+1298

No files matched your search

+2
View File
@@ -13,6 +13,8 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| archive | 7z | .7z | yes | - | methods: "copy", "lzma", "lzma2", "deflate", "bcj", "delta", encrypted: false | `tests/archive/7z.luau` |
| archive | br | .br | yes | - | stream: true | `tests/archive/br.luau` |
| 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 | xz | .xz .txz .lzma | yes | - | stream: true, filters: "lzma2", "lzma", "delta", "x86", "powerpc", "arm", "armthumb", "sparc", "arm64" | `tests/archive/xz.luau` |
| archive | zst | .zst .tzst | yes | - | stream: true | `tests/archive/zst.luau` |
+24
View File
@@ -110,6 +110,30 @@ local list: { Entry } = {
return require("@formats/archive/bz2")
end,
},
{
name = "gzip",
category = "archive",
path = "archive/gzip",
extensions = { "gz", "tgz", "gzip" },
mime = { "application/gzip" },
deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/Deflate", "containers/Archive", "containers/Tar" },
caps = { decode = true, encode = true, stream = true },
load = function()
return require("@formats/archive/gzip")
end,
},
{
name = "tar",
category = "archive",
path = "archive/tar",
extensions = { "tar" },
mime = { "application/x-tar" },
deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Tar" },
caps = { decode = true, encode = true, variants = { "ustar", "pax", "gnu" } },
load = function()
return require("@formats/archive/tar")
end,
},
{
name = "xz",
category = "archive",
+187
View File
@@ -0,0 +1,187 @@
--!strict
-- archive/gzip: gzip files (RFC 1952) as a single-stream Archive: one entry, named after the header's FNAME (else the
-- file name without .gz, else "data"), with the header's MTIME; concatenated members decode as one stream, as gzip -d
-- does. Writing: an Archive with one entry (or a buffer / string) becomes one member with FNAME and MTIME; an Archive
-- with several entries is written as a tar inside the gzip (a .tar.gz). The api unwraps a .tar.gz / .tgz on load (the
-- inner tar, meta.compression = "gzip"). Deflate is codecs/Deflate. Not supported: FHCRC verification.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Deflate = require("@formats/codecs/Deflate")
local Archive = require("@formats/containers/Archive")
local Tar = require("@formats/containers/Tar")
-- ------------------------------------------------------------------------------------------------ contract
local Gzip = {
name = "gzip",
category = "archive",
extensions = { "gz", "tgz", "gzip" },
mime = { "application/gzip" },
deps = { "core/Err", "core/Bytes", "core/Crc32", "codecs/Deflate", "containers/Archive", "containers/Tar" },
caps = { decode = true, encode = true, stream = true },
}
export type DecodeOptions = { name: string? } -- the file name (the api passes it): names the entry without FNAME
export type EncodeOptions = {
level: number?, -- 0..9, default 6
name: string?, -- FNAME (default: the entry's name; none for a buffer)
mtime: number?, -- MTIME (default: the entry's mtime, else 0)
}
-- ------------------------------------------------------------------------------------------------ sniff
function Gzip.sniff(r: Bytes.Reader): number
return if r:peek(3) == "\31\139\8" then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
-- header(r) -> { name, comment, mtime, os } of the first member (nil fields when absent)
local function header(b: buffer, o: number, e: number): { [string]: any }
local h: { [string]: any } = {}
if o + 10 > e then
return h
end
local flg = buffer.readu8(b, o + 3)
h.mtime = buffer.readu32(b, o + 4)
h.os = buffer.readu8(b, o + 9)
local q = o + 10
if bit32.band(flg, 4) ~= 0 and q + 2 <= e then
q += 2 + buffer.readu16(b, q)
end
for _, f in { { 8, "name" }, { 16, "comment" } } do
if bit32.band(flg, f[1]) ~= 0 then
local s = q
while q < e and buffer.readu8(b, q) ~= 0 do
q += 1
end
if q < e then
h[f[2]] = buffer.readstring(b, s, q - s)
end
q += 1
end
end
return h
end
function Gzip.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local out, err = Deflate.gunzip(r.buf, r.base, r.limit - r.base)
if not out then
return nil, err
end
local h = header(r.buf, r.base, r.limit)
local a = Archive.new("gzip", function(arc: any, o: any?): (buffer?, Err.Err?)
return Gzip.encode(arc, o)
end)
a.meta.stream = true
a.meta.source = { format = "gzip", os = h.os }
a.meta.comment = h.comment
local name = h.name
if not name or name == "" or string.find(name, "[/\\]") then
name = Archive.streamName(opts, Gzip.extensions)
end
Archive.put(a, {
name = name,
size = buffer.len(out),
compressedSize = r.limit - r.base,
method = "deflate",
mtime = if h.mtime and h.mtime > 0 then h.mtime else nil,
dir = false,
data = out,
})
return a, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Gzip.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local o = opts or {}
local level = if o.level == nil then 6 else o.level
if type(level) ~= "number" or level < 0 or level > 9 or level % 1 ~= 0 then
return nil, Err.new(Err.ARG, "level must be 0..9")
end
local data: buffer
local name: string? = o.name
local mtime: number = o.mtime or 0
if type(value) == "buffer" then
data = value
elseif type(value) == "string" then
data = buffer.fromstring(value)
else
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 files = {}
for _, it in items do
if not it.entry.dir then
table.insert(files, it)
end
end
if #files == 1 and #items == 1 then
local b, err = files[1].read()
if not b then
return nil, err
end
data = b
name = name or files[1].entry.name
mtime = o.mtime or files[1].entry.mtime or 0
else
-- several entries: a tar inside
local list = {}
for _, it in items do
local e: any = it.entry
local b = nil
if not e.dir then
local rb, err = it.read()
if not rb then
return nil, err
end
b = rb
end
table.insert(list, { name = e.name, data = b, dir = e.dir, mtime = e.mtime, mode = e.mode })
end
local t, terr = Tar.write(list)
if not t then
return nil, terr
end
data = t
end
end
if type(mtime) ~= "number" or mtime < 0 or mtime >= 2 ^ 32 then
mtime = 0
end
local raw, cerr = Deflate.compress(data, { level = level })
if not raw then
return nil, cerr
end
local w = Bytes.writer(buffer.len(raw) + 32 + (if name then #name else 0))
w:string("\31\139\8")
w:u8(if name then 8 else 0)
w:u32le(math.floor(mtime))
w:u8(if level >= 9 then 2 elseif level <= 1 then 4 else 0)
w:u8(255)
if name then
local z = string.find(name, "\0", 1, true)
w:cstring(if z then string.sub(name, 1, z - 1) else name)
end
w:bytes(raw)
w:u32le(Crc32.raw(data, 0, buffer.len(data)))
w:u32le(buffer.len(data) % 4294967296)
return w:finish(), nil
end
-- ------------------------------------------------------------------------------------------------ extras
-- new(data?, name?) -> a gzip Archive holding one entry (add() replaces / adds; several entries write a .tar.gz)
function Gzip.new(data: (buffer | string)?, name: string?): any
local a = Archive.new("gzip", function(arc: any, o: any?): (buffer?, Err.Err?)
return Gzip.encode(arc, o)
end)
a.meta.stream = true
a.meta.source = { format = "gzip" }
if data then
a:add(name or "data", data)
end
return a
end
return Gzip
+120
View File
@@ -0,0 +1,120 @@
--!strict
-- archive/tar: tar archives (ustar, pax, GNU long names; see containers/Tar), read into the standard Archive value
-- (entries read lazily: a copy of the stored bytes) and written from any Archive value (a tar, a zip, a 7z: list() +
-- read()). Compressed tars (.tar.gz / .tgz / .tar.zst / .tar.xz / .tar.bz2 / .tar.br) load through the api, which
-- unwraps the single-stream archive and sniffs again (meta.compression names the outer format).
-- Not supported: sparse files, multi-volume archives.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Archive = require("@formats/containers/Archive")
local Tar = require("@formats/containers/Tar")
-- ------------------------------------------------------------------------------------------------ contract
local TarFormat = {
name = "tar",
category = "archive",
extensions = { "tar" },
mime = { "application/x-tar" },
deps = { "core/Err", "core/Bytes", "containers/Archive", "containers/Tar" },
caps = { decode = true, encode = true, variants = { "ustar", "pax", "gnu" } },
}
export type DecodeOptions = { maxEntries: number? } -- default 1e6
export type EncodeOptions = { format: ("pax" | "gnu" | "ustar")? } -- default "pax": ustar + pax records when needed
-- ------------------------------------------------------------------------------------------------ sniff
function TarFormat.sniff(r: Bytes.Reader): number
if r:remaining() < 512 then
return 0
end
if not Tar.valid(r.buf, r.pos) then
return 0
end
return if r:peek(5, 257) == "ustar" then 0.95 else 0.6
end
-- ------------------------------------------------------------------------------------------------ decode
local function lazy(b: buffer, at: number, n: number): () -> (buffer?, Err.Err?)
return function(): (buffer?, Err.Err?)
local out = buffer.create(n)
buffer.copy(out, 0, b, at, n)
return out, nil
end
end
local function encode(archive: any, opts: any?): (buffer?, Err.Err?)
return TarFormat.encode(archive, opts)
end
function TarFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local list, err = Tar.read(r.buf, r.base, r.limit - r.base, opts)
if not list then
return nil, err
end
local a = Archive.new("tar", encode)
for _, e in list do
Archive.put(a, {
name = e.name,
size = e.size,
dir = e.dir,
mtime = e.mtime,
mode = e.mode,
uid = e.uid,
gid = e.gid,
uname = e.uname,
gname = e.gname,
type = e.type,
link = e.link,
method = "store",
load = if e.dir or e.size == 0 then nil else lazy(r.buf, e.offset, e.size),
})
end
a.meta.source = { format = "tar" }
return a, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function TarFormat.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local items = Archive.entries(archive)
if not items then
return nil, Err.new(Err.ARG, "expected an Archive")
end
local list: { Tar.WriteEntry } = {}
for _, it in items do
local e: any = it.entry
local data: buffer? = nil
if not e.dir and e.type ~= "1" and e.type ~= "2" then
local b, err = it.read()
if not b then
return nil, err
end
data = b
end
table.insert(list, {
name = e.name,
data = data,
dir = e.dir,
type = if type(e.type) == "string" and #e.type == 1 then e.type else nil,
link = if type(e.link) == "string" then e.link else nil,
mode = if type(e.mode) == "number" then e.mode else nil,
uid = if type(e.uid) == "number" then e.uid else nil,
gid = if type(e.gid) == "number" then e.gid else nil,
uname = if type(e.uname) == "string" then e.uname else nil,
gname = if type(e.gname) == "string" then e.gname else nil,
mtime = if type(e.mtime) == "number" then e.mtime else nil,
})
end
return Tar.write(list, opts)
end
-- ------------------------------------------------------------------------------------------------ extras
-- new() -> an empty tar Archive: a:add(name, data, { mtime, mode, dir }); a:write()
function TarFormat.new(): any
local a = Archive.new("tar", encode)
a.meta.source = { format = "tar" }
return a
end
return TarFormat
+426
View File
@@ -0,0 +1,426 @@
--!strict
-- containers/Tar: tar archives (POSIX.1-1988 ustar, POSIX.1-2001 pax, GNU), read and written. Reading handles
-- v7 / ustar / GNU / pax headers: the ustar name prefix, pax extended headers ('x' per file, 'g' global: path,
-- linkpath, size, mtime, uid, gid, uname, gname), GNU long names and link names ('L' / 'K'), base-256 numeric fields,
-- header checksums (unsigned and the historical signed sum) and the end-of-archive blocks. Writing produces ustar
-- headers, with a pax extended header for what ustar cannot hold (long or non-ASCII names, sizes of 8 GiB and more,
-- fractional / negative mtimes) or, with opts.format = "gnu", GNU 'L' / 'K' records. Written from POSIX
-- (pax(1), IEEE Std 1003.1-2017) and the GNU tar manual. Not supported: sparse files (GNU 'S', pax GNU.sparse), multi-
-- volume archives (they list, with type "S" / "M"; reading them returns their stored bytes).
--
-- local entries, err = Tar.read(buf, offset?, length?) -- { { name, size, type, mode, mtime, link, offset, ... } }
-- local out, err = Tar.write({ { name = "a.txt", data = buf, mtime = 0 }, { name = "d/", dir = true } }, opts)
--
-- Never throws: bad data returns nil, Err.
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Tar = {}
export type Entry = {
name: string,
size: number,
type: string, -- "0" file, "5" directory, "2" symlink, "1" hard link, "3" / "4" devices, "6" fifo, ...
dir: boolean,
mode: number,
uid: number,
gid: number,
mtime: number,
link: string?,
uname: string?,
gname: string?,
offset: number, -- absolute offset of the data in the buffer
pax: { [string]: string }?,
}
local BLOCK = 512
local function zeros(b: buffer, o: number): boolean
for i = 0, BLOCK - 1, 4 do
if buffer.readu32(b, o + i) ~= 0 then
return false
end
end
return true
end
-- a numeric field: octal text (NUL / space terminated) or base-256 (high bit of the first byte)
local function number(b: buffer, o: number, n: number): number?
local first = buffer.readu8(b, o)
if first >= 0x80 then
local v = first - (if first >= 0xC0 then 0x100 else 0x80) -- 0xFF.. = negative
for i = 1, n - 1 do
v = v * 256 + buffer.readu8(b, o + i)
end
return v
end
local s = buffer.readstring(b, o, n)
s = string.match(s, "^[ %z]*([0-7]*)") or ""
if s == "" then
return 0
end
return tonumber(s, 8)
end
local function str(b: buffer, o: number, n: number): string
local s = buffer.readstring(b, o, n)
local z = string.find(s, "\0", 1, true)
return if z then string.sub(s, 1, z - 1) else s
end
local function checksum(b: buffer, o: number): (number, number)
local u, s = 0, 0
for i = 0, BLOCK - 1 do
local v = if i >= 148 and i < 156 then 32 else buffer.readu8(b, o + i)
u += v
s += if v >= 128 then v - 256 else v
end
return u, s
end
-- valid(buf, offset) -> true when the block at offset is a tar header with a correct checksum
function Tar.valid(b: buffer, o: number): boolean
if o + BLOCK > buffer.len(b) or zeros(b, o) then
return false
end
local want = number(b, o + 148, 8)
local u, s = checksum(b, o)
return want == u or want == s
end
-- pax records "len key=value\n" -> { key = value }
local function pax(b: buffer, o: number, n: number, into: { [string]: string }): boolean
local s = buffer.readstring(b, o, n)
local p = 1
while p <= #s do
if string.byte(s, p) == 0 then
break
end
local len = string.match(s, "^(%d+) ", p)
if not len then
return false
end
local l = tonumber(len) :: number
if l < #len + 3 or p + l - 1 > #s then
return false
end
local rec = string.sub(s, p + #len + 1, p + l - 2) -- without the trailing newline
local eq = string.find(rec, "=", 1, true)
if not eq then
return false
end
into[string.sub(rec, 1, eq - 1)] = string.sub(rec, eq + 1)
p += l
end
return true
end
export type ReadOptions = { maxEntries: number? } -- default 1e6
-- read(buf, offset?, length?, opts?) -> { Entry } | nil, Err
function Tar.read(b: buffer, offset: number?, length: number?, opts: ReadOptions?): ({ Entry }?, Err.Err?)
local o = offset or 0
local e = math.min(buffer.len(b), o + (length or (buffer.len(b) - o)))
local maxEntries = (opts and opts.maxEntries) or 1e6
local out: { Entry } = {}
local global: { [string]: string } = {}
local nextPax: { [string]: string }? = nil
local longName: string? = nil
local longLink: string? = nil
local p = o
while true do
if p + BLOCK > e then
if p == e then
break -- no end-of-archive blocks: accepted, as GNU tar does (with a warning)
end
return nil, Err.new(Err.TRUNCATED, "header past the end", p)
end
if zeros(b, p) then
break -- end of archive (one or two zero blocks; what follows is padding)
end
local want = number(b, p + 148, 8)
local u, s = checksum(b, p)
if want ~= u and want ~= s then
return nil, Err.new(if #out == 0 then Err.CORRUPT else Err.CHECKSUM, "bad header checksum", p + 148)
end
local typ = buffer.readstring(b, p + 156, 1)
if typ == "\0" then
typ = "0"
end
local size = number(b, p + 124, 12)
if not size or size < 0 then
return nil, Err.new(Err.CORRUPT, "bad size field", p + 124)
end
local data = p + BLOCK
local nextHeader = data + (size + BLOCK - 1) // BLOCK * BLOCK
local ustar = buffer.readstring(b, p + 257, 5) == "ustar"
-- meta records: pax / GNU long names
if typ == "x" or typ == "g" or typ == "L" or typ == "K" then
if data + size > e then
return nil, Err.new(Err.TRUNCATED, "extended header past the end", data)
end
if typ == "x" or typ == "g" then
local into = if typ == "g" then global else (nextPax or {})
if not pax(b, data, size, into) then
return nil, Err.new(Err.CORRUPT, "bad pax record", data)
end
if typ == "x" then
nextPax = into
end
elseif typ == "L" then
longName = str(b, data, size)
else
longLink = str(b, data, size)
end
p = nextHeader
continue
end
local name = str(b, p, 100)
if ustar then
local prefix = str(b, p + 345, 155)
if prefix ~= "" and buffer.readstring(b, p + 257, 8) ~= "ustar \0" then -- (GNU uses the field for times)
name = prefix .. "/" .. name
end
end
local entry: Entry = {
name = name,
size = size,
type = typ,
dir = typ == "5",
mode = number(b, p + 100, 8) or 0,
uid = number(b, p + 108, 8) or 0,
gid = number(b, p + 116, 8) or 0,
mtime = number(b, p + 136, 12) or 0,
link = if typ == "1" or typ == "2" then str(b, p + 157, 100) else nil,
uname = if ustar then str(b, p + 265, 32) else nil,
gname = if ustar then str(b, p + 297, 32) else nil,
offset = data,
pax = nil,
}
if longName then
entry.name = longName
end
if longLink then
entry.link = longLink
end
local px = nextPax
for _, rec in { global, px } do
if rec then
if rec.path then
entry.name = rec.path
end
if rec.linkpath then
entry.link = rec.linkpath
end
if rec.size then
local sz = tonumber(rec.size)
if not sz or sz < 0 or sz % 1 ~= 0 then
return nil, Err.new(Err.CORRUPT, "bad pax size", p)
end
entry.size = sz
end
if rec.mtime then
entry.mtime = tonumber(rec.mtime) or entry.mtime
end
if rec.uid then
entry.uid = tonumber(rec.uid) or entry.uid
end
if rec.gid then
entry.gid = tonumber(rec.gid) or entry.gid
end
if rec.uname then
entry.uname = rec.uname
end
if rec.gname then
entry.gname = rec.gname
end
end
end
if px then
entry.pax = px
end
if typ == "5" or string.sub(entry.name, -1) == "/" and (typ == "0" and entry.size == 0) then
entry.dir = true
end
-- links, devices, fifos and directories carry no data (whatever the size field says, except GNU dumpdir)
local dataSize = if typ == "1" or typ == "2" or typ == "3" or typ == "4" or typ == "6" or typ == "5" then 0 else entry.size
if typ == "5" or typ == "1" or typ == "2" then
entry.size = 0
end
nextHeader = data + (dataSize + BLOCK - 1) // BLOCK * BLOCK
if typ ~= "5" and data + dataSize > e then
return nil, Err.new(Err.TRUNCATED, "entry " .. entry.name .. " data past the end", data)
end
table.insert(out, entry)
if #out > maxEntries then
return nil, Err.new(Err.LIMIT, "more than " .. maxEntries .. " entries")
end
nextPax, longName, longLink = nil, nil, nil
p = nextHeader
end
return out, nil
end
-- ------------------------------------------------------------------------------------------------ writing
export type WriteEntry = {
name: string,
data: buffer?,
dir: boolean?,
type: string?, -- default "0" ("5" for dir)
link: string?,
mode: number?, -- default 0o644 (0o755 for directories)
uid: number?,
gid: number?,
uname: string?,
gname: string?,
mtime: number?, -- unix seconds (default 0)
}
export type WriteOptions = { format: ("pax" | "gnu" | "ustar")? } -- default "pax" (ustar headers + pax when needed)
local function octal(w: buffer, o: number, n: number, v: number): boolean
-- n - 1 octal digits and a NUL; false when it does not fit
local s = string.format("%o", v)
if v < 0 or v % 1 ~= 0 or #s > n - 1 then
return false
end
buffer.writestring(w, o, string.rep("0", n - 1 - #s) .. s)
buffer.writeu8(w, o + n - 1, 0)
return true
end
local function field(w: buffer, o: number, n: number, s: string)
buffer.writestring(w, o, string.sub(s, 1, n))
end
local function ascii(s: string): boolean
return not string.find(s, "[\128-\255]")
end
local function paxRecord(key: string, value: string): string
local body = " " .. key .. "=" .. value .. "\n"
local n = #body + 1
while #tostring(n) + #body ~= n do
n = #tostring(n) + #body
end
return tostring(n) .. body
end
-- one header block (the checksum filled in)
local function header(name: string, typ: string, size: number, e: WriteEntry, prefix: string, link: string, gnu: boolean): buffer
local h = buffer.create(BLOCK)
field(h, 0, 100, name)
local mode = e.mode or (if typ == "5" then 0x1ED else 0x1A4)
octal(h, 100, 8, mode % 0x200000)
octal(h, 108, 8, math.clamp(math.floor(e.uid or 0), 0, 0x1FFFFF))
octal(h, 116, 8, math.clamp(math.floor(e.gid or 0), 0, 0x1FFFFF))
octal(h, 124, 12, size)
octal(h, 136, 12, math.clamp(math.floor(e.mtime or 0), 0, 8 ^ 11 - 1))
field(h, 148, 8, " ")
field(h, 156, 1, typ)
field(h, 157, 100, link)
field(h, 257, 8, if gnu then "ustar \0" else "ustar\00000")
field(h, 265, 32, e.uname or "")
field(h, 297, 32, e.gname or "")
field(h, 345, 155, prefix)
local u = checksum(h, 0)
field(h, 148, 8, string.format("%06o", u) .. "\0 ")
return h
end
-- split a long path into ustar prefix (<= 155) + name (<= 100) at a slash, or nil
local function split(path: string): (string?, string?)
if #path <= 100 then
return "", path
end
for i = 2, math.min(#path - 1, 156) do -- the shortest prefix that works, as Python's tarfile
if string.sub(path, i, i) == "/" and i - 1 <= 155 and #path - i <= 100 then
return string.sub(path, 1, i - 1), string.sub(path, i + 1)
end
end
return nil, nil
end
-- write(entries, opts?) -> buffer | nil, Err
function Tar.write(entries: { WriteEntry }, opts: WriteOptions?): (buffer?, Err.Err?)
local fmt = (opts and opts.format) or "pax"
local w = Bytes.writer(BLOCK * (2 * #entries + 2))
for i, e in entries do
if type(e) ~= "table" or type(e.name) ~= "string" or e.name == "" then
return nil, Err.new(Err.ARG, "entry " .. i .. ": needs a name")
end
local data = e.data or buffer.create(0)
local typ = e.type or (if e.dir then "5" else "0")
local name = e.name
if typ == "5" and string.sub(name, -1) ~= "/" then
name ..= "/"
end
local size = if typ == "0" or typ == "7" then buffer.len(data) else 0
local link = e.link or ""
-- ustar splits long names into prefix + name; pax and GNU (as Python's tarfile and GNU tar) record them whole
local prefix, short
if fmt == "ustar" then
prefix, short = split(name)
elseif #name <= 100 then
prefix, short = "", name
end
local paxRecs: { string } = {}
-- GNU headers hold any bytes (UTF-8 names stay raw); ustar / pax headers are ASCII
local needName = prefix == nil or (fmt ~= "gnu" and not ascii(name))
local needLink = #link > 100 or (fmt ~= "gnu" and not ascii(link))
if needName or needLink then
if fmt == "ustar" then
return nil, Err.new(Err.ARG, "entry " .. name .. ": name or link too long / not ASCII for ustar")
elseif fmt == "gnu" then
if needName then
local ln = buffer.fromstring(name .. "\0")
w:bytes(header("././@LongLink", "L", buffer.len(ln), { mode = 0 } :: any, "", "", true))
w:bytes(ln)
w:fill(0, (BLOCK - buffer.len(ln) % BLOCK) % BLOCK)
end
if needLink then
local ll = buffer.fromstring(link .. "\0")
w:bytes(header("././@LongLink", "K", buffer.len(ll), { mode = 0 } :: any, "", "", true))
w:bytes(ll)
w:fill(0, (BLOCK - buffer.len(ll) % BLOCK) % BLOCK)
end
else
if needName then
table.insert(paxRecs, paxRecord("path", name))
end
if needLink then
table.insert(paxRecs, paxRecord("linkpath", link))
end
end
end
if size >= 8 ^ 11 then
if fmt ~= "pax" then
return nil, Err.new(Err.ARG, "entry " .. name .. ": 8 GiB or more needs pax")
end
table.insert(paxRecs, paxRecord("size", tostring(size)))
end
local mt = e.mtime or 0
if fmt == "pax" and (mt < 0 or mt % 1 ~= 0 or mt >= 8 ^ 11) then
table.insert(paxRecs, paxRecord("mtime", string.format("%.9f", mt):gsub("0+$", ""):gsub("%.$", "")))
end
if #paxRecs > 0 then
local body = buffer.fromstring(table.concat(paxRecs))
w:bytes(header("././@PaxHeader", "x", buffer.len(body), { mode = 0 } :: any, "", "", false))
w:bytes(body)
w:fill(0, (BLOCK - buffer.len(body) % BLOCK) % BLOCK)
end
if prefix == nil or (fmt ~= "gnu" and not ascii(name)) then
-- the header keeps an ASCII stand-in (each non-ASCII character as "?", as Python's tarfile)
local stand = if fmt == "gnu" then name else string.gsub(name, "[\192-\255][\128-\191]*", "?")
prefix, short = "", string.sub(stand, 1, 100)
end
w:bytes(header(short :: string, typ, if size >= 8 ^ 11 then 0 else size, e, prefix :: string, string.sub(link, 1, 100), fmt == "gnu"))
if size > 0 then
w:bytes(data)
w:fill(0, (BLOCK - size % BLOCK) % BLOCK)
end
end
w:fill(0, BLOCK * 2)
return w:finish(), nil
end
return Tar
+93
View File
@@ -0,0 +1,93 @@
-- archive/gzip tests: members from Python's gzip and the gzip CLI (FNAME, MTIME, levels, concatenated members) decode
-- to one entry with the right name / mtime / data; the writer round-trips (buffer, string, one-entry archive, several
-- entries as a .tar.gz) and keeps FNAME / MTIME; the api; errors; the fuzz pass. Fixtures: tools/fixtures/tar.py.
local T = require("@tests/T")
local F = require("@formats")
local Gzip = require("@formats/archive/gzip")
local Deflate = require("@formats/codecs/Deflate")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/tar")
local t = T.suite("gzip")
t:eq(Gzip.name, "gzip", "name")
for _, c in Fx.gzips do
local a, err = Gzip.decode(Bytes.reader(buffer.fromstring(c.data)))
t:check(a, c.name .. ": " .. tostring(err))
t:check(a.meta.stream, c.name .. ": single stream")
local l = a:list()
t:eq(#l, 1, c.name .. ": one entry")
t:eq(l[1].name, c.entry, c.name .. ": entry name")
t:eq(l[1].mtime, if c.mtime > 0 then c.mtime else nil, c.name .. ": mtime")
t:eq(l[1].size, c.size, c.name .. ": size")
t:eq(Crc32.of((a:read(l[1].name))), c.crc, c.name .. ": data")
t:eq(F.detect(c.data), "gzip", c.name .. ": F.detect")
end
-- the file name names the entry when there is no FNAME
do
local a = F.load(Fx.gzips[2].data, { name = "dir/notes.txt.gz" })
t:eq(a:list()[1].name, "notes.txt", "entry named after the file")
local b = F.load(Fx.gzips[2].data, { name = "x.tgz" })
t:eq(b:list()[1].name, "x.tar", ".tgz entry is a .tar")
end
-- writing
do
local text = string.rep("gzip round trip ", 500)
for _, level in { 0, 1, 6, 9 } do
local z = Gzip.encode(text, { level = level }) :: buffer
t:eq(buffer.tostring((Deflate.gunzip(z))), text, "string level " .. level)
end
local one = Gzip.new(text, "notes.txt")
one._byName["notes.txt"].mtime = 1600000000
local z = one:write()
local back = Gzip.decode(Bytes.reader(z :: buffer))
t:eq(back:list()[1].name, "notes.txt", "FNAME written")
t:eq(back:list()[1].mtime, 1600000000, "MTIME written")
t:eq(buffer.tostring((back:read("notes.txt"))), text, "one-entry archive round trip")
-- a decoded gzip saves back as gzip (its source format)
local g = F.load(Fx.gzips[1].data)
local again = F.load(F.save(g))
t:eq(again:list()[1].name, "story.txt", "F.save(gzip) keeps the name")
-- several entries: a .tar.gz, which the api unwraps
local multi = Gzip.new()
multi:add("a.txt", "A")
multi:add("b.txt", "BB")
local tgz = multi:write()
local tar = F.load(tgz)
t:eq(tar.format, "tar", "several entries write a .tar.gz")
t:eq(tar.meta.compression, "gzip", "unwrapped")
t:eq(buffer.tostring((tar:read("b.txt"))), "BB", ".tar.gz entry")
-- any archive converts: tar -> gzip -> tar
local tb = F.convert(Fx.tars[1].data, "gzip")
local t2 = F.load(tb)
t:eq(#t2:list(), #Fx.tars[1].entries, "tar -> tar.gz -> tar")
local _, e = Gzip.encode(text, { level = 12 })
t:check(e and e.code == Err.ARG, "bad level")
local _, e2 = Gzip.encode({ kind = "image" })
t:check(e2 and e2.code == Err.ARG, "not an archive")
end
-- errors
do
local d = Fx.gzips[1].data
local _, e1 = Gzip.decode(Bytes.reader(buffer.fromstring(string.sub(d, 1, 20))))
t:check(e1 and e1.code == Err.TRUNCATED, "truncated: " .. tostring(e1))
local b = buffer.fromstring(d)
buffer.writeu8(b, #d - 6, bit32.bxor(buffer.readu8(b, #d - 6), 1))
local _, e2 = Gzip.decode(Bytes.reader(b))
t:check(e2 and e2.code == Err.CHECKSUM, "crc: " .. tostring(e2))
end
local samples = {}
for _, c in Fx.gzips do
table.insert(samples, c.data)
end
t:fuzz("decode", function(b: buffer)
return Gzip.decode(Bytes.reader(b))
end, samples, { mutations = 20 })
t:done()
+156
View File
@@ -0,0 +1,156 @@
-- archive/tar tests: archives from Python's tarfile (ustar / GNU / pax) and GNU tar (ustar / gnu / posix / v7) list
-- the same entries as tarfile reads (names, types, sizes, links, mtimes, modes, data CRCs); the writer produces the same
-- bytes as tarfile for the same entries in all three formats and round-trips; Archive values (add / read / write,
-- conversion of a gzip / any archive to tar); .tar.gz / .tgz / .tar.bz2 / .tar.xz / .tar.zst / .tar.br load through the
-- api as the tar inside; errors; the fuzz pass. Fixtures: tools/fixtures/tar.py.
local T = require("@tests/T")
local F = require("@formats")
local TarF = require("@formats/archive/tar")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/tar")
local t = T.suite("tar")
t:eq(TarF.name, "tar", "name")
local function check(a: any, want: any, label: string)
local list = a:list()
t:eq(#list, #want, label .. ": entry count")
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 " .. w.name)
t:eq(e.type, w.type, label .. ": " .. w.name .. " type")
t:eq(e.size, w.size, label .. ": " .. w.name .. " size")
t:eq(e.mtime, w.mtime, label .. ": " .. w.name .. " mtime")
t:eq(e.mode, w.mode, label .. ": " .. w.name .. " mode")
t:eq(e.link, w.link, label .. ": " .. w.name .. " link")
t:eq(e.dir, w.type == "5", label .. ": " .. w.name .. " dir")
if w.crc then
local b, err = a:read(w.name)
t:check(b, label .. ": read " .. w.name .. ": " .. tostring(err))
t:eq(Crc32.of(b), w.crc, label .. ": " .. w.name .. " data")
end
end
end
-- 1. reading
for _, c in Fx.tars do
local a, err = TarF.decode(Bytes.reader(buffer.fromstring(c.data)))
t:check(a, c.name .. ": " .. tostring(err))
check(a, c.entries, c.name)
t:eq(F.detect(c.data), "tar", c.name .. ": F.detect")
t:note("%-18s %2d entries", c.name, #c.entries)
end
-- 2. writing: byte-identical to Python's tarfile (which pads to 10240-byte records)
for _, w in Fx.writes do
local list = {}
for _, e in w.entries do
table.insert(list, {
name = e.name,
data = if e.data then buffer.fromstring(e.data) else nil,
dir = e.dir,
type = e.type,
link = e.link,
mode = e.mode or (if e.dir then 0x1ED else 0x1A4),
mtime = 1700000000,
uname = "user",
gname = "group",
})
end
local a = TarF.new()
for _, e in list do
a:add(e.name, e.data or "", { dir = e.dir, mtime = e.mtime, mode = e.mode })
local ent = a._byName[e.name]
ent.type, ent.link, ent.uname, ent.gname = e.type, e.link, e.uname, e.gname
end
local out, err = a:write({ format = w.format })
t:check(out, w.format .. ": write: " .. tostring(err))
local s = buffer.tostring(out :: buffer)
local ref = w.data
t:check(#s <= #ref and string.sub(ref, 1, #s) == s and not string.find(string.sub(ref, #s + 1), "[^%z]"), w.format .. ": bytes identical to tarfile")
local back = TarF.decode(Bytes.reader(out :: buffer))
t:eq(#back:list(), #list, w.format .. ": round trip count")
for _, e in w.entries do
if e.data then
t:eq(buffer.tostring((back:read(e.name))), e.data, w.format .. ": round trip " .. e.name)
end
end
end
-- 3. Archive values: add / read / write, other archives to tar
do
local a = TarF.new()
a:add("a.txt", "alpha", { mtime = 5 })
a:add("b/", "", { dir = true })
a:add("b/c.bin", buffer.fromstring("\0\1\2"))
a:add("a.txt", "replaced")
t:eq(#a:list(), 3, "add replaces by name")
local buf = F.save(a)
t:check(buf, "F.save(tar archive) uses the source format")
local back = F.load(buf)
t:eq(buffer.tostring(back:read("a.txt")), "replaced", "read back")
t:check(back:list()[2].dir, "directory entry")
local _, e = back:read("missing")
t:check(e and e.code == Err.ARG, "missing entry")
-- a gzip (single-stream archive) converts to a tar holding its one entry
local g = F.load(Fx.gzips[1].data)
local tb = F.save(g, nil, { format = "tar" })
local ta = F.load(tb)
t:eq(ta:list()[1].name, "story.txt", "gzip -> tar entry name")
t:eq(ta:list()[1].size, Fx.gzips[1].size, "gzip -> tar entry size")
end
-- 4. compressed tars through the api
for _, w in Fx.wrapped do
local a, err = F.load(w.data, { name = w.name })
t:check(a, w.name .. ": " .. tostring(err))
t:eq(a.format, "tar", w.name .. ": unwrapped to the tar")
t:eq(a.meta.compression, w.outer, w.name .. ": meta.compression")
check(a, Fx.innerEntries, w.name)
local outer = F.load(w.data, { name = w.name, unwrap = false })
t:eq(outer.format, w.outer, w.name .. ": unwrap = false keeps the outer archive")
t:eq(outer:list()[1].name, "a.tar", w.name .. ": inner entry named after the file")
end
-- 5. errors
do
local good = Fx.tars[1].data
local b = buffer.fromstring(good)
buffer.writeu8(b, 10, buffer.readu8(b, 10) + 1)
local _, e1 = TarF.decode(Bytes.reader(b))
t:check(e1 and e1.code == Err.CORRUPT, "first header checksum: " .. tostring(e1))
local _, e2 = TarF.decode(Bytes.reader(buffer.fromstring(string.sub(good, 1, 700))))
t:check(e2 and e2.code == Err.TRUNCATED, "truncated data: " .. tostring(e2))
local _, e3 = TarF.encode({ kind = "image" })
t:check(e3 and e3.code == Err.ARG, "encode a non-archive")
local u = TarF.new()
u:add(string.rep("y", 120), "x")
local _, e4 = u:write({ format = "ustar" })
t:check(e4 and e4.code == Err.ARG, "ustar cannot hold a 120-byte name without a slash")
t:eq(TarF.sniff(Bytes.reader(buffer.fromstring(string.rep("\0", 1024)))), 0, "zeros are not a tar")
end
local samples = {}
for _, c in Fx.tars do
if #c.data <= 30000 then
table.insert(samples, c.data)
end
end
t:fuzz("decode", function(b: buffer)
local a = TarF.decode(Bytes.reader(b))
if a then
for _, e in a:list() do
a:read(e.name)
end
a:write()
end
return a
end, samples, { mutations = 30, keepHeader = 0 })
t:done()
+165
View File
@@ -0,0 +1,165 @@
-- containers/Tar and containers/Archive tests: hand-made headers for the edge cases the reference archives do not hit
-- (base-256 numbers, the historical signed checksum, GNU 'K' long links, pax 'g' global records, pax size overrides,
-- v7 headers without magic, a missing end-of-archive marker), the writer's GNU / pax extensions (long links, fractional
-- and negative mtimes), and Archive helpers (streamName, entries of foreign archive values, failing loaders).
local T = require("@tests/T")
local Tar = require("@formats/containers/Tar")
local Archive = require("@formats/containers/Archive")
local Err = require("@formats/core/Err")
local t = T.suite("containers/tar")
-- a header block built by hand
local function hdr(fields: { [string]: any }): buffer
local h = buffer.create(512)
buffer.writestring(h, 0, fields.name or "f")
buffer.writestring(h, 100, fields.mode or "0000644\0")
buffer.writestring(h, 124, fields.size or "00000000000\0")
buffer.writestring(h, 136, fields.mtime or "00000000000\0")
buffer.writestring(h, 156, fields.type or "0")
if fields.link then
buffer.writestring(h, 157, fields.link)
end
if fields.magic ~= false then
buffer.writestring(h, 257, "ustar\00000")
end
if fields.raw then
for at, v in fields.raw do
buffer.writeu8(h, at, v)
end
end
buffer.writestring(h, 148, " ")
local sum, signed = 0, 0
for i = 0, 511 do
local v = buffer.readu8(h, i)
sum += v
signed += if v >= 128 then v - 256 else v
end
buffer.writestring(h, 148, string.format("%06o\0 ", if fields.signed then signed % 0x40000 else sum))
return h
end
local function cat(parts: { any }): buffer
local s = {}
for _, p in parts do
table.insert(s, if type(p) == "string" then p else buffer.tostring(p))
end
return buffer.fromstring(table.concat(s))
end
local function block(s: string): string
return s .. string.rep("\0", (512 - #s % 512) % 512)
end
local END = string.rep("\0", 1024)
-- base-256 size (GNU), checksum with the signed sum, no end marker
do
local raw = { [124] = 0x80 }
for i = 125, 134 do
raw[i] = 0
end
raw[135] = 5
local b = cat({ hdr({ name = "big\200", raw = raw, signed = true }), block("hello") })
local list, err = Tar.read(b)
t:check(list, "base-256 / signed checksum: " .. tostring(err))
t:eq(list[1].size, 5, "base-256 size")
t:check(Tar.valid(b, 0), "valid() accepts the signed sum")
end
-- GNU long link ('K'), pax global + per-file records, v7 header
do
local rec = "21 path=from/pax.txt\n"
local glob = "20 uname=globaluser\n"
local b = cat({
hdr({ name = "././@LongLink", type = "K", size = string.format("%011o\0", 131) }),
block(string.rep("L", 130) .. "\0"),
hdr({ name = "sym", type = "2", link = "short" }),
hdr({ name = "pax_global", type = "g", size = string.format("%011o\0", #glob) }),
block(glob),
hdr({ name = "PaxHeaders/x", type = "x", size = string.format("%011o\0", #rec + 15) }),
block(rec .. "15 size=000003\n"),
hdr({ name = "ignored-name", size = "00000000077\0" }),
block("abc"),
hdr({ name = "v7file", magic = false, size = "00000000002\0", mtime = "12345670123\0" }),
block("v7"),
END,
})
local list, err = Tar.read(b)
t:check(list, "extensions: " .. tostring(err))
t:eq(#list, 3, "meta records are not entries")
t:eq(list[1].link, string.rep("L", 130), "GNU long link")
t:eq(list[2].name, "from/pax.txt", "pax path")
t:eq(list[2].size, 3, "pax size overrides the header")
t:eq(list[2].uname, "globaluser", "pax global record")
t:eq(list[3].name, "v7file", "v7 header")
t:eq(list[3].mtime, tonumber("12345670123", 8), "octal mtime")
t:eq(list[3].uname, "globaluser", "global records apply to later entries")
end
-- errors
do
local _, e1 = Tar.read(cat({ hdr({ size = "00000002000\0" }), block("x") }))
t:check(e1 and e1.code == Err.TRUNCATED, "data past the end: " .. tostring(e1))
local _, e2 = Tar.read(cat({ hdr({ type = "x", size = "00000000010\0" }), block("garbage!"), END }))
t:check(e2 and e2.code == Err.CORRUPT, "bad pax record: " .. tostring(e2))
local good = hdr({})
local bad = cat({ good, hdr({ name = "two" }) })
buffer.writeu8(bad, 513, 77)
local _, e3 = Tar.read(bad)
t:check(e3 and e3.code == Err.CHECKSUM, "second header checksum: " .. tostring(e3))
local list = Tar.read(buffer.create(0))
t:check(list and #list == 0, "empty input is an empty archive")
end
-- writer extensions
do
local long = string.rep("n", 120)
for _, fmt in { "gnu", "pax" } do
local out = Tar.write({
{ name = long, data = buffer.fromstring("x"), mtime = -5.25 },
{ name = "l", type = "2", link = string.rep("k", 150) },
}, { format = fmt :: any }) :: buffer
local list = Tar.read(out) :: any
t:eq(list[1].name, long, fmt .. ": long name")
t:eq(list[2].link, string.rep("k", 150), fmt .. ": long link")
if fmt == "pax" then
t:eq(list[1].mtime, -5.25, "pax fractional negative mtime")
end
end
local _, e = Tar.write({ { name = "" } })
t:check(e and e.code == Err.ARG, "empty name")
end
-- Archive helpers
do
t:eq(Archive.streamName({ name = "/x/y/notes.txt.gz" }, { "gz" }), "notes.txt", "streamName strips the extension")
t:eq(Archive.streamName({ name = "a.tbz2" }, { "bz2" }), "a.tar", "streamName .tbz2")
t:eq(Archive.streamName(nil, { "gz" }), "data", "streamName default")
t:eq(Archive.streamName({ name = "plain" }, { "gz" }), "plain", "streamName without an extension")
local foreign = {
kind = "archive",
list = function()
return { { name = "a", size = 1, dir = false } }
end,
read = function()
error("boom")
end,
}
local items = Archive.entries(foreign) :: any
t:eq(#items, 1, "entries of a foreign archive")
local b, e = items[1].read()
t:check(b == nil and e and e.code == Err.CORRUPT, "a throwing read() becomes an Err")
t:check(Archive.entries({ kind = "image" }) == nil, "not an archive")
local a = Archive.new("x")
Archive.put(a, { name = "f", size = 1, dir = false, load = function()
error("bad")
end })
local _, e2 = a:read("f")
t:check(e2 and e2.code == Err.CORRUPT, "a throwing loader becomes an Err")
local _, e3 = a:write()
t:check(e3 and e3.code == Err.UNSUPPORTED, "read-only archives")
end
t:fuzz("read", function(b: buffer)
return Tar.read(b)
end, { buffer.tostring(Tar.write({ { name = string.rep("p", 130), data = buffer.fromstring("abc") }, { name = "d", dir = true } }) :: buffer) }, { mutations = 60 })
t:done()
+125
View File
@@ -0,0 +1,125 @@
# tar + gzip fixtures (tools/fixtures.py): reference archives from Python's tarfile (ustar / GNU / pax formats, long
# names, non-ASCII names, links, directories, pax mtimes) and from the host / nix GNU tar (--format=ustar / gnu /
# posix / v7), gzip members from Python's gzip and the gzip CLI (FNAME, MTIME, levels, concatenated members), and
# compressed tars (.tar.gz, .tgz, .tar.zst, .tar.xz, .tar.bz2, .tar.br) for the api's unwrap.
# tests/gen/tar.luau { files = { { name, data, ... } }, writes = { { format, entries, data } }, tars = { { name,
# data, entries = { { name, size, type, link?, mtime, mode, crc } } } }, gzips = { ... },
# wrapped = { { name, data, inner = "tar" } } }
import bz2, gzip, io, json, lzma, os, shutil, subprocess, tarfile, tempfile, zlib
def tool(name, pkg, argv, input=None, cwd=None):
exe = shutil.which(name)
cmd = ([exe] if exe else ["nix", "shell", "nixpkgs#" + pkg, "-c", name]) + argv
return subprocess.run(cmd, input=input, capture_output=True, check=True, cwd=cwd).stdout
def entries_of(data):
out = []
with tarfile.open(fileobj=io.BytesIO(data)) 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, "mtime": m.mtime, "mode": m.mode}
if m.issym() or m.islnk():
e["link"] = m.linkname
if m.isfile():
e["crc"] = zlib.crc32(t.extractfile(m).read())
out.append(e)
return out
def generate(ctx):
rng = ctx.rng(5)
files = [
("hello.txt", b"hello, tar\n"),
("empty", b""),
("dir/sub/data.bin", rng.randbytes(3000)),
("exact512", bytes(range(256)) * 2),
("d" * 60 + "/" + "e" * 60 + "/long-name-over-100-bytes.txt", b"long " * 50),
("x" * 150, b"no slash to split at"),
("unicodé/naïve-ファイル.txt", "ünïcödé".encode()),
]
# the writer test: the same entries through Python's tarfile in three formats (fixed metadata)
writes = []
for fmt, pf in (("ustar", tarfile.USTAR_FORMAT), ("gnu", tarfile.GNU_FORMAT), ("pax", tarfile.PAX_FORMAT)):
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w", format=pf) as t:
ents = []
for name, data in files:
if fmt == "ustar" and (not name.isascii() or name.startswith("x" * 101)):
continue
ti = tarfile.TarInfo(name)
ti.size, ti.mtime, ti.mode, ti.uname, ti.gname = len(data), 1700000000, 0o644, "user", "group"
t.addfile(ti, io.BytesIO(data))
ents.append({"name": name, "data": data})
ti = tarfile.TarInfo("adir")
ti.type, ti.mtime, ti.mode, ti.uname, ti.gname = tarfile.DIRTYPE, 1700000000, 0o755, "user", "group"
t.addfile(ti)
ents.append({"name": "adir", "dir": True})
ti = tarfile.TarInfo("link-to-hello")
ti.type, ti.linkname, ti.mtime, ti.mode, ti.uname, ti.gname = tarfile.SYMTYPE, "hello.txt", 1700000000, 0o777, "user", "group"
t.addfile(ti)
ents.append({"name": "link-to-hello", "type": "2", "link": "hello.txt", "mode": 0o777})
writes.append({"format": fmt, "entries": ents, "data": buf.getvalue()})
tars = []
for w in writes:
tars.append({"name": "python-" + w["format"], "data": w["data"], "entries": entries_of(w["data"])})
# pax with a fractional mtime and a huge uid
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w", format=tarfile.PAX_FORMAT) as t:
ti = tarfile.TarInfo("frac.txt")
ti.size, ti.mtime, ti.uid = 3, 1600000000.5, 3000000
t.addfile(ti, io.BytesIO(b"abc"))
tars.append({"name": "python-pax-extras", "data": buf.getvalue(), "entries": entries_of(buf.getvalue())})
# GNU tar on a real tree
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.makedirs(os.path.join(root, "emptydir"))
os.symlink("hello.txt", os.path.join(root, "sym"))
os.link(os.path.join(root, "hello.txt"), os.path.join(root, "hard"))
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)
for fmt in ("ustar", "gnu", "posix", "v7"):
argv = ["--format=" + fmt, "--sort=name", "--owner=0", "--group=0", "--numeric-owner", "-cf", "-", "."]
if fmt in ("ustar", "v7"):
argv = ["--exclude=./" + "x" * 150, "--exclude=./d" + "d" * 59] + argv
if fmt == "v7":
argv = ["--exclude=./unicodé"] + argv
data = tool("tar", "gnutar", argv, cwd=root)
tars.append({"name": "gnutar-" + fmt, "data": data, "entries": entries_of(data)})
finally:
shutil.rmtree(tmp)
# gzip
text = ("The quick brown fox jumps over the lazy dog. " * 300).encode()
gzips = []
b = io.BytesIO()
with gzip.GzipFile(filename="story.txt", mode="wb", fileobj=b, mtime=1234567890, compresslevel=9) as g:
g.write(text)
gzips.append({"name": "python-fname", "data": b.getvalue(), "entry": "story.txt", "mtime": 1234567890, "crc": zlib.crc32(text), "size": len(text)})
gzips.append({"name": "python-noname", "data": gzip.compress(text, 1, mtime=0), "entry": "data", "mtime": 0, "crc": zlib.crc32(text), "size": len(text)})
cli = tool("gzip", "gzip", ["-9", "-n", "-c"], input=text)
gzips.append({"name": "cli-n", "data": cli, "entry": "data", "mtime": 0, "crc": zlib.crc32(text), "size": len(text)})
two = gzip.compress(text[:1000], mtime=0) + gzip.compress(text[1000:], mtime=0)
gzips.append({"name": "members", "data": two, "entry": "data", "mtime": 0, "crc": zlib.crc32(text), "size": len(text)})
# compressed tars
inner = writes[2]["data"]
wrapped = [
{"name": "a.tar.gz", "data": gzip.compress(inner, mtime=0), "outer": "gzip"},
{"name": "a.tgz", "data": tool("gzip", "gzip", ["-c", "-n"], input=inner), "outer": "gzip"},
{"name": "a.tar.bz2", "data": bz2.compress(inner), "outer": "bz2"},
{"name": "a.tar.xz", "data": lzma.compress(inner), "outer": "xz"},
{"name": "a.tar.zst", "data": tool("zstd", "zstd", ["-c", "-q"], input=inner), "outer": "zst"},
{"name": "a.tar.br", "data": ctx.python(["brotli"], "import brotli, sys; sys.stdout.buffer.write(brotli.compress(sys.stdin.buffer.read()))", input=inner), "outer": "br"},
]
ctx.emit("tar", {"files": [{"name": n, "data": d} for n, d in files], "writes": writes, "tars": tars,
"gzips": gzips, "wrapped": wrapped, "innerEntries": entries_of(inner)})