Debian Codegraph @

CorsixTH/Lua/filesystem.lua

raw
1 --[[ Copyright (c) 2010 Peter "Corsix" Cawley
2
3 Permission is hereby granted, free of charge, to any person obtaining a copy of
4 this software and associated documentation files (the "Software"), to deal in
5 the Software without restriction, including without limitation the rights to
6 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
7 of the Software, and to permit persons to whom the Software is furnished to do
8 so, subject to the following conditions:
9
10 The above copyright notice and this permission notice shall be included in all
11 copies or substantial portions of the Software.
12
13 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19 SOFTWARE. --]]
20
21 local pathsep = package.config:sub(1, 1)
22 local part_pattern = "[^" .. pathsep .. "]+"
23
24 local ISO_FS = require("TH").iso_fs
25
26 --! Layer for abstracting away differences in file systems.
27 --
28 -- In the traditional case, the FileSystem is associated with a path on the
29 -- actual filesystem, from which all other operations are considered relative.
30 --
31 -- The FileSystem is also able to delegate operations to the ISO_FS library
32 -- in the engine for reading / listing files off an ISO image instead of a
33 -- file system.
34 class "FileSystem"
35
36 ---@type FileSystem
37 local FileSystem = _G["FileSystem"]
38
39 function FileSystem:FileSystem()
40 -- A mapping of normalized file names in the current directory to their
41 -- actual path names.
42 self.files = nil
43
44 -- A mapping of normalized directory names in the current directory to
45 -- an object containing their actual physical path.
46 self.sub_dirs = nil
47
48 -- The actual filesystem path that is the basis/root of this FileSystem. Not
49 -- used when a provider is specified.
50 self.physical_path = nil
51
52 -- The ISO_FS provider if we are reading from an ISO instead of a
53 -- filesystem, otherwise nil.
54 self.provider = nil
55 end
56
57 --! Convert a file name to a canonical, case insensitive format.
58 -- The format is based on the limitations of the ISO filesystem.
59 local function normalise(str)
60 return str:upper():gsub("_", "-")
61 end
62
63 --! Populate the files and sub_dirs values for the current FileSystem path.
64 function FileSystem:_enumerate()
65 self.sub_dirs = {}
66 self.files = {}
67 for item in lfs.dir(self.physical_path) do
68 local path = self.physical_path .. pathsep .. item
69 if lfs.attributes(path, "mode") == "directory" then
70 self.sub_dirs[normalise(item)] = {physical_path = path}
71 else
72 self.files[normalise(item)] = path
73 end
74 end
75 end
76
77 --! Test if file name has an .iso or .dmg extension
78 function FileSystem:isIso(name)
79 if name == nil then
80 return false
81 end
82
83 local ext = name:lower():match("%.(.+)$")
84 return ext == 'iso' or ext == 'iso9660$' or ext == 'dmg'
85 end
86
87 --! Set the root physical path for this FileSystem.
88 -- If the path is an ISO then set the provider. If the path is a directory
89 -- then set the physical_path and populate the files and sub_dirs.
90 --
91 --!param physical_path (string) a path on the filesystem to either a directory
92 -- or theme hospital ISO file.
93 function FileSystem:setRoot(physical_path)
94 if self:isIso(physical_path) then
95 self.physical_path = physical_path
96 local provider, status, err = ISO_FS(physical_path, pathsep)
97 self.provider = provider
98 return status, err
99 end
100
101 if physical_path:sub(-1) == pathsep then
102 -- Trim off the trailing separator (lfs doesn't like querying the mode of a
103 -- directory with a trailing slash on win32)
104 physical_path = physical_path:sub(1, -2)
105 end
106 if lfs.attributes(physical_path, "mode") ~= "directory" then
107 return nil, "Specified path ('" .. physical_path .. "') is not a directory"
108 end
109
110 self.provider = nil
111 self.physical_path = physical_path
112 self:_enumerate()
113
114 return true
115 end
116
117 --! list the files in the given path.
118 --
119 --!param virtual_path (string) a path relative to the FileSystem root.
120 --!param ... (string) the virtual_path may be split into separate arguments
121 -- for each level in the filesystem.
122 --!return (object) a map of normalized names to actual names of files.
123 function FileSystem:listFiles(virtual_path, ...)
124 if ... then
125 virtual_path = table.concat({virtual_path, ...}, pathsep)
126 end
127 if self.provider then
128 return self.provider:listFiles(virtual_path)
129 elseif not self.sub_dirs then
130 return nil, "Filesystem layer not initialised"
131 end
132 for part in virtual_path:gmatch(part_pattern) do
133 local part_u = normalise(part)
134 if self.sub_dirs[part_u] then
135 self = self.sub_dirs[part_u]
136 if not self.files then
137 FileSystem._enumerate(self)
138 end
139 elseif self.files[part_u] then
140 return nil, ("Attempt to access file '%s' as if it were a directory while trying to enumerate '%s'"):format(part, virtual_path)
141 else
142 return nil, ("Unable to find '%s' while trying to enumerate '%s'"):format(part, virtual_path)
143 end
144 end
145 return self.files
146 end
147
148 --! Combine the given path segments into a single path string.
149 --!param virtual_path (string) a path relative to the FileSystem root.
150 --!param ... (string) the virtual_path may be split into separate arguments
151 -- for each level in the filesystem.
152 local function getFullPath(virtual_path, ...)
153 if ... then
154 virtual_path = table.concat({virtual_path, ...}, pathsep)
155 end
156 return virtual_path
157 end
158
159 --! Return the contents of the file at the given path.
160 --
161 --!param virtual_path (string) a path relative to the FileSystem root.
162 --!param ... (string) the virtual_path may be split into separate arguments
163 -- for each level in the filesystem.
164 function FileSystem:readContents(virtual_path, ...)
165 virtual_path = getFullPath(virtual_path, ...)
166 if self.provider then
167 return self.provider:readContents(virtual_path)
168 end
169
170 local file, err = self:_getFilePath(virtual_path)
171 if not file then
172 return file, err
173 end
174 local f, e = io.open(file, "rb")
175 if not f then
176 return nil, e
177 end
178 local data = f:read("*a")
179 f:close()
180 return data
181 end
182
183 --! Determines if the given path points to a real file.
184 --
185 --!param virtual_path (string) a path relative to the FileSystem root.
186 --!param ... (string) the virtual_path may be split into separate arguments
187 -- for each level in the filesystem.
188 function FileSystem:fileExists(virtual_path, ...)
189 virtual_path = getFullPath(virtual_path, ...)
190 if self.provider then
191 local found, err = self.provider:fileExists(virtual_path)
192 if found then
193 return true
194 else
195 return nil, err
196 end
197 end
198
199 local s, e = self:_getFilePath(virtual_path)
200 return (not not s), e
201 end
202
203 --! Get the size of the file at the given path.
204 --
205 --!param virtual_path (string) a path relative to the FileSystem root.
206 --!param ... (string) the virtual_path may be split into separate arguments
207 -- for each level in the filesystem.
208 --!return (numeric) Number of bytes in the given file. Nil if the file doesn't
209 -- exist.
210 function FileSystem:fileSize(virtual_path, ...)
211 virtual_path = getFullPath(virtual_path, ...)
212 if self.provider then
213 return self.provider:fileSize(virtual_path)
214 end
215
216 local s, e = self:_getFilePath(virtual_path)
217 if not s then
218 return nil, e
219 end
220 return lfs.attributes(s, "size")
221 end
222
223 --! Get a URI for the file.
224 --
225 -- The returned URI formats match those described by <https://ffmpeg.org/ffmpeg-protocols.html>.
226 --
227 --!param virtual_path (string) a path relative to the FileSystem root.
228 --!param ... (string) the virtual_path may be split into separate arguments
229 -- for each level in the filesystem.
230 --!return (string) A uri representing the files location
231 function FileSystem:fileUri(virtual_path, ...)
232 virtual_path = getFullPath(virtual_path, ...)
233 if self.provider then
234 local fileStart, fileEnd = self.provider:fileOffsets(virtual_path)
235 return 'subfile,,start,' .. fileStart .. ',end,' .. fileEnd .. ',,:' .. self.physical_path
236 end
237 return 'file:' .. virtual_path
238 end
239
240 -- If the file exists and we are not using a provider then return a FileSystem
241 -- rooted in the directory that the directory the file is contained in.
242 -- Otherwise return nil and an error message.
243 function FileSystem:_getFilePath(virtual_path, ...)
244 virtual_path = getFullPath(virtual_path, ...)
245 if self.provider then
246 return nil, "This function is not supported for providers"
247 end
248 if not self.sub_dirs then
249 return nil, "Filesystem layer not initialised"
250 end
251 local is_file = false
252 for part in virtual_path:gmatch(part_pattern) do
253 if is_file then
254 return nil, ("Attempt to access file '%s' as if it were a directory while trying to read '%s'"):format(part, virtual_path)
255 end
256 local part_u = normalise(part)
257 if self.sub_dirs[part_u] then
258 self = self.sub_dirs[part_u]
259 if not self.files then
260 FileSystem._enumerate(self)
261 end
262 elseif self.files[part_u] then
263 self = self.files[part_u]
264 is_file = true
265 else
266 return nil, ("Unable to find '%s' while trying to read '%s'"):format(part, virtual_path)
267 end
268 end
269 if not is_file then
270 return nil, ("Attempt to access directory '%s' as if it were a file"):format(virtual_path)
271 end
272 return self
273 end