46 lines
2.2 KiB
Luau
46 lines
2.2 KiB
Luau
-- examples/archive.luau: builds a zip, lists and reads it, edits it, converts it to a .tar.gz and back, and gzips a
|
|
-- single file. Run from the repository root: luau examples/archive.luau (docs/guide/archive.md explains the API).
|
|
local F = require("@formats")
|
|
|
|
-- a new zip: a directory, a text file, an incompressible file stored as is
|
|
local zip = F.format("zip").create()
|
|
zip:add("game/", nil)
|
|
zip:add("game/readme.txt", string.rep("formats-luau reads and writes archives. ", 20), { level = 9 })
|
|
local noise = buffer.create(2048)
|
|
local seed = 7
|
|
for i = 0, 2047 do
|
|
seed = (seed * 1103515245 + 12345) % 2147483648
|
|
buffer.writeu8(noise, i, seed // 65536 % 256)
|
|
end
|
|
zip:add("game/noise.bin", noise, { method = "store" })
|
|
local zipBytes = assert(F.save(zip, nil, { format = "zip", comment = "example" }))
|
|
print(string.format("zip: %d bytes", buffer.len(zipBytes)))
|
|
|
|
-- list and read
|
|
local loaded = assert(F.archive.load(zipBytes))
|
|
for _, e in loaded:list() do
|
|
print(string.format(" %-18s %6d -> %6s %s", e.name, e.size, tostring(e.compressedSize), e.method or (if e.dir then "dir" else "")))
|
|
end
|
|
local readme = assert(loaded:read("game/readme.txt"))
|
|
assert(buffer.len(readme) == 800)
|
|
|
|
-- edit: replace one entry, drop another, save (unchanged entries are copied without recompressing)
|
|
loaded:add("game/readme.txt", "short now")
|
|
assert(loaded:remove("game/noise.bin"))
|
|
local edited = assert(F.save(loaded))
|
|
assert(#F.archive.load(edited):list() == 2)
|
|
|
|
-- convert to .tar.gz: it loads back as the tar inside, with meta.compression = "gzip"
|
|
local tgz = assert(F.convert(edited, "tgz"))
|
|
local tar = assert(F.archive.load(tgz))
|
|
assert(tar.format == "tar" and tar.meta.compression == "gzip")
|
|
print(string.format("tar.gz: %d bytes, %d entries, read back as %s inside %s", buffer.len(tgz), #tar:list(), tar.format, tar.meta.compression))
|
|
assert(buffer.tostring(assert(tar:read("game/readme.txt"))) == "short now")
|
|
|
|
-- one file through gzip
|
|
local gz = assert(F.save(readme, nil, { format = "gzip", name = "readme.txt" }))
|
|
local single = assert(F.archive.load(gz))
|
|
assert(single.meta.stream and single:list()[1].name == "readme.txt")
|
|
print(string.format("gzip: %d -> %d bytes", buffer.len(readme), buffer.len(gz)))
|
|
print("archive example: ok")
|