1 -- $Id: filename.lua,v 1.1 2005/03/29 20:58:31 cpressey Exp $
5 local POSIX
= require("posix")
12 -- Package of routines for manipulating filenames.
13 -- Also contains convenience functions for querying the
14 -- status of files in the filesystem named by those filenames.
20 -- Add a trailing slash to a pathname, if needed.
22 FileName
.add_trailing_slash
= function(path
)
23 if string.sub(path
, -1) ~= "/" then
31 -- Remove any leading slash from a pathname.
33 FileName
.remove_leading_slash
= function(path
)
34 if string.sub(path
, 1, 1) == "/" then
35 return string.sub(path
, 2)
42 -- Remove the trailing slash of a pathname, if present.
44 FileName
.remove_trailing_slash
= function(path
)
45 if string.sub(path
, -1) == "/" then
46 return string.sub(path
, 1, string.len(path
) - 1)
53 -- Pure Lua version of dirname.
55 FileName
.dirname
= function(path
)
58 string.sub(path
, -1) == "/" or
59 string.sub(path
, -2) == "/." or
60 string.sub(path
, -3) == "/.." or
61 (string.sub(path
, -1) == "." and
62 string.len(path
) == 1) or
63 (string.sub(path
, -2) == ".." and
64 string.len(path
) == 2) then
67 path
= string.sub(path
, 1, -2)
72 if string.sub(path
, -1) ~= "/" then
80 -- Pure Lua version of basename.
82 FileName
.basename
= function(path
)
83 local i
= string.len(path
)
85 while string.sub(path
, i
, i
) == "/" and i
> 0 do
86 path
= string.sub(path
, 1, i
- 1)
90 if string.sub(path
, i
, i
) == "/" then
96 path
= string.sub(path
, i
+ 1, -1)
106 -- Query file status in the underlying file system.
107 -- If the given file is the thing the test is asking for, return 'true'.
108 -- If it's not that type of thing, but it does exist, return 'false'.
109 -- If it doesn't even exist, return 'nil'.
112 FileName
.is_dir
= function(path
)
113 local stat
= POSIX
.stat(path
)
118 return stat
.type == "directory"
122 FileName
.is_file
= function(path
)
123 local stat
= POSIX
.stat(path
)
128 return stat
.type == "regular"
132 FileName
.is_program
= function(path
)
133 local stat
= POSIX
.stat(path
)
138 return stat
.type == "regular" and
139 string.sub(stat
.mode
, 9, 9) == "x"