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
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2023 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) || os(Linux) || os(Android)
import NIOCore
import SystemPackage
/// A handle for a file system object.
///
/// There is a hierarchy of file handle protocols which allow for different functionality. All
/// file handle protocols refine the base ``FileHandleProtocol`` protocol.
///
/// ```
/// ┌────────────────────┐
/// │ FileHandleProtocol │
/// │ [Protocol] │
/// └────────────────────┘
/// ▲
/// ┌──────────────────────────────┼────────────────────────────────┐
/// │ │ │
/// ┌────────────────────────────┐ ┌────────────────────────────┐ ┌─────────────────────────────┐
/// │ ReadableFileHandleProtocol │ │ WritableFileHandleProtocol │ │ DirectoryFileHandleProtocol │
/// │ [Protocol] │ │ [Protocol] │ │ [Protocol] │
/// └────────────────────────────┘ └────────────────────────────┘ └─────────────────────────────┘
/// ```
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
public protocol FileHandleProtocol {
/// Returns information about the file.
///
/// Information is typically gathered by calling `fstat(2)` on the file.
///
/// - Returns: Information about the open file.
func info() async throws -> FileInfo
/// Replaces the permissions set on the file.
///
/// Permissions are typically set using `fchmod(2)`.
///
/// - Parameters:
/// - permissions: The permissions to set on the file.
func replacePermissions(_ permissions: FilePermissions) async throws
/// Adds permissions to the existing permissions set for the file.
///
/// This is equivalent to retrieving the permissions, merging them with the provided
/// permissions and then replacing the permissions on the file.
///
/// - Parameters:
/// - permissions: The permissions to add to the file.
/// - Returns: The updated permissions.
@discardableResult
func addPermissions(_ permissions: FilePermissions) async throws -> FilePermissions
/// Remove permissions from the existing permissions set for the file.
///
/// This is equivalent to retrieving the permissions, subtracting any of the provided
/// permissions and then replacing the permissions on the file.
///
/// - Parameters:
/// - permissions: The permissions to remove from the file.
/// - Returns: The updated permissions.
@discardableResult
func removePermissions(_ permissions: FilePermissions) async throws -> FilePermissions
/// Returns an array containing the names of all extended attributes set on the file.
///
/// Attributes names are typically fetched using `flistxattr(2)`.
func attributeNames() async throws -> [String]
/// Returns the value for the named attribute if it exists; `nil` otherwise.
///
/// Attribute values are typically fetched using `fgetxattr(2)`.
///
/// - Parameters:
/// - name: The name of the attribute.
/// - Returns: The bytes of the value set for the attribute. If no value is set an empty array
/// is returned.
func valueForAttribute(_ name: String) async throws -> [UInt8]
/// Replaces the value for the named attribute, creating it if it didn't already exist.
///
/// Attribute values are typically replaced using `fsetxattr(2)`.
///
/// - Parameters:
/// - bytes: The bytes to set as the value for the attribute.
/// - name: The name of the attribute.
func updateValueForAttribute(
_ bytes: some (Sendable & RandomAccessCollection<UInt8>),
attribute name: String
) async throws
/// Removes the value for the named attribute if it exists.
///
/// Attribute values are typically removed using `fremovexattr(2)`.
///
/// - Parameter name: The name of the attribute to remove.
func removeValueForAttribute(_ name: String) async throws
/// Synchronize modified data and metadata to a permanent storage device.
///
/// This is typically achieved using `fsync(2)`.
func synchronize() async throws
/// Runs the provided callback with the file descriptor for this handle.
///
/// This function should be used with caution: the `FileDescriptor` must not be escaped from
/// the closure nor should it be closed. Where possible make use of the methods defined
/// on ``FileHandleProtocol`` instead; this function is intended as an escape hatch.
///
/// Note that `execute` is not run if the handle has already been closed.
///
/// - Parameter execute: A closure to run.
/// - Returns: The result of the closure.
func withUnsafeDescriptor<R: Sendable>(
_ execute: @Sendable @escaping (FileDescriptor) throws -> R
) async throws -> R
/// Detaches and returns the file descriptor from the handle.
///
/// After detaching the file descriptor the handle is rendered invalid. All methods will throw
/// an appropriate error if called. Detaching the descriptor yields ownerships to the caller.
///
/// - Returns: The detached `FileDescriptor`
func detachUnsafeFileDescriptor() throws -> FileDescriptor
/// Closes the file handle.
///
/// It is important to close a handle once it has been finished with to avoid leaking
/// resources. Prefer using APIs which provided scoped access to a file handle which
/// manage lifecycles on your behalf. Note that if the handle has been detached via
/// ``detachUnsafeFileDescriptor()`` then it is not necessary to close the handle.
///
/// After closing the handle calls to other functions will throw an appropriate error.
func close() async throws
}
// MARK: - Readable
/// A handle for reading data from an open file.
///
/// ``ReadableFileHandleProtocol`` refines ``FileHandleProtocol`` to add requirements for reading data from a file.
///
/// There are two requirements for implementing this protocol:
/// 1. ``readChunk(fromAbsoluteOffset:length:)``, and
/// 2. ``readChunks(chunkLength:)
///
/// A number of overloads are provided which provide sensible defaults.
///
/// Conformance to ``ReadableFileHandleProtocol`` also provides
/// ``readToEnd(fromAbsoluteOffset:maximumSizeAllowed:)`` (and various overloads with sensible
/// defaults) for reading the contents of a file into memory.
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
public protocol ReadableFileHandleProtocol: FileHandleProtocol {
/// Returns a slice of bytes read from the file.
///
/// The length of the slice to read indicates the largest size in bytes that the returned slice
/// may be. The slice may be shorter than the given `length` if there are fewer bytes from the
/// `offset` to the end of the file.
///
/// - Parameters:
/// - offset: The absolute offset into the file to read from.
/// - length: The maximum number of bytes to read as a ``ByteCount``.
/// - Returns: The bytes read from the file.
func readChunk(fromAbsoluteOffset offset: Int64, length: ByteCount) async throws -> ByteBuffer
/// Returns an asynchronous sequence of chunks read from the file.
///
/// - Parameters:
/// - range: The absolute offsets into the file to read.
/// - chunkLength: The maximum length of the chunk to read as a ``ByteCount``.
/// - Returns: A sequence of chunks read from the file.
func readChunks(in range: Range<Int64>, chunkLength: ByteCount) -> FileChunks
}
// MARK: - Read chunks with default chunk length
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
extension ReadableFileHandleProtocol {
/// Returns an asynchronous sequence of chunks read from the file.
///
/// - Parameters:
/// - range: A range of offsets in the file to read.
/// - chunkLength: The length of chunks to read, defaults to 128 KiB.
/// - as: Type of chunk to read.
/// - SeeAlso: ``ReadableFileHandleProtocol/readChunks(in:chunkLength:)-2dz6``
/// - Returns: An `AsyncSequence` of chunks read from the file.
public func readChunks(
in range: ClosedRange<Int64>,
chunkLength: ByteCount = .kibibytes(128)
) -> FileChunks {
return self.readChunks(in: Range(range), chunkLength: chunkLength)
}
/// Returns an asynchronous sequence of chunks read from the file.
///
/// - Parameters:
/// - range: A range of offsets in the file to read.
/// - chunkLength: The length of chunks to read, defaults to 128 KiB.
/// - as: Type of chunk to read.
/// - SeeAlso: ``ReadableFileHandleProtocol/readChunks(in:chunkLength:)-2dz6``
/// - Returns: An `AsyncSequence` of chunks read from the file.
public func readChunks(
in range: Range<Int64>,
chunkLength: ByteCount = .kibibytes(128)
) -> FileChunks {
return self.readChunks(in: range, chunkLength: chunkLength)
}
/// Returns an asynchronous sequence of chunks read from the file.
///
/// - Parameters:
/// - range: A range of offsets in the file to read.
/// - chunkLength: The length of chunks to read, defaults to 128 KiB.
/// - as: Type of chunk to read.
/// - SeeAlso: ``ReadableFileHandleProtocol/readChunks(in:chunkLength:)-2dz6``.
/// - Returns: An `AsyncSequence` of chunks read from the file.
public func readChunks(
in range: PartialRangeFrom<Int64>,
chunkLength: ByteCount = .kibibytes(128)
) -> FileChunks {
let newRange = range.lowerBound..<Int64.max
return self.readChunks(in: newRange, chunkLength: chunkLength)
}
/// Returns an asynchronous sequence of chunks read from the file.
///
/// - Parameters:
/// - range: A range of offsets in the file to read.
/// - chunkLength: The length of chunks to read, defaults to 128 KiB.
/// - as: Type of chunk to read.
/// - SeeAlso: ``ReadableFileHandleProtocol/readChunks(in:chunkLength:)-2dz6``.
/// - Returns: An `AsyncSequence` of chunks read from the file.
public func readChunks(
in range: PartialRangeThrough<Int64>,
chunkLength: ByteCount = .kibibytes(128)
) -> FileChunks {
let newRange = 0...range.upperBound
return self.readChunks(in: newRange, chunkLength: chunkLength)
}
/// Returns an asynchronous sequence of chunks read from the file.
///
/// - Parameters:
/// - range: A range of offsets in the file to read.
/// - chunkLength: The length of chunks to read, defaults to 128 KiB.
/// - as: Type of chunk to read.
/// - SeeAlso: ``ReadableFileHandleProtocol/readChunks(in:chunkLength:)-2dz6``.
/// - Returns: An `AsyncSequence` of chunks read from the file.
public func readChunks(
in range: PartialRangeUpTo<Int64>,
chunkLength: ByteCount = .kibibytes(128)
) -> FileChunks {
let newRange = 0..<range.upperBound
return self.readChunks(in: newRange, chunkLength: chunkLength)
}
/// Returns an asynchronous sequence of chunks read from the file.
///
/// - Parameters:
/// - range: A range of offsets in the file to read.
/// - chunkLength: The length of chunks to read, defaults to 128 KiB.
/// - as: Type of chunk to read.
/// - SeeAlso: ``ReadableFileHandleProtocol/readChunks(in:chunkLength:)-2dz6``.
/// - Returns: An `AsyncSequence` of chunks read from the file.
public func readChunks(
in range: UnboundedRange,
chunkLength: ByteCount = .kibibytes(128)
) -> FileChunks {
return self.readChunks(in: 0..<Int64.max, chunkLength: chunkLength)
}
/// Returns an asynchronous sequence of chunks read from the file.
///
/// - Parameters:
/// - range: A range of offsets in the file to read.
/// - chunkLength: The length of chunks to read, defaults to 128 KiB.
/// - as: Type of chunk to read.
/// - SeeAlso: ``ReadableFileHandleProtocol/readChunks(in:chunkLength:)-2dz6``.
/// - Returns: An `AsyncSequence` of chunks read from the file.
public func readChunks(
chunkLength: ByteCount = .kibibytes(128)
) -> FileChunks {
return self.readChunks(in: ..., chunkLength: chunkLength)
}
}
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
extension ReadableFileHandleProtocol {
/// Returns the contents of a file by loading it into memory.
///
/// - Important: This method checks whether the file is seekable or not (i.e., whether it's a socket,
/// pipe or FIFO), and will throw ``FileSystemError/Code-swift.struct/unsupported`` if
/// an offset other than zero is passed.
///
/// - Parameters:
/// - offset: The absolute offset into the file to read from. Defaults to zero.
/// - maximumSizeAllowed: The maximum size of file to read, as a ``ByteCount``.
/// - Returns: The bytes read from the file.
/// - Throws: ``FileSystemError`` with code ``FileSystemError/Code-swift.struct/resourceExhausted`` if there
/// are more bytes to read than `maximumBytesAllowed`.
/// ``FileSystemError/Code-swift.struct/unsupported`` if file is unseekable and
/// `offset` is not 0.
public func readToEnd(
fromAbsoluteOffset offset: Int64 = 0,
maximumSizeAllowed: ByteCount
) async throws -> ByteBuffer {
let info = try await self.info()
let fileSize = Int64(info.size)
let readSize = max(Int(fileSize - offset), 0)
if readSize > maximumSizeAllowed.bytes {
throw FileSystemError(
code: .resourceExhausted,
message: """
There are more bytes to read (\(readSize)) than the maximum size allowed \
(\(maximumSizeAllowed)). Read the file in chunks or increase the maximum size \
allowed.
""",
cause: nil,
location: .here()
)
}
let isSeekable = !(info.type == .fifo || info.type == .socket)
if isSeekable {
// Limit the size of single shot reads. If the system is busy then avoid slowing down other
// work by blocking an I/O executor thread while doing a large read. The limit is somewhat
// arbitrary.
let singleShotReadLimit = 64 * 1024 * 1024
// If the file size isn't 0 but the read size is, then it means that
// we are intending to read an empty fragment: we can just return
// fast and skip any reads.
// If the file size is 0, we can't conclude anything about the size
// of the file, as `stat` will return 0 for unbounded files.
// If this happens, just read in chunks to make sure the whole file
// is read (up to `maximumSizeAllowed` bytes).
var forceChunkedRead = false
if fileSize > 0 {
if readSize == 0 {
return ByteBuffer()
}
} else {
forceChunkedRead = true
}
if !forceChunkedRead, readSize <= singleShotReadLimit {
return try await self.readChunk(
fromAbsoluteOffset: offset,
length: .bytes(Int64(readSize))
)
} else {
var accumulator = ByteBuffer()
accumulator.reserveCapacity(readSize)
for try await chunk in self.readChunks(in: offset..., chunkLength: .mebibytes(8)) {
accumulator.writeImmutableBuffer(chunk)
if accumulator.readableBytes > maximumSizeAllowed.bytes {
throw FileSystemError(
code: .resourceExhausted,
message: """
There are more bytes to read than the maximum size allowed \
(\(maximumSizeAllowed)). Read the file in chunks or increase the maximum size \
allowed.
""",
cause: nil,
location: .here()
)
}
}
return accumulator
}
} else {
guard offset == 0 else {
throw FileSystemError(
code: .unsupported,
message: "File is unseekable.",
cause: nil,
location: .here()
)
}
var accumulator = ByteBuffer()
accumulator.reserveCapacity(readSize)
for try await chunk in self.readChunks(in: ..., chunkLength: .mebibytes(8)) {
accumulator.writeImmutableBuffer(chunk)
if accumulator.readableBytes > maximumSizeAllowed.bytes {
throw FileSystemError(
code: .resourceExhausted,
message: """
There are more bytes to read than the maximum size allowed \
(\(maximumSizeAllowed)). Read the file in chunks or increase the maximum size \
allowed.
""",
cause: nil,
location: .here()
)
}
}
return accumulator
}
}
}
// MARK: - Writable
/// A file handle suitable for writing.
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
public protocol WritableFileHandleProtocol: FileHandleProtocol {
/// Write the given bytes to the open file.
///
/// - Important: This method checks whether the file is seekable or not (i.e., whether it's a socket,
/// pipe or FIFO), and will throw ``FileSystemError/Code-swift.struct/unsupported``
/// if an offset other than zero is passed.
///
/// - Parameters:
/// - bytes: The bytes to write.
/// - offset: The absolute offset into the file to write the bytes.
/// - Returns: The number of bytes written.
/// - Throws: ``FileSystemError/Code-swift.struct/unsupported`` if file is
/// unseekable and `offset` is not 0.
@discardableResult
func write(
contentsOf bytes: some (Sequence<UInt8> & Sendable),
toAbsoluteOffset offset: Int64
) async throws -> Int64
/// Resizes a file to the given size.
///
/// - Parameters:
/// - size: The number of bytes to resize the file to as a ``ByteCount``.
func resize(
to size: ByteCount
) async throws
/// Closes the file handle.
///
/// It is important to close a handle once it has been finished with to avoid leaking
/// resources. Prefer using APIs which provided scoped access to a file handle which
/// manage lifecycles on your behalf. Note that if the handle has been detached via
/// ``FileHandleProtocol/detachUnsafeFileDescriptor()`` then it is not necessary to close
/// the handle.
///
/// After closing the handle calls to other functions will throw an appropriate error.
///
/// - Parameters:
/// - makeChangesVisible: Whether the changes made to the file will be made visibile. This
/// parameter is ignored unless ``OpenOptions/NewFile/transactionalCreation`` was
/// set to `true`. When `makeChangesVisible` is `true`, the file will be created on the
/// filesystem with the expected name, otherwise no file will be created or the original
/// file won't be modified (if one existed).
func close(makeChangesVisible: Bool) async throws
}
/// A file handle which is suitable for reading and writing.
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
public typealias ReadableAndWritableFileHandleProtocol = ReadableFileHandleProtocol
& WritableFileHandleProtocol
// MARK: - Directory
/// A handle suitable for directories.
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
public protocol DirectoryFileHandleProtocol: FileHandleProtocol {
/// The type of ``ReadableFileHandleProtocol`` to return when opening files for reading.
associatedtype ReadFileHandle: ReadableFileHandleProtocol
/// The type of ``WritableFileHandleProtocol`` to return when opening files for writing.
associatedtype WriteFileHandle: WritableFileHandleProtocol
/// The type of ``ReadableAndWritableFileHandleProtocol`` to return when opening files for reading and writing.
associatedtype ReadWriteFileHandle: ReadableAndWritableFileHandleProtocol
/// Returns an `AsyncSequence` of entries in the open directory.
///
/// You can recurse into and list the contents of any subdirectories by setting `recursive`
/// to `true`. The current (".") and parent ("..") directory entries are not included. The order
/// of entries is arbitrary and shouldn't be relied upon.
///
/// - Parameter recursive: Whether subdirectories should be recursively visited.
/// - Returns: An `AsyncSequence` of directory entries.
func listContents(recursive: Bool) -> DirectoryEntries
/// Opens the file at `path` for reading and returns a handle to it.
///
/// If `path` is a relative path then it is opened relative to the handle. The file being
/// opened must already exist otherwise this function will throw a ``FileSystemError`` with
/// code ``FileSystemError/Code-swift.struct/notFound``.
///
/// - Parameters:
/// - path: The path of the directory to open relative to the open file.
/// - options: How the file should be opened.
/// - Returns: A read-only handle to the opened file.
func openFile(
forReadingAt path: FilePath,
options: OpenOptions.Read
) async throws -> ReadFileHandle
/// Opens the file at `path` for writing and returns a handle to it.
///
/// If `path` is a relative path then it is opened relative to the handle.
///
/// - Parameters:
/// - path: The path of the file to open relative to the open file.
/// - options: How the file should be opened.
/// - Returns: A write-only handle to the opened file.
func openFile(
forWritingAt path: FilePath,
options: OpenOptions.Write
) async throws -> WriteFileHandle
/// Opens the file at `path` for reading and writing and returns a handle to it.
///
/// If `path` is a relative path then it is opened relative to the handle.
///
/// - Parameters:
/// - path: The path of the file to open relative to the open file.
/// - options: How the file should be opened.
func openFile(
forReadingAndWritingAt path: FilePath,
options: OpenOptions.Write
) async throws -> ReadWriteFileHandle
/// Opens the directory at `path` and returns a handle to it.
///
/// The directory being opened must already exist otherwise this function will throw an error.
/// If `path` is a relative path then it is opened relative to the handle.
///
/// - Parameters:
/// - path: The path of the directory to open.
/// - options: How the file should be opened.
/// - Returns: A handle to the opened directory.
func openDirectory(
atPath path: FilePath,
options: OpenOptions.Directory
) async throws -> Self
}
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
extension DirectoryFileHandleProtocol {
/// Returns an `AsyncSequence` of entries in the open directory.
///
/// The current (".") and parent ("..") directory entries are not included. The order of entries
/// is arbitrary and should not be relied upon.
public func listContents() -> DirectoryEntries {
return self.listContents(recursive: false)
}
}
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
extension DirectoryFileHandleProtocol {
/// Opens the file at the given path and provides scoped read access to it.
///
/// The file remains open during lifetime of the `execute` block and will be closed
/// automatically before the call returns. Files may also be opened in write-only and read-write
/// mode by calling ``withFileHandle(forWritingAt:options:execute:)``
/// and ``withFileHandle(forReadingAndWritingAt:options:execute:)``,
/// respectively.
///
/// If `path` is a relative path then it is opened relative to the handle. The file being
/// opened must already exist otherwise this function will throw a ``FileSystemError`` with
/// code ``FileSystemError/Code-swift.struct/notFound``.
///
/// - Parameters:
/// - path: The path of the file to open for reading.
/// - options: How the file should be opened.
/// - body: A closure which provides read-only access to the open file. The file is closed
/// automatically after the closure exits.
/// - Important: The handle passed to `execute` must not escape the closure.
/// - Returns: The result of the `execute` closure.
public func withFileHandle<R: Sendable>(
forReadingAt path: FilePath,
options: OpenOptions.Read = OpenOptions.Read(),
execute body: (_ read: ReadFileHandle) async throws -> R
) async throws -> R {
let handle = try await self.openFile(forReadingAt: path, options: options)
return try await withUncancellableTearDown {
return try await body(handle)
} tearDown: { _ in
try await handle.close()
}
}
/// Opens the file at the given path and provides scoped write access to it.
///
/// The file remains open during lifetime of the `execute` block and will be closed
/// automatically before the call returns. Files may also be opened in read-only or read-write
/// mode by calling ``withFileHandle(forReadingAt:options:execute:)`` and
/// ``withFileHandle(forReadingAndWritingAt:options:execute:)``,
/// respectively.
///
/// If `path` is a relative path then it is opened relative to the handle.
///
/// - Parameters:
/// - path: The path of the file to open for reading.
/// - options: How the file should be opened.
/// - body: A closure which provides write-only access to the open file. The file is closed
/// automatically after the closure exits.
/// - Important: The handle passed to `execute` must not escape the closure.
/// - Returns: The result of the `execute` closure.
public func withFileHandle<R: Sendable>(
forWritingAt path: FilePath,
options: OpenOptions.Write = .newFile(replaceExisting: false),
execute body: (_ write: WriteFileHandle) async throws -> R
) async throws -> R {
let handle = try await self.openFile(forWritingAt: path, options: options)
return try await withUncancellableTearDown {
return try await body(handle)
} tearDown: { result in
switch result {
case .success:
try await handle.close(makeChangesVisible: true)
case .failure:
try await handle.close(makeChangesVisible: false)
}
}
}
/// Opens the file at the given path and provides scoped read-write access to it.
///
/// The file remains open during lifetime of the `execute` block and will be closed
/// automatically before the call returns. Files may also be opened in read-only or write-only
/// mode by calling ``withFileHandle(forReadingAt:options:execute:)`` and
/// ``withFileHandle(forWritingAt:options:execute:)``, respectively.
///
/// If `path` is a relative path then it is opened relative to the handle.
///
/// - Parameters:
/// - path: The path of the file to open for reading and writing.
/// - options: How the file should be opened.
/// - body: A closure which provides access to the open file. The file is closed
/// automatically after the closure exits.
/// - Important: The handle passed to `execute` must not escape the closure.
/// - Returns: The result of the `execute` closure.
public func withFileHandle<R: Sendable>(
forReadingAndWritingAt path: FilePath,
options: OpenOptions.Write = .newFile(replaceExisting: false),
execute body: (_ readWrite: ReadWriteFileHandle) async throws -> R
) async throws -> R {
let handle = try await self.openFile(forReadingAndWritingAt: path, options: options)
return try await withUncancellableTearDown {
return try await body(handle)
} tearDown: { result in
switch result {
case .success:
try await handle.close(makeChangesVisible: true)
case .failure:
try await handle.close(makeChangesVisible: false)
}
}
}
/// Opens the directory at the given path and provides scoped access to it.
///
/// - Parameters:
/// - path: The path of the directory to open.
/// - body: A closure which provides access to the directory.
/// - Important: The handle passed to `execute` must not escape the closure.
/// - Returns: The result of the `execute` closure.
public func withDirectoryHandle<R: Sendable>(
atPath path: FilePath,
options: OpenOptions.Directory = OpenOptions.Directory(),
execute body: (_ directory: Self) async throws -> R
) async throws -> R {
let handle = try await self.openDirectory(atPath: path, options: options)
return try await withUncancellableTearDown {
return try await body(handle)
} tearDown: { _ in
try await handle.close()
}
}
}
#endif
|