Skip to content

Instantly share code, notes, and snippets.

@MCJack123
Created December 9, 2022 07:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MCJack123/0680bc261cf4511b4ad10f731c37e852 to your computer and use it in GitHub Desktop.
Save MCJack123/0680bc261cf4511b4ad10f731c37e852 to your computer and use it in GitHub Desktop.
Pure Lua implementation of CraftOS `fs.find`
-- 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