2021-01-23 22:31:04 +01:00
|
|
|
local Gio = require("lgi").Gio
|
|
|
|
|
|
|
|
local _filesystem = {}
|
|
|
|
|
|
|
|
--- Get a list of files from a given directory.
|
|
|
|
-- @string path The directory to search.
|
|
|
|
-- @tparam[opt] table exts Specific extensions to limit the search to. eg:`{ "jpg", "png" }`
|
|
|
|
-- If ommited, all files are considered.
|
|
|
|
-- @bool[opt=false] recursive List files from subdirectories
|
|
|
|
-- @staticfct bling.helpers.filesystem.get_random_file_from_dir
|
|
|
|
function _filesystem.list_directory_files(path, exts, recursive)
|
|
|
|
recursive = recursive or false
|
|
|
|
local files, valid_exts = {}, {}
|
|
|
|
|
|
|
|
-- Transforms { "jpg", ... } into { [jpg] = #, ... }
|
2021-08-27 20:01:22 +02:00
|
|
|
if exts then
|
|
|
|
for i, j in ipairs(exts) do
|
|
|
|
valid_exts[j:lower()] = i
|
|
|
|
end
|
|
|
|
end
|
2021-01-23 22:31:04 +01:00
|
|
|
|
|
|
|
-- Build a table of files from the path with the required extensions
|
2021-08-27 20:01:22 +02:00
|
|
|
local file_list = Gio.File.new_for_path(path):enumerate_children(
|
|
|
|
"standard::*",
|
|
|
|
0
|
|
|
|
)
|
2021-01-23 22:31:04 +01:00
|
|
|
if file_list then
|
2021-08-27 20:01:22 +02:00
|
|
|
for file in function()
|
|
|
|
return file_list:next_file()
|
|
|
|
end do
|
2021-01-23 22:31:04 +01:00
|
|
|
local file_type = file:get_file_type()
|
|
|
|
if file_type == "REGULAR" then
|
|
|
|
local file_name = file:get_display_name()
|
2021-08-27 20:01:22 +02:00
|
|
|
if
|
|
|
|
not exts
|
|
|
|
or valid_exts[file_name:lower():match(".+%.(.*)$") or ""]
|
|
|
|
then
|
2021-01-23 22:31:04 +01:00
|
|
|
table.insert(files, file_name)
|
|
|
|
end
|
|
|
|
elseif recursive and file_type == "DIRECTORY" then
|
|
|
|
local file_name = file:get_display_name()
|
2021-08-27 20:01:22 +02:00
|
|
|
files = gears.table.join(
|
|
|
|
files,
|
|
|
|
list_directory_files(file_name, exts, recursive)
|
|
|
|
)
|
2021-01-23 22:31:04 +01:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
return files
|
|
|
|
end
|
|
|
|
|
|
|
|
return _filesystem
|