Skip to content

Commit

Permalink
Add Folder.createFileIfNeeded()
Browse files Browse the repository at this point in the history
Just like `Folder.createSubfolderIfNeeded()`, this new API enables the user
to only create a file if one is missing.
  • Loading branch information
JohnSundell committed Mar 11, 2017
1 parent 9b6a705 commit 883ffed
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
17 changes: 17 additions & 0 deletions Sources/Files.swift
Original file line number Diff line number Diff line change
Expand Up @@ -548,6 +548,23 @@ public final class Folder: FileSystem.Item, FileSystemIterable {

return try File(path: filePath, using: fileManager)
}

/**
* Either return an existing file, or create a new one, for a given name
*
* - parameter fileName: The name of the file to either get or create
* - parameter dataExpression: An expression resulting in any data that a new file should contain.
* Will only be evaluated & used in case a new file is created.
*
* - throws: `File.Error.writeFailed` if the file couldn't be created
*/
public func createFileIfNeeded(withName fileName: String, contents dataExpression: @autoclosure () -> Data = .init()) throws -> File {
if let existingFile = try? file(named: fileName) {
return existingFile
}

return try createFile(named: fileName, contents: dataExpression())
}

/**
* Create a subfolder of this folder and return it
Expand Down
9 changes: 9 additions & 0 deletions Tests/FilesTests/FilesTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -408,6 +408,15 @@ class FilesTests: XCTestCase {
}
}

func testCreateFileIfNeeded() {
performTest {
let fileA = try folder.createFileIfNeeded(withName: "file", contents: "Hello".data(using: .utf8)!)
let fileB = try folder.createFileIfNeeded(withName: "file", contents: "World".data(using: .utf8)!)
try XCTAssertEqual(fileA.readAsString(), "Hello")
try XCTAssertEqual(fileA.read(), fileB.read())
}
}

func testCreateFolderIfNeeded() {
performTest {
let subfolderA = try FileSystem().createFolderIfNeeded(at: folder.path + "one/two/three")
Expand Down

0 comments on commit 883ffed

Please sign in to comment.