Skip to content

Commit 03800bf

Browse files
committed
Make Pathname#mkpath builtin
[Feature #17473]
1 parent 4fab4cf commit 03800bf

2 files changed

Lines changed: 28 additions & 10 deletions

File tree

lib/pathname.rb

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -38,16 +38,6 @@ def find(ignore_error: true) # :yield: pathname
3838

3939

4040
class Pathname # * FileUtils *
41-
# Creates a full path, including any intermediate directories that don't yet
42-
# exist.
43-
#
44-
# See FileUtils.mkpath and FileUtils.mkdir_p
45-
def mkpath(mode: nil)
46-
require 'fileutils'
47-
FileUtils.mkpath(@path, mode: mode)
48-
self
49-
end
50-
5141
# Recursively deletes a directory, including all directories beneath it.
5242
#
5343
# See FileUtils.rm_rf

pathname_builtin.rb

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,34 @@ class Pathname
4444

4545
# :startdoc:
4646

47+
# Creates a full path, including any intermediate directories that don't yet
48+
# exist.
49+
#
50+
# See FileUtils.mkpath and FileUtils.mkdir_p
51+
def mkpath(mode: nil)
52+
path = @path == '/' ? @path : @path.chomp('/')
53+
54+
stack = []
55+
until File.directory?(path) || File.dirname(path) == path
56+
stack.push path
57+
path = File.dirname(path)
58+
end
59+
60+
stack.reverse_each do |dir|
61+
dir = dir == '/' ? dir : dir.chomp('/')
62+
if mode
63+
Dir.mkdir dir, mode
64+
File.chmod mode, dir
65+
else
66+
Dir.mkdir dir
67+
end
68+
rescue SystemCallError
69+
raise unless File.directory?(dir)
70+
end
71+
72+
self
73+
end
74+
4775
# chop_basename(path) -> [pre-basename, basename] or nil
4876
def chop_basename(path) # :nodoc:
4977
base = File.basename(path)

0 commit comments

Comments
 (0)