forked from JohnSundell/Files
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Files.swift
1159 lines (1003 loc) · 40.9 KB
/
Files.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Files
*
* Copyright (c) 2017 John Sundell. Licensed under the MIT license, as follows:
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import Foundation
// MARK: - Public API
/**
* Class that represents a file system
*
* You only have to interact with this class in case you want to get a reference
* to a system folder (like the temporary cache folder, or the user's home folder).
*
* To open other files & folders, use the `File` and `Folder` class respectively.
*/
public class FileSystem {
fileprivate let fileManager: FileManager
/**
* Class that represents an item that's stored by a file system
*
* This is an abstract base class, that has two publically initializable concrete
* implementations, `File` and `Folder`. You can use the APIs available on this class
* to perform operations that are supported by both files & folders.
*/
public class Item: Equatable, CustomStringConvertible {
#if os(macOS)
/// The attributes of the `FileSystem.Item` on mac os platform.
public typealias Attributes = [FileAttributeKey: Any]
#endif
/// Errror type used for invalid paths for files or folders
public enum PathError: Error, Equatable, CustomStringConvertible {
/// Thrown when an empty path was given when initializing a file
case empty
/// Thrown when an item of the expected type wasn't found for a given path (contains the path)
case invalid(String)
/// Operator used to compare two instances for equality
public static func ==(lhs: PathError, rhs: PathError) -> Bool {
switch lhs {
case .empty:
switch rhs {
case .empty:
return true
case .invalid(_):
return false
}
case .invalid(let pathA):
switch rhs {
case .empty:
return false
case .invalid(let pathB):
return pathA == pathB
}
}
}
/// A string describing the error
public var description: String {
switch self {
case .empty:
return "Empty path given"
case .invalid(let path):
return "Invalid path given: \(path)"
}
}
}
/// Error type used for failed operations run on files or folders
public enum OperationError: Error, Equatable, CustomStringConvertible {
/// Thrown when a file or folder couldn't be renamed (contains the item)
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)
/// Operator used to compare two instances for equality
public static func ==(lhs: OperationError, rhs: OperationError) -> Bool {
switch lhs {
case .renameFailed(let itemA):
switch rhs {
case .renameFailed(let itemB):
return itemA == itemB
case .moveFailed(_):
return false
case .copyFailed(_):
return false
case .deleteFailed(_):
return false
}
case .moveFailed(let itemA):
switch rhs {
case .renameFailed(_):
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
}
case .deleteFailed(let itemA):
switch rhs {
case .renameFailed(_):
return false
case .moveFailed(_):
return false
case .copyFailed(_):
return false
case .deleteFailed(let itemB):
return itemA == itemB
}
}
}
/// A string describing the error
public var description: String {
switch self {
case .renameFailed(let item):
return "Failed to rename item: \(item)"
case .moveFailed(let item):
return "Failed to move item: \(item)"
case .copyFailed(let item):
return "Failed to copy item: \(item)"
case .deleteFailed(let item):
return "Failed to delete item: \(item)"
}
}
}
/// Operator used to compare two instances for equality
public static func ==(lhs: Item, rhs: Item) -> Bool {
guard lhs.kind == rhs.kind else {
return false
}
return lhs.path == rhs.path
}
/// The path of the item, relative to the root of the file system
public private(set) var path: String
/// The name of the item (including any extension)
public private(set) var name: String
/// The name of the item (excluding any extension)
public var nameExcludingExtension: String {
guard let `extension` = `extension` else {
return name
}
let endIndex = name.index(name.endIndex, offsetBy: -`extension`.count - 1)
return String(name[..<endIndex])
}
/// Any extension that the item has
public var `extension`: String? {
let components = name.components(separatedBy: ".")
guard components.count > 1 else {
return nil
}
return components.last
}
/// The date when the item was last modified
public private(set) lazy var modificationDate: Date = self.loadModificationDate()
/// The folder that the item is contained in, or `nil` if this item is the root folder of the file system
public var parent: Folder? {
return fileManager.parentPath(for: path).flatMap { parentPath in
return try? Folder(path: parentPath, using: fileManager)
}
}
/// A string describing the item
public var description: String {
return "\(kind)(name: \(name), path: \(path))"
}
fileprivate let kind: Kind
fileprivate let fileManager: FileManager
#if os(macOS)
/// The file attributes of the item on file system.
@available(macOS 10.5, *)
public var attributes: Attributes? {
get {
return try? fileManager.attributesOfItem(atPath: path)
}
set {
try? fileManager.setAttributes(newValue ?? [:], ofItemAtPath: path)
}
}
#endif
fileprivate init(path: String, kind: Kind, using fileManager: FileManager) throws {
guard !path.isEmpty else {
throw PathError.empty
}
let path = try fileManager.absolutePath(for: path)
guard fileManager.itemKind(atPath: path) == kind else {
throw PathError.invalid(path)
}
self.path = path
self.fileManager = fileManager
self.kind = kind
let pathComponents = path.pathComponents
switch kind {
case .file:
self.name = pathComponents.last!
case .folder:
self.name = pathComponents[pathComponents.count - 2]
}
}
/**
* Rename the item
*
* - parameter newName: The new name that the item should have
* - parameter keepExtension: Whether the file should keep the same extension as it had before (defaults to `true`)
*
* - throws: `FileSystem.Item.OperationError.renameFailed` if the item couldn't be renamed
*/
public func rename(to newName: String, keepExtension: Bool = true) throws {
guard let parent = parent else {
throw OperationError.renameFailed(self)
}
var newName = newName
if keepExtension {
if let `extension` = `extension` {
let extensionString = ".\(`extension`)"
if !newName.hasSuffix(extensionString) {
newName += extensionString
}
}
}
var newPath = parent.path + newName
if kind == .folder && !newPath.hasSuffix("/") {
newPath += "/"
}
do {
try fileManager.moveItem(atPath: path, toPath: newPath)
name = newName
path = newPath
} catch {
throw OperationError.renameFailed(self)
}
}
/**
* Move this item to a new folder
*
* - parameter newParent: The new parent folder that the item should be moved to
*
* - throws: `FileSystem.Item.OperationError.moveFailed` if the item couldn't be moved
*/
public func move(to newParent: Folder) throws {
var newPath = newParent.path + name
if kind == .folder && !newPath.hasSuffix("/") {
newPath += "/"
}
do {
try fileManager.moveItem(atPath: path, toPath: newPath)
path = newPath
} catch {
throw OperationError.moveFailed(self)
}
}
/**
* Delete the item from disk
*
* The item will be immediately deleted. If this is a folder, all of its contents will also be deleted.
*
* - throws: `FileSystem.Item.OperationError.deleteFailed` if the item coudn't be deleted
*/
public func delete() throws {
do {
try fileManager.removeItem(atPath: path)
} catch {
throw OperationError.deleteFailed(self)
}
}
}
/// A reference to the temporary folder used by this file system
public var temporaryFolder: Folder {
return try! Folder(path: NSTemporaryDirectory(), using: fileManager)
}
/// A reference to the current user's home folder
public var homeFolder: Folder {
return try! Folder(path: ProcessInfo.processInfo.homeFolderPath, using: fileManager)
}
// A reference to the folder that is the current working directory
public var currentFolder: Folder {
return try! Folder(path: "")
}
/**
* Initialize an instance of this class
*
* - parameter fileManager: Optionally give a custom file manager to use to perform operations
*/
public init(using fileManager: FileManager = .default) {
self.fileManager = fileManager
}
/**
* Create a new file at a given path
*
* - parameter path: The path at which a file should be created. If the path is missing intermediate
* parent folders, those will be created as well.
*
* - throws: `File.Error.writeFailed`
*
* - returns: The file that was created
*/
@discardableResult public func createFile(at path: String, contents: Data = Data()) throws -> File {
let path = try fileManager.absolutePath(for: path)
guard let parentPath = fileManager.parentPath(for: path) else {
throw File.Error.writeFailed
}
do {
let index = path.index(path.startIndex, offsetBy: parentPath.count + 1)
let name = String(path[index...])
return try createFolder(at: parentPath).createFile(named: name, contents: contents)
} catch {
throw File.Error.writeFailed
}
}
/**
* 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
*
* - parameter path: The path at which a folder should be created. If the path is missing intermediate
* parent folders, those will be created as well.
*
* - throws: `Folder.Error.creatingFolderFailed`
*
* - returns: The folder that was created
*/
@discardableResult public func createFolder(at path: String) throws -> Folder {
do {
let path = try fileManager.absolutePath(for: path)
try fileManager.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
return try Folder(path: path, using: fileManager)
} catch {
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`
*/
@discardableResult public func createFolderIfNeeded(at path: String) throws -> Folder {
if let existingFolder = try? Folder(path: path, using: fileManager) {
return existingFolder
}
return try createFolder(at: path)
}
}
/**
* Class representing a file that's stored by a file system
*
* You initialize this class with a path, or by asking a folder to return a file for a given name
*/
public final class File: FileSystem.Item, FileSystemIterable {
/// Error type specific to file-related operations
public enum Error: Swift.Error, CustomStringConvertible {
/// Thrown when a file couldn't be written to
case writeFailed
/// Thrown when a file couldn't be read, either because it was malformed or because it has been deleted
case readFailed
/// A string describing the error
public var description: String {
switch self {
case .writeFailed:
return "Failed to write to file"
case .readFailed:
return "Failed to read file"
}
}
}
/**
* Initialize an instance of this class with a path pointing to a file
*
* - parameter path: The path of the file to create a representation of
* - parameter fileManager: Optionally give a custom file manager to use to look up the file
*
* - throws: `FileSystemItem.Error` in case an empty path was given, or if the path given doesn't
* point to a readable file.
*/
public init(path: String, using fileManager: FileManager = .default) throws {
try super.init(path: path, kind: .file, using: fileManager)
}
/**
* Read the data contained within this file
*
* - throws: `File.Error.readFailed` if the file's data couldn't be read
*/
public func read() throws -> Data {
do {
return try Data(contentsOf: URL(fileURLWithPath: path))
} catch {
throw Error.readFailed
}
}
/**
* Read the data contained within this file, and convert it to a string
*
* - throws: `File.Error.readFailed` if the file's data couldn't be read as a string
*/
public func readAsString(encoding: String.Encoding = .utf8) throws -> String {
guard let string = try String(data: read(), encoding: encoding) else {
throw Error.readFailed
}
return string
}
/**
* Read the data contained within this file, and convert it to an int
*
* - throws: `File.Error.readFailed` if the file's data couldn't be read as an int
*/
public func readAsInt() throws -> Int {
guard let int = try Int(readAsString()) else {
throw Error.readFailed
}
return int
}
/**
* Write data to the file, replacing its current content
*
* - parameter data: The data to write to the file
*
* - throws: `File.Error.writeFailed` if the file couldn't be written to
*/
public func write(data: Data) throws {
do {
try data.write(to: URL(fileURLWithPath: path))
} catch {
throw Error.writeFailed
}
}
/**
* Write a string to the file, replacing its current content
*
* - parameter string: The string to write to the file
* - parameter encoding: Optionally give which encoding that the string should be encoded in (defaults to UTF-8)
*
* - throws: `File.Error.writeFailed` if the string couldn't be encoded, or written to the file
*/
public func write(string: String, encoding: String.Encoding = .utf8) throws {
guard let data = string.data(using: encoding) else {
throw Error.writeFailed
}
try write(data: data)
}
/**
* Append data to the end of the file
*
* - parameter data: The data to append to the file
*
* - throws: `File.Error.writeFailed` if the file couldn't be written to
*/
public func append(data: Data) throws {
do {
let handle = try FileHandle(forWritingTo: URL(fileURLWithPath: path))
handle.seekToEndOfFile()
handle.write(data)
handle.closeFile()
} catch {
throw Error.writeFailed
}
}
/**
* Append a string to the end of the file
*
* - parameter string: The string to append to the file
* - parameter encoding: Optionally give which encoding that the string should be encoded in (defaults to UTF-8)
*
* - throws: `File.Error.writeFailed` if the string couldn't be encoded, or written to the file
*/
public func append(string: String, encoding: String.Encoding = .utf8) throws {
guard let data = string.data(using: encoding) else {
throw Error.writeFailed
}
try append(data: data)
}
/**
* Copy this file to a new folder
*
* - parameter folder: The folder that the file should be copy to
*
* - throws: `FileSystem.Item.OperationError.copyFailed` if the file couldn't be copied
*/
@discardableResult public func copy(to folder: Folder) throws -> File {
let newPath = folder.path + name
do {
try fileManager.copyItem(atPath: path, toPath: newPath)
return try File(path: newPath)
} catch {
throw OperationError.copyFailed(self)
}
}
}
/**
* Class representing a folder that's stored by a file system
*
* You initialize this class with a path, or by asking a folder to return a subfolder for a given name
*/
public final class Folder: FileSystem.Item, FileSystemIterable {
/// Error type specific to folder-related operations
public enum Error: Swift.Error, CustomStringConvertible {
/// Thrown when a folder couldn't be created
case creatingFolderFailed
@available(*, deprecated: 1.4.0, renamed: "creatingFolderFailed")
case creatingSubfolderFailed
/// A string describing the error
public var description: String {
switch self {
case .creatingFolderFailed:
return "Failed to create folder"
case .creatingSubfolderFailed:
return "Failed to create subfolder"
}
}
}
/// The sequence of files that are contained within this folder (non-recursive)
public var files: FileSystemSequence<File> {
return makeFileSequence()
}
/// The sequence of folders that are subfolers of this folder (non-recursive)
public var subfolders: FileSystemSequence<Folder> {
return makeSubfolderSequence()
}
/// A reference to the folder that is the current working directory
public static var current: Folder {
return FileSystem(using: .default).currentFolder
}
/// A reference to the current user's home folder
public static var home: Folder {
return FileSystem(using: .default).homeFolder
}
/// A reference to the temporary folder used by this file system
public static var temporary: Folder {
return FileSystem(using: .default).temporaryFolder
}
/**
* Initialize an instance of this class with a path pointing to a folder
*
* - parameter path: The path of the folder to create a representation of
* - parameter fileManager: Optionally give a custom file manager to use to look up the folder
*
* - throws: `FileSystemItem.Error` in case an empty path was given, or if the path given doesn't
* point to a readable folder.
*/
public init(path: String, using fileManager: FileManager = .default) throws {
var path = path
if path.isEmpty {
path = fileManager.currentDirectoryPath
}
if !path.hasSuffix("/") {
path += "/"
}
try super.init(path: path, kind: .folder, using: fileManager)
}
/**
* Return a file with a given name that is contained in this folder
*
* - parameter fileName: The name of the file to return
*
* - throws: `File.PathError.invalid` if the file couldn't be found
*/
public func file(named fileName: String) throws -> File {
return try File(path: path + fileName, using: fileManager)
}
/**
* Return a file at a given path that is contained in this folder's tree
*
* - parameter filePath: The subpath of the file to return. Relative to this folder.
*
* - throws: `File.PathError.invalid` if the file couldn't be found
*/
public func file(atPath filePath: String) throws -> File {
return try File(path: path + filePath, using: fileManager)
}
/**
* Return whether this folder contains a file with a given name
*
* - parameter fileName: The name of the file to check for
*/
public func containsFile(named fileName: String) -> Bool {
return (try? file(named: fileName)) != nil
}
/**
* Return a folder with a given name that is contained in this folder
*
* - parameter folderName: The name of the folder to return
*
* - throws: `Folder.PathError.invalid` if the folder couldn't be found
*/
public func subfolder(named folderName: String) throws -> Folder {
return try Folder(path: path + folderName, using: fileManager)
}
/**
* Return a folder at a given path that is contained in this folder's tree
*
* - parameter folderPath: The subpath of the folder to return. Relative to this folder.
*
* - throws: `Folder.PathError.invalid` if the folder couldn't be found
*/
public func subfolder(atPath folderPath: String) throws -> Folder {
return try Folder(path: path + folderPath, using: fileManager)
}
/**
* Return whether this folder contains a subfolder with a given name
*
* - parameter folderName: The name of the folder to check for
*/
public func containsSubfolder(named folderName: String) -> Bool {
return (try? subfolder(named: folderName)) != nil
}
/**
* Create a file in this folder and return it
*
* - parameter fileName: The name of the file to create
* - parameter data: Optionally give any data that the file should contain
*
* - throws: `File.Error.writeFailed` if the file couldn't be created
*
* - returns: The file that was created
*/
@discardableResult public func createFile(named fileName: String, contents data: Data = .init()) throws -> File {
let filePath = path + fileName
guard fileManager.createFile(atPath: filePath, contents: data, attributes: nil) else {
throw File.Error.writeFailed
}
return try File(path: filePath, using: fileManager)
}
/**
* Create a file in this folder and return it
*
* - parameter fileName: The name of the file to create
* - parameter contents: The string content that the file should contain
* - parameter encoding: The encoding that the given string content should be encoded with
*
* - throws: `File.Error.writeFailed` if the file couldn't be created
*
* - returns: The file that was created
*/
@discardableResult public func createFile(named fileName: String, contents: String, encoding: String.Encoding = .utf8) throws -> File {
let file = try createFile(named: fileName)
try file.write(string: contents, encoding: encoding)
return file
}
/**
* 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
*/
@discardableResult 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
*
* - parameter folderName: The name of the folder to create
*
* - throws: `Folder.Error.creatingFolderFailed` if the subfolder couldn't be created
*
* - returns: The folder that was created
*/
@discardableResult public func createSubfolder(named folderName: String) throws -> Folder {
let subfolderPath = path + folderName
do {
try fileManager.createDirectory(atPath: subfolderPath, withIntermediateDirectories: false, attributes: nil)
return try Folder(path: subfolderPath, using: fileManager)
} catch {
throw Error.creatingFolderFailed
}
}
/**
* Either return an existing subfolder, or create a new one, for a given name
*
* - parameter folderName: The name of the folder to either get or create
*
* - throws: `Folder.Error.creatingFolderFailed`
*/
@discardableResult public func createSubfolderIfNeeded(withName folderName: String) throws -> Folder {
if let existingFolder = try? subfolder(named: folderName) {
return existingFolder
}
return try createSubfolder(named: folderName)
}
/**
* Create a sequence containing the files that are contained within this folder
*
* - parameter recursive: Whether the files contained in all subfolders of this folder should also be included
* - parameter includeHidden: Whether hidden (dot) files should be included in the sequence (default: false)
*
* If `recursive = true` the folder tree will be traversed depth-first
*/
public func makeFileSequence(recursive: Bool = false, includeHidden: Bool = false) -> FileSystemSequence<File> {
return FileSystemSequence(folder: self, recursive: recursive, includeHidden: includeHidden, using: fileManager)
}
/**
* Create a sequence containing the folders that are subfolders of this folder
*
* - parameter recursive: Whether the entire folder tree contained under this folder should also be included
* - parameter includeHidden: Whether hidden (dot) files should be included in the sequence (default: false)
*
* If `recursive = true` the folder tree will be traversed depth-first
*/
public func makeSubfolderSequence(recursive: Bool = false, includeHidden: Bool = false) -> FileSystemSequence<Folder> {
return FileSystemSequence(folder: self, recursive: recursive, includeHidden: includeHidden, using: fileManager)
}
/**
* Move the contents (both files and subfolders) of this folder to a new parent folder
*
* - parameter newParent: The new parent folder that the contents of this folder should be moved to
* - parameter includeHidden: Whether hidden (dot) files should be moved (default: false)
*/
public func moveContents(to newParent: Folder, includeHidden: Bool = false) throws {
try makeFileSequence(includeHidden: includeHidden).forEach { try $0.move(to: newParent) }
try makeSubfolderSequence(includeHidden: includeHidden).forEach { try $0.move(to: newParent) }
}
/**
* Empty this folder, removing all of its content
*
* - parameter includeHidden: Whether hidden files (dot) files contained within the folder should also be removed
*
* This will still keep the folder itself on disk. If you wish to delete the folder as well, call `delete()` on it.
*/
public func empty(includeHidden: Bool = false) throws {
try makeFileSequence(includeHidden: includeHidden).forEach { try $0.delete() }
try makeSubfolderSequence(includeHidden: includeHidden).forEach { try $0.delete() }
}
/**
* Copy this folder to a new folder
*
* - parameter folder: The folder that the folder should be copy to
*
* - throws: `FileSystem.Item.OperationError.copyFailed` if the folder couldn't be copied
*/
@discardableResult public func copy(to folder: Folder) throws -> Folder {
let newPath = folder.path + name
do {
try fileManager.copyItem(atPath: path, toPath: newPath)
return try Folder(path: newPath)
} catch {
throw OperationError.copyFailed(self)
}
}
}
/// Protocol adopted by file system types that may be iterated over (this protocol is an implementation detail)
public protocol FileSystemIterable {
/// Initialize an instance with a path and a file manager
init(path: String, using fileManager: FileManager) throws
}
/**
* A sequence used to iterate over file system items
*
* You don't create instances of this class yourself. Instead, you can access various sequences on a `Folder`, for example
* containing its files and subfolders. The sequence is lazily evaluated when you perform operations on it.
*/
public class FileSystemSequence<T: FileSystem.Item>: Sequence, CustomStringConvertible where T: FileSystemIterable {
/// The number of items contained in this sequence. Accessing this causes the sequence to be evaluated.
public var count: Int {
var count = 0
forEach { _ in count += 1 }
return count
}
/// An array containing the names of all the items contained in this sequence. Accessing this causes the sequence to be evaluated.
public var names: [String] {
return map { $0.name }
}
/// The first item of the sequence. Accessing this causes the sequence to be evaluated until an item is found
public var first: T? {
return makeIterator().next()
}
/// The last item of the sequence. Accessing this causes the sequence to be evaluated.
public var last: T? {
var item: T?
forEach { item = $0 }
return item
}
private let folder: Folder
private let recursive: Bool
private let includeHidden: Bool
private let fileManager: FileManager
fileprivate init(folder: Folder, recursive: Bool, includeHidden: Bool, using fileManager: FileManager) {
self.folder = folder
self.recursive = recursive
self.includeHidden = includeHidden
self.fileManager = fileManager
}
/// Create an iterator to use to iterate over the sequence
public func makeIterator() -> FileSystemIterator<T> {
return FileSystemIterator(folder: folder, recursive: recursive, includeHidden: includeHidden, using: fileManager)
}
/// Move all the items in this sequence to a new folder. See `FileSystem.Item.move(to:)` for more info.
public func move(to newParent: Folder) throws {
try forEach { try $0.move(to: newParent) }
}
public var description: String {
return map { $0.description }.joined(separator: "\n")
}
}
/// Iterator used to iterate over an instance of `FileSystemSequence`
public class FileSystemIterator<T: FileSystem.Item>: IteratorProtocol where T: FileSystemIterable {
private let folder: Folder
private let recursive: Bool
private let includeHidden: Bool
private let fileManager: FileManager
private lazy var itemNames: [String] = {
self.fileManager.itemNames(inFolderAtPath: self.folder.path)
}()
private lazy var childIteratorQueue = [FileSystemIterator]()
private var currentChildIterator: FileSystemIterator?
fileprivate init(folder: Folder, recursive: Bool, includeHidden: Bool, using fileManager: FileManager) {
self.folder = folder
self.recursive = recursive
self.includeHidden = includeHidden
self.fileManager = fileManager
}
/// Advance the iterator to the next element
public func next() -> T? {
if itemNames.isEmpty {
if let childIterator = currentChildIterator {
if let next = childIterator.next() {
return next
}
}
guard !childIteratorQueue.isEmpty else {
return nil
}
currentChildIterator = childIteratorQueue.removeFirst()
return next()
}
let nextItemName = itemNames.removeFirst()
guard includeHidden || !nextItemName.hasPrefix(".") else {
return next()
}
let nextItemPath = folder.path + nextItemName
let nextItem = try? T(path: nextItemPath, using: fileManager)