Reduce differences with root_skels in contrib.
[dragonfly.git] / contrib / bsdinstaller-1.1.6 / src / lib / lua / filename / filename.lua
blob6bd7500194620f64c39685aefd969f3f90db9d82
1 -- $Id: filename.lua,v 1.1 2005/03/29 20:58:31 cpressey Exp $
3 module("filename")
5 local POSIX = require("posix")
7 --[[----------]]--
8 --[[ FileName ]]--
9 --[[----------]]--
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.
17 FileName = {}
20 -- Add a trailing slash to a pathname, if needed.
22 FileName.add_trailing_slash = function(path)
23 if string.sub(path, -1) ~= "/" then
24 return path .. "/"
25 else
26 return path
27 end
28 end
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)
36 else
37 return path
38 end
39 end
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)
47 else
48 return path
49 end
50 end
53 -- Pure Lua version of dirname.
55 FileName.dirname = function(path)
56 while true do
57 if path == "" or
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
65 break
66 end
67 path = string.sub(path, 1, -2)
68 end
69 if path == "" then
70 path = "."
71 end
72 if string.sub(path, -1) ~= "/" then
73 path = path .. "/"
74 end
76 return path
77 end
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)
87 i = i - 1
88 end
89 while i > 0 do
90 if string.sub(path, i, i) == "/" then
91 break
92 end
93 i = i - 1
94 end
95 if i > 0 then
96 path = string.sub(path, i + 1, -1)
97 end
98 if path == "" then
99 path = "/"
102 return path
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)
115 if not stat then
116 return nil
117 else
118 return stat.type == "directory"
122 FileName.is_file = function(path)
123 local stat = POSIX.stat(path)
125 if not stat then
126 return nil
127 else
128 return stat.type == "regular"
132 FileName.is_program = function(path)
133 local stat = POSIX.stat(path)
135 if not stat then
136 return nil
137 else
138 return stat.type == "regular" and
139 string.sub(stat.mode, 9, 9) == "x"
143 return FileName