diff options
author | Kaarle Ritvanen <kaarle.ritvanen@datakunkku.fi> | 2012-12-16 19:10:38 +0200 |
---|---|---|
committer | Kaarle Ritvanen <kaarle.ritvanen@datakunkku.fi> | 2012-12-16 19:10:38 +0200 |
commit | e4361842fcdec369fbd4466f2528b2815f504ff9 (patch) | |
tree | 4694ca56f9e9a4869763d8fe1f31a81f6f62ac0b /acf/path.lua | |
download | acf2-e4361842fcdec369fbd4466f2528b2815f504ff9.tar.bz2 acf2-e4361842fcdec369fbd4466f2528b2815f504ff9.tar.xz |
initial version
Diffstat (limited to 'acf/path.lua')
-rw-r--r-- | acf/path.lua | 61 |
1 files changed, 61 insertions, 0 deletions
diff --git a/acf/path.lua b/acf/path.lua new file mode 100644 index 0000000..9b709e9 --- /dev/null +++ b/acf/path.lua @@ -0,0 +1,61 @@ +--[[ +Copyright (c) 2012 Kaarle Ritvanen +See LICENSE file for license details +--]] + +module(..., package.seeall) + +require 'stringy' + +local function filter(func, tbl) + local res = {} + for k, v in pairs(tbl) do if func(v) then res[k] = v end end + return res +end + + +function is_absolute(path) + return string.sub(path, 1, 1) == '/' +end + +function to_absolute(path, base) + if not is_absolute(path) then + path = base..(base ~= '/' and '/' or '')..path + end + local comps = split(path) + local i = 1 + while i <= #comps do + if comps[i] == '..' then + if i == 1 then error('Invalid path: '..path) end + table.remove(comps, i - 1) + table.remove(comps, i - 1) + i = i - 1 + else i = i + 1 end + end + return '/'..table.concat(comps, '/') +end + +function join(p1, p2, ...) + if not p2 then return p1 end + if not is_absolute(p2) then p2 = '/'..p2 end + return join((p1 == '/' and '' or p1)..p2, unpack(arg)) +end + +function split(path) + -- assume absolute paths + assert(is_absolute(path)) + if path == '/' then return {} end + return filter(function(s) return s > '' end, + stringy.split(string.sub(path, 2, -1), '/')) +end + +function parent(path) + local comps = split(path) + table.remove(comps) + return join('/', unpack(comps)) +end + +function name(path) + local comps = split(path) + return comps[#comps] +end |