Files
rosetta/src/Formats/containers/Archive.luau
T

228 lines
7.7 KiB
Luau

--!strict
-- containers/Archive: the in-memory Archive value (Types.Archive) that archive formats return. Entries hold their data
-- or a lazy loader (decompressed on read); add() appends or replaces an entry; write() calls the format's encoder
-- (attached by the format), so an archive read from a .tar writes back as a .tar, and any Archive (a zip, a 7z) can be
-- encoded by any writable archive format through its list() / read().
--
-- local a = Archive.new("tar", Tar.encode) -- encode(archive, opts) -> buffer | nil, Err
-- Archive.put(a, { name = "a.txt", size = 3, data = buf, mtime = 0 })
-- Archive.put(a, { name = "b.bin", size = n, load = function() return inflate(...) end })
-- a:list() a:read("a.txt") a:add("c.txt", "text") a:write()
--
-- Single-stream archives (gzip, zst, xz, bz2, br) set meta.stream = true and hold one entry; the api unwraps them
-- (a .tar.gz loads as the tar inside). Never throws: read of a missing entry or a failed loader returns nil, Err.
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Archive = {}
-- an entry: the Types.ArchiveEntry fields plus format extras (mode, uid, gid, link, type, ...) and its data source
export type Entry = {
name: string,
size: number,
compressedSize: number?,
method: string?,
mtime: number?,
dir: boolean,
data: buffer?,
load: (() -> (buffer?, Err.Err?))?,
[string]: any,
}
export type Encoder = (archive: any, opts: any?) -> (buffer?, Err.Err?)
local Methods = {}
Methods.__index = Methods
-- the public fields of an entry (no data / loader)
local function public(e: Entry): Types.ArchiveEntry
local out: any = {}
for k, v in e :: any do
if k ~= "data" and k ~= "load" then
out[k] = v
end
end
return out
end
function Methods.list(self: any): { Types.ArchiveEntry }
local out = table.create(#self._entries) :: { Types.ArchiveEntry }
for i, e in self._entries do
out[i] = public(e)
end
return out
end
-- read(name) -> buffer | nil, Err (directories read as an empty buffer)
function Methods.read(self: any, name: string): (buffer?, Err.Err?)
local e: Entry? = self._byName[name]
if not e then
return nil, Err.new(Err.ARG, "no entry named " .. tostring(name))
end
if e.data then
return e.data, nil
end
if e.load then
local ok, b, err = pcall(e.load)
if not ok then
return nil, Err.new(Err.CORRUPT, "entry " .. name .. ": " .. tostring(b))
end
if not b then
return nil, err or Err.new(Err.CORRUPT, "entry " .. name .. ": decode failed")
end
return b, nil
end
return buffer.create(0), nil
end
-- add(name, data, opts?) -> (): opts.mtime (unix seconds), opts.dir, opts.mode; replaces an entry of the same name
function Methods.add(self: any, name: string, data: buffer | string, opts: any?)
local b: buffer = if type(data) == "string" then buffer.fromstring(data) elseif type(data) == "buffer" then data else buffer.create(0)
local o = opts or {}
local e: Entry = {
name = name,
size = buffer.len(b),
dir = o.dir == true,
mtime = o.mtime,
mode = o.mode,
data = b,
}
Archive.put(self, e)
end
-- write(opts?) -> buffer | nil, Err: the archive's own format (opts.format is handled by the api)
function Methods.write(self: any, opts: any?): (buffer?, Err.Err?)
local enc: Encoder? = self._encode
if not enc then
return nil, Err.new(Err.UNSUPPORTED, self.format .. " archives are read-only")
end
return enc(self, opts)
end
-- new(format, encode?) -> an empty Archive
function Archive.new(format: string, encode: Encoder?): any
return setmetatable({
kind = "archive",
format = format,
meta = {},
_entries = {} :: { Entry },
_byName = {} :: { [string]: Entry },
_encode = encode,
}, Methods)
end
-- put(archive, entry): append (or replace by name) an entry
function Archive.put(a: any, e: Entry)
local old = a._byName[e.name]
if old then
local i = table.find(a._entries, old)
if i then
a._entries[i] = e
end
else
table.insert(a._entries, e)
end
a._byName[e.name] = e
end
-- entries(value) -> { { entry, read: () -> (buffer?, Err?) } } for any Archive-shaped value (ours or another
-- format's): what encoders iterate. nil when the value is not an archive.
function Archive.entries(value: any): { { entry: Types.ArchiveEntry, read: () -> (buffer?, Err.Err?) } }?
if type(value) ~= "table" or value.kind ~= "archive" or type(value.list) ~= "function" or type(value.read) ~= "function" then
return nil
end
local ok, list = pcall(value.list, value)
if not ok or type(list) ~= "table" then
return nil
end
local out = {}
for _, e in list do
if type(e) == "table" and type(e.name) == "string" then
table.insert(out, {
entry = e,
read = function(): (buffer?, Err.Err?)
local rok, b, err = pcall(value.read, value, e.name)
if not rok then
return nil, Err.new(Err.CORRUPT, tostring(b))
end
return b, err
end,
})
end
end
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
-- fromDos(stamp) -> unix seconds | nil: an MS-DOS date and time (stamp = date * 65536 + time, as LHA / ARJ / ZIP store
-- them little endian; local time without a zone, read as UTC); nil for a zero or invalid date
function Archive.fromDos(stamp: number): number?
local time, date = stamp % 65536, stamp // 65536
local y, m, d = 1980 + bit32.rshift(date, 9), bit32.band(bit32.rshift(date, 5), 15), bit32.band(date, 31)
if date == 0 or m < 1 or m > 12 or d < 1 then
return nil
end
local secs = bit32.rshift(time, 11) * 3600 + bit32.band(bit32.rshift(time, 5), 63) * 60 + bit32.band(time, 31) * 2
return Types.Date.daysFromCivil(y, m, d) * 86400 + secs
end
-- toDos(unix?) -> date * 65536 + time (clamped to 1980-01-01 .. 2107-12-31)
function Archive.toDos(t: number?): number
if type(t) ~= "number" or t ~= t or t < 315532800 then
return 0x210000 -- 1980-01-01 00:00
end
local s = math.floor(t)
local days = s // 86400
local rem = s - days * 86400
local y, m, d = Types.Date.civilFromDays(days)
if y > 2107 then
y, m, d, rem = 2107, 12, 31, 86398
end
return ((y - 1980) * 512 + m * 32 + d) * 65536 + (rem // 3600) * 2048 + ((rem // 60) % 60) * 32 + (rem % 60) // 2
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
local name = if type(opts) == "table" and type(opts.name) == "string" then opts.name else nil
if not name then
return "data"
end
local base = string.match(name, "([^/\\]+)$") or name
local stem, ext = string.match(base, "^(.+)%.([%w]+)$")
if stem and ext then
local e = string.lower(ext)
if e == "tgz" or e == "tbz2" or e == "tbz" or e == "txz" or e == "tzst" then
return stem .. ".tar"
end
if table.find(exts, e) then
return stem
end
end
return base
end
return Archive