path.lua

changeset 2
3975fa5ed630
child 3
b2df1b3f2c83
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/path.lua	Sat Sep 12 21:27:57 2009 +0300
@@ -0,0 +1,83 @@
+
+module("path", package.seeall)
+
+require("tuple")
+require("lfs")
+require("err")
+require("config")
+
+local sep=config.dirsep
+
+function join(p, f)
+    return p..sep..f
+end
+
+function dirbasename(p)
+    local d, b = string.match(p,
+        "(.*)"..sep.."+([^"..sep.."]+)"..sep.."*$")
+    if not b then
+        return string.match(p, "([^"..sep.."]*")
+    else
+        return d, b
+    end
+end
+
+function dirname(p)
+    return tuple.fst(dirbasename(p))
+end
+
+function basename(p)
+    return tuple.snd(dirbasename(p))
+end
+
+-- would rather do this as an iterator, but can't
+-- coroutine.yield from gsub handler
+function split(p)
+    local t={}
+    local head=""
+    local s, p2 = string.match(p, "^("..sep.."+)(.*)$")
+    if s then
+        table.insert(t, "/.") -- root
+        p=p2
+    end
+    string.gsub(p, "([^"..sep.."]+)"..sep.."+", 
+            function(d) table.insert(t, d); end)
+    return t
+end
+
+function parts(p)
+    local s={i=1, t=split(p)}
+    local function g(s)
+        local v=s.t[s.i]
+        s.i=s.i+1
+        return v
+    end
+    return g, s
+end
+
+function makepath(p)
+    local head=""
+    for d in parts(p) do
+        head=head..d
+        local a=lfs.attributes(head)
+        if not a then
+            local success, e = lfs.mkdir(head)
+            if not success then
+                err.file(head, e)
+            end
+        elseif a.mode~="directory" then
+            err.file(head, "not a directory")
+        end
+        head=head..sep
+    end
+end
+
+--[[
+print(dirbasename("/foo/bar/baz"))
+
+for k in parts("//foo/bar/baz/quk") do
+    print(k)
+end
+
+makepath("foo/bar/baz/quk")
+--]]

mercurial