path.lua

changeset 3
b2df1b3f2c83
parent 2
3975fa5ed630
child 7
038275cd92ed
--- a/path.lua	Sat Sep 12 21:27:57 2009 +0300
+++ b/path.lua	Sun Sep 13 22:22:47 2009 +0300
@@ -9,14 +9,18 @@
 local sep=config.dirsep
 
 function join(p, f)
-    return p..sep..f
+    if p=="" then
+        return f
+    else
+        return p..sep..f
+    end
 end
 
 function dirbasename(p)
     local d, b = string.match(p,
-        "(.*)"..sep.."+([^"..sep.."]+)"..sep.."*$")
+        "^(.*)"..sep.."+([^"..sep.."]+)"..sep.."*$")
     if not b then
-        return string.match(p, "([^"..sep.."]*")
+        return "", p
     else
         return d, b
     end
@@ -26,10 +30,23 @@
     return tuple.fst(dirbasename(p))
 end
 
+function dirname_slash(p)
+    local dn=dirname(p)
+    if dn=="" then
+        return dn
+    else
+        return dn..sep
+    end
+end
+
 function basename(p)
     return tuple.snd(dirbasename(p))
 end
 
+function rmext(p)
+    return string.gsub(p, "%.[^.]*$", "")
+end
+
 -- would rather do this as an iterator, but can't
 -- coroutine.yield from gsub handler
 function split(p)
@@ -40,11 +57,12 @@
         table.insert(t, "/.") -- root
         p=p2
     end
-    string.gsub(p, "([^"..sep.."]+)"..sep.."+", 
+    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)
@@ -55,8 +73,8 @@
     return g, s
 end
 
-function makepath(p)
-    local head=""
+function makepath(p, head)
+    head=head or ""
     for d in parts(p) do
         head=head..d
         local a=lfs.attributes(head)
@@ -71,13 +89,22 @@
         head=head..sep
     end
 end
+]]
 
---[[
-print(dirbasename("/foo/bar/baz"))
-
-for k in parts("//foo/bar/baz/quk") do
-    print(k)
+function simplify(p)
+    local capts={}
+    local start=string.match(p, "^(/)")
+    string.gsub(p, "([^/]+)",
+    function(e)
+        if e==".." and #capts > 1 then
+            capts[#capts]=nil
+        elseif e~="." then
+            table.insert(capts, e)
+        end  
+    end)
+    return (start or "")..table.concat(capts, "/")
 end
 
-makepath("foo/bar/baz/quk")
---]]
+function to_root(p)
+    return string.rep("../",#(split(p))-1)
+end

mercurial