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

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

-- test
t( dirhas( "tmpdir", "xyz.txt" ), "tmpdir/xyz.txt" )
t( dirhas( "tmpdir", "xyz" ), nil )

t( dirhas( "tmpdir", "xyz.txt", "directory" ), nil )
t( dirhas( "tmpdir", "xyz.txt", "file" ), "tmpdir/xyz.txt" )

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

t()