Sat, 12 Sep 2009 21:27:57 +0300
(don't know)
2 | 1 | |
2 | module("path", package.seeall) | |
3 | ||
4 | require("tuple") | |
5 | require("lfs") | |
6 | require("err") | |
7 | require("config") | |
8 | ||
9 | local sep=config.dirsep | |
10 | ||
11 | function join(p, f) | |
12 | return p..sep..f | |
13 | end | |
14 | ||
15 | function dirbasename(p) | |
16 | local d, b = string.match(p, | |
17 | "(.*)"..sep.."+([^"..sep.."]+)"..sep.."*$") | |
18 | if not b then | |
19 | return string.match(p, "([^"..sep.."]*") | |
20 | else | |
21 | return d, b | |
22 | end | |
23 | end | |
24 | ||
25 | function dirname(p) | |
26 | return tuple.fst(dirbasename(p)) | |
27 | end | |
28 | ||
29 | function basename(p) | |
30 | return tuple.snd(dirbasename(p)) | |
31 | end | |
32 | ||
33 | -- would rather do this as an iterator, but can't | |
34 | -- coroutine.yield from gsub handler | |
35 | function split(p) | |
36 | local t={} | |
37 | local head="" | |
38 | local s, p2 = string.match(p, "^("..sep.."+)(.*)$") | |
39 | if s then | |
40 | table.insert(t, "/.") -- root | |
41 | p=p2 | |
42 | end | |
43 | string.gsub(p, "([^"..sep.."]+)"..sep.."+", | |
44 | function(d) table.insert(t, d); end) | |
45 | return t | |
46 | end | |
47 | ||
48 | function parts(p) | |
49 | local s={i=1, t=split(p)} | |
50 | local function g(s) | |
51 | local v=s.t[s.i] | |
52 | s.i=s.i+1 | |
53 | return v | |
54 | end | |
55 | return g, s | |
56 | end | |
57 | ||
58 | function makepath(p) | |
59 | local head="" | |
60 | for d in parts(p) do | |
61 | head=head..d | |
62 | local a=lfs.attributes(head) | |
63 | if not a then | |
64 | local success, e = lfs.mkdir(head) | |
65 | if not success then | |
66 | err.file(head, e) | |
67 | end | |
68 | elseif a.mode~="directory" then | |
69 | err.file(head, "not a directory") | |
70 | end | |
71 | head=head..sep | |
72 | end | |
73 | end | |
74 | ||
75 | --[[ | |
76 | print(dirbasename("/foo/bar/baz")) | |
77 | ||
78 | for k in parts("//foo/bar/baz/quk") do | |
79 | print(k) | |
80 | end | |
81 | ||
82 | makepath("foo/bar/baz/quk") | |
83 | --]] |