rmdirtree

function rmdirtree( path ) --> res, err

Description

Removes a directory with all the files and subdirectires inside.

Parameters

path

The directory that should be removed.

Return Values

res

true or nil if an error occurse.

err

A message if an error occurse otherwise nil.

Code

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

--ZFUNC-rmdirtree-v1
local function rmdirtree( path ) --> res, err
   --ZFUNC-isdodd-v1
   local function isdodd( e )
      if e == "." or e == ".." then
         return true
      end

      return false
   end

   for entry in lfs.dir( path ) do
      if not isdodd( entry ) then
         local entrypath = path.."/"..entry
         local mode = lfs.attributes( entrypath, "mode" )
         local res, err = true, nil
         if mode == "directory" then
            res, err = rmdirtree( entrypath )
         else
            res, err = os.remove( entrypath )
         end
         if err then return res, err end
      end
   end

   return os.remove( path )
end

return rmdirtree

Examples

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

-- test
t.ok( mkdirtree{
   [ "tmp_rmdirtree" ] = {
      [ "fa.txt" ] = "",
      [ "da" ] = {
         [ "dab" ] = {},
         [ "fab.txt" ] = "content",
      }
   }
} )

res, err = rmdirtree( "tmp_rmdirtree" )
t.ok( res )
t.is( nil, err )

t.done()

See also