dirhas

function dirhas( path, name [, mode] ) --> entrypath

Description

Checks if the directory behind the path contains an entry with the specified name. It allows also to check the mode(file, directory, …) of the entry.

Parameters

path

Path that should be checked.

name

Name of the entry the function looks for.

mode

Optional string representing a associated protection mode (the values can be file, directory, link, socket, named pipe, char device, block device or other)

Return Values

entrypath

The path to the entry inside the directory, otherwise nil.

Code

local lfs = require( "lfs" ) --ZREQ-lfs

--ZFUNC-dirhas-v1
local function dirhas( path, name, mode ) --> entrypath
   local modeval = lfs.attributes( path, "mode" )
   if modeval ~= "directory" then return nil end

   for entry in lfs.dir( path ) do
      if entry == name then
         local entrypath = path.."/"..entry

         if mode then
            local modeval = lfs.attributes( entrypath, "mode" )
            if modeval ~= mode then
               return nil
            end
         end

         return entrypath
      end
   end

   return nil
end

return dirhas

Example

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

-- setup
t.ok( mkdirtree{
   [ "tmpdir" ] = {
      [ "abc.txt" ] = "",
      [ "xyz.txt" ] = ""
   }
} )

-- test
t.ok( dirhas( "tmpdir", "xyz.txt" ) )
t.nok( dirhas( "tmpdir", "xyz" ) )

t.nok( dirhas( "tmpdir", "xyz.txt", "directory" ) )
t.ok( dirhas( "tmpdir", "xyz.txt", "file" ) )

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

t.done()

See also