Add ls method to prevfile

This commit is contained in:
The Magician 2023-11-18 17:12:57 +00:00
parent 877ae6e460
commit 8ea961ff93
2 changed files with 96 additions and 7 deletions

View File

@ -1,9 +1,75 @@
describe("prevfile", function() function get_directory_iterator_from_table(table)
return function(directory)
local index = 0
local filenames = table
return function()
index = index + 1
return filenames[index]
end
end
end
describe("ls", function()
local lfs = require "lfs"
local prevfile = require "prevfile" local prevfile = require "prevfile"
it("returns nil when target directory is empty", function() insulate("if directory does not exist", function()
previous = prevfile.prevfile("dummy/") lfs.dir = function(directory) error("No such file or directory") end
assert.are.equals(nil, previous) it("should return nil", function()
local files = prevfile.ls("/testdir")
assert.equals(nil, files)
end)
end)
insulate("if directory is empty", function()
lfs.dir = get_directory_iterator_from_table({})
it("should return empty table", function()
local files = prevfile.ls("/testdir")
assert.are.same({}, files)
end)
it("should call lfs.dir with target directory", function()
spy.on(lfs, "dir")
local test_directory = "/testdir"
prevfile.ls(test_directory)
assert.stub(lfs.dir).was_called_with(test_directory)
end)
end)
insulate("if directory contains files", function()
lfs.dir = get_directory_iterator_from_table({"a.txt", "b.txt", "z.txt", "c.txt"})
it("should return the files in lexographical order", function()
local files = prevfile.ls("/testdir")
assert.are.same({"a.txt", "b.txt", "c.txt", "z.txt"}, files)
end)
end)
insulate("if directory contains numerically-named files", function()
lfs.dir = get_directory_iterator_from_table({"/testdir/709.txt", "/testdir/71.txt", "/testdir/710.txt"})
it("should return the files in numerical order", function()
local files = prevfile.ls("/testdir")
assert.are.same({"/testdir/71.txt", "/testdir/709.txt", "/testdir/710.txt"}, files)
end)
end)
insulate("if directory contains hidden files", function()
lfs.dir = get_directory_iterator_from_table({"a.txt", ".b.txt.swp", "c.txt"})
it("should exclude them from the listing", function()
local files = prevfile.ls("/testdir")
assert.are.same({"a.txt", "c.txt"}, files)
end)
end) end)
end) end)

View File

@ -1,7 +1,30 @@
local prevfile = {} local lfs = require "lfs"
function prevfile.prevfile(target_directory) local prevfile = {}
return nil
local function padnum(d)
local dec, n = string.match(d, "(%.?)0*(.+)")
return #dec > 0 and ("%.12f"):format(d) or ("%s%03d%s"):format(dec, #n, n)
end
local function humansort(a, b)
return tostring(a):gsub("%.?%d+", padnum) < tostring(b):gsub("%.?%d+", padnum)
end
function prevfile.ls(directory)
if not pcall(lfs.dir, directory) then
return nil
end
local files = {}
for file in lfs.dir(directory) do
if string.sub(file, 1, 1) ~= "." then
table.insert(files, file)
end
end
table.sort(files, humansort)
return files
end end
return prevfile return prevfile