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( "tapered" )
local mkdirtree = require( "mkdirtree" )
-- util functions
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.ok( res )
t.is( nil, err )

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

t.ok( rmdirtree( "root" ) )
t.ok( rmdirtree( "doot" ) )

lfs.mkdir( "xxx" )

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

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

t.ok( res )
t.is( nil, err )

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

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

t.done()

See also