-
Notifications
You must be signed in to change notification settings - Fork 125
/
Copy pathFileSystem.swift
927 lines (773 loc) · 31.6 KB
/
FileSystem.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
/*
This source file is part of the Swift.org open source project
Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import TSCLibc
import Foundation
public enum FileSystemError: Swift.Error {
/// Access to the path is denied.
///
/// This is used when an operation cannot be completed because a component of
/// the path cannot be accessed.
///
/// Used in situations that correspond to the POSIX EACCES error code.
case invalidAccess
/// IO Error encoding
///
/// This is used when an operation cannot be completed due to an otherwise
/// unspecified IO error.
case ioError
/// Is a directory
///
/// This is used when an operation cannot be completed because a component
/// of the path which was expected to be a file was not.
///
/// Used in situations that correspond to the POSIX EISDIR error code.
case isDirectory
/// No such path exists.
///
/// This is used when a path specified does not exist, but it was expected
/// to.
///
/// Used in situations that correspond to the POSIX ENOENT error code.
case noEntry
/// Not a directory
///
/// This is used when an operation cannot be completed because a component
/// of the path which was expected to be a directory was not.
///
/// Used in situations that correspond to the POSIX ENOTDIR error code.
case notDirectory
/// Unsupported operation
///
/// This is used when an operation is not supported by the concrete file
/// system implementation.
case unsupported
/// An unspecific operating system error.
case unknownOSError
/// File or folder already exists at destination.
///
/// This is thrown when copying or moving a file or directory but the destination
/// path already contains a file or folder.
case alreadyExistsAtDestination
}
public extension FileSystemError {
init(errno: Int32) {
switch errno {
case TSCLibc.EACCES:
self = .invalidAccess
case TSCLibc.EISDIR:
self = .isDirectory
case TSCLibc.ENOENT:
self = .noEntry
case TSCLibc.ENOTDIR:
self = .notDirectory
default:
self = .unknownOSError
}
}
}
/// Defines the file modes.
public enum FileMode {
public enum Option: Int {
case recursive
case onlyFiles
}
case userUnWritable
case userWritable
case executable
internal var setMode: (Int16) -> Int16 {
switch self {
case .userUnWritable:
// r-x rwx rwx
return {$0 & 0o577}
case .userWritable:
// -w- --- ---
return {$0 | 0o200}
case .executable:
// --x --x --x
return {$0 | 0o111}
}
}
}
// FIXME: Design an asynchronous story?
//
/// Abstracted access to file system operations.
///
/// This protocol is used to allow most of the codebase to interact with a
/// natural filesystem interface, while still allowing clients to transparently
/// substitute a virtual file system or redirect file system operations.
///
/// - Note: All of these APIs are synchronous and can block.
public protocol FileSystem: class {
/// Check whether the given path exists and is accessible.
func exists(_ path: AbsolutePath, followSymlink: Bool) -> Bool
/// Check whether the given path is accessible and a directory.
func isDirectory(_ path: AbsolutePath) -> Bool
/// Check whether the given path is accessible and a file.
func isFile(_ path: AbsolutePath) -> Bool
/// Check whether the given path is an accessible and executable file.
func isExecutableFile(_ path: AbsolutePath) -> Bool
/// Check whether the given path is accessible and is a symbolic link.
func isSymlink(_ path: AbsolutePath) -> Bool
// FIXME: Actual file system interfaces will allow more efficient access to
// more data than just the name here.
//
/// Get the contents of the given directory, in an undefined order.
func getDirectoryContents(_ path: AbsolutePath) throws -> [String]
/// Get the current working directory (similar to `getcwd(3)`), which can be
/// different for different (virtualized) implementations of a FileSystem.
/// The current working directory can be empty if e.g. the directory became
/// unavailable while the current process was still working in it.
/// This follows the POSIX `getcwd(3)` semantics.
var currentWorkingDirectory: AbsolutePath? { get }
/// Change the current working directory.
/// - Parameters:
/// - path: The path to the directory to change the current working directory to.
func changeCurrentWorkingDirectory(to path: AbsolutePath) throws
/// Get the home directory of current user
var homeDirectory: AbsolutePath { get }
/// Create the given directory.
func createDirectory(_ path: AbsolutePath) throws
/// Create the given directory.
///
/// - recursive: If true, create missing parent directories if possible.
func createDirectory(_ path: AbsolutePath, recursive: Bool) throws
// FIXME: This is obviously not a very efficient or flexible API.
//
/// Get the contents of a file.
///
/// - Returns: The file contents as bytes, or nil if missing.
func readFileContents(_ path: AbsolutePath) throws -> ByteString
// FIXME: This is obviously not a very efficient or flexible API.
//
/// Write the contents of a file.
func writeFileContents(_ path: AbsolutePath, bytes: ByteString) throws
// FIXME: This is obviously not a very efficient or flexible API.
//
/// Write the contents of a file.
func writeFileContents(_ path: AbsolutePath, bytes: ByteString, atomically: Bool) throws
/// Recursively deletes the file system entity at `path`.
///
/// If there is no file system entity at `path`, this function does nothing (in particular, this is not considered
/// to be an error).
func removeFileTree(_ path: AbsolutePath) throws
/// Change file mode.
func chmod(_ mode: FileMode, path: AbsolutePath, options: Set<FileMode.Option>) throws
/// Returns the file info of the given path.
///
/// The method throws if the underlying stat call fails.
func getFileInfo(_ path: AbsolutePath) throws -> FileInfo
/// Copy a file or directory.
func copy(from sourcePath: AbsolutePath, to destinationPath: AbsolutePath) throws
/// Move a file or directory.
func move(from sourcePath: AbsolutePath, to destinationPath: AbsolutePath) throws
}
/// Convenience implementations (default arguments aren't permitted in protocol
/// methods).
public extension FileSystem {
/// exists override with default value.
func exists(_ path: AbsolutePath) -> Bool {
return exists(path, followSymlink: true)
}
/// Default implementation of createDirectory(_:)
func createDirectory(_ path: AbsolutePath) throws {
try createDirectory(path, recursive: false)
}
// Change file mode.
func chmod(_ mode: FileMode, path: AbsolutePath) throws {
try chmod(mode, path: path, options: [])
}
// Unless the file system type provides an override for this method, throw
// if `atomically` is `true`, otherwise fall back to whatever implementation already exists.
func writeFileContents(_ path: AbsolutePath, bytes: ByteString, atomically: Bool) throws {
guard !atomically else {
throw FileSystemError.unsupported
}
try writeFileContents(path, bytes: bytes)
}
/// Write to a file from a stream producer.
func writeFileContents(_ path: AbsolutePath, body: (WritableByteStream) -> Void) throws {
let contents = BufferedOutputByteStream()
body(contents)
try createDirectory(path.parentDirectory, recursive: true)
try writeFileContents(path, bytes: contents.bytes)
}
func getFileInfo(_ path: AbsolutePath) throws -> FileInfo {
throw FileSystemError.unsupported
}
}
/// Concrete FileSystem implementation which communicates with the local file system.
private class LocalFileSystem: FileSystem {
func isExecutableFile(_ path: AbsolutePath) -> Bool {
// Our semantics doesn't consider directories.
return (self.isFile(path) || self.isSymlink(path)) && FileManager.default.isExecutableFile(atPath: path.pathString)
}
func exists(_ path: AbsolutePath, followSymlink: Bool) -> Bool {
if followSymlink {
return FileManager.default.fileExists(atPath: path.pathString)
}
return (try? FileManager.default.attributesOfItem(atPath: path.pathString)) != nil
}
func isDirectory(_ path: AbsolutePath) -> Bool {
var isDirectory: ObjCBool = false
let exists: Bool = FileManager.default.fileExists(atPath: path.pathString, isDirectory: &isDirectory)
return exists && isDirectory.boolValue
}
func isFile(_ path: AbsolutePath) -> Bool {
let path = resolveSymlinks(path)
let attrs = try? FileManager.default.attributesOfItem(atPath: path.pathString)
return attrs?[.type] as? FileAttributeType == .typeRegular
}
func isSymlink(_ path: AbsolutePath) -> Bool {
let attrs = try? FileManager.default.attributesOfItem(atPath: path.pathString)
return attrs?[.type] as? FileAttributeType == .typeSymbolicLink
}
func getFileInfo(_ path: AbsolutePath) throws -> FileInfo {
let attrs = try FileManager.default.attributesOfItem(atPath: path.pathString)
return FileInfo(attrs)
}
var currentWorkingDirectory: AbsolutePath? {
let cwdStr = FileManager.default.currentDirectoryPath
#if _runtime(_ObjC)
// The ObjC runtime indicates that the underlying Foundation has ObjC
// interoperability in which case the return type of
// `fileSystemRepresentation` is different from the Swift implementation
// of Foundation.
return try? AbsolutePath(validating: cwdStr)
#else
let fsr: UnsafePointer<Int8> = cwdStr.fileSystemRepresentation
defer { fsr.deallocate() }
return try? AbsolutePath(validating: String(cString: fsr))
#endif
}
func changeCurrentWorkingDirectory(to path: AbsolutePath) throws {
guard isDirectory(path) else {
throw FileSystemError.notDirectory
}
guard FileManager.default.changeCurrentDirectoryPath(path.pathString) else {
throw FileSystemError.unknownOSError
}
}
var homeDirectory: AbsolutePath {
return AbsolutePath(NSHomeDirectory())
}
func getDirectoryContents(_ path: AbsolutePath) throws -> [String] {
#if canImport(Darwin)
return try FileManager.default.contentsOfDirectory(atPath: path.pathString)
#else
do {
return try FileManager.default.contentsOfDirectory(atPath: path.pathString)
} catch let error as NSError {
// Fixup error from corelibs-foundation.
if error.code == CocoaError.fileReadNoSuchFile.rawValue, !error.userInfo.keys.contains(NSLocalizedDescriptionKey) {
var userInfo = error.userInfo
userInfo[NSLocalizedDescriptionKey] = "The folder “\(path.basename)” doesn’t exist."
throw NSError(domain: error.domain, code: error.code, userInfo: userInfo)
}
throw error
}
#endif
}
func createDirectory(_ path: AbsolutePath, recursive: Bool) throws {
// Don't fail if path is already a directory.
if isDirectory(path) { return }
try FileManager.default.createDirectory(atPath: path.pathString, withIntermediateDirectories: recursive, attributes: [:])
}
func readFileContents(_ path: AbsolutePath) throws -> ByteString {
// Open the file.
let fp = fopen(path.pathString, "rb")
if fp == nil {
throw FileSystemError(errno: errno)
}
defer { fclose(fp) }
// Read the data one block at a time.
let data = BufferedOutputByteStream()
var tmpBuffer = [UInt8](repeating: 0, count: 1 << 12)
while true {
let n = fread(&tmpBuffer, 1, tmpBuffer.count, fp)
if n < 0 {
if errno == EINTR { continue }
throw FileSystemError.ioError
}
if n == 0 {
if ferror(fp) != 0 {
throw FileSystemError.ioError
}
break
}
data <<< tmpBuffer[0..<n]
}
return data.bytes
}
func writeFileContents(_ path: AbsolutePath, bytes: ByteString) throws {
// Open the file.
let fp = fopen(path.pathString, "wb")
if fp == nil {
throw FileSystemError(errno: errno)
}
defer { fclose(fp) }
// Write the data in one chunk.
var contents = bytes.contents
while true {
let n = fwrite(&contents, 1, contents.count, fp)
if n < 0 {
if errno == EINTR { continue }
throw FileSystemError.ioError
}
if n != contents.count {
throw FileSystemError.ioError
}
break
}
}
func writeFileContents(_ path: AbsolutePath, bytes: ByteString, atomically: Bool) throws {
// Perform non-atomic writes using the fast path.
if !atomically {
return try writeFileContents(path, bytes: bytes)
}
try bytes.withData {
try $0.write(to: URL(fileURLWithPath: path.pathString), options: .atomic)
}
}
func removeFileTree(_ path: AbsolutePath) throws {
if self.exists(path, followSymlink: false) {
try FileManager.default.removeItem(atPath: path.pathString)
}
}
func chmod(_ mode: FileMode, path: AbsolutePath, options: Set<FileMode.Option>) throws {
guard exists(path) else { return }
func setMode(path: String) throws {
let attrs = try FileManager.default.attributesOfItem(atPath: path)
// Skip if only files should be changed.
if options.contains(.onlyFiles) && attrs[.type] as? FileAttributeType != .typeRegular {
return
}
// Compute the new mode for this file.
let currentMode = attrs[.posixPermissions] as! Int16
let newMode = mode.setMode(currentMode)
guard newMode != currentMode else { return }
try FileManager.default.setAttributes([.posixPermissions : newMode],
ofItemAtPath: path)
}
try setMode(path: path.pathString)
guard isDirectory(path) else { return }
guard let traverse = FileManager.default.enumerator(
at: URL(fileURLWithPath: path.pathString),
includingPropertiesForKeys: nil) else {
throw FileSystemError.noEntry
}
if !options.contains(.recursive) {
traverse.skipDescendants()
}
while let path = traverse.nextObject() {
try setMode(path: (path as! URL).path)
}
}
func copy(from sourcePath: AbsolutePath, to destinationPath: AbsolutePath) throws {
guard exists(sourcePath) else { throw FileSystemError.noEntry }
guard !exists(destinationPath) else { throw FileSystemError.alreadyExistsAtDestination }
try FileManager.default.copyItem(at: sourcePath.asURL, to: destinationPath.asURL)
}
func move(from sourcePath: AbsolutePath, to destinationPath: AbsolutePath) throws {
guard exists(sourcePath) else { throw FileSystemError.noEntry }
guard !exists(destinationPath) else { throw FileSystemError.alreadyExistsAtDestination }
try FileManager.default.moveItem(at: sourcePath.asURL, to: destinationPath.asURL)
}
}
// FIXME: This class does not yet support concurrent mutation safely.
//
/// Concrete FileSystem implementation which simulates an empty disk.
public class InMemoryFileSystem: FileSystem {
private class Node {
/// The actual node data.
let contents: NodeContents
init(_ contents: NodeContents) {
self.contents = contents
}
/// Creates deep copy of the object.
func copy() -> Node {
return Node(contents.copy())
}
}
private enum NodeContents {
case file(ByteString)
case directory(DirectoryContents)
/// Creates deep copy of the object.
func copy() -> NodeContents {
switch self {
case .file(let bytes):
return .file(bytes)
case .directory(let contents):
return .directory(contents.copy())
}
}
}
private class DirectoryContents {
var entries: [String: Node]
init(entries: [String: Node] = [:]) {
self.entries = entries
}
/// Creates deep copy of the object.
func copy() -> DirectoryContents {
let contents = DirectoryContents()
for (key, node) in entries {
contents.entries[key] = node.copy()
}
return contents
}
}
/// The root filesytem.
private var root: Node
public init() {
root = Node(.directory(DirectoryContents()))
}
/// Creates deep copy of the object.
public func copy() -> InMemoryFileSystem {
let fs = InMemoryFileSystem()
fs.root = root.copy()
return fs
}
/// Get the node corresponding to the given path.
private func getNode(_ path: AbsolutePath) throws -> Node? {
func getNodeInternal(_ path: AbsolutePath) throws -> Node? {
// If this is the root node, return it.
if path.isRoot {
return root
}
// Otherwise, get the parent node.
guard let parent = try getNodeInternal(path.parentDirectory) else {
return nil
}
// If we didn't find a directory, this is an error.
guard case .directory(let contents) = parent.contents else {
throw FileSystemError.notDirectory
}
// Return the directory entry.
return contents.entries[path.basename]
}
// Get the node that corresponds to the path.
return try getNodeInternal(path)
}
// MARK: FileSystem Implementation
public func exists(_ path: AbsolutePath, followSymlink: Bool) -> Bool {
do {
return try getNode(path) != nil
} catch {
return false
}
}
public func isDirectory(_ path: AbsolutePath) -> Bool {
do {
if case .directory? = try getNode(path)?.contents {
return true
}
return false
} catch {
return false
}
}
public func isFile(_ path: AbsolutePath) -> Bool {
do {
if case .file? = try getNode(path)?.contents {
return true
}
return false
} catch {
return false
}
}
public func isSymlink(_ path: AbsolutePath) -> Bool {
// FIXME: Always return false until in-memory implementation
// gets symbolic link semantics.
return false
}
public func isExecutableFile(_ path: AbsolutePath) -> Bool {
// FIXME: Always return false until in-memory implementation
// gets permission semantics.
return false
}
/// Virtualized current working directory.
public var currentWorkingDirectory: AbsolutePath? {
return AbsolutePath("/")
}
public func changeCurrentWorkingDirectory(to path: AbsolutePath) throws {
throw FileSystemError.unsupported
}
public var homeDirectory: AbsolutePath {
// FIXME: Maybe we should allow setting this when creating the fs.
return AbsolutePath("/home/user")
}
public func getDirectoryContents(_ path: AbsolutePath) throws -> [String] {
guard let node = try getNode(path) else {
throw FileSystemError.noEntry
}
guard case .directory(let contents) = node.contents else {
throw FileSystemError.notDirectory
}
// FIXME: Perhaps we should change the protocol to allow lazy behavior.
return [String](contents.entries.keys)
}
public func createDirectory(_ path: AbsolutePath, recursive: Bool) throws {
// Ignore if client passes root.
guard !path.isRoot else {
return
}
// Get the parent directory node.
let parentPath = path.parentDirectory
guard let parent = try getNode(parentPath) else {
// If the parent doesn't exist, and we are recursive, then attempt
// to create the parent and retry.
if recursive && path != parentPath {
// Attempt to create the parent.
try createDirectory(parentPath, recursive: true)
// Re-attempt creation, non-recursively.
return try createDirectory(path, recursive: false)
} else {
// Otherwise, we failed.
throw FileSystemError.noEntry
}
}
// Check that the parent is a directory.
guard case .directory(let contents) = parent.contents else {
// The parent isn't a directory, this is an error.
throw FileSystemError.notDirectory
}
// Check if the node already exists.
if let node = contents.entries[path.basename] {
// Verify it is a directory.
guard case .directory = node.contents else {
// The path itself isn't a directory, this is an error.
throw FileSystemError.notDirectory
}
// We are done.
return
}
// Otherwise, the node does not exist, create it.
contents.entries[path.basename] = Node(.directory(DirectoryContents()))
}
public func readFileContents(_ path: AbsolutePath) throws -> ByteString {
// Get the node.
guard let node = try getNode(path) else {
throw FileSystemError.noEntry
}
// Check that the node is a file.
guard case .file(let contents) = node.contents else {
// The path is a directory, this is an error.
throw FileSystemError.isDirectory
}
// Return the file contents.
return contents
}
public func writeFileContents(_ path: AbsolutePath, bytes: ByteString) throws {
// It is an error if this is the root node.
let parentPath = path.parentDirectory
guard path != parentPath else {
throw FileSystemError.isDirectory
}
// Get the parent node.
guard let parent = try getNode(parentPath) else {
throw FileSystemError.noEntry
}
// Check that the parent is a directory.
guard case .directory(let contents) = parent.contents else {
// The parent isn't a directory, this is an error.
throw FileSystemError.notDirectory
}
// Check if the node exists.
if let node = contents.entries[path.basename] {
// Verify it is a file.
guard case .file = node.contents else {
// The path is a directory, this is an error.
throw FileSystemError.isDirectory
}
}
// Write the file.
contents.entries[path.basename] = Node(.file(bytes))
}
public func writeFileContents(_ path: AbsolutePath, bytes: ByteString, atomically: Bool) throws {
// In memory file system's writeFileContents is already atomic, so ignore the parameter here
// and just call the base implementation.
try writeFileContents(path, bytes: bytes)
}
public func removeFileTree(_ path: AbsolutePath) throws {
// Ignore root and get the parent node's content if its a directory.
guard !path.isRoot,
let parent = try? getNode(path.parentDirectory),
case .directory(let contents) = parent.contents else {
return
}
// Set it to nil to release the contents.
contents.entries[path.basename] = nil
}
public func chmod(_ mode: FileMode, path: AbsolutePath, options: Set<FileMode.Option>) throws {
// FIXME: We don't have these semantics in InMemoryFileSystem.
}
public func copy(from sourcePath: AbsolutePath, to destinationPath: AbsolutePath) throws {
// Get the source node.
guard let source = try getNode(sourcePath) else {
throw FileSystemError.noEntry
}
// Create directory to destination parent.
guard let destinationParent = try getNode(destinationPath.parentDirectory) else {
throw FileSystemError.noEntry
}
// Check that the parent is a directory.
guard case .directory(let contents) = destinationParent.contents else {
throw FileSystemError.notDirectory
}
guard contents.entries[destinationPath.basename] == nil else {
throw FileSystemError.alreadyExistsAtDestination
}
contents.entries[destinationPath.basename] = source
}
public func move(from sourcePath: AbsolutePath, to destinationPath: AbsolutePath) throws {
// Get the source parent node.
guard let sourceParent = try getNode(sourcePath.parentDirectory) else {
throw FileSystemError.noEntry
}
// Check that the parent is a directory.
guard case .directory(let contents) = sourceParent.contents else {
throw FileSystemError.notDirectory
}
try copy(from: sourcePath, to: destinationPath)
contents.entries[sourcePath.basename] = nil
}
}
/// A rerooted view on an existing FileSystem.
///
/// This is a simple wrapper which creates a new FileSystem view into a subtree
/// of an existing filesystem. This is useful for passing to clients which only
/// need access to a subtree of the filesystem but should otherwise remain
/// oblivious to its concrete location.
///
/// NOTE: The rerooting done here is purely at the API level and does not
/// inherently prevent access outside the rerooted path (e.g., via symlinks). It
/// is designed for situations where a client is only interested in the contents
/// *visible* within a subpath and is agnostic to the actual location of those
/// contents.
public class RerootedFileSystemView: FileSystem {
/// The underlying file system.
private var underlyingFileSystem: FileSystem
/// The root path within the containing file system.
private let root: AbsolutePath
public init(_ underlyingFileSystem: FileSystem, rootedAt root: AbsolutePath) {
self.underlyingFileSystem = underlyingFileSystem
self.root = root
}
/// Adjust the input path for the underlying file system.
private func formUnderlyingPath(_ path: AbsolutePath) -> AbsolutePath {
if path == AbsolutePath.root {
return root
} else {
// FIXME: Optimize?
return root.appending(RelativePath(String(path.pathString.dropFirst(1))))
}
}
// MARK: FileSystem Implementation
public func exists(_ path: AbsolutePath, followSymlink: Bool) -> Bool {
return underlyingFileSystem.exists(formUnderlyingPath(path), followSymlink: followSymlink)
}
public func isDirectory(_ path: AbsolutePath) -> Bool {
return underlyingFileSystem.isDirectory(formUnderlyingPath(path))
}
public func isFile(_ path: AbsolutePath) -> Bool {
return underlyingFileSystem.isFile(formUnderlyingPath(path))
}
public func isSymlink(_ path: AbsolutePath) -> Bool {
return underlyingFileSystem.isSymlink(formUnderlyingPath(path))
}
public func isExecutableFile(_ path: AbsolutePath) -> Bool {
return underlyingFileSystem.isExecutableFile(formUnderlyingPath(path))
}
/// Virtualized current working directory.
public var currentWorkingDirectory: AbsolutePath? {
return AbsolutePath("/")
}
public func changeCurrentWorkingDirectory(to path: AbsolutePath) throws {
throw FileSystemError.unsupported
}
public var homeDirectory: AbsolutePath {
fatalError("homeDirectory on RerootedFileSystemView is not supported.")
}
public func getDirectoryContents(_ path: AbsolutePath) throws -> [String] {
return try underlyingFileSystem.getDirectoryContents(formUnderlyingPath(path))
}
public func createDirectory(_ path: AbsolutePath, recursive: Bool) throws {
let path = formUnderlyingPath(path)
return try underlyingFileSystem.createDirectory(path, recursive: recursive)
}
public func readFileContents(_ path: AbsolutePath) throws -> ByteString {
return try underlyingFileSystem.readFileContents(formUnderlyingPath(path))
}
public func writeFileContents(_ path: AbsolutePath, bytes: ByteString) throws {
let path = formUnderlyingPath(path)
return try underlyingFileSystem.writeFileContents(path, bytes: bytes)
}
public func removeFileTree(_ path: AbsolutePath) throws {
try underlyingFileSystem.removeFileTree(path)
}
public func chmod(_ mode: FileMode, path: AbsolutePath, options: Set<FileMode.Option>) throws {
try underlyingFileSystem.chmod(mode, path: path, options: options)
}
public func copy(from sourcePath: AbsolutePath, to destinationPath: AbsolutePath) throws {
try underlyingFileSystem.copy(from: formUnderlyingPath(sourcePath), to: formUnderlyingPath(sourcePath))
}
public func move(from sourcePath: AbsolutePath, to destinationPath: AbsolutePath) throws {
try underlyingFileSystem.move(from: formUnderlyingPath(sourcePath), to: formUnderlyingPath(sourcePath))
}
}
/// Public access to the local FS proxy.
public var localFileSystem: FileSystem = LocalFileSystem()
extension FileSystem {
/// Print the filesystem tree of the given path.
///
/// For debugging only.
public func dumpTree(at path: AbsolutePath = .root) {
print(".")
do {
try recurse(fs: self, path: path)
} catch {
print("\(error)")
}
}
/// Write bytes to the path if the given contents are different.
public func writeIfChanged(path: AbsolutePath, bytes: ByteString) throws {
try createDirectory(path.parentDirectory, recursive: true)
// Return if the contents are same.
if isFile(path), try readFileContents(path) == bytes {
return
}
try writeFileContents(path, bytes: bytes)
}
/// Helper method to recurse and print the tree.
private func recurse(fs: FileSystem, path: AbsolutePath, prefix: String = "") throws {
let contents = try fs.getDirectoryContents(path)
for (idx, entry) in contents.enumerated() {
let isLast = idx == contents.count - 1
let line = prefix + (isLast ? "└── " : "├── ") + entry
print(line)
let entryPath = path.appending(component: entry)
if fs.isDirectory(entryPath) {
let childPrefix = prefix + (isLast ? " " : "│ ")
try recurse(fs: fs, path: entryPath, prefix: String(childPrefix))
}
}
}
}
#if !os(Windows)
extension dirent {
/// Get the directory name.
///
/// This returns nil if the name is not valid UTF8.
public var name: String? {
var d_name = self.d_name
return withUnsafePointer(to: &d_name) {
String(validatingUTF8: UnsafeRawPointer($0).assumingMemoryBound(to: CChar.self))
}
}
}
#endif