mkdirtree

function mkdirtree( tree [,root] ) --> res, err

Description

Allows to create multiple files and directories.

Parameters

tree

Lua table where keys represent the names and the following two value types are allowed:

  • table = dictionaries

  • string = content of the file

root

Optional root directory where the tree will be created.

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-mkdirtree-v1
local function mkdirtree( tree, root ) --> res, err
   --ZFUNC-writefile-v1
   local function writefile( filename, ... )
      local f, err = io.open( filename, "w" )
      if err then return nil, err end

      local wres, err = f:write( ... )
      if err then return nil, err end

      return f:close()
   end

   root = root or "."

   for name, v in pairs( tree ) do
      local path = root.."/"..name
      local res, err
      if type( v ) == "table" then
         lfs.mkdir( path )
         res, err = mkdirtree( v, path )
      elseif type( v ) == "string" then
         local res, err = writefile( path, v )
      else
         res = nil
         err = string.format( "invalid value type: %q", type( v ) )
      end

      if err then return res, err end
   end

   return true
end

return mkdirtree

Examples

local t = require( "taptest" )
local mkdirtree = require( "mkdirtree" )
local readfile = require( "readfile" )
local rmdirtree = require( "rmdirtree" )

-- test
res, err = mkdirtree{
   [ "root" ] = {
      [ "fa.txt" ] = "",
      [ "da" ]  = {
         [ "dab" ] = {},
         [ "fab.txt" ] = "content"
      }
   },
   [ "doot" ] = {
      [ "last.txt" ] = "the is the end"
   }
}

t( res, true )
t( err, nil )

t( readfile( "root/fa.txt" ), "" )
t( readfile( "root/da/fab.txt" ), "content" )
t( readfile( "doot/last.txt" ), "the is the end" )

t( rmdirtree( "root" ), true )
t( rmdirtree( "doot" ), true )

lfs.mkdir( "xxx" )

tree = {
  [ "zzz" ] = {
    [ "foo.txt" ] = "foo",
    [ "bar.txt" ] = "bar"
  }
}

res, err = mkdirtree( tree, "xxx" )

t( res, true )
t( err, nil )

t( readfile( "xxx/zzz/foo.txt" ), "foo" )
t( readfile( "xxx/zzz/bar.txt" ), "bar" )

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

t()

See also