From 2626a3c18dc8a790dc824967d110b31c86a4f4cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20Zaja=CC=A8c?= Date: Mon, 29 May 2017 17:02:55 +0200 Subject: [PATCH] Method for creaating file if needed from FileSystem --- Sources/Files.swift | 18 ++++++++++++++++++ Tests/FilesTests/FilesTests.swift | 13 +++++++++++++ 2 files changed, 31 insertions(+) diff --git a/Sources/Files.swift b/Sources/Files.swift index ed2fb8c..c2b7133 100644 --- a/Sources/Files.swift +++ b/Sources/Files.swift @@ -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 * diff --git a/Tests/FilesTests/FilesTests.swift b/Tests/FilesTests/FilesTests.swift index 0b7a183..04af624 100644 --- a/Tests/FilesTests/FilesTests.swift +++ b/Tests/FilesTests/FilesTests.swift @@ -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"