From cf1b97a080e6698d11200426018c5478d3858f75 Mon Sep 17 00:00:00 2001 From: Artem Novichkov Date: Sat, 9 Sep 2017 15:24:42 +0600 Subject: [PATCH] Add copy function for item Related to #22 --- Sources/Files.swift | 37 +++++++++++++++++++++++++++++++ Tests/FilesTests/FilesTests.swift | 13 +++++++++++ 2 files changed, 50 insertions(+) diff --git a/Sources/Files.swift b/Sources/Files.swift index 532c832..5664cf8 100644 --- a/Sources/Files.swift +++ b/Sources/Files.swift @@ -89,6 +89,8 @@ public class FileSystem { case renameFailed(Item) /// Thrown when a file or folder couldn't be moved (contains the item) case moveFailed(Item) + /// Thrown when a file or folder couldn't be copied (contains the item) + case copyFailed(Item) /// Thrown when a file or folder couldn't be deleted (contains the item) case deleteFailed(Item) @@ -101,6 +103,8 @@ public class FileSystem { return itemA == itemB case .moveFailed(_): return false + case .copyFailed(_): + return false case .deleteFailed(_): return false } @@ -110,6 +114,19 @@ public class FileSystem { return false case .moveFailed(let itemB): return itemA == itemB + case .copyFailed(_): + return false + case .deleteFailed(_): + return false + } + case .copyFailed(let itemA): + switch rhs { + case .renameFailed(_): + return false + case .moveFailed(_): + return false + case .copyFailed(let itemB): + return itemA == itemB case .deleteFailed(_): return false } @@ -119,6 +136,8 @@ public class FileSystem { return false case .moveFailed(_): return false + case .copyFailed(_): + return false case .deleteFailed(let itemB): return itemA == itemB } @@ -264,6 +283,24 @@ public class FileSystem { } } + /** + * Copy this item to a new folder + * + * - parameter folder: The folder that the item should be copy to + * + * - throws: `FileSystem.Item.OperationError.copyFailed` if the item couldn't be copied + */ + public func copy(to folder: Folder) throws { + let newPath = folder.path + name + + do { + try fileManager.copyItem(atPath: path, toPath: newPath) + path = newPath + } catch { + throw OperationError.copyFailed(self) + } + } + /** * Delete the item from disk * diff --git a/Tests/FilesTests/FilesTests.swift b/Tests/FilesTests/FilesTests.swift index 909ae22..318afdd 100644 --- a/Tests/FilesTests/FilesTests.swift +++ b/Tests/FilesTests/FilesTests.swift @@ -260,6 +260,19 @@ class FilesTests: XCTestCase { } } + func testCopyingFiles() { + performTest { + let file = try folder.createFile(named: "A") + + let subfolder = try folder.createSubfolder(named: "folder") + try file.copy(to: subfolder) + try XCTAssertNotNil(folder.file(named: "A")) + try XCTAssertNotNil(subfolder.file(named: "A")) + try XCTAssertEqual(file.read(), subfolder.file(named: "A").read()) + XCTAssertEqual(folder.files.count, 1) + } + } + func testEnumeratingFiles() { performTest { try folder.createFile(named: "1")