Method: FileUtils.mkdir_p

Defined in:
lib/fileutils.rb

.mkdir_p(list, mode: nil, noop: nil, verbose: nil) ⇒ Object

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.



206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
# File 'lib/fileutils.rb', line 206

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.map {|path| remove_trailing_slash(path)}.each do |path|
    # 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)
    end
    stack.pop                 # 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