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( "taptest" )
local collectk = require( "collectk" )
local dirmatch = require( "dirmatch" )
local mkdirtree = require( "mkdirtree" )
local rmdirtree = require( "rmdirtree" )

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

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

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

-- teardown
t( rmdirtree( "tmp_dirmatch" ), true )

t()