Skip to content

Commit

Permalink
[utils] Added dirtree + test #19
Browse files Browse the repository at this point in the history
  • Loading branch information
nemesifier committed May 27, 2016
1 parent c2f5440 commit 210d3b1
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
23 changes: 23 additions & 0 deletions openwisp-config/files/lib/openwisp/utils.lua
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
-- openwisp uci utils
require('lfs')

function starts_with_dot(str)
if string.sub(str, 1, 1) == '.' then
Expand Down Expand Up @@ -104,3 +105,25 @@ function is_table_empty(t)
end
return true
end

-- Code by David Kastrup
-- http://lua-users.org/wiki/DirTreeIterator
function dirtree(dir)
assert(dir and dir ~= '', 'directory parameter is missing or empty')
if string.sub(dir, -1) == '/' then
local dir = string.sub(dir, 1, -2)
end
local function yieldtree(dir)
for entry in lfs.dir(dir) do
if entry ~= '.' and entry ~= '..' then
entry = dir .. '/' ..entry
local attr = lfs.attributes(entry)
coroutine.yield(entry,attr)
if attr.mode == 'directory' then
yieldtree(entry)
end
end
end
end
return coroutine.wrap(function() yieldtree(dir) end)
end
13 changes: 13 additions & 0 deletions openwisp-config/tests/test_utils.lua
Original file line number Diff line number Diff line change
Expand Up @@ -229,4 +229,17 @@ function TestUtils.test_merge_uci_list_duplicate()
luaunit.assertEquals(count, 1)
end

function TestUtils.test_dirtree()
os.execute('rm '..write_dir..'/*')
os.execute('touch '..write_dir..'/f1')
os.execute('touch '..write_dir..'/f2')
os.execute('mkdir '..write_dir..'/inner')
os.execute('touch '..write_dir..'/f3')
count = 0
for filename, attr in dirtree(write_dir) do
count = count + 1
end
luaunit.assertEquals(count, 4)
end

os.exit(luaunit.LuaUnit.run())

0 comments on commit 210d3b1

Please sign in to comment.