From d477d9a06904c11cd8622da0a161ea6c2e080713 Mon Sep 17 00:00:00 2001 From: XeonSquared Date: Mon, 31 Jul 2017 12:10:07 +1000 Subject: [PATCH] added a ported, minimal version of the fs API from MultICE --- modules/lib/fs.lua | 73 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 modules/lib/fs.lua diff --git a/modules/lib/fs.lua b/modules/lib/fs.lua new file mode 100644 index 0000000..89c62f6 --- /dev/null +++ b/modules/lib/fs.lua @@ -0,0 +1,73 @@ +do + _G.fs = {} + local fT,hT = {},{["_c"]=0} + function fs.mount(mp,pr) + fT[mp] = pr + end + function fs.simplify(p) + local pt,npt,rp = {},{},"" + for P in p:gmatch("[^/]+") do + pt[#pt+1] = P + end + for k,v in pairs(pt) do + if v == ".." then + npt[#npt] = nil + elseif v ~= "." then + npt[#npt+1] = v + end + end + for k,v in pairs(npt) do + rp=rp.."/"..v + end + if p:sub(1,1) ~= "/" then rp = rp:sub(2) end + return rp + end + function fs.resolve(p) + if p:sub(1,1) ~= "/" then -- absolute/relative path + p=(os.getenv("PWD") or "").."/"..p + end + p=fs.simplify(p) + local pt = {} + for P in p:gmatch("[^/]+") do + pt[#pt+1] = P + end + return pt, p:match("/?(.-)/"), p:match("/?.-/(.+)") + end + function fs.open(p,m) + local _,d,p = fs.resolve(p) + local d = fT[d] + local f,C=d.open(p,m),hT._c + if f then + hT._c = C + 1 + hT[C] = {d,f} + return C + end + return false + end + function fs.close(h) + if hT[h] then + hT[h][1].close(hT[h][2]) + end + return false + end + function fs.read(h,n) + if hT[h] then + return hT[h][1].read(hT[h][2],n) + end + return false + end + function fs.readall(f) + local s="" + repeat + c=fs.read(f,2048) + s=s..c + until c=="" + return s + end + function fs.write(h,d) + if hT[h] then + return hT[h][1].write(hT[h][2],d) + end + return false + end +end