Skip to content

Commit 329456b

Browse files
committed
Fix crashes when creating directories at single component relative paths
Bail early if after calling deletingLastPathComponent the path is empty. There is no point in doing a traversal and trying to create an empty directory at the parent path. In addition, this ends up tripping a pre-condition when we try finding the next parent path component again. This addresses SR-4570.
1 parent a4ca69e commit 329456b

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

Foundation/FileManager.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,7 @@ open class FileManager : NSObject {
150150
var isDir: ObjCBool = false
151151
if !fileExists(atPath: path, isDirectory: &isDir) {
152152
let parent = path._nsObject.deletingLastPathComponent
153-
if !fileExists(atPath: parent, isDirectory: &isDir) {
153+
if !parent.isEmpty && !fileExists(atPath: parent, isDirectory: &isDir) {
154154
try createDirectory(atPath: parent, withIntermediateDirectories: true, attributes: attributes)
155155
}
156156
if mkdir(path, S_IRWXU | S_IRWXG | S_IRWXO) != 0 {

TestFoundation/TestFileManager.swift

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ class TestFileManager : XCTestCase {
3333
("test_copyItemAtPathToPath", test_copyItemAtPathToPath),
3434
("test_homedirectoryForUser", test_homedirectoryForUser),
3535
("test_temporaryDirectoryForUser", test_temporaryDirectoryForUser),
36+
("test_creatingDirectoryWithShortIntermediatePath", test_creatingDirectoryWithShortIntermediatePath),
3637
]
3738
}
3839

@@ -111,6 +112,20 @@ class TestFileManager : XCTestCase {
111112
}
112113
}
113114

115+
func test_creatingDirectoryWithShortIntermediatePath() {
116+
let fileManager = FileManager.default
117+
fileManager.changeCurrentDirectoryPath(NSTemporaryDirectory())
118+
119+
let relativePath = NSUUID().uuidString
120+
121+
do {
122+
try fileManager.createDirectory(atPath: relativePath, withIntermediateDirectories: true, attributes: nil)
123+
try fileManager.removeItem(atPath: relativePath)
124+
} catch {
125+
XCTFail("Failed to create and clean up directory")
126+
}
127+
}
128+
114129
func test_moveFile() {
115130
let fm = FileManager.default
116131
let path = NSTemporaryDirectory() + "testfile\(NSUUID().uuidString)"

0 commit comments

Comments
 (0)