scan.lua

Sun, 06 Sep 2020 22:12:52 +0300

author
Tuomo Valkonen <tuomov@iki.fi>
date
Sun, 06 Sep 2020 22:12:52 +0300
changeset 35
2f927eae429b
parent 26
77cd7b8fb6a6
permissions
-rw-r--r--

Don't auto-create directories that will be empty


--@module scan
local scan={}

local lfs=require('lfs')
local path=require('mypath')

local function filtered_dir(d) 
    local f, s_, v_ = lfs.dir(d)
    local function g(s, v)
        while true do
            local vn=f(s, v)
            if vn~='.' and vn~='..' then
                return vn
            end
        end
    end
    return g, s_, v_
end

function scan.scan(d)
    local h={}
    for f in filtered_dir(d) do
        local n=d..'/'..f
        local a=lfs.attributes(n)
        if a.mode=='directory' then
            local nh=scan.scan(n)
            h[f]=nh
        elseif a.mode=='file' then
            h[f]=true
        end
    end
    return h
end

function scan.hfold(h, a, f, g)
    for n, c in pairs(h) do
        if type(c)=='table' then
            scan.hfold(c, f(a, n), f, g)
        else
            g(a, n)
        end
    end
end

function scan.map(h, g, d)
    local function dir(prefix, name)
        local p=path.join(prefix, name)
        if d then
            d(p)
        end
        return p
    end
    
    local function file(prefix, name)
        local f=path.join(prefix, name)
        g(f)
    end
    
    scan.hfold(h, "", dir, file)
end

return scan

mercurial