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 945abe6d94
commit a9110bdab2
9 files changed
+1298

No files matched your search

+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