Method: FileUtils.mkpath

Defined in:
lib/fileutils.rb

.mkpathObject

Creates a directory and all its parent directories. For example,

FileUtils.mkdir_p '/usr/local/lib/ruby'

causes to make following directories, if they do not exist.

  • /usr

  • /usr/local

  • /usr/local/lib

  • /usr/local/lib/ruby

You can pass several directories at a time in a list.


242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
# File 'lib/fileutils.rb', line 242

def mkdir_p(list, mode: nil, noop: nil, verbose: nil)
  list = fu_list(list)
  fu_output_message "mkdir -p #{mode ? ('-m %03o ' % mode) : ''}#{list.join ' '}" if verbose
  return *list if noop

  list.each do |item|
    path = remove_trailing_slash(item)

    # optimize for the most common case
    begin
      fu_mkdir path, mode
      next
    rescue SystemCallError
      next if File.directory?(path)
    end

    stack = []
    until path == stack.last   # dirname("/")=="/", dirname("C:/")=="C:/"
      stack.push path
      path = File.dirname(path)
      break if File.directory?(path)
    end
    stack.pop if path == stack.last   # root directory should exist
    stack.reverse_each do |dir|
      begin
        fu_mkdir dir, mode
      rescue SystemCallError
        raise unless File.directory?(dir)
      end
    end
  end

  return *list
end