Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 42 additions & 11 deletions src/util/filesystem.lua
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
local OS = require("util.os") --- pulls in string

---@class FileInfo
---@field type love.FileType
---@field size number?
---@field modtime number?

local FS = {
path_sep = (function()
if love and love.system
Expand Down Expand Up @@ -122,15 +127,23 @@ if love and not TESTING then
--- @param path string
--- @param filtertype love.FileType?
--- @param vfs boolean?
--- @return boolean
function FS.exists(path, filtertype, vfs)
--- @return FileInfo?
function FS.getInfo(path, filtertype, vfs)
if vfs then
return LFS.getInfo(path, filtertype) and true or false
return LFS.getInfo(path, filtertype)
else
return _fs.getInfo(path, filtertype) and true or false
return _fs.getInfo(path, filtertype)
end
end

--- @param path string
--- @param filtertype love.FileType?
--- @param vfs boolean?
--- @return boolean
function FS.exists(path, filtertype, vfs)
return FS.getInfo(path, filtertype, vfs) and true or false
end

--- @param path string
--- @return boolean success
function FS.mkdir(path)
Expand Down Expand Up @@ -407,14 +420,32 @@ else
end

--- @param path string
--- @param filtertype love.FileType?
--- @return FileInfo?
function FS.getInfo(path, filtertype)
local attrs = lfs.attributes(path)
if not attrs then return end

--- @type table<string, love.FileType>
local types = {
Comment thread
dsent marked this conversation as resolved.
file = 'file',
directory = 'directory',
}
local filetype = types[attrs.mode] or 'other'
if filtertype and filtertype ~= filetype then return end

return {
type = filetype,
size = attrs.size,
modtime = attrs.modification,
}
end

--- @param path string
--- @param filtertype love.FileType?
--- @return boolean exists
function FS.exists(path)
local f = io.open(path, 'r')
if f then
io.close(f)
return true
end
return false
function FS.exists(path, filtertype)
return FS.getInfo(path, filtertype) and true or false
end

--- @param path string
Expand Down
20 changes: 20 additions & 0 deletions tests/util/fs_spec.lua
Original file line number Diff line number Diff line change
Expand Up @@ -52,4 +52,24 @@ describe("FS utils", function()
assert.are.equal('a/b/c', FS.join_path('a', 'b', 'c'))
end)
end)

describe('gets file information', function()
local path

after_each(function()
if path then os.remove(path) end
end)

it('returns metadata and applies the type filter', function()
path = os.tmpname()
local ok = FS.write(path, 'x = 1\n')
assert.is_true(ok)

local info = assert(FS.getInfo(path, 'file'))
assert.same('file', info.type)
assert.same(6, info.size)
assert.is_number(info.modtime)
assert.is_nil(FS.getInfo(path, 'directory'))
end)
end)
end)
Loading