Skip to content

Commit

Permalink
pl.dir: convert dir.walk from coroutine to iterator
Browse files Browse the repository at this point in the history
  • Loading branch information
hishamhm authored and Tieske committed Sep 27, 2020
1 parent c0d2a7a commit 5d23672
Showing 1 changed file with 22 additions and 10 deletions.
32 changes: 22 additions & 10 deletions lua/pl/dir.lua
Original file line number Diff line number Diff line change
Expand Up @@ -271,15 +271,6 @@ local function _dirfiles(dirname,attrib)
end


local function _walker(root,bottom_up,attrib)
local dirs,files = _dirfiles(root,attrib)
if not bottom_up then yield(root,dirs,files) end
for i,d in ipairs(dirs) do
_walker(root..path.sep..d,bottom_up,attrib)
end
if bottom_up then yield(root,dirs,files) end
end

--- return an iterator which walks through a directory tree starting at root.
-- The iterator returns (root,dirs,files)
-- Note that dirs and files are lists of names (i.e. you must say path.join(root,d)
Expand All @@ -301,7 +292,28 @@ function dir.walk(root,bottom_up,follow_links)
else
attrib = path.link_attrib
end
return wrap(function () _walker(root,bottom_up,attrib) end)

local to_scan = { root }
local to_return = {}
local iter = function()
while #to_scan > 0 do
local current_root = table.remove(to_scan)
local dirs,files = _dirfiles(current_root, attrib)
for _, d in ipairs(dirs) do
table.insert(to_scan, current_root..path.sep..d)
end
if not bottom_up then
return current_root, dirs, files
else
table.insert(to_return, { current_root, dirs, files })
end
end
if #to_return > 0 then
return utils.unpack(table.remove(to_return))
end
end

return iter
end

--- remove a whole directory tree.
Expand Down

0 comments on commit 5d23672

Please sign in to comment.