Skip to content

Commit

Permalink
Add FileSystem.createFolderIfNeeded()
Browse files Browse the repository at this point in the history
This new method either returns an existing folder at a path, or creates
a new one if none exists.
  • Loading branch information
JohnSundell committed Mar 7, 2017
1 parent 9b5bb0c commit a66a2e4
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
16 changes: 16 additions & 0 deletions Sources/Files.swift
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,22 @@ public class FileSystem {
throw Folder.Error.creatingFolderFailed
}
}

/**
* Either return an existing folder, or create a new one, at a given path
*
* - parameter path: The path for which a folder should either be returned or created at. If the folder
* is missing, any intermediate parent folders will also be created.
*
* - throws: `Folder.Error.creatingFolderFailed`
*/
public func createFolderIfNeeded(at path: String) throws -> Folder {
if let existingFolder = try? Folder(path: path, using: fileManager) {
return existingFolder
}

return try createFolder(at: path)
}
}

/**
Expand Down
11 changes: 11 additions & 0 deletions Tests/FilesTests/FilesTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -372,6 +372,17 @@ class FilesTests: XCTestCase {
_ = try Folder(path: folderPath)
}
}

func testCreateFolderIfNeeded() {
performTest {
let subfolderA = try FileSystem().createFolderIfNeeded(at: folder.path + "one/two/three")
try subfolderA.createFile(named: "file")
let subfolderB = try FileSystem().createFolderIfNeeded(at: subfolderA.path)
XCTAssertEqual(subfolderA, subfolderB)
XCTAssertEqual(subfolderA.files.count, subfolderB.files.count)
XCTAssertEqual(subfolderA.files.first, subfolderB.files.first)
}
}

func testUsingCustomFileManager() {
class FileManagerMock: FileManager {
Expand Down

0 comments on commit a66a2e4

Please sign in to comment.