defripper-cd2025/fileops.lua
2022-11-23 12:27:16 -05:00

58 lines
1.6 KiB
Lua

-- LUALOCALS < ---------------------------------------------------------
local error, io, ipairs, minetest, pairs, string, type
= error, io, ipairs, minetest, pairs, string, type
local io_open, string_format, string_gsub
= io.open, string.format, string.gsub
-- LUALOCALS > ---------------------------------------------------------
local include = ...
local mediacache = include("mediacache")
local function getdir(s)
if not minetest.mkdir(s) then return error(string_format("failed to mkdir %q", s)) end
return s
end
local function cpfile(src, dst)
local done = io_open(dst, "rb")
if done then
done:close()
return true
end
local sf = io_open(src, "rb")
if not sf then return error(string_format("failed to read %q", src)) end
local df = io_open(dst, "wb")
if not sf then return error(string_format("failed to write %q", dst)) end
while true do
local chunk = sf:read(65536)
if not chunk then
sf:close()
df:close()
return true
end
df:write(chunk)
end
end
local function ripmedia(reffed, thing, dest, rel, test)
test = test or function(a, b) return a == b end
if type(thing) == "string" then
for _, s in ipairs(string_gsub(thing, "[\\[:,=&{]", "^"):split("^")) do
for k, v in pairs(mediacache) do
if test(s, k) then
local fulldest = getdir(dest .. "/" .. rel) .. "/" .. k
cpfile(v, fulldest)
reffed[fulldest] = true
end
end
end
elseif type(thing) == "table" then
if thing.name then return ripmedia(reffed, thing.name, dest, rel, test) end
for _, v in pairs(thing) do
ripmedia(reffed, v, dest, rel, test)
end
end
end
return getdir, ripmedia