Skip to content

Commit

Permalink
Method for creaating file if needed from FileSystem
Browse files Browse the repository at this point in the history
  • Loading branch information
cojoj committed May 29, 2017
1 parent 928e4b9 commit 2626a3c
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
18 changes: 18 additions & 0 deletions Sources/Files.swift
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,24 @@ public class FileSystem {
}
}

/**
* Either return an existing file, or create a new one, at a given path.
*
* - parameter path: The path for which a file should either be returned or created at. If the folder
* is missing, any intermediate parent folders will also be created.
*
* - throws: `File.Error.writeFailed`
*
* - returns: The file that was either created or found.
*/
@discardableResult public func createFileIfNeeded(at path: String, contents: Data = Data()) throws -> File {
if let existingFile = try? File(path: path, using: fileManager) {
return existingFile
}

return try createFile(at: path, contents: contents)
}

/**
* Create a new folder at a given path
*
Expand Down
13 changes: 13 additions & 0 deletions Tests/FilesTests/FilesTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -459,6 +459,19 @@ class FilesTests: XCTestCase {
}
}

func testCreateFileFromFileSystemIfNeeded() {
performTest {
let path = folder.path + "one/two/three/file"
let contentA = "Hello".data(using: .utf8)!
let contentB = "World".data(using: .utf8)!
let fileA = try FileSystem().createFileIfNeeded(at: path, contents: contentA)
let fileB = try FileSystem().createFileIfNeeded(at: path, contents: contentB)

try XCTAssertEqual(fileA.readAsString(), "Hello")
try XCTAssertEqual(fileA.read(), fileB.read())
}
}

func testCreatingFolderFromFileSystem() {
performTest {
let folderPath = folder.path + "one/two/three"
Expand Down

0 comments on commit 2626a3c

Please sign in to comment.