dirmatch

function dirmatch( path, pattern ) --> iter

Description

Creates a Lua interator over the entries in a directory where the name matches the pattern. Raises an error if path is not a directory.

Parameters

path

A path to a directory in the filesystem.

pattern

Lua pattern to identify the relevant entries.

Return Values

iter

Lua iterator over the entries that match the pattern.

Code

local lfs = require( "lfs" ) --ZREQ-lfs
--ZFUNC-dirmatch-v1
local function dirmatch( path, pattern ) --> iter
   local function yielddir( path )
      for entry in lfs.dir( path ) do
         if entry:find( pattern ) then
            coroutine.yield( entry )
         end
      end
   end

   return coroutine.wrap( function() yielddir( path ) end )
end

return dirmatch

Examples

local t = require( "tapered" )
local dirmatch = require( "dirmatch" )
-- util functions
local collectk = require( "collectk" )
local mkdirtree = require( "mkdirtree" )
local rmdirtree = require( "rmdirtree" )

-- setup
t.ok( mkdirtree{
   [ "tmp_dirmatch" ] = {
      [ "adir" ] = {},
      [ "afile" ] = "",
      [ "bdir" ] = {},
      [ "bfile" ] = ""
   }
} )

-- test
res = collectk( dirmatch( "tmp_dirmatch", "^a" ) )
table.sort( res )
t.is( #res, 2 )
t.is( "adir", res[ 1 ] )
t.is( "afile", res[ 2 ] )

res = collectk( dirmatch( "tmp_dirmatch", "file$" ) )
table.sort( res )
t.is( #res, 2 )
t.is( "afile", res[ 1 ] )
t.is( "bfile", res[ 2 ] )

-- teardown
t.ok( rmdirtree( "tmp_dirmatch" ) )

t.done()