From 210d3b1e0b3f8838589434e6520d49a4ad3af94f Mon Sep 17 00:00:00 2001 From: Federico Capoano Date: Fri, 27 May 2016 17:08:06 +0200 Subject: [PATCH] [utils] Added dirtree + test #19 --- openwisp-config/files/lib/openwisp/utils.lua | 23 ++++++++++++++++++++ openwisp-config/tests/test_utils.lua | 13 +++++++++++ 2 files changed, 36 insertions(+) diff --git a/openwisp-config/files/lib/openwisp/utils.lua b/openwisp-config/files/lib/openwisp/utils.lua index ac98754..c22b411 100644 --- a/openwisp-config/files/lib/openwisp/utils.lua +++ b/openwisp-config/files/lib/openwisp/utils.lua @@ -1,4 +1,5 @@ -- openwisp uci utils +require('lfs') function starts_with_dot(str) if string.sub(str, 1, 1) == '.' then @@ -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 diff --git a/openwisp-config/tests/test_utils.lua b/openwisp-config/tests/test_utils.lua index 266ba95..4e0e613 100644 --- a/openwisp-config/tests/test_utils.lua +++ b/openwisp-config/tests/test_utils.lua @@ -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())