Created
December 9, 2022 07:37
-
-
Save MCJack123/0680bc261cf4511b4ad10f731c37e852 to your computer and use it in GitHub Desktop.
Pure Lua implementation of CraftOS `fs.find`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Licensed as CC0 | |
local expect = dofile "/rom/modules/main/cc/expect.lua" | |
local function splitPath(p) | |
local retval = {} | |
for m in p:gmatch("[^/]+") do table.insert(retval, m) end | |
return retval | |
end | |
local function aux_find(parts, p) | |
local ok, t = pcall(fs.list, p or "") | |
if #parts == 0 then return fs.getName(p) elseif not ok then return nil end | |
local parts2 = {} | |
for i, v in ipairs(parts) do parts2[i] = v end | |
local name = table.remove(parts2, 1) | |
local retval = {} | |
for _, k in pairs(t) do if k:match("^" .. name:gsub("([%%%.])", "%%%1"):gsub("%*", "%.%*") .. "$") then retval[k] = aux_find(parts2, fs.combine(p or "", k)) end end | |
return retval | |
end | |
local function combineKeys(t, prefix) | |
prefix = prefix or "" | |
if t == nil then return {} end | |
local retval = {} | |
for k,v in pairs(t) do | |
if type(v) == "string" then table.insert(retval, prefix .. k) | |
else for _,w in ipairs(combineKeys(v, prefix .. k .. "/")) do table.insert(retval, w) end end | |
end | |
return retval | |
end | |
local function find(wildcard) | |
expect(1, wildcard, "string") | |
local retval = {} | |
for _,v in ipairs(combineKeys(aux_find(splitPath(wildcard)))) do table.insert(retval, v) end | |
table.sort(retval) | |
return retval | |
end | |
return find |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment