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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344
|
/*
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
import Dispatch
public struct FileSystemError: Error, Equatable, Sendable {
public enum Kind: Equatable, Sendable {
/// 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(code: Int32)
/// 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 at a given path.
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
/// If an unspecified error occurs when trying to change directories.
case couldNotChangeDirectory
/// If a mismatch is detected in byte count when writing to a file.
case mismatchedByteCount(expected: Int, actual: Int)
}
/// The kind of the error being raised.
public let kind: Kind
/// The absolute path to the file associated with the error, if available.
public let path: AbsolutePath?
public init(_ kind: Kind, _ path: AbsolutePath? = nil) {
self.kind = kind
self.path = path
}
}
extension FileSystemError: CustomNSError {
public var errorUserInfo: [String : Any] {
return [NSLocalizedDescriptionKey: "\(self)"]
}
}
public extension FileSystemError {
init(errno: Int32, _ path: AbsolutePath) {
switch errno {
case TSCLibc.EACCES:
self.init(.invalidAccess, path)
case TSCLibc.EISDIR:
self.init(.isDirectory, path)
case TSCLibc.ENOENT:
self.init(.noEntry, path)
case TSCLibc.ENOTDIR:
self.init(.notDirectory, path)
case TSCLibc.EEXIST:
self.init(.alreadyExistsAtDestination, path)
default:
self.init(.ioError(code: errno), path)
}
}
}
/// Defines the file modes.
public enum FileMode: Sendable {
public enum Option: Int, Sendable {
case recursive
case onlyFiles
}
case userUnWritable
case userWritable
case executable
public func setMode(_ originalMode: Int16) -> Int16 {
switch self {
case .userUnWritable:
// r-x rwx rwx
return originalMode & 0o577
case .userWritable:
// -w- --- ---
return originalMode | 0o200
case .executable:
// --x --x --x
return originalMode | 0o111
}
}
}
/// Extended file system attributes that can applied to a given file path. See also ``FileSystem/hasAttribute(_:_:)``.
public enum FileSystemAttribute: RawRepresentable {
#if canImport(Darwin)
case quarantine
#endif
public init?(rawValue: String) {
switch rawValue {
#if canImport(Darwin)
case "com.apple.quarantine":
self = .quarantine
#endif
default:
return nil
}
}
public var rawValue: String {
switch self {
#if canImport(Darwin)
case .quarantine:
return "com.apple.quarantine"
#endif
}
}
}
// 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: Sendable {
/// Check whether the given path exists and is accessible.
@_disfavoredOverload
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
/// Check whether the given path is accessible and readable.
func isReadable(_ path: AbsolutePath) -> Bool
/// Check whether the given path is accessible and writable.
func isWritable(_ path: AbsolutePath) -> Bool
/// Returns any known item replacement directories for a given path. These may be used by platform-specific
/// libraries to handle atomic file system operations, such as deletion.
func itemReplacementDirectories(for path: AbsolutePath) throws -> [AbsolutePath]
@available(*, deprecated, message: "use `hasAttribute(_:_:)` instead")
func hasQuarantineAttribute(_ path: AbsolutePath) -> Bool
/// Returns `true` if a given path has an attribute with a given name applied when file system supports this
/// attribute. Returns `false` if such attribute is not applied or it isn't supported.
func hasAttribute(_ name: FileSystemAttribute, _ 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.
@_disfavoredOverload
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
@_disfavoredOverload
var homeDirectory: AbsolutePath { get throws }
/// Get the caches directory of current user
@_disfavoredOverload
var cachesDirectory: AbsolutePath? { get }
/// Get the temp directory
@_disfavoredOverload
var tempDirectory: AbsolutePath { get throws }
/// 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
/// Creates a symbolic link of the source path at the target path
/// - Parameters:
/// - path: The path at which to create the link.
/// - destination: The path to which the link points to.
/// - relative: If `relative` is true, the symlink contents will be a relative path, otherwise it will be absolute.
func createSymbolicLink(_ path: AbsolutePath, pointingAt destination: AbsolutePath, relative: 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
/// Execute the given block while holding the lock.
func withLock<T>(on path: AbsolutePath, type: FileLock.LockType, blocking: Bool, _ body: () throws -> T) throws -> T
/// Execute the given block while holding the lock.
func withLock<T>(on path: AbsolutePath, type: FileLock.LockType, blocking: Bool, _ body: () async throws -> T) async throws -> T
}
/// Convenience implementations (default arguments aren't permitted in protocol
/// methods).
public extension FileSystem {
/// exists override with default value.
@_disfavoredOverload
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.
@_disfavoredOverload
func writeFileContents(_ path: AbsolutePath, bytes: ByteString, atomically: Bool) throws {
guard !atomically else {
throw FileSystemError(.unsupported, path)
}
try writeFileContents(path, bytes: bytes)
}
/// Write to a file from a stream producer.
@_disfavoredOverload
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, path)
}
func withLock<T>(on path: AbsolutePath, _ body: () throws -> T) throws -> T {
return try withLock(on: path, type: .exclusive, body)
}
func withLock<T>(on path: AbsolutePath, type: FileLock.LockType, _ body: () throws -> T) throws -> T {
return try withLock(on: path, type: type, blocking: true, body)
}
func withLock<T>(on path: AbsolutePath, type: FileLock.LockType, blocking: Bool, _ body: () throws -> T) throws -> T {
throw FileSystemError(.unsupported, path)
}
func withLock<T>(on path: AbsolutePath, type: FileLock.LockType, _ body: () async throws -> T) async throws -> T {
return try await withLock(on: path, type: type, blocking: true, body)
}
func withLock<T>(on path: AbsolutePath, type: FileLock.LockType, blocking: Bool, _ body: () async throws -> T) async throws -> T {
throw FileSystemError(.unsupported, path)
}
func hasQuarantineAttribute(_ path: AbsolutePath) -> Bool { false }
func hasAttribute(_ name: FileSystemAttribute, _ path: AbsolutePath) -> Bool { false }
func itemReplacementDirectories(for path: AbsolutePath) throws -> [AbsolutePath] { [] }
}
/// Concrete FileSystem implementation which communicates with the local file system.
private struct 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 {
guard let path = try? resolveSymlinks(path) else {
return false
}
let attrs = try? FileManager.default.attributesOfItem(atPath: path.pathString)
return attrs?[.type] as? FileAttributeType == .typeRegular
}
func isSymlink(_ path: AbsolutePath) -> Bool {
let url = NSURL(fileURLWithPath: path.pathString)
// We are intentionally using `NSURL.resourceValues(forKeys:)` here since it improves performance on Darwin platforms.
let result = try? url.resourceValues(forKeys: [.isSymbolicLinkKey])
return (result?[.isSymbolicLinkKey] as? Bool) == true
}
func isReadable(_ path: AbsolutePath) -> Bool {
FileManager.default.isReadableFile(atPath: path.pathString)
}
func isWritable(_ path: AbsolutePath) -> Bool {
FileManager.default.isWritableFile(atPath: path.pathString)
}
func getFileInfo(_ path: AbsolutePath) throws -> FileInfo {
let attrs = try FileManager.default.attributesOfItem(atPath: path.pathString)
return FileInfo(attrs)
}
func hasAttribute(_ name: FileSystemAttribute, _ path: AbsolutePath) -> Bool {
#if canImport(Darwin)
let bufLength = getxattr(path.pathString, name.rawValue, nil, 0, 0, 0)
return bufLength > 0
#else
return false
#endif
}
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(String(cString: fsr))
#endif
}
func changeCurrentWorkingDirectory(to path: AbsolutePath) throws {
guard isDirectory(path) else {
throw FileSystemError(.notDirectory, path)
}
guard FileManager.default.changeCurrentDirectoryPath(path.pathString) else {
throw FileSystemError(.couldNotChangeDirectory, path)
}
}
var homeDirectory: AbsolutePath {
get throws {
return try AbsolutePath(validating: NSHomeDirectory())
}
}
var cachesDirectory: AbsolutePath? {
return FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first.flatMap { try? AbsolutePath(validating: $0.path) }
}
var tempDirectory: AbsolutePath {
get throws {
let override = ProcessEnv.block["TMPDIR"] ?? ProcessEnv.block["TEMP"] ?? ProcessEnv.block["TMP"]
if let path = override.flatMap({ try? AbsolutePath(validating: $0) }) {
return path
}
return try AbsolutePath(validating: NSTemporaryDirectory())
}
}
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 createSymbolicLink(_ path: AbsolutePath, pointingAt destination: AbsolutePath, relative: Bool) throws {
let destString = relative ? destination.relative(to: path.parentDirectory).pathString : destination.pathString
try FileManager.default.createSymbolicLink(atPath: path.pathString, withDestinationPath: destString)
}
func readFileContents(_ path: AbsolutePath) throws -> ByteString {
// Open the file.
guard let fp = fopen(path.pathString, "rb") else {
throw FileSystemError(errno: errno, path)
}
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(code: errno), path)
}
if n == 0 {
let errno = ferror(fp)
if errno != 0 {
throw FileSystemError(.ioError(code: errno), path)
}
break
}
data.send(tmpBuffer[0..<n])
}
return data.bytes
}
func writeFileContents(_ path: AbsolutePath, bytes: ByteString) throws {
// Open the file.
guard let fp = fopen(path.pathString, "wb") else {
throw FileSystemError(errno: errno, path)
}
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(code: errno), path)
}
if n != contents.count {
throw FileSystemError(.mismatchedByteCount(expected: contents.count, actual: n), path)
}
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 {
do {
try FileManager.default.removeItem(atPath: path.pathString)
} catch let error as NSError {
// If we failed because the directory doesn't actually exist anymore, ignore the error.
if !(error.domain == NSCocoaErrorDomain && error.code == NSFileNoSuchFileError) {
throw error
}
}
}
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, path)
}
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, sourcePath) }
guard !exists(destinationPath)
else { throw FileSystemError(.alreadyExistsAtDestination, destinationPath) }
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, sourcePath) }
guard !exists(destinationPath)
else { throw FileSystemError(.alreadyExistsAtDestination, destinationPath) }
try FileManager.default.moveItem(at: sourcePath.asURL, to: destinationPath.asURL)
}
func withLock<T>(on path: AbsolutePath, type: FileLock.LockType, blocking: Bool, _ body: () throws -> T) throws -> T {
try FileLock.withLock(fileToLock: path, type: type, blocking: blocking, body: body)
}
func withLock<T>(
on path: AbsolutePath,
type: FileLock.LockType,
blocking: Bool,
_ body: () async throws -> T
) async throws -> T {
try await FileLock.withLock(fileToLock: path, type: type, blocking: blocking, body: body)
}
func itemReplacementDirectories(for path: AbsolutePath) throws -> [AbsolutePath] {
let result = try FileManager.default.url(for: .itemReplacementDirectory, in: .userDomainMask, appropriateFor: path.asURL, create: false)
let path = try AbsolutePath(validating: result.path)
// Foundation returns a path that is unique every time, so we return both that path, as well as its parent.
return [path, path.parentDirectory]
}
}
/// Concrete FileSystem implementation which simulates an empty disk.
public final class InMemoryFileSystem: FileSystem {
/// Private internal representation of a file system node.
/// Not thread-safe.
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 internal representation the contents of a file system node.
/// Not thread-safe.
private enum NodeContents {
case file(ByteString)
case directory(DirectoryContents)
case symlink(String)
/// 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())
case .symlink(let path):
return .symlink(path)
}
}
}
/// Private internal representation the contents of a directory.
/// Not thread-safe.
private final 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 node of the filesystem.
private var root: Node
/// Protects `root` and everything underneath it.
/// FIXME: Using a single lock for this is a performance problem, but in
/// reality, the only practical use for InMemoryFileSystem is for unit
/// tests.
private let lock = NSLock()
/// A map that keeps weak references to all locked files.
private var lockFiles = Dictionary<AbsolutePath, WeakReference<DispatchQueue>>()
/// Used to access lockFiles in a thread safe manner.
private let lockFilesLock = NSLock()
/// Exclusive file system lock vended to clients through `withLock()`.
/// Used to ensure that DispatchQueues are released when they are no longer in use.
private struct WeakReference<Value: AnyObject> {
weak var reference: Value?
init(_ value: Value?) {
self.reference = value
}
}
public init() {
root = Node(.directory(DirectoryContents()))
}
/// Creates deep copy of the object.
public func copy() -> InMemoryFileSystem {
return lock.withLock {
let fs = InMemoryFileSystem()
fs.root = root.copy()
return fs
}
}
/// Private function to look up the node corresponding to a path.
/// Not thread-safe.
private func getNode(_ path: AbsolutePath, followSymlink: Bool = true) 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, path.parentDirectory)
}
// Return the directory entry.
let node = contents.entries[path.basename]
switch node?.contents {
case .directory, .file:
return node
case .symlink(let destination):
let destination = try AbsolutePath(validating: destination, relativeTo: path.parentDirectory)
return followSymlink ? try getNodeInternal(destination) : node
case .none:
return nil
}
}
// Get the node that corresponds to the path.
return try getNodeInternal(path)
}
// MARK: FileSystem Implementation
public func exists(_ path: AbsolutePath, followSymlink: Bool) -> Bool {
return lock.withLock {
do {
switch try getNode(path, followSymlink: followSymlink)?.contents {
case .file, .directory, .symlink: return true
case .none: return false
}
} catch {
return false
}
}
}
public func isDirectory(_ path: AbsolutePath) -> Bool {
return lock.withLock {
do {
if case .directory? = try getNode(path)?.contents {
return true
}
return false
} catch {
return false
}
}
}
public func isFile(_ path: AbsolutePath) -> Bool {
return lock.withLock {
do {
if case .file? = try getNode(path)?.contents {
return true
}
return false
} catch {
return false
}
}
}
public func isSymlink(_ path: AbsolutePath) -> Bool {
return lock.withLock {
do {
if case .symlink? = try getNode(path, followSymlink: false)?.contents {
return true
}
return false
} catch {
return false
}
}
}
public func isReadable(_ path: AbsolutePath) -> Bool {
self.exists(path)
}
public func isWritable(_ path: AbsolutePath) -> Bool {
self.exists(path)
}
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 try? AbsolutePath(validating: "/")
}
public func changeCurrentWorkingDirectory(to path: AbsolutePath) throws {
throw FileSystemError(.unsupported, path)
}
public var homeDirectory: AbsolutePath {
get throws {
// FIXME: Maybe we should allow setting this when creating the fs.
return try AbsolutePath(validating: "/home/user")
}
}
public var cachesDirectory: AbsolutePath? {
return try? self.homeDirectory.appending(component: "caches")
}
public var tempDirectory: AbsolutePath {
get throws {
return try AbsolutePath(validating: "/tmp")
}
}
public func getDirectoryContents(_ path: AbsolutePath) throws -> [String] {
return try lock.withLock {
guard let node = try getNode(path) else {
throw FileSystemError(.noEntry, path)
}
guard case .directory(let contents) = node.contents else {
throw FileSystemError(.notDirectory, path)
}
// FIXME: Perhaps we should change the protocol to allow lazy behavior.
return [String](contents.entries.keys)
}
}
/// Not thread-safe.
private 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, parentPath)
}
}
// 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, parentPath)
}
// 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, path)
}
// We are done.
return
}
// Otherwise, the node does not exist, create it.
contents.entries[path.basename] = Node(.directory(DirectoryContents()))
}
public func createDirectory(_ path: AbsolutePath, recursive: Bool) throws {
return try lock.withLock {
try _createDirectory(path, recursive: recursive)
}
}
public func createSymbolicLink(_ path: AbsolutePath, pointingAt destination: AbsolutePath, relative: Bool) throws {
return try lock.withLock {
// Create directory to destination parent.
guard let destinationParent = try getNode(path.parentDirectory) else {
throw FileSystemError(.noEntry, path.parentDirectory)
}
// Check that the parent is a directory.
guard case .directory(let contents) = destinationParent.contents else {
throw FileSystemError(.notDirectory, path.parentDirectory)
}
guard contents.entries[path.basename] == nil else {
throw FileSystemError(.alreadyExistsAtDestination, path)
}
let destination = relative ? destination.relative(to: path.parentDirectory).pathString : destination.pathString
contents.entries[path.basename] = Node(.symlink(destination))
}
}
public func readFileContents(_ path: AbsolutePath) throws -> ByteString {
return try lock.withLock {
// Get the node.
guard let node = try getNode(path) else {
throw FileSystemError(.noEntry, path)
}
// 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, path)
}
// Return the file contents.
return contents
}
}
public func writeFileContents(_ path: AbsolutePath, bytes: ByteString) throws {
return try lock.withLock {
// It is an error if this is the root node.
let parentPath = path.parentDirectory
guard path != parentPath else {
throw FileSystemError(.isDirectory, path)
}
// Get the parent node.
guard let parent = try getNode(parentPath) else {
throw FileSystemError(.noEntry, parentPath)
}
// 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, parentPath)
}
// 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, path)
}
}
// 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 {
return lock.withLock {
// 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.
}
/// Private implementation of core copying function.
/// Not thread-safe.
private func _copy(from sourcePath: AbsolutePath, to destinationPath: AbsolutePath) throws {
// Get the source node.
guard let source = try getNode(sourcePath) else {
throw FileSystemError(.noEntry, sourcePath)
}
// Create directory to destination parent.
guard let destinationParent = try getNode(destinationPath.parentDirectory) else {
throw FileSystemError(.noEntry, destinationPath.parentDirectory)
}
// Check that the parent is a directory.
guard case .directory(let contents) = destinationParent.contents else {
throw FileSystemError(.notDirectory, destinationPath.parentDirectory)
}
guard contents.entries[destinationPath.basename] == nil else {
throw FileSystemError(.alreadyExistsAtDestination, destinationPath)
}
contents.entries[destinationPath.basename] = source
}
public func copy(from sourcePath: AbsolutePath, to destinationPath: AbsolutePath) throws {
return try lock.withLock {
try _copy(from: sourcePath, to: destinationPath)
}
}
public func move(from sourcePath: AbsolutePath, to destinationPath: AbsolutePath) throws {
return try lock.withLock {
// Get the source parent node.
guard let sourceParent = try getNode(sourcePath.parentDirectory) else {
throw FileSystemError(.noEntry, sourcePath.parentDirectory)
}
// Check that the parent is a directory.
guard case .directory(let contents) = sourceParent.contents else {
throw FileSystemError(.notDirectory, sourcePath.parentDirectory)
}
try _copy(from: sourcePath, to: destinationPath)
contents.entries[sourcePath.basename] = nil
}
}
public func withLock<T>(on path: AbsolutePath, type: FileLock.LockType, blocking: Bool, _ body: () throws -> T) throws -> T {
if !blocking {
throw FileSystemError(.unsupported, path)
}
let resolvedPath: AbsolutePath = try lock.withLock {
if case let .symlink(destination) = try getNode(path)?.contents {
return try AbsolutePath(validating: destination, relativeTo: path.parentDirectory)
} else {
return path
}
}
let fileQueue: DispatchQueue = lockFilesLock.withLock {
if let queueReference = lockFiles[resolvedPath], let queue = queueReference.reference {
return queue
} else {
let queue = DispatchQueue(label: "org.swift.swiftpm.in-memory-file-system.file-queue", attributes: .concurrent)
lockFiles[resolvedPath] = WeakReference(queue)
return queue
}
}
return try fileQueue.sync(flags: type == .exclusive ? .barrier : .init() , execute: body)
}
}
// Internal state of `InMemoryFileSystem` is protected with a lock in all of its `public` methods.
#if compiler(>=5.7)
extension InMemoryFileSystem: @unchecked Sendable {}
#else
extension InMemoryFileSystem: UnsafeSendable {}
#endif
/// 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 final 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) throws -> AbsolutePath {
if path == AbsolutePath.root {
return root
} else {
// FIXME: Optimize?
return try AbsolutePath(validating: String(path.pathString.dropFirst(1)), relativeTo: root)
}
}
// MARK: FileSystem Implementation
public func exists(_ path: AbsolutePath, followSymlink: Bool) -> Bool {
guard let underlying = try? formUnderlyingPath(path) else {
return false
}
return underlyingFileSystem.exists(underlying, followSymlink: followSymlink)
}
public func isDirectory(_ path: AbsolutePath) -> Bool {
guard let underlying = try? formUnderlyingPath(path) else {
return false
}
return underlyingFileSystem.isDirectory(underlying)
}
public func isFile(_ path: AbsolutePath) -> Bool {
guard let underlying = try? formUnderlyingPath(path) else {
return false
}
return underlyingFileSystem.isFile(underlying)
}
public func isSymlink(_ path: AbsolutePath) -> Bool {
guard let underlying = try? formUnderlyingPath(path) else {
return false
}
return underlyingFileSystem.isSymlink(underlying)
}
public func isReadable(_ path: AbsolutePath) -> Bool {
guard let underlying = try? formUnderlyingPath(path) else {
return false
}
return underlyingFileSystem.isReadable(underlying)
}
public func isWritable(_ path: AbsolutePath) -> Bool {
guard let underlying = try? formUnderlyingPath(path) else {
return false
}
return underlyingFileSystem.isWritable(underlying)
}
public func isExecutableFile(_ path: AbsolutePath) -> Bool {
guard let underlying = try? formUnderlyingPath(path) else {
return false
}
return underlyingFileSystem.isExecutableFile(underlying)
}
/// Virtualized current working directory.
public var currentWorkingDirectory: AbsolutePath? {
return try? AbsolutePath(validating: "/")
}
public func changeCurrentWorkingDirectory(to path: AbsolutePath) throws {
throw FileSystemError(.unsupported, path)
}
public var homeDirectory: AbsolutePath {
fatalError("homeDirectory on RerootedFileSystemView is not supported.")
}
public var cachesDirectory: AbsolutePath? {
fatalError("cachesDirectory on RerootedFileSystemView is not supported.")
}
public var tempDirectory: AbsolutePath {
fatalError("tempDirectory 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 = try formUnderlyingPath(path)
return try underlyingFileSystem.createDirectory(path, recursive: recursive)
}
public func createSymbolicLink(_ path: AbsolutePath, pointingAt destination: AbsolutePath, relative: Bool) throws {
let path = try formUnderlyingPath(path)
let destination = try formUnderlyingPath(destination)
return try underlyingFileSystem.createSymbolicLink(path, pointingAt: destination, relative: relative)
}
public func readFileContents(_ path: AbsolutePath) throws -> ByteString {
return try underlyingFileSystem.readFileContents(formUnderlyingPath(path))
}
public func writeFileContents(_ path: AbsolutePath, bytes: ByteString) throws {
let path = try formUnderlyingPath(path)
return try underlyingFileSystem.writeFileContents(path, bytes: bytes)
}
public func removeFileTree(_ path: AbsolutePath) throws {
try underlyingFileSystem.removeFileTree(formUnderlyingPath(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 func withLock<T>(on path: AbsolutePath, type: FileLock.LockType, blocking: Bool, _ body: () throws -> T) throws -> T {
return try underlyingFileSystem.withLock(on: formUnderlyingPath(path), type: type, blocking: blocking, body)
}
}
// `RerootedFileSystemView` doesn't hold any internal state and can be considered `Sendable` since
// `underlyingFileSystem` is required to be `Sendable`.
#if compiler(>=5.7)
extension RerootedFileSystemView: @unchecked Sendable {}
#else
extension RerootedFileSystemView: UnsafeSendable {}
#endif
private var _localFileSystem: FileSystem = LocalFileSystem()
/// Public access to the local FS proxy.
public var localFileSystem: FileSystem {
get {
return _localFileSystem
}
@available(*, deprecated, message: "This global should never be mutable and is supposed to be read-only. Deprecated in Apr 2023.")
set {
_localFileSystem = newValue
}
}
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
|