mirror of
https://github.com/apple/swift-nio
synced 2026-11-26 04:57:49 +00:00
Add back _NIOFileSystem (#3367)
Motivation: In #3363 we converted `_NIOFileSystem` to `NIOFileSystem` and removed the (unreleased) overloads for FilePath/NIOFilePath. This change adds back `_NIOFileSystem` such that it matches the API it had at 2.86.0. Modifications: - Add back `_NIOFileSystem` and `_NIOFileSystemFoundationCompat` such that their API is at 2.86.0 Result: - `NIOFileSystem` uses `NIOFilePath` - `_NIOFileSystem` uses `FilePath`
This commit is contained in:
1 parent
e95d742160
commit
66a85ba0e2
44 files changed
+14220
No files matched your search
@@ -66,6 +66,8 @@ let package = Package(
|
||||
.library(name: "NIOTestUtils", targets: ["NIOTestUtils"]),
|
||||
.library(name: "NIOFileSystem", targets: ["NIOFileSystem"]),
|
||||
.library(name: "NIOFileSystemFoundationCompat", targets: ["NIOFileSystemFoundationCompat"]),
|
||||
.library(name: "_NIOFileSystem", targets: ["_NIOFileSystem"]),
|
||||
.library(name: "_NIOFileSystemFoundationCompat", targets: ["_NIOFileSystemFoundationCompat"]),
|
||||
],
|
||||
targets: [
|
||||
// MARK: - Targets
|
||||
@@ -269,6 +271,34 @@ let package = Package(
|
||||
swiftSettings: strictConcurrencySettings
|
||||
),
|
||||
|
||||
.target(
|
||||
name: "_NIOFileSystem",
|
||||
dependencies: [
|
||||
"NIOCore",
|
||||
"NIOPosix",
|
||||
"CNIOLinux",
|
||||
"CNIODarwin",
|
||||
swiftAtomics,
|
||||
swiftCollections,
|
||||
swiftSystem,
|
||||
],
|
||||
path: "Sources/_NIOFileSystem",
|
||||
exclude: includePrivacyManifest ? [] : ["PrivacyInfo.xcprivacy"],
|
||||
resources: includePrivacyManifest ? [.copy("PrivacyInfo.xcprivacy")] : [],
|
||||
swiftSettings: strictConcurrencySettings + [
|
||||
.define("ENABLE_MOCKING", .when(configuration: .debug))
|
||||
]
|
||||
),
|
||||
.target(
|
||||
name: "_NIOFileSystemFoundationCompat",
|
||||
dependencies: [
|
||||
"_NIOFileSystem",
|
||||
"NIOFoundationCompat",
|
||||
],
|
||||
path: "Sources/_NIOFileSystemFoundationCompat",
|
||||
swiftSettings: strictConcurrencySettings
|
||||
),
|
||||
|
||||
// MARK: - Examples
|
||||
|
||||
.executableTarget(
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2025 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 canImport(Darwin) || os(Linux) || os(Android)
|
||||
import NIOCore
|
||||
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
extension Array where Element == UInt8 {
|
||||
/// Reads the contents of the file at the path.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The path of the file to read.
|
||||
/// - maximumSizeAllowed: The maximum size of file which can be read, in bytes, as a ``ByteCount``.
|
||||
/// - fileSystem: The ``FileSystemProtocol`` instance to use to read the file.
|
||||
public init(
|
||||
contentsOf path: FilePath,
|
||||
maximumSizeAllowed: ByteCount,
|
||||
fileSystem: some FileSystemProtocol
|
||||
) async throws {
|
||||
let byteBuffer = try await fileSystem.withFileHandle(forReadingAt: path) { handle in
|
||||
try await handle.readToEnd(maximumSizeAllowed: maximumSizeAllowed)
|
||||
}
|
||||
|
||||
self = Self(buffer: byteBuffer)
|
||||
}
|
||||
|
||||
/// Reads the contents of the file at the path using ``FileSystem``.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The path of the file to read.
|
||||
/// - maximumSizeAllowed: The maximum size of file which can be read, as a ``ByteCount``.
|
||||
public init(
|
||||
contentsOf path: FilePath,
|
||||
maximumSizeAllowed: ByteCount
|
||||
) async throws {
|
||||
self = try await Self(
|
||||
contentsOf: path,
|
||||
maximumSizeAllowed: maximumSizeAllowed,
|
||||
fileSystem: .shared
|
||||
)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,56 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2025 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 canImport(Darwin) || os(Linux) || os(Android)
|
||||
import NIOCore
|
||||
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
extension ArraySlice where Element == UInt8 {
|
||||
/// Reads the contents of the file at the path.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The path of the file to read.
|
||||
/// - maximumSizeAllowed: The maximum size of file which can be read, in bytes, as a ``ByteCount``.
|
||||
/// - fileSystem: The ``FileSystemProtocol`` instance to use to read the file.
|
||||
public init(
|
||||
contentsOf path: FilePath,
|
||||
maximumSizeAllowed: ByteCount,
|
||||
fileSystem: some FileSystemProtocol
|
||||
) async throws {
|
||||
let bytes = try await Array(
|
||||
contentsOf: path,
|
||||
maximumSizeAllowed: maximumSizeAllowed,
|
||||
fileSystem: fileSystem
|
||||
)
|
||||
|
||||
self = Self(bytes)
|
||||
}
|
||||
|
||||
/// Reads the contents of the file at the path using ``FileSystem``.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The path of the file to read.
|
||||
/// - maximumSizeAllowed: The maximum size of file which can be read, as a ``ByteCount``.
|
||||
public init(
|
||||
contentsOf path: FilePath,
|
||||
maximumSizeAllowed: ByteCount
|
||||
) async throws {
|
||||
self = try await Self(
|
||||
contentsOf: path,
|
||||
maximumSizeAllowed: maximumSizeAllowed,
|
||||
fileSystem: .shared
|
||||
)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,244 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import DequeModule
|
||||
import NIOCore
|
||||
|
||||
/// A reader which maintains a buffer of bytes read from the file.
|
||||
///
|
||||
/// You can create a reader from a ``ReadableFileHandleProtocol`` by calling
|
||||
/// ``ReadableFileHandleProtocol/bufferedReader(startingAtAbsoluteOffset:capacity:)``. Call
|
||||
/// ``read(_:)`` to read a fixed number of bytes from the file or ``read(while:)-8aukk`` to read
|
||||
/// from the file while the bytes match a predicate.
|
||||
///
|
||||
/// You can also read bytes without returning them to caller by calling ``drop(_:)`` and
|
||||
/// ``drop(while:)``.
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
public struct BufferedReader<Handle: ReadableFileHandleProtocol> {
|
||||
/// The handle to read from.
|
||||
private let handle: Handle
|
||||
|
||||
/// The offset for the next read from the file.
|
||||
private var offset: Int64
|
||||
|
||||
/// Whether the reader has read to the end of the file.
|
||||
private var readEOF = false
|
||||
|
||||
/// A buffer containing the read bytes.
|
||||
private var buffer: ByteBuffer
|
||||
|
||||
/// The capacity of the buffer.
|
||||
public let capacity: Int
|
||||
|
||||
/// The number of bytes currently in the buffer.
|
||||
public var count: Int {
|
||||
self.buffer.readableBytes
|
||||
}
|
||||
|
||||
internal init(wrapping readableHandle: Handle, initialOffset: Int64, capacity: Int) {
|
||||
precondition(
|
||||
initialOffset >= 0,
|
||||
"initialOffset (\(initialOffset)) must be greater than or equal to zero"
|
||||
)
|
||||
precondition(capacity > 0, "capacity (\(capacity)) must be greater than zero")
|
||||
self.handle = readableHandle
|
||||
self.offset = initialOffset
|
||||
self.capacity = capacity
|
||||
self.buffer = ByteBuffer()
|
||||
}
|
||||
|
||||
private mutating func readFromFile(_ count: Int) async throws -> ByteBuffer {
|
||||
let bytes = try await self.handle.readChunk(
|
||||
fromAbsoluteOffset: self.offset,
|
||||
length: .bytes(Int64(count))
|
||||
)
|
||||
// Reading short means reading end-of-file.
|
||||
self.readEOF = bytes.readableBytes < count
|
||||
self.offset += Int64(bytes.readableBytes)
|
||||
return bytes
|
||||
}
|
||||
|
||||
/// Read at most `count` bytes from the file; reads short if not enough bytes are available.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - count: The number of bytes to read.
|
||||
/// - Returns: The bytes read from the buffer.
|
||||
public mutating func read(_ count: ByteCount) async throws -> ByteBuffer {
|
||||
let byteCount = Int(count.bytes)
|
||||
guard byteCount > 0 else { return ByteBuffer() }
|
||||
|
||||
if let bytes = self.buffer.readSlice(length: byteCount) {
|
||||
return bytes
|
||||
} else {
|
||||
// Not enough bytes: read enough for the caller and to fill the buffer back to capacity.
|
||||
var buffer = self.buffer
|
||||
self.buffer = ByteBuffer()
|
||||
|
||||
// The bytes to read from the chunk is the difference in what the caller requested
|
||||
// and is already stored in buffer. Note that if we get to the end of the file this
|
||||
// number could be larger than the available number of bytes.
|
||||
let bytesFromChunk = byteCount &- buffer.readableBytes
|
||||
let bytesToRead = bytesFromChunk + self.capacity
|
||||
|
||||
// Read a chunk from the file and store it.
|
||||
let chunk = try await self.readFromFile(bytesToRead)
|
||||
self.buffer.writeImmutableBuffer(chunk)
|
||||
|
||||
// Finally read off the required bytes from the chunk we just read. If we read short
|
||||
// then the chunk we just appended might not less than 'bytesFromChunk', that's fine,
|
||||
// just take what's available.
|
||||
var slice = self.buffer.readSlice(length: min(bytesFromChunk, chunk.readableBytes))!
|
||||
buffer.writeBuffer(&slice)
|
||||
|
||||
return buffer
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads from the current position in the file until `predicate` returns `false` and returns
|
||||
/// the read bytes.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - predicate: A predicate which evaluates to `true` for all bytes returned.
|
||||
/// - Returns: A tuple containing the bytes read from the file in its first component, and a boolean
|
||||
/// indicating whether we've stopped reading because EOF has been reached, or because the predicate
|
||||
/// condition doesn't hold true anymore.
|
||||
public mutating func read(
|
||||
while predicate: (UInt8) -> Bool
|
||||
) async throws -> (bytes: ByteBuffer, readEOF: Bool) {
|
||||
// Check if the required bytes are in the buffer already.
|
||||
let view = self.buffer.readableBytesView
|
||||
|
||||
if let index = view.firstIndex(where: { !predicate($0) }) {
|
||||
// Got an index; slice off the front of the buffer.
|
||||
let prefix = view[..<index]
|
||||
let buffer = ByteBuffer(prefix)
|
||||
self.buffer.moveReaderIndex(forwardBy: buffer.readableBytes)
|
||||
|
||||
// If we reached this codepath, it's because at least one element
|
||||
// in the buffer makes the predicate false. This means that we have
|
||||
// stopped reading because the condition doesn't hold true anymore.
|
||||
return (buffer, false)
|
||||
}
|
||||
|
||||
// The predicate holds true for all bytes in the buffer, start consuming chunks from the
|
||||
// iterator.
|
||||
while !self.readEOF {
|
||||
var chunk = try await self.readFromFile(self.capacity)
|
||||
let view = chunk.readableBytesView
|
||||
|
||||
if let index = view.firstIndex(where: { !predicate($0) }) {
|
||||
// Found a byte for which the predicate doesn't hold. Consume the entire buffer and
|
||||
// the front of this slice.
|
||||
let chunkPrefix = view[..<index]
|
||||
self.buffer.writeBytes(chunkPrefix)
|
||||
chunk.moveReaderIndex(forwardBy: chunkPrefix.count)
|
||||
|
||||
let buffer = self.buffer
|
||||
self.buffer = chunk
|
||||
|
||||
// If we reached this codepath, it's because at least one element
|
||||
// in the buffer makes the predicate false. This means that we have
|
||||
// stopped reading because the condition doesn't hold true anymore.
|
||||
return (buffer, false)
|
||||
} else {
|
||||
// Predicate holds for all bytes. Continue reading.
|
||||
self.buffer.writeBuffer(&chunk)
|
||||
}
|
||||
}
|
||||
|
||||
// Read end-of-file and the predicate still holds for all bytes:
|
||||
// clear the buffer and return all bytes.
|
||||
let buffer = self.buffer
|
||||
self.buffer = ByteBuffer()
|
||||
return (buffer, true)
|
||||
}
|
||||
|
||||
/// Reads and discards the given number of bytes.
|
||||
///
|
||||
/// - Parameter count: The number of bytes to read and discard.
|
||||
public mutating func drop(_ count: Int) async throws {
|
||||
if count > self.buffer.readableBytes {
|
||||
self.offset += Int64(count &- self.buffer.readableBytes)
|
||||
self.buffer.clear()
|
||||
} else {
|
||||
self.buffer.moveReaderIndex(forwardBy: count)
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads and discards bytes until `predicate` returns `false.`
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - predicate: A predicate which evaluates to `true` for all dropped bytes.
|
||||
public mutating func drop(while predicate: (UInt8) -> Bool) async throws {
|
||||
let view = self.buffer.readableBytesView
|
||||
|
||||
if let index = view.firstIndex(where: { !predicate($0) }) {
|
||||
let slice = view[..<index]
|
||||
self.buffer.moveReaderIndex(forwardBy: slice.count)
|
||||
return
|
||||
}
|
||||
|
||||
// Didn't hit the predicate for buffered bytes; drop them all and consume the source.
|
||||
self.buffer.clear(minimumCapacity: min(self.buffer.capacity, self.capacity))
|
||||
|
||||
while !self.readEOF {
|
||||
var chunk = try await self.readFromFile(self.capacity)
|
||||
let view = chunk.readableBytesView
|
||||
|
||||
if let index = view.firstIndex(where: { !predicate($0) }) {
|
||||
let slice = view[..<index]
|
||||
chunk.moveReaderIndex(forwardBy: slice.count)
|
||||
self.buffer.writeBuffer(&chunk)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// swift-format-ignore: AmbiguousTrailingClosureOverload
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
extension BufferedReader {
|
||||
/// Reads from the current position in the file until `predicate` returns `false` and returns
|
||||
/// the read bytes.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - predicate: A predicate which evaluates to `true` for all bytes returned.
|
||||
/// - Returns: The bytes read from the file.
|
||||
/// - Important: This method has been deprecated: use ``read(while:)-8aukk`` instead.
|
||||
@available(*, deprecated, message: "Use the read(while:) method returning a (ByteBuffer, Bool) tuple instead.")
|
||||
public mutating func read(
|
||||
while predicate: (UInt8) -> Bool
|
||||
) async throws -> ByteBuffer {
|
||||
try await self.read(while: predicate).bytes
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
extension ReadableFileHandleProtocol {
|
||||
/// Creates a new ``BufferedReader`` for this file handle.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - initialOffset: The offset to begin reading from, defaults to zero.
|
||||
/// - capacity: The capacity of the buffer in bytes, as a ``ByteCount``. Defaults to 512 KiB.
|
||||
/// - Returns: A ``BufferedReader``.
|
||||
public func bufferedReader(
|
||||
startingAtAbsoluteOffset initialOffset: Int64 = 0,
|
||||
capacity: ByteCount = .kibibytes(512)
|
||||
) -> BufferedReader<Self> {
|
||||
BufferedReader(wrapping: self, initialOffset: initialOffset, capacity: Int(capacity.bytes))
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
extension BufferedReader: Sendable where Handle: Sendable {}
|
||||
@@ -0,0 +1,248 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import NIOCore
|
||||
|
||||
/// A writer which buffers bytes in memory before writing them to the file system.
|
||||
///
|
||||
/// You can create a ``BufferedWriter`` by calling
|
||||
/// ``WritableFileHandleProtocol/bufferedWriter(startingAtAbsoluteOffset:capacity:)`` on
|
||||
/// ``WritableFileHandleProtocol`` and write bytes to it with one of the following methods:
|
||||
/// - ``BufferedWriter/write(contentsOf:)-1rkf6``
|
||||
/// - ``BufferedWriter/write(contentsOf:)-7cs3v``
|
||||
/// - ``BufferedWriter/write(contentsOf:)-66cts``
|
||||
///
|
||||
/// If a call to one of the write functions reaches the buffers ``BufferedWriter/capacity`` the
|
||||
/// buffer automatically writes its contents to the file.
|
||||
///
|
||||
/// - Remark: The writer reclaims the buffer's memory when it grows to more than twice the
|
||||
/// configured size.
|
||||
///
|
||||
/// To write the bytes in the buffer to the file system before the buffer is full
|
||||
/// use ``BufferedWriter/flush()``.
|
||||
///
|
||||
/// - Important: You should you call ``BufferedWriter/flush()`` when you have finished appending
|
||||
/// to write any remaining data to the file system.
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
public struct BufferedWriter<Handle: WritableFileHandleProtocol> {
|
||||
private let handle: Handle
|
||||
/// Offset for the next write.
|
||||
private var offset: Int64
|
||||
/// A buffer of bytes to write.
|
||||
private var buffer: [UInt8] = []
|
||||
|
||||
/// The maximum number of bytes to buffer before the buffer is automatically flushed.
|
||||
public let capacity: Int
|
||||
|
||||
/// The number of bytes in the buffer.
|
||||
///
|
||||
/// You can flush the buffer manually by calling ``flush()``.
|
||||
public var bufferedBytes: Int {
|
||||
self.buffer.count
|
||||
}
|
||||
|
||||
/// The capacity of the buffer.
|
||||
@_spi(Testing)
|
||||
public var bufferCapacity: Int {
|
||||
self.buffer.capacity
|
||||
}
|
||||
|
||||
internal init(wrapping writableHandle: Handle, initialOffset: Int64, capacity: Int) {
|
||||
precondition(
|
||||
initialOffset >= 0,
|
||||
"initialOffset (\(initialOffset)) must be greater than or equal to zero"
|
||||
)
|
||||
precondition(capacity > 0, "capacity (\(capacity)) must be greater than zero")
|
||||
self.handle = writableHandle
|
||||
self.offset = initialOffset
|
||||
self.capacity = capacity
|
||||
}
|
||||
|
||||
/// Write the contents of the collection of bytes to the buffer.
|
||||
///
|
||||
/// If the number of bytes in the buffer exceeds the size of the buffer then they're
|
||||
/// automatically written to the file system.
|
||||
///
|
||||
/// - Remark: The writer reclaims the buffer's memory when it grows to more than twice the
|
||||
/// configured size.
|
||||
///
|
||||
/// To manually flush bytes use ``flush()``.
|
||||
///
|
||||
/// - Parameter bytes: The bytes to write to the buffer.
|
||||
/// - Returns: The number of bytes written into the buffered writer.
|
||||
@discardableResult
|
||||
public mutating func write(contentsOf bytes: some Sequence<UInt8>) async throws -> Int64 {
|
||||
let bufferSize = Int64(self.buffer.count)
|
||||
self.buffer.append(contentsOf: bytes)
|
||||
let bytesWritten = Int64(self.buffer.count) &- bufferSize
|
||||
|
||||
if self.buffer.count >= self.capacity {
|
||||
try await self.flush()
|
||||
}
|
||||
|
||||
return bytesWritten
|
||||
}
|
||||
|
||||
/// Write the contents of the `ByteBuffer` into the buffer.
|
||||
///
|
||||
/// If the number of bytes in the buffer exceeds the size of the buffer then they're
|
||||
/// automatically written to the file system.
|
||||
///
|
||||
/// - Remark: The writer reclaims the buffer's memory when it grows to more than twice the
|
||||
/// configured size.
|
||||
///
|
||||
/// To manually flush bytes use ``flush()``.
|
||||
///
|
||||
/// - Parameter bytes: The bytes to write to the buffer.
|
||||
/// - Returns: The number of bytes written into the buffered writer.
|
||||
@discardableResult
|
||||
public mutating func write(contentsOf bytes: ByteBuffer) async throws -> Int64 {
|
||||
try await self.write(contentsOf: bytes.readableBytesView)
|
||||
}
|
||||
|
||||
/// Write the contents of the `AsyncSequence` of byte chunks to the buffer.
|
||||
///
|
||||
/// If appending a chunk to the buffer causes it to exceed the capacity of the buffer then the
|
||||
/// contents of the buffer are automatically written to the file system.
|
||||
///
|
||||
/// - Remark: The writer reclaims the buffer's memory when it grows to more than twice the
|
||||
/// configured size.
|
||||
///
|
||||
/// To manually flush bytes use ``flush()``.
|
||||
///
|
||||
/// - Parameter chunks: The `AsyncSequence` of byte chunks to write to the buffer.
|
||||
/// - Returns: The number of bytes written into the buffered writer.
|
||||
@discardableResult
|
||||
public mutating func write<Chunks: AsyncSequence>(
|
||||
contentsOf chunks: Chunks
|
||||
) async throws -> Int64 where Chunks.Element: Sequence<UInt8> {
|
||||
var bytesWritten: Int64 = 0
|
||||
do {
|
||||
for try await chunk in chunks {
|
||||
bytesWritten += try await self.write(contentsOf: chunk)
|
||||
}
|
||||
} catch let error as FileSystemError {
|
||||
// From call to 'write'.
|
||||
throw error
|
||||
} catch let error {
|
||||
// From iterating the async sequence.
|
||||
throw FileSystemError(
|
||||
code: .unknown,
|
||||
message: "AsyncSequence of bytes threw error while writing to the buffered writer.",
|
||||
cause: error,
|
||||
location: .here()
|
||||
)
|
||||
}
|
||||
return bytesWritten
|
||||
}
|
||||
|
||||
/// Write the contents of the `AsyncSequence` of `ByteBuffer`s into the buffer.
|
||||
///
|
||||
/// If appending a chunk to the buffer causes it to exceed the capacity of the buffer then the
|
||||
/// contents of the buffer are automatically written to the file system.
|
||||
///
|
||||
/// - Remark: The writer reclaims the buffer's memory when it grows to more than twice the
|
||||
/// configured size.
|
||||
///
|
||||
/// To manually flush bytes use ``flush()``.
|
||||
///
|
||||
/// - Parameter chunks: The `AsyncSequence` of `ByteBuffer`s to write.
|
||||
/// - Returns: The number of bytes written into the buffered writer.
|
||||
@discardableResult
|
||||
public mutating func write<Chunks: AsyncSequence>(
|
||||
contentsOf chunks: Chunks
|
||||
) async throws -> Int64 where Chunks.Element == ByteBuffer {
|
||||
try await self.write(contentsOf: chunks.map { $0.readableBytesView })
|
||||
}
|
||||
|
||||
/// Write the contents of the `AsyncSequence` of bytes the buffer.
|
||||
///
|
||||
/// If appending a byte to the buffer causes it to exceed the capacity of the buffer then the
|
||||
/// contents of the buffer are automatically written to the file system.
|
||||
///
|
||||
/// - Remark: The writer reclaims the buffer's memory when it grows to more than twice the
|
||||
/// configured size.
|
||||
///
|
||||
/// To manually flush bytes use ``flush()``.
|
||||
///
|
||||
/// - Parameter bytes: The `AsyncSequence` of bytes to write to the buffer.
|
||||
@discardableResult
|
||||
public mutating func write<Bytes: AsyncSequence>(
|
||||
contentsOf bytes: Bytes
|
||||
) async throws -> Int64 where Bytes.Element == UInt8 {
|
||||
try await self.write(contentsOf: bytes.map { CollectionOfOne($0) })
|
||||
}
|
||||
|
||||
/// Flush any buffered bytes to the file system.
|
||||
///
|
||||
/// - Important: You should you call ``flush()`` when you have finished writing to ensure the
|
||||
/// buffered writer writes any remaining data to the file system.
|
||||
public mutating func flush() async throws {
|
||||
if self.buffer.isEmpty { return }
|
||||
|
||||
try await self.handle.write(contentsOf: self.buffer, toAbsoluteOffset: self.offset)
|
||||
self.offset += Int64(self.buffer.count)
|
||||
|
||||
// The buffer may grow beyond the specified buffer size. Keep the capacity if it's less than
|
||||
// double the intended size, otherwise reclaim the memory.
|
||||
let keepCapacity = self.buffer.capacity <= (self.capacity * 2)
|
||||
self.buffer.removeAll(keepingCapacity: keepCapacity)
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
extension WritableFileHandleProtocol {
|
||||
/// Creates a new ``BufferedWriter`` for this file handle.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - initialOffset: The offset to begin writing at, defaults to zero.
|
||||
/// - capacity: The capacity of the buffer in bytes, as a ``ByteCount``. The writer writes the contents of its
|
||||
/// buffer to the file system when it exceeds this capacity. Defaults to 512 KiB.
|
||||
/// - Returns: A ``BufferedWriter``.
|
||||
public func bufferedWriter(
|
||||
startingAtAbsoluteOffset initialOffset: Int64 = 0,
|
||||
capacity: ByteCount = .kibibytes(512)
|
||||
) -> BufferedWriter<Self> {
|
||||
BufferedWriter(
|
||||
wrapping: self,
|
||||
initialOffset: initialOffset,
|
||||
capacity: Int(capacity.bytes)
|
||||
)
|
||||
}
|
||||
|
||||
/// Convenience function that creates a buffered reader, executes
|
||||
/// the closure that writes the contents into the buffer and calls 'flush()'.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - initialOffset: The offset to begin writing at, defaults to zero.
|
||||
/// - capacity: The capacity of the buffer in bytes, as a ``ByteCount``. The writer writes the contents of its
|
||||
/// buffer to the file system when it exceeds this capacity. Defaults to 512 KiB.
|
||||
/// - body: The closure that writes the contents to the buffer created in this method.
|
||||
/// - Returns: The result of the executed closure.
|
||||
public func withBufferedWriter<Result>(
|
||||
startingAtAbsoluteOffset initialOffset: Int64 = 0,
|
||||
capacity: ByteCount = .kibibytes(512),
|
||||
execute body: (inout BufferedWriter<Self>) async throws -> Result
|
||||
) async throws -> Result {
|
||||
var bufferedWriter = self.bufferedWriter(startingAtAbsoluteOffset: initialOffset, capacity: capacity)
|
||||
return try await withUncancellableTearDown {
|
||||
try await body(&bufferedWriter)
|
||||
} tearDown: { _ in
|
||||
try await bufferedWriter.flush()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
extension BufferedWriter: Sendable where Handle: Sendable {}
|
||||
@@ -0,0 +1,97 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2025 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import NIOCore
|
||||
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
extension ByteBuffer {
|
||||
/// Reads the contents of the file at the path.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The path of the file to read.
|
||||
/// - maximumSizeAllowed: The maximum size of file which can be read, in bytes, as a ``ByteCount``.
|
||||
/// - fileSystem: The ``FileSystemProtocol`` instance to use to read the file.
|
||||
public init(
|
||||
contentsOf path: FilePath,
|
||||
maximumSizeAllowed: ByteCount,
|
||||
fileSystem: some FileSystemProtocol
|
||||
) async throws {
|
||||
self = try await fileSystem.withFileHandle(forReadingAt: path) { handle in
|
||||
try await handle.readToEnd(
|
||||
fromAbsoluteOffset: 0,
|
||||
maximumSizeAllowed: maximumSizeAllowed
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the contents of the file at the path using ``FileSystem``.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The path of the file to read.
|
||||
/// - maximumSizeAllowed: The maximum size of file which can be read, as a ``ByteCount``.
|
||||
public init(
|
||||
contentsOf path: FilePath,
|
||||
maximumSizeAllowed: ByteCount
|
||||
) async throws {
|
||||
self = try await Self(
|
||||
contentsOf: path,
|
||||
maximumSizeAllowed: maximumSizeAllowed,
|
||||
fileSystem: .shared
|
||||
)
|
||||
}
|
||||
|
||||
/// Writes the readable bytes of the ``ByteBuffer`` to a file.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The path of the file to write the contents of the sequence to.
|
||||
/// - offset: The offset into the file to write to, defaults to zero.
|
||||
/// - options: Options for opening the file, defaults to creating a new file.
|
||||
/// - fileSystem: The ``FileSystemProtocol`` instance to use.
|
||||
/// - Returns: The number of bytes written to the file.
|
||||
@discardableResult
|
||||
public func write(
|
||||
toFileAt path: FilePath,
|
||||
absoluteOffset offset: Int64 = 0,
|
||||
options: OpenOptions.Write = .newFile(replaceExisting: false),
|
||||
fileSystem: some FileSystemProtocol
|
||||
) async throws -> Int64 {
|
||||
try await self.readableBytesView.write(
|
||||
toFileAt: path,
|
||||
absoluteOffset: offset,
|
||||
options: options,
|
||||
fileSystem: fileSystem
|
||||
)
|
||||
}
|
||||
|
||||
/// Writes the readable bytes of the ``ByteBuffer`` to a file.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The path of the file to write the contents of the sequence to.
|
||||
/// - offset: The offset into the file to write to, defaults to zero.
|
||||
/// - options: Options for opening the file, defaults to creating a new file.
|
||||
/// - Returns: The number of bytes written to the file.
|
||||
@discardableResult
|
||||
public func write(
|
||||
toFileAt path: FilePath,
|
||||
absoluteOffset offset: Int64 = 0,
|
||||
options: OpenOptions.Write = .newFile(replaceExisting: false)
|
||||
) async throws -> Int64 {
|
||||
try await self.write(
|
||||
toFileAt: path,
|
||||
absoluteOffset: offset,
|
||||
options: options,
|
||||
fileSystem: .shared
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// Represents the number of bytes.
|
||||
public struct ByteCount: Hashable, Sendable {
|
||||
/// The number of bytes
|
||||
public var bytes: Int64
|
||||
|
||||
/// Returns a ``ByteCount`` with a given number of bytes
|
||||
/// - Parameter count: The number of bytes
|
||||
public static func bytes(_ count: Int64) -> ByteCount {
|
||||
ByteCount(bytes: count)
|
||||
}
|
||||
|
||||
/// Returns a ``ByteCount`` with a given number of kilobytes
|
||||
///
|
||||
/// One kilobyte is 1000 bytes.
|
||||
///
|
||||
/// - Parameter count: The number of kilobytes
|
||||
public static func kilobytes(_ count: Int64) -> ByteCount {
|
||||
ByteCount(bytes: 1000 * count)
|
||||
}
|
||||
|
||||
/// Returns a ``ByteCount`` with a given number of megabytes
|
||||
///
|
||||
/// One megabyte is 1,000,000 bytes.
|
||||
///
|
||||
/// - Parameter count: The number of megabytes
|
||||
public static func megabytes(_ count: Int64) -> ByteCount {
|
||||
ByteCount(bytes: 1000 * 1000 * count)
|
||||
}
|
||||
|
||||
/// Returns a ``ByteCount`` with a given number of gigabytes
|
||||
///
|
||||
/// One gigabyte is 1,000,000,000 bytes.
|
||||
///
|
||||
/// - Parameter count: The number of gigabytes
|
||||
public static func gigabytes(_ count: Int64) -> ByteCount {
|
||||
ByteCount(bytes: 1000 * 1000 * 1000 * count)
|
||||
}
|
||||
|
||||
/// Returns a ``ByteCount`` with a given number of kibibytes
|
||||
///
|
||||
/// One kibibyte is 1024 bytes.
|
||||
///
|
||||
/// - Parameter count: The number of kibibytes
|
||||
public static func kibibytes(_ count: Int64) -> ByteCount {
|
||||
ByteCount(bytes: 1024 * count)
|
||||
}
|
||||
|
||||
/// Returns a ``ByteCount`` with a given number of mebibytes
|
||||
///
|
||||
/// One mebibyte is 10,485,760 bytes.
|
||||
///
|
||||
/// - Parameter count: The number of mebibytes
|
||||
public static func mebibytes(_ count: Int64) -> ByteCount {
|
||||
ByteCount(bytes: 1024 * 1024 * count)
|
||||
}
|
||||
|
||||
/// Returns a ``ByteCount`` with a given number of gibibytes
|
||||
///
|
||||
/// One gibibyte is 10,737,418,240 bytes.
|
||||
///
|
||||
/// - Parameter count: The number of gibibytes
|
||||
public static func gibibytes(_ count: Int64) -> ByteCount {
|
||||
ByteCount(bytes: 1024 * 1024 * 1024 * count)
|
||||
}
|
||||
}
|
||||
|
||||
extension ByteCount {
|
||||
/// A ``ByteCount`` for the maximum amount of bytes that can be written to `ByteBuffer`.
|
||||
internal static var byteBufferCapacity: ByteCount {
|
||||
#if arch(arm) || arch(i386) || arch(arm64_32) || arch(wasm32)
|
||||
// on 32-bit platforms we can't make use of a whole UInt32.max (as it doesn't fit in an Int)
|
||||
let byteBufferMaxIndex = UInt32(Int.max)
|
||||
#else
|
||||
// on 64-bit platforms we're good
|
||||
let byteBufferMaxIndex = UInt32.max
|
||||
#endif
|
||||
|
||||
return ByteCount(bytes: Int64(byteBufferMaxIndex))
|
||||
}
|
||||
|
||||
/// A ``ByteCount`` for an unlimited amount of bytes.
|
||||
public static var unlimited: ByteCount {
|
||||
ByteCount(bytes: .max)
|
||||
}
|
||||
}
|
||||
|
||||
extension ByteCount: AdditiveArithmetic {
|
||||
public static var zero: ByteCount { ByteCount(bytes: 0) }
|
||||
|
||||
public static func + (lhs: ByteCount, rhs: ByteCount) -> ByteCount {
|
||||
ByteCount(bytes: lhs.bytes + rhs.bytes)
|
||||
}
|
||||
|
||||
public static func - (lhs: ByteCount, rhs: ByteCount) -> ByteCount {
|
||||
ByteCount(bytes: lhs.bytes - rhs.bytes)
|
||||
}
|
||||
}
|
||||
|
||||
extension ByteCount: Comparable {
|
||||
public static func < (lhs: ByteCount, rhs: ByteCount) -> Bool {
|
||||
lhs.bytes < rhs.bytes
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2025 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import SystemPackage
|
||||
|
||||
extension String {
|
||||
/// Writes the UTF8 encoded `String` to a file.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The path of the file to write the `String` to.
|
||||
/// - offset: The offset into the file to write to, defaults to zero.
|
||||
/// - options: Options for opening the file, defaults to creating a new file.
|
||||
/// - fileSystem: The ``FileSystemProtocol`` instance to use.
|
||||
/// - Returns: The number of bytes written to the file.
|
||||
@discardableResult
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
public func write(
|
||||
toFileAt path: FilePath,
|
||||
absoluteOffset offset: Int64 = 0,
|
||||
options: OpenOptions.Write = .newFile(replaceExisting: false),
|
||||
fileSystem: some FileSystemProtocol
|
||||
) async throws -> Int64 {
|
||||
try await self.utf8.write(
|
||||
toFileAt: path,
|
||||
absoluteOffset: offset,
|
||||
options: options,
|
||||
fileSystem: fileSystem
|
||||
)
|
||||
}
|
||||
|
||||
/// Writes the UTF8 encoded `String` to a file.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The path of the file to write the `String` to.
|
||||
/// - offset: The offset into the file to write to, defaults to zero.
|
||||
/// - options: Options for opening the file, defaults to creating a new file.
|
||||
/// - Returns: The number of bytes written to the file.
|
||||
@discardableResult
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
public func write(
|
||||
toFileAt path: FilePath,
|
||||
absoluteOffset offset: Int64 = 0,
|
||||
options: OpenOptions.Write = .newFile(replaceExisting: false)
|
||||
) async throws -> Int64 {
|
||||
try await self.write(
|
||||
toFileAt: path,
|
||||
absoluteOffset: offset,
|
||||
options: options,
|
||||
fileSystem: .shared
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
extension Sequence<UInt8> where Self: Sendable {
|
||||
/// Writes the contents of the `Sequence` to a file.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The path of the file to write the contents of the sequence to.
|
||||
/// - offset: The offset into the file to write to, defaults to zero.
|
||||
/// - options: Options for opening the file, defaults to creating a new file.
|
||||
/// - fileSystem: The ``FileSystemProtocol`` instance to use.
|
||||
/// - Returns: The number of bytes written to the file.
|
||||
@discardableResult
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
public func write(
|
||||
toFileAt path: FilePath,
|
||||
absoluteOffset offset: Int64 = 0,
|
||||
options: OpenOptions.Write = .newFile(replaceExisting: false),
|
||||
fileSystem: some FileSystemProtocol
|
||||
) async throws -> Int64 {
|
||||
try await fileSystem.withFileHandle(forWritingAt: path, options: options) { handle in
|
||||
try await handle.write(contentsOf: self, toAbsoluteOffset: offset)
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes the contents of the `Sequence` to a file.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The path of the file to write the contents of the sequence to.
|
||||
/// - offset: The offset into the file to write to, defaults to zero.
|
||||
/// - options: Options for opening the file, defaults to creating a new file.
|
||||
/// - Returns: The number of bytes written to the file.
|
||||
@discardableResult
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
public func write(
|
||||
toFileAt path: FilePath,
|
||||
absoluteOffset offset: Int64 = 0,
|
||||
options: OpenOptions.Write = .newFile(replaceExisting: false)
|
||||
) async throws -> Int64 {
|
||||
try await self.write(
|
||||
toFileAt: path,
|
||||
absoluteOffset: offset,
|
||||
options: options,
|
||||
fileSystem: .shared
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
extension AsyncSequence where Self.Element: Sequence<UInt8>, Self: Sendable {
|
||||
/// Writes the contents of the `AsyncSequence` to a file.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The path of the file to write the contents of the sequence to.
|
||||
/// - offset: The offset into the file to write to, defaults to zero.
|
||||
/// - options: Options for opening the file, defaults to creating a new file.
|
||||
/// - fileSystem: The ``FileSystemProtocol`` instance to use.
|
||||
/// - Returns: The number of bytes written to the file.
|
||||
@discardableResult
|
||||
public func write(
|
||||
toFileAt path: FilePath,
|
||||
absoluteOffset offset: Int64 = 0,
|
||||
options: OpenOptions.Write = .newFile(replaceExisting: false),
|
||||
fileSystem: some FileSystemProtocol
|
||||
) async throws -> Int64 {
|
||||
try await fileSystem.withFileHandle(forWritingAt: path, options: options) { handle in
|
||||
var writer = handle.bufferedWriter(startingAtAbsoluteOffset: offset)
|
||||
let bytesWritten = try await writer.write(contentsOf: self)
|
||||
try await writer.flush()
|
||||
return bytesWritten
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes the contents of the `AsyncSequence` to a file.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The path of the file to write the contents of the sequence to.
|
||||
/// - offset: The offset into the file to write to, defaults to zero.
|
||||
/// - options: Options for opening the file, defaults to creating a new file.
|
||||
/// - Returns: The number of bytes written to the file.
|
||||
@discardableResult
|
||||
public func write(
|
||||
toFileAt path: FilePath,
|
||||
absoluteOffset offset: Int64 = 0,
|
||||
options: OpenOptions.Write = .newFile(replaceExisting: false)
|
||||
) async throws -> Int64 {
|
||||
try await self.write(
|
||||
toFileAt: path,
|
||||
absoluteOffset: offset,
|
||||
options: options,
|
||||
fileSystem: .shared
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
extension AsyncSequence where Self.Element == UInt8, Self: Sendable {
|
||||
/// Writes the contents of the `AsyncSequence` to a file.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The path of the file to write the contents of the sequence to.
|
||||
/// - offset: The offset into the file to write to, defaults to zero.
|
||||
/// - options: Options for opening the file, defaults to creating a new file.
|
||||
/// - fileSystem: The ``FileSystemProtocol`` instance to use.
|
||||
/// - Returns: The number of bytes written to the file.
|
||||
@discardableResult
|
||||
public func write(
|
||||
toFileAt path: FilePath,
|
||||
absoluteOffset offset: Int64 = 0,
|
||||
options: OpenOptions.Write = .newFile(replaceExisting: false),
|
||||
fileSystem: some FileSystemProtocol
|
||||
) async throws -> Int64 {
|
||||
try await fileSystem.withFileHandle(forWritingAt: path, options: options) { handle in
|
||||
var writer = handle.bufferedWriter(startingAtAbsoluteOffset: offset)
|
||||
let bytesWritten = try await writer.write(contentsOf: self)
|
||||
try await writer.flush()
|
||||
return bytesWritten
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes the contents of the `AsyncSequence` to a file.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The path of the file to write the contents of the sequence to.
|
||||
/// - offset: The offset into the file to write to, defaults to zero.
|
||||
/// - options: Options for opening the file, defaults to creating a new file.
|
||||
/// - Returns: The number of bytes written to the file.
|
||||
@discardableResult
|
||||
public func write(
|
||||
toFileAt path: FilePath,
|
||||
absoluteOffset offset: Int64 = 0,
|
||||
options: OpenOptions.Write = .newFile(replaceExisting: false)
|
||||
) async throws -> Int64 {
|
||||
try await self.write(
|
||||
toFileAt: path,
|
||||
absoluteOffset: offset,
|
||||
options: options,
|
||||
fileSystem: .shared
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,742 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import CNIODarwin
|
||||
import CNIOLinux
|
||||
import NIOConcurrencyHelpers
|
||||
import NIOCore
|
||||
import NIOPosix
|
||||
import SystemPackage
|
||||
|
||||
/// An `AsyncSequence` of entries in a directory.
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
public struct DirectoryEntries: AsyncSequence, Sendable {
|
||||
public typealias AsyncIterator = DirectoryIterator
|
||||
public typealias Element = DirectoryEntry
|
||||
|
||||
/// The sequence.
|
||||
private let batchedSequence: Batched
|
||||
|
||||
/// Creates a new ``DirectoryEntries`` sequence.
|
||||
internal init(handle: SystemFileHandle, recursive: Bool) {
|
||||
self.batchedSequence = Batched(handle: handle, recursive: recursive)
|
||||
}
|
||||
|
||||
/// Creates a ``DirectoryEntries`` sequence by wrapping an `AsyncSequence` of _batches_ of
|
||||
/// directory entries.
|
||||
@preconcurrency
|
||||
public init<S: AsyncSequence & Sendable>(wrapping sequence: S)
|
||||
where S.Element == Batched.Element, S.AsyncIterator: _NIOFileSystemSendableMetatype {
|
||||
self.batchedSequence = Batched(wrapping: sequence)
|
||||
}
|
||||
|
||||
public func makeAsyncIterator() -> DirectoryIterator {
|
||||
DirectoryIterator(iterator: self.batchedSequence.makeAsyncIterator())
|
||||
}
|
||||
|
||||
/// Returns a sequence of directory entry batches.
|
||||
///
|
||||
/// The batched sequence has its element type as `Array<DirectoryEntry>` rather
|
||||
/// than `DirectoryEntry`. This can enable better performance by reducing the number of
|
||||
/// executor hops.
|
||||
public func batched() -> Batched {
|
||||
self.batchedSequence
|
||||
}
|
||||
|
||||
/// An `AsyncIteratorProtocol` of `DirectoryEntry`.
|
||||
public struct DirectoryIterator: AsyncIteratorProtocol {
|
||||
/// The batched iterator to consume from.
|
||||
private var iterator: Batched.AsyncIterator
|
||||
/// A slice of the current batch being iterated.
|
||||
private var currentBatch: ArraySlice<DirectoryEntry>
|
||||
|
||||
init(iterator: Batched.AsyncIterator) {
|
||||
self.iterator = iterator
|
||||
self.currentBatch = []
|
||||
}
|
||||
|
||||
public mutating func next() async throws -> DirectoryEntry? {
|
||||
if self.currentBatch.isEmpty {
|
||||
let batch = try await self.iterator.next()
|
||||
self.currentBatch = (batch ?? [])[...]
|
||||
}
|
||||
|
||||
return self.currentBatch.popFirst()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
extension DirectoryEntries.AsyncIterator: Sendable {}
|
||||
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
extension DirectoryEntries {
|
||||
/// An `AsyncSequence` of batches of directory entries.
|
||||
///
|
||||
/// The ``Batched`` sequence uses `Array<DirectoryEntry>` as its element type rather
|
||||
/// than `DirectoryEntry`. This can enable better performance by reducing the number of
|
||||
/// executor hops at the cost of ease-of-use.
|
||||
public struct Batched: AsyncSequence, Sendable {
|
||||
public typealias AsyncIterator = BatchedIterator
|
||||
public typealias Element = [DirectoryEntry]
|
||||
|
||||
private let stream: BufferedOrAnyStream<[DirectoryEntry], DirectoryEntryProducer>
|
||||
|
||||
/// Creates a ``DirectoryEntries/Batched`` sequence by wrapping an `AsyncSequence`
|
||||
/// of directory entry batches.
|
||||
@preconcurrency
|
||||
public init<S: AsyncSequence & Sendable>(wrapping sequence: S)
|
||||
where S.Element == Element, S.AsyncIterator: _NIOFileSystemSendableMetatype {
|
||||
self.stream = BufferedOrAnyStream<[DirectoryEntry], DirectoryEntryProducer>(wrapping: sequence)
|
||||
}
|
||||
|
||||
fileprivate init(handle: SystemFileHandle, recursive: Bool) {
|
||||
// Expanding the batches yields watermarks of 256 and 512 directory entries.
|
||||
let stream = NIOThrowingAsyncSequenceProducer.makeBatchedDirectoryEntryStream(
|
||||
handle: handle,
|
||||
recursive: recursive,
|
||||
entriesPerBatch: 64,
|
||||
lowWatermark: 4,
|
||||
highWatermark: 8
|
||||
)
|
||||
|
||||
self.stream = BufferedOrAnyStream(wrapping: stream)
|
||||
}
|
||||
|
||||
public func makeAsyncIterator() -> BatchedIterator {
|
||||
BatchedIterator(wrapping: self.stream.makeAsyncIterator())
|
||||
}
|
||||
|
||||
/// An `AsyncIteratorProtocol` of `Array<DirectoryEntry>`.
|
||||
public struct BatchedIterator: AsyncIteratorProtocol {
|
||||
private var iterator: BufferedOrAnyStream<[DirectoryEntry], DirectoryEntryProducer>.AsyncIterator
|
||||
|
||||
fileprivate init(
|
||||
wrapping iterator: BufferedOrAnyStream<[DirectoryEntry], DirectoryEntryProducer>.AsyncIterator
|
||||
) {
|
||||
self.iterator = iterator
|
||||
}
|
||||
|
||||
public mutating func next() async throws -> [DirectoryEntry]? {
|
||||
try await self.iterator.next()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
extension DirectoryEntries.Batched.AsyncIterator: Sendable {}
|
||||
|
||||
// MARK: - Internal
|
||||
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
extension NIOThrowingAsyncSequenceProducer
|
||||
where
|
||||
Element == [DirectoryEntry],
|
||||
Failure == (any Error),
|
||||
Strategy == NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark,
|
||||
Delegate == DirectoryEntryProducer
|
||||
{
|
||||
fileprivate static func makeBatchedDirectoryEntryStream(
|
||||
handle: SystemFileHandle,
|
||||
recursive: Bool,
|
||||
entriesPerBatch: Int,
|
||||
lowWatermark: Int,
|
||||
highWatermark: Int
|
||||
) -> NIOThrowingAsyncSequenceProducer<
|
||||
[DirectoryEntry], any Error, NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark,
|
||||
DirectoryEntryProducer
|
||||
> {
|
||||
let producer = DirectoryEntryProducer(
|
||||
handle: handle,
|
||||
recursive: recursive,
|
||||
entriesPerBatch: entriesPerBatch
|
||||
)
|
||||
|
||||
let nioThrowingAsyncSequence = NIOThrowingAsyncSequenceProducer.makeSequence(
|
||||
elementType: [DirectoryEntry].self,
|
||||
backPressureStrategy: NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark(
|
||||
lowWatermark: lowWatermark,
|
||||
highWatermark: highWatermark
|
||||
),
|
||||
finishOnDeinit: false,
|
||||
delegate: producer
|
||||
)
|
||||
|
||||
producer.setSequenceProducerSource(nioThrowingAsyncSequence.source)
|
||||
|
||||
return nioThrowingAsyncSequence.sequence
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
private typealias DirectoryEntrySequenceProducer = NIOThrowingAsyncSequenceProducer<
|
||||
[DirectoryEntry], Error, NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark, DirectoryEntryProducer
|
||||
>
|
||||
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
private final class DirectoryEntryProducer: NIOAsyncSequenceProducerDelegate {
|
||||
let state: NIOLockedValueBox<DirectoryEnumerator>
|
||||
let entriesPerBatch: Int
|
||||
|
||||
init(handle: SystemFileHandle, recursive: Bool, entriesPerBatch: Int) {
|
||||
let state = DirectoryEnumerator(handle: handle, recursive: recursive)
|
||||
self.state = NIOLockedValueBox(state)
|
||||
self.entriesPerBatch = entriesPerBatch
|
||||
}
|
||||
|
||||
func didTerminate() {
|
||||
guard let threadPool = self.state.withLockedValue({ $0.threadPoolForClosing() }) else {
|
||||
return
|
||||
}
|
||||
|
||||
threadPool.submit { _ in // always run, even if cancelled
|
||||
self.state.withLockedValue { state in
|
||||
state.closeIfNecessary()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// sets the source within the producer state
|
||||
func setSequenceProducerSource(_ sequenceProducerSource: DirectoryEntrySequenceProducer.Source) {
|
||||
self.state.withLockedValue { state in
|
||||
switch state.state {
|
||||
case .idle:
|
||||
state.sequenceProducerSource = sequenceProducerSource
|
||||
case .done:
|
||||
sequenceProducerSource.finish()
|
||||
case .open, .openPausedProducing:
|
||||
fatalError()
|
||||
case .modifying:
|
||||
fatalError()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func clearSource() {
|
||||
self.state.withLockedValue { state in
|
||||
state.sequenceProducerSource = nil
|
||||
}
|
||||
}
|
||||
|
||||
/// The 'entry point' for producing elements.
|
||||
///
|
||||
/// Calling this function will start producing directory entries asynchronously by dispatching
|
||||
/// work to the IO executor and feeding the result back to the stream source. On yielding to the
|
||||
/// source it will either produce more or be scheduled to produce more. Stopping production
|
||||
/// is signalled via the stream's 'onTermination' handler.
|
||||
func produceMore() {
|
||||
let threadPool = self.state.withLockedValue { state in
|
||||
state.produceMore()
|
||||
}
|
||||
|
||||
// No thread pool means we're done.
|
||||
guard let threadPool = threadPool else { return }
|
||||
|
||||
threadPool.submit {
|
||||
let result: Result<[DirectoryEntry], Error>
|
||||
switch $0 {
|
||||
case .active:
|
||||
result = Result { try self.nextBatch() }
|
||||
case .cancelled:
|
||||
result = .failure(CancellationError())
|
||||
}
|
||||
self.onNextBatchResult(result)
|
||||
}
|
||||
}
|
||||
|
||||
func pauseProducing() {
|
||||
self.state.withLockedValue { state in
|
||||
state.pauseProducing()
|
||||
}
|
||||
}
|
||||
|
||||
private func nextBatch() throws -> [DirectoryEntry] {
|
||||
try self.state.withLockedValue { state in
|
||||
try state.next(self.entriesPerBatch)
|
||||
}
|
||||
}
|
||||
|
||||
private func onNextBatchResult(_ result: Result<[DirectoryEntry], Error>) {
|
||||
switch result {
|
||||
case let .success(entries):
|
||||
self.onNextBatch(entries)
|
||||
case let .failure(error):
|
||||
// Failed to read more entries: close and notify the stream so consumers receive the
|
||||
// error.
|
||||
self.close()
|
||||
let source = self.state.withLockedValue { state in
|
||||
state.sequenceProducerSource
|
||||
}
|
||||
source?.finish(error)
|
||||
self.clearSource()
|
||||
}
|
||||
}
|
||||
|
||||
private func onNextBatch(_ entries: [DirectoryEntry]) {
|
||||
let source = self.state.withLockedValue { state in
|
||||
state.sequenceProducerSource
|
||||
}
|
||||
|
||||
guard let source else {
|
||||
assertionFailure("unexpectedly missing source")
|
||||
return
|
||||
}
|
||||
|
||||
// No entries were read: this must be the end (as the batch size must be greater than zero).
|
||||
if entries.isEmpty {
|
||||
source.finish()
|
||||
self.clearSource()
|
||||
return
|
||||
}
|
||||
|
||||
// Reading short means reading EOF. The enumerator closes itself in that case.
|
||||
let readEOF = entries.count < self.entriesPerBatch
|
||||
|
||||
// Entries were produced: yield them and maybe produce more.
|
||||
let writeResult = source.yield(contentsOf: CollectionOfOne(entries))
|
||||
|
||||
// Exit early if EOF was read; no use in trying to produce more.
|
||||
if readEOF {
|
||||
source.finish()
|
||||
self.clearSource()
|
||||
return
|
||||
}
|
||||
|
||||
switch writeResult {
|
||||
case .produceMore:
|
||||
self.produceMore()
|
||||
case .stopProducing:
|
||||
self.pauseProducing()
|
||||
case .dropped:
|
||||
// The source is finished; mark ourselves as done.
|
||||
self.close()
|
||||
}
|
||||
}
|
||||
|
||||
private func close() {
|
||||
guard let threadPool = self.state.withLockedValue({ $0.threadPoolForClosing() }) else {
|
||||
return
|
||||
}
|
||||
|
||||
threadPool.submit { _ in // always run, even if cancelled
|
||||
self.state.withLockedValue { state in
|
||||
state.closeIfNecessary()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Enumerates a directory in batches.
|
||||
///
|
||||
/// Note that this is not a `Sequence` because we allow for errors to be thrown on `next()`.
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
private struct DirectoryEnumerator: Sendable {
|
||||
internal enum State: @unchecked Sendable {
|
||||
case modifying
|
||||
case idle(SystemFileHandle.SendableView, recursive: Bool)
|
||||
case open(NIOThreadPool, Source, [DirectoryEntry])
|
||||
case openPausedProducing(NIOThreadPool, Source, [DirectoryEntry])
|
||||
case done
|
||||
}
|
||||
|
||||
/// The source of directory entries.
|
||||
internal enum Source {
|
||||
case readdir(CInterop.DirPointer)
|
||||
case fts(CInterop.FTSPointer)
|
||||
}
|
||||
|
||||
/// The current state of enumeration.
|
||||
internal var state: State
|
||||
|
||||
/// The path to the directory being enumerated.
|
||||
private let path: FilePath
|
||||
|
||||
/// The route via which directory entry batches are yielded,
|
||||
/// the sourcing end of the `DirectoryEntrySequenceProducer`
|
||||
internal var sequenceProducerSource: DirectoryEntrySequenceProducer.Source?
|
||||
|
||||
/// Information about an entry returned by FTS. See 'fts(3)'.
|
||||
private enum FTSInfo: Hashable, Sendable {
|
||||
case directoryPreOrder
|
||||
case directoryCausingCycle
|
||||
case ftsDefault
|
||||
case directoryUnreadable
|
||||
case dotFile
|
||||
case directoryPostOrder
|
||||
case error
|
||||
case regularFile
|
||||
case noStatInfoAvailable
|
||||
case noStatInfoRequested
|
||||
case symbolicLink
|
||||
case symbolicLinkToNonExistentTarget
|
||||
|
||||
init?(rawValue: UInt16) {
|
||||
switch Int32(rawValue) {
|
||||
case FTS_D:
|
||||
self = .directoryPreOrder
|
||||
case FTS_DC:
|
||||
self = .directoryCausingCycle
|
||||
case FTS_DEFAULT:
|
||||
self = .ftsDefault
|
||||
case FTS_DNR:
|
||||
self = .directoryUnreadable
|
||||
case FTS_DOT:
|
||||
self = .dotFile
|
||||
case FTS_DP:
|
||||
self = .directoryPostOrder
|
||||
case FTS_ERR:
|
||||
self = .error
|
||||
case FTS_F:
|
||||
self = .regularFile
|
||||
case FTS_NS:
|
||||
self = .noStatInfoAvailable
|
||||
case FTS_NSOK:
|
||||
self = .noStatInfoRequested
|
||||
case FTS_SL:
|
||||
self = .symbolicLink
|
||||
case FTS_SLNONE:
|
||||
self = .symbolicLinkToNonExistentTarget
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal init(handle: SystemFileHandle, recursive: Bool) {
|
||||
self.state = .idle(handle.sendableView, recursive: recursive)
|
||||
self.path = handle.path
|
||||
}
|
||||
|
||||
internal mutating func produceMore() -> NIOThreadPool? {
|
||||
switch self.state {
|
||||
case let .idle(handle, _):
|
||||
return handle.threadPool
|
||||
case let .open(threadPool, _, _):
|
||||
return threadPool
|
||||
case .openPausedProducing(let threadPool, let source, let array):
|
||||
self.state = .open(threadPool, source, array)
|
||||
return threadPool
|
||||
case .done:
|
||||
return nil
|
||||
case .modifying:
|
||||
fatalError()
|
||||
}
|
||||
}
|
||||
|
||||
internal mutating func pauseProducing() {
|
||||
switch self.state {
|
||||
case .open(let threadPool, let source, let array):
|
||||
self.state = .openPausedProducing(threadPool, source, array)
|
||||
case .idle:
|
||||
() // we won't apply back pressure until something has been read
|
||||
case .openPausedProducing, .done:
|
||||
() // no-op
|
||||
case .modifying:
|
||||
fatalError()
|
||||
}
|
||||
}
|
||||
|
||||
internal func threadPoolForClosing() -> NIOThreadPool? {
|
||||
switch self.state {
|
||||
case .open(let threadPool, _, _), .openPausedProducing(let threadPool, _, _):
|
||||
return threadPool
|
||||
case .idle, .done:
|
||||
// Don't need to close in the idle state: we don't own the handle.
|
||||
return nil
|
||||
case .modifying:
|
||||
fatalError()
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the next batch of directory entries.
|
||||
internal mutating func next(_ count: Int) throws -> [DirectoryEntry] {
|
||||
while true {
|
||||
switch self.process(count) {
|
||||
case let .yield(result):
|
||||
return try result.get()
|
||||
case .continue:
|
||||
()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Closes the descriptor, if necessary.
|
||||
internal mutating func closeIfNecessary() {
|
||||
switch self.state {
|
||||
case .idle:
|
||||
// We don't own the handle so don't close it.
|
||||
self.state = .done
|
||||
|
||||
case .open(_, let mode, _), .openPausedProducing(_, let mode, _):
|
||||
self.state = .done
|
||||
switch mode {
|
||||
case .readdir(let dir):
|
||||
_ = Libc.closedir(dir)
|
||||
case .fts(let fts):
|
||||
_ = Libc.ftsClose(fts)
|
||||
}
|
||||
|
||||
case .done:
|
||||
()
|
||||
|
||||
case .modifying:
|
||||
fatalError()
|
||||
}
|
||||
}
|
||||
|
||||
private enum ProcessResult {
|
||||
case yield(Result<[DirectoryEntry], FileSystemError>)
|
||||
case `continue`
|
||||
}
|
||||
|
||||
private mutating func makeReaddirSource(
|
||||
_ handle: SystemFileHandle.SendableView
|
||||
) -> Result<Source, FileSystemError> {
|
||||
handle._duplicate().mapError { dupError in
|
||||
FileSystemError(
|
||||
message: "Unable to open directory stream for '\(handle.path)'.",
|
||||
wrapping: dupError
|
||||
)
|
||||
}.flatMap { descriptor in
|
||||
// We own the descriptor and cede ownership if 'opendir' succeeds; if it doesn't we need
|
||||
// to close it.
|
||||
descriptor.opendir().mapError { errno in
|
||||
// Close the descriptor on error.
|
||||
try? descriptor.close()
|
||||
return FileSystemError.fdopendir(errno: errno, path: handle.path, location: .here())
|
||||
}
|
||||
}.map {
|
||||
.readdir($0)
|
||||
}
|
||||
}
|
||||
|
||||
private mutating func makeFTSSource(
|
||||
_ handle: SystemFileHandle.SendableView
|
||||
) -> Result<Source, FileSystemError> {
|
||||
Libc.ftsOpen(handle.path, options: [.noChangeDir, .physical]).mapError { errno in
|
||||
FileSystemError.open("fts_open", error: errno, path: handle.path, location: .here())
|
||||
}.map {
|
||||
.fts($0)
|
||||
}
|
||||
}
|
||||
|
||||
private mutating func processOpenState(
|
||||
threadPool: NIOThreadPool,
|
||||
dir: CInterop.DirPointer,
|
||||
entries: inout [DirectoryEntry],
|
||||
count: Int
|
||||
) -> (State, ProcessResult) {
|
||||
entries.removeAll(keepingCapacity: true)
|
||||
entries.reserveCapacity(count)
|
||||
|
||||
while entries.count < count {
|
||||
switch Libc.readdir(dir) {
|
||||
case let .success(.some(entry)):
|
||||
// Skip "." and ".." (and empty paths)
|
||||
if self.isThisOrParentDirectory(entry.pointee) {
|
||||
continue
|
||||
}
|
||||
|
||||
let fileType = FileType(direntType: entry.pointee.d_type)
|
||||
let name: FilePath.Component
|
||||
#if canImport(Darwin)
|
||||
// Safe to force unwrap: may be nil if empty, a root, or more than one component.
|
||||
// Empty is checked for above, root can't exist within a directory, and directory
|
||||
// items must be a single path component.
|
||||
name = FilePath.Component(platformString: CNIODarwin_dirent_dname(entry))!
|
||||
#else
|
||||
name = FilePath.Component(platformString: CNIOLinux_dirent_dname(entry))!
|
||||
#endif
|
||||
|
||||
let fullPath = self.path.appending(name)
|
||||
// '!' is okay here: the init returns nil if there is an empty path which we know
|
||||
// isn't the case as 'self.path' is non-empty.
|
||||
entries.append(DirectoryEntry(path: fullPath, type: fileType)!)
|
||||
|
||||
case .success(.none):
|
||||
// Nothing we can do on failure so ignore the result.
|
||||
_ = Libc.closedir(dir)
|
||||
return (.done, .yield(.success(entries)))
|
||||
|
||||
case let .failure(errno):
|
||||
// Nothing we can do on failure so ignore the result.
|
||||
_ = Libc.closedir(dir)
|
||||
let error = FileSystemError.readdir(
|
||||
errno: errno,
|
||||
path: self.path,
|
||||
location: .here()
|
||||
)
|
||||
return (.done, .yield(.failure(error)))
|
||||
}
|
||||
}
|
||||
|
||||
// We must have hit our 'count' limit.
|
||||
return (.open(threadPool, .readdir(dir), entries), .yield(.success(entries)))
|
||||
}
|
||||
|
||||
private mutating func processOpenState(
|
||||
threadPool: NIOThreadPool,
|
||||
fts: CInterop.FTSPointer,
|
||||
entries: inout [DirectoryEntry],
|
||||
count: Int
|
||||
) -> (State, ProcessResult) {
|
||||
entries.removeAll(keepingCapacity: true)
|
||||
entries.reserveCapacity(count)
|
||||
|
||||
while entries.count < count {
|
||||
switch Libc.ftsRead(fts) {
|
||||
case .success(.some(let entry)):
|
||||
let info = FTSInfo(rawValue: entry.pointee.fts_info)
|
||||
switch info {
|
||||
case .directoryPreOrder:
|
||||
let entry = DirectoryEntry(path: entry.path, type: .directory)!
|
||||
entries.append(entry)
|
||||
|
||||
case .directoryPostOrder:
|
||||
() // Don't visit directories twice.
|
||||
|
||||
case .regularFile:
|
||||
let entry = DirectoryEntry(path: entry.path, type: .regular)!
|
||||
entries.append(entry)
|
||||
|
||||
case .symbolicLink, .symbolicLinkToNonExistentTarget:
|
||||
let entry = DirectoryEntry(path: entry.path, type: .symlink)!
|
||||
entries.append(entry)
|
||||
|
||||
case .ftsDefault:
|
||||
// File type is unknown.
|
||||
let entry = DirectoryEntry(path: entry.path, type: .unknown)!
|
||||
entries.append(entry)
|
||||
|
||||
case .error:
|
||||
let errno = Errno(rawValue: entry.pointee.fts_errno)
|
||||
let error = FileSystemError(
|
||||
code: .unknown,
|
||||
message: "Can't read file system tree.",
|
||||
cause: FileSystemError.SystemCallError(systemCall: "fts_read", errno: errno),
|
||||
location: .here()
|
||||
)
|
||||
_ = Libc.ftsClose(fts)
|
||||
return (.done, .yield(.failure(error)))
|
||||
|
||||
case .directoryCausingCycle:
|
||||
() // Cycle found, ignore it and continue.
|
||||
case .directoryUnreadable:
|
||||
() // Can't read directory, ignore it and continue iterating.
|
||||
case .dotFile:
|
||||
() // Ignore "." and ".."
|
||||
case .noStatInfoAvailable:
|
||||
() // No stat info available so we can't list the entry, ignore it.
|
||||
case .noStatInfoRequested:
|
||||
() // Shouldn't happen.
|
||||
|
||||
case nil:
|
||||
() // Unknown, ignore.
|
||||
}
|
||||
|
||||
case .success(.none):
|
||||
// No entries left to iterate.
|
||||
_ = Libc.ftsClose(fts)
|
||||
return (.done, .yield(.success(entries)))
|
||||
|
||||
case .failure(let errno):
|
||||
// Nothing we can do on failure so ignore the result.
|
||||
_ = Libc.ftsClose(fts)
|
||||
let error = FileSystemError.ftsRead(
|
||||
errno: errno,
|
||||
path: self.path,
|
||||
location: .here()
|
||||
)
|
||||
return (.done, .yield(.failure(error)))
|
||||
}
|
||||
}
|
||||
|
||||
// We must have hit our 'count' limit.
|
||||
return (.open(threadPool, .fts(fts), entries), .yield(.success(entries)))
|
||||
}
|
||||
|
||||
private mutating func process(_ count: Int) -> ProcessResult {
|
||||
switch self.state {
|
||||
case let .idle(handle, recursive):
|
||||
let result: Result<Source, FileSystemError>
|
||||
|
||||
if recursive {
|
||||
result = self.makeFTSSource(handle)
|
||||
} else {
|
||||
result = self.makeReaddirSource(handle)
|
||||
}
|
||||
|
||||
switch result {
|
||||
case let .success(source):
|
||||
self.state = .open(handle.threadPool, source, [])
|
||||
return .continue
|
||||
|
||||
case let .failure(error):
|
||||
self.state = .done
|
||||
return .yield(.failure(error))
|
||||
}
|
||||
|
||||
case .open(let threadPool, let mode, var entries):
|
||||
self.state = .modifying
|
||||
|
||||
switch mode {
|
||||
case .readdir(let dir):
|
||||
let (state, result) = self.processOpenState(
|
||||
threadPool: threadPool,
|
||||
dir: dir,
|
||||
entries: &entries,
|
||||
count: count
|
||||
)
|
||||
self.state = state
|
||||
return result
|
||||
|
||||
case .fts(let fts):
|
||||
let (state, result) = self.processOpenState(
|
||||
threadPool: threadPool,
|
||||
fts: fts,
|
||||
entries: &entries,
|
||||
count: count
|
||||
)
|
||||
self.state = state
|
||||
return result
|
||||
}
|
||||
|
||||
case .openPausedProducing:
|
||||
return .yield(.success([]))
|
||||
|
||||
case .done:
|
||||
return .yield(.success([]))
|
||||
|
||||
case .modifying:
|
||||
fatalError()
|
||||
}
|
||||
}
|
||||
|
||||
private func isThisOrParentDirectory(_ entry: CInterop.DirEnt) -> Bool {
|
||||
let dot = CChar(bitPattern: UInt8(ascii: "."))
|
||||
switch (entry.d_name.0, entry.d_name.1, entry.d_name.2) {
|
||||
case (0, _, _), (dot, 0, _), (dot, dot, 0):
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension UnsafeMutablePointer<CInterop.FTSEnt> {
|
||||
fileprivate var path: FilePath {
|
||||
FilePath(platformString: self.pointee.fts_path!)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2025 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import SystemPackage
|
||||
|
||||
/// Information about an item within a directory.
|
||||
public struct DirectoryEntry: Sendable, Hashable, Equatable {
|
||||
/// The path of the directory entry.
|
||||
///
|
||||
/// - Precondition: The path must have at least one component.
|
||||
public let path: FilePath
|
||||
|
||||
/// The name of the entry; the final component of the ``path``.
|
||||
///
|
||||
/// If `path` is "/Users/tim/path-to-4T.key" then `name` will be "path-to-4T.key".
|
||||
public var name: FilePath.Component {
|
||||
self.path.lastComponent!
|
||||
}
|
||||
|
||||
/// The type of entry.
|
||||
public var type: FileType
|
||||
|
||||
/// Creates a directory entry; returns `nil` if `path` has no components.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The path of the directory entry which must contain at least one component.
|
||||
/// - type: The type of entry.
|
||||
public init?(path: FilePath, type: FileType) {
|
||||
if path.components.isEmpty {
|
||||
return nil
|
||||
}
|
||||
|
||||
self.path = path
|
||||
self.type = type
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// These types are used in our public API; expose them to make
|
||||
// life easier for users.
|
||||
@_exported import enum SystemPackage.CInterop
|
||||
@_exported import struct SystemPackage.Errno
|
||||
@_exported import struct SystemPackage.FileDescriptor
|
||||
@_exported import struct SystemPackage.FilePath
|
||||
@_exported import struct SystemPackage.FilePermissions
|
||||
@@ -0,0 +1,547 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import NIOConcurrencyHelpers
|
||||
import NIOCore
|
||||
import NIOPosix
|
||||
import SystemPackage
|
||||
|
||||
/// An `AsyncSequence` of ordered chunks read from a file.
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
public struct FileChunks: AsyncSequence, Sendable {
|
||||
enum ChunkRange {
|
||||
case entireFile
|
||||
case partial(Range<Int64>)
|
||||
}
|
||||
|
||||
public typealias Element = ByteBuffer
|
||||
|
||||
/// The buffered stream.
|
||||
private let stream: BufferedOrAnyStream<ByteBuffer, FileChunkProducer>
|
||||
|
||||
/// Create a ``FileChunks`` sequence backed by wrapping an `AsyncSequence`.
|
||||
@preconcurrency
|
||||
public init<S: AsyncSequence & Sendable>(wrapping sequence: S)
|
||||
where S.Element == ByteBuffer, S.AsyncIterator: _NIOFileSystemSendableMetatype {
|
||||
self.stream = BufferedOrAnyStream(wrapping: sequence)
|
||||
}
|
||||
|
||||
internal init(
|
||||
handle: SystemFileHandle,
|
||||
chunkLength: ByteCount,
|
||||
range: Range<Int64>
|
||||
) {
|
||||
let chunkRange: ChunkRange
|
||||
if range.lowerBound == 0, range.upperBound == .max {
|
||||
chunkRange = .entireFile
|
||||
} else {
|
||||
chunkRange = .partial(range)
|
||||
}
|
||||
|
||||
// TODO: choose reasonable watermarks; this should likely be at least somewhat dependent
|
||||
// on the chunk size.
|
||||
let stream = NIOThrowingAsyncSequenceProducer.makeFileChunksStream(
|
||||
of: ByteBuffer.self,
|
||||
handle: handle,
|
||||
chunkLength: chunkLength.bytes,
|
||||
range: chunkRange,
|
||||
lowWatermark: 4,
|
||||
highWatermark: 8
|
||||
)
|
||||
|
||||
self.stream = BufferedOrAnyStream(wrapping: stream)
|
||||
}
|
||||
|
||||
public func makeAsyncIterator() -> FileChunkIterator {
|
||||
FileChunkIterator(wrapping: self.stream.makeAsyncIterator())
|
||||
}
|
||||
|
||||
public struct FileChunkIterator: AsyncIteratorProtocol {
|
||||
private var iterator: BufferedOrAnyStream<ByteBuffer, FileChunkProducer>.AsyncIterator
|
||||
|
||||
fileprivate init(wrapping iterator: BufferedOrAnyStream<ByteBuffer, FileChunkProducer>.AsyncIterator) {
|
||||
self.iterator = iterator
|
||||
}
|
||||
|
||||
public mutating func next() async throws -> ByteBuffer? {
|
||||
try await self.iterator.next()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
extension FileChunks.FileChunkIterator: Sendable {}
|
||||
|
||||
// MARK: - Internal
|
||||
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
private typealias FileChunkSequenceProducer = NIOThrowingAsyncSequenceProducer<
|
||||
ByteBuffer, Error, NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark, FileChunkProducer
|
||||
>
|
||||
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
extension NIOThrowingAsyncSequenceProducer
|
||||
where
|
||||
Element == ByteBuffer,
|
||||
Failure == Error,
|
||||
Strategy == NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark,
|
||||
Delegate == FileChunkProducer
|
||||
{
|
||||
static func makeFileChunksStream(
|
||||
of: Element.Type = Element.self,
|
||||
handle: SystemFileHandle,
|
||||
chunkLength: Int64,
|
||||
range: FileChunks.ChunkRange,
|
||||
lowWatermark: Int,
|
||||
highWatermark: Int
|
||||
) -> FileChunkSequenceProducer {
|
||||
|
||||
let producer = FileChunkProducer(
|
||||
range: range,
|
||||
handle: handle,
|
||||
chunkLength: chunkLength
|
||||
)
|
||||
|
||||
let nioThrowingAsyncSequence = NIOThrowingAsyncSequenceProducer.makeSequence(
|
||||
elementType: ByteBuffer.self,
|
||||
backPressureStrategy: NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark(
|
||||
lowWatermark: lowWatermark,
|
||||
highWatermark: highWatermark
|
||||
),
|
||||
finishOnDeinit: false,
|
||||
delegate: producer
|
||||
)
|
||||
|
||||
producer.setSource(nioThrowingAsyncSequence.source)
|
||||
|
||||
return nioThrowingAsyncSequence.sequence
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
private final class FileChunkProducer: NIOAsyncSequenceProducerDelegate, Sendable {
|
||||
let state: NIOLockedValueBox<ProducerState>
|
||||
|
||||
let path: FilePath
|
||||
let chunkLength: Int64
|
||||
|
||||
init(range: FileChunks.ChunkRange, handle: SystemFileHandle, chunkLength: Int64) {
|
||||
let state: ProducerState
|
||||
switch range {
|
||||
case .entireFile:
|
||||
state = .init(handle: handle, range: nil)
|
||||
case .partial(let partialRange):
|
||||
state = .init(handle: handle, range: partialRange)
|
||||
}
|
||||
|
||||
self.state = NIOLockedValueBox(state)
|
||||
self.path = handle.path
|
||||
self.chunkLength = chunkLength
|
||||
}
|
||||
|
||||
/// sets the source within the producer state
|
||||
func setSource(_ source: FileChunkSequenceProducer.Source) {
|
||||
self.state.withLockedValue { state in
|
||||
switch state.state {
|
||||
case .producing, .pausedProducing:
|
||||
state.source = source
|
||||
case .done(let emptyRange):
|
||||
if emptyRange {
|
||||
source.finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func clearSource() {
|
||||
self.state.withLockedValue { state in
|
||||
state.source = nil
|
||||
}
|
||||
}
|
||||
|
||||
/// The 'entry point' for producing elements.
|
||||
///
|
||||
/// Calling this function will start producing file chunks asynchronously by dispatching work
|
||||
/// to the IO executor and feeding the result back to the stream source. On yielding to the
|
||||
/// source it will either produce more or be scheduled to produce more. Stopping production
|
||||
/// is signaled via the stream's 'onTermination' handler.
|
||||
func produceMore() {
|
||||
let threadPool = self.state.withLockedValue { state in
|
||||
state.activeThreadPool()
|
||||
}
|
||||
// No thread pool means we're done.
|
||||
guard let threadPool = threadPool else { return }
|
||||
|
||||
threadPool.submit { workItemState in
|
||||
// update state to reflect that we have been requested to perform a read
|
||||
// the read may be performed immediately, queued to be performed later or ignored
|
||||
let requestedReadAction = self.state.withLockedValue { state in
|
||||
state.requestedProduceMore()
|
||||
}
|
||||
|
||||
switch requestedReadAction {
|
||||
case .performRead:
|
||||
let result: Result<ByteBuffer, Error>
|
||||
switch workItemState {
|
||||
case .active:
|
||||
result = Result { try self.readNextChunk() }
|
||||
case .cancelled:
|
||||
result = .failure(CancellationError())
|
||||
}
|
||||
|
||||
switch result {
|
||||
case let .success(bytes):
|
||||
self.didReadNextChunk(bytes)
|
||||
case let .failure(error):
|
||||
// Failed to read: update our state then notify the stream so consumers receive the
|
||||
// error.
|
||||
let source = self.state.withLockedValue { state in
|
||||
state.done()
|
||||
return state.source
|
||||
}
|
||||
source?.finish(error)
|
||||
self.clearSource()
|
||||
}
|
||||
|
||||
case .stop:
|
||||
return
|
||||
}
|
||||
|
||||
let performedReadAction = self.state.withLockedValue { state in
|
||||
state.performedProduceMore()
|
||||
}
|
||||
|
||||
switch performedReadAction {
|
||||
case .readMore:
|
||||
self.produceMore()
|
||||
case .stop:
|
||||
return
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private func readNextChunk() throws -> ByteBuffer {
|
||||
try self.state.withLockedValue { state in
|
||||
state.fileReadingState()
|
||||
}.flatMap {
|
||||
if let (descriptor, range) = $0 {
|
||||
if let range {
|
||||
let remainingBytes = range.upperBound - range.lowerBound
|
||||
let clampedLength = min(self.chunkLength, remainingBytes)
|
||||
return descriptor.readChunk(
|
||||
fromAbsoluteOffset: range.lowerBound,
|
||||
length: clampedLength
|
||||
).mapError { error in
|
||||
.read(usingSyscall: .pread, error: error, path: self.path, location: .here())
|
||||
}
|
||||
} else {
|
||||
return descriptor.readChunk(length: self.chunkLength).mapError { error in
|
||||
.read(usingSyscall: .read, error: error, path: self.path, location: .here())
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// nil means done: return empty to indicate the stream should finish.
|
||||
return .success(ByteBuffer())
|
||||
}
|
||||
}.get()
|
||||
}
|
||||
|
||||
private func didReadNextChunk(_ buffer: ByteBuffer) {
|
||||
let chunkLength = self.chunkLength
|
||||
assert(buffer.readableBytes <= chunkLength)
|
||||
|
||||
let (source, initialState): (FileChunkSequenceProducer.Source?, ProducerState.State) = self.state
|
||||
.withLockedValue { state in
|
||||
state.didReadBytes(buffer.readableBytes)
|
||||
|
||||
// finishing short indicates the file is done
|
||||
if buffer.readableBytes < chunkLength {
|
||||
state.state = .done(emptyRange: false)
|
||||
}
|
||||
return (state.source, state.state)
|
||||
}
|
||||
|
||||
guard let source else {
|
||||
return
|
||||
}
|
||||
|
||||
// No bytes were produced, nothing more to do.
|
||||
if buffer.readableBytes == 0 {
|
||||
source.finish()
|
||||
self.clearSource()
|
||||
}
|
||||
|
||||
// Yield bytes and maybe produce more.
|
||||
let yieldResult = source.yield(contentsOf: CollectionOfOne(buffer))
|
||||
|
||||
switch initialState {
|
||||
case .done:
|
||||
source.finish()
|
||||
self.clearSource()
|
||||
return
|
||||
case .producing, .pausedProducing:
|
||||
()
|
||||
}
|
||||
|
||||
switch yieldResult {
|
||||
case .produceMore:
|
||||
()
|
||||
case .stopProducing:
|
||||
self.state.withLockedValue { state in state.pauseProducing() }
|
||||
case .dropped:
|
||||
// The source is finished; mark ourselves as done.
|
||||
self.state.withLockedValue { state in state.done() }
|
||||
}
|
||||
}
|
||||
|
||||
func didTerminate() {
|
||||
self.state.withLockedValue { state in
|
||||
state.done()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
private struct ProducerState: Sendable {
|
||||
fileprivate struct Producing {
|
||||
/// Possible states for activity relating to performing a read from disk
|
||||
internal enum ActivityState {
|
||||
/// The producer is not currently performing a read from disk
|
||||
case inactive
|
||||
/// The producer is in the critical section for reading from disk
|
||||
case active
|
||||
/// The producer is in the critical section for reading from disk and a further read has been requested.
|
||||
/// This can happen e.g. if a sequence indicates that production should be paused then unpauses and calls
|
||||
/// back into the code before the initial read block has exited.
|
||||
case activeAndQueued
|
||||
}
|
||||
|
||||
/// The handle to read from.
|
||||
var handle: SystemFileHandle.SendableView
|
||||
|
||||
/// An optional range containing the offsets to read from and up to (exclusive)
|
||||
/// The lower bound should be updated after each successful read.
|
||||
/// The upper bound should be used to check if producer should stop.
|
||||
/// If no range is present, then read entire file.
|
||||
var range: Range<Int64>?
|
||||
|
||||
/// Keep track of whether or not we are currently actively engaged in a read
|
||||
/// to protect against re-entrant behavior.
|
||||
var activityState: ActivityState = .inactive
|
||||
}
|
||||
|
||||
internal enum State {
|
||||
/// Can potentially produce values (if the handle is not closed).
|
||||
case producing(Producing)
|
||||
/// Backpressure policy means that we should stop producing new values for now
|
||||
case pausedProducing(Producing)
|
||||
/// Done producing values either by reaching EOF, some error or the stream terminating.
|
||||
case done(emptyRange: Bool)
|
||||
}
|
||||
|
||||
internal var state: State
|
||||
|
||||
/// The route via which file chunks are yielded,
|
||||
/// the sourcing end of the `FileChunkSequenceProducer`
|
||||
internal var source: FileChunkSequenceProducer.Source?
|
||||
|
||||
init(handle: SystemFileHandle, range: Range<Int64>?) {
|
||||
if let range, range.isEmpty {
|
||||
self.state = .done(emptyRange: true)
|
||||
} else {
|
||||
self.state = .producing(.init(handle: handle.sendableView, range: range))
|
||||
}
|
||||
}
|
||||
|
||||
/// Actions which may be taken after 'produce more' is requested.
|
||||
///
|
||||
/// Either perform the read immediately or (optionally queue the read then) stop.
|
||||
internal enum RequestedProduceMoreAction {
|
||||
case performRead
|
||||
case stop
|
||||
}
|
||||
|
||||
/// Update state to reflect that 'produce more' has been requested.
|
||||
mutating func requestedProduceMore() -> RequestedProduceMoreAction {
|
||||
switch self.state {
|
||||
case .producing(var producingState):
|
||||
switch producingState.activityState {
|
||||
case .inactive:
|
||||
producingState.activityState = .active
|
||||
self.state = .producing(producingState)
|
||||
return .performRead
|
||||
case .active:
|
||||
producingState.activityState = .activeAndQueued
|
||||
self.state = .producing(producingState)
|
||||
return .stop
|
||||
case .activeAndQueued:
|
||||
return .stop
|
||||
}
|
||||
|
||||
case .pausedProducing(var producingState):
|
||||
switch producingState.activityState {
|
||||
case .inactive:
|
||||
producingState.activityState = .active
|
||||
self.state = .producing(producingState)
|
||||
return .performRead
|
||||
case .active:
|
||||
producingState.activityState = .activeAndQueued
|
||||
self.state = .pausedProducing(producingState)
|
||||
return .stop
|
||||
case .activeAndQueued:
|
||||
return .stop
|
||||
}
|
||||
|
||||
case .done:
|
||||
return .stop
|
||||
}
|
||||
}
|
||||
|
||||
/// Actions which may be taken after a more data is produced.
|
||||
///
|
||||
/// Either go on to read more or stop.
|
||||
internal enum PerformedProduceMoreAction {
|
||||
case readMore
|
||||
case stop
|
||||
}
|
||||
|
||||
/// Update state to reflect that a more data has been produced.
|
||||
mutating func performedProduceMore() -> PerformedProduceMoreAction {
|
||||
switch self.state {
|
||||
case .producing(var producingState):
|
||||
let oldActivityState = producingState.activityState
|
||||
|
||||
producingState.activityState = .inactive
|
||||
self.state = .producing(producingState)
|
||||
|
||||
switch oldActivityState {
|
||||
case .inactive:
|
||||
preconditionFailure()
|
||||
case .active, .activeAndQueued:
|
||||
return .readMore
|
||||
}
|
||||
|
||||
case .pausedProducing(var producingState):
|
||||
let oldActivityState = producingState.activityState
|
||||
|
||||
producingState.activityState = .inactive
|
||||
self.state = .pausedProducing(producingState)
|
||||
|
||||
switch oldActivityState {
|
||||
case .inactive:
|
||||
preconditionFailure()
|
||||
case .active:
|
||||
return .stop
|
||||
case .activeAndQueued:
|
||||
return .readMore
|
||||
}
|
||||
|
||||
case .done:
|
||||
return .stop
|
||||
}
|
||||
}
|
||||
|
||||
mutating func activeThreadPool() -> NIOThreadPool? {
|
||||
switch self.state {
|
||||
case .producing(let producingState), .pausedProducing(let producingState):
|
||||
return producingState.handle.threadPool
|
||||
case .done:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
mutating func fileReadingState() -> Result<(FileDescriptor, Range<Int64>?)?, FileSystemError> {
|
||||
switch self.state {
|
||||
case .producing(let producingState), .pausedProducing(let producingState):
|
||||
if let descriptor = producingState.handle.descriptorIfAvailable() {
|
||||
return .success((descriptor, producingState.range))
|
||||
} else {
|
||||
let error = FileSystemError(
|
||||
code: .closed,
|
||||
message: "Cannot read from closed file ('\(producingState.handle.path)').",
|
||||
cause: nil,
|
||||
location: .here()
|
||||
)
|
||||
return .failure(error)
|
||||
}
|
||||
case .done:
|
||||
return .success(nil)
|
||||
}
|
||||
}
|
||||
|
||||
mutating func didReadBytes(_ count: Int) {
|
||||
switch self.state {
|
||||
case var .producing(state):
|
||||
switch state.updateRangeWithReadBytes(count) {
|
||||
case .moreToRead:
|
||||
self.state = .producing(state)
|
||||
case .cannotReadMore:
|
||||
self.state = .done(emptyRange: false)
|
||||
}
|
||||
case var .pausedProducing(state):
|
||||
switch state.updateRangeWithReadBytes(count) {
|
||||
case .moreToRead:
|
||||
self.state = .pausedProducing(state)
|
||||
case .cannotReadMore:
|
||||
self.state = .done(emptyRange: false)
|
||||
}
|
||||
case .done:
|
||||
()
|
||||
}
|
||||
}
|
||||
|
||||
mutating func pauseProducing() {
|
||||
switch self.state {
|
||||
case .producing(let state):
|
||||
self.state = .pausedProducing(state)
|
||||
case .pausedProducing, .done:
|
||||
()
|
||||
}
|
||||
}
|
||||
|
||||
mutating func done() {
|
||||
self.state = .done(emptyRange: false)
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
extension ProducerState.Producing {
|
||||
internal enum RangeUpdateOutcome {
|
||||
case moreToRead
|
||||
case cannotReadMore
|
||||
}
|
||||
|
||||
/// Updates the range (the offsets to read from and up to) to reflect the number of bytes which have been read.
|
||||
/// - Parameter count: The number of bytes which have been read.
|
||||
/// - Returns: Returns `.moreToRead` if there are no remaining bytes to read, `.cannotReadMore` otherwise.
|
||||
mutating func updateRangeWithReadBytes(_ count: Int) -> RangeUpdateOutcome {
|
||||
guard let currentRange = self.range else {
|
||||
// we are reading the whole file, just keep going
|
||||
return .moreToRead
|
||||
}
|
||||
|
||||
let newLowerBound = currentRange.lowerBound + Int64(count)
|
||||
|
||||
// we have run out of bytes to read, we are done
|
||||
if newLowerBound >= currentRange.upperBound {
|
||||
self.range = currentRange.upperBound..<currentRange.upperBound
|
||||
return .cannotReadMore
|
||||
}
|
||||
|
||||
// update range, we are not done
|
||||
self.range = newLowerBound..<currentRange.upperBound
|
||||
return .moreToRead
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,357 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2025 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import NIOCore
|
||||
|
||||
/// Provides a ``FileHandle``.
|
||||
///
|
||||
/// Users should not implement or rely on this protocol; its purpose is to reduce boilerplate
|
||||
/// by providing a default implementation of ``FileHandleProtocol`` for types which hold
|
||||
/// a ``FileHandle``.
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
public protocol _HasFileHandle: FileHandleProtocol {
|
||||
var fileHandle: FileHandle { get }
|
||||
}
|
||||
|
||||
// Provides an implementation of `FileHandleProtocol` by calling through to `FileHandle`.
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
extension _HasFileHandle {
|
||||
public func info() async throws -> FileInfo {
|
||||
try await self.fileHandle.info()
|
||||
}
|
||||
|
||||
public func replacePermissions(_ permissions: FilePermissions) async throws {
|
||||
try await self.fileHandle.replacePermissions(permissions)
|
||||
}
|
||||
|
||||
public func addPermissions(_ permissions: FilePermissions) async throws -> FilePermissions {
|
||||
try await self.fileHandle.addPermissions(permissions)
|
||||
}
|
||||
|
||||
public func removePermissions(_ permissions: FilePermissions) async throws -> FilePermissions {
|
||||
try await self.fileHandle.removePermissions(permissions)
|
||||
}
|
||||
|
||||
public func attributeNames() async throws -> [String] {
|
||||
try await self.fileHandle.attributeNames()
|
||||
}
|
||||
|
||||
public func valueForAttribute(_ name: String) async throws -> [UInt8] {
|
||||
try await self.fileHandle.valueForAttribute(name)
|
||||
}
|
||||
|
||||
public func updateValueForAttribute(
|
||||
_ bytes: some (Sendable & RandomAccessCollection<UInt8>),
|
||||
attribute name: String
|
||||
) async throws {
|
||||
try await self.fileHandle.updateValueForAttribute(bytes, attribute: name)
|
||||
}
|
||||
|
||||
public func removeValueForAttribute(_ name: String) async throws {
|
||||
try await self.fileHandle.removeValueForAttribute(name)
|
||||
}
|
||||
|
||||
public func synchronize() async throws {
|
||||
try await self.fileHandle.synchronize()
|
||||
}
|
||||
|
||||
public func withUnsafeDescriptor<R: Sendable>(
|
||||
_ execute: @Sendable @escaping (FileDescriptor) throws -> R
|
||||
) async throws -> R {
|
||||
try await self.fileHandle.withUnsafeDescriptor {
|
||||
try execute($0)
|
||||
}
|
||||
}
|
||||
|
||||
public func detachUnsafeFileDescriptor() throws -> FileDescriptor {
|
||||
try self.fileHandle.detachUnsafeFileDescriptor()
|
||||
}
|
||||
|
||||
public func close() async throws {
|
||||
try await self.fileHandle.close()
|
||||
}
|
||||
|
||||
public func setTimes(
|
||||
lastAccess: FileInfo.Timespec?,
|
||||
lastDataModification: FileInfo.Timespec?
|
||||
) async throws {
|
||||
try await self.fileHandle.setTimes(
|
||||
lastAccess: lastAccess,
|
||||
lastDataModification: lastDataModification
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Implements ``FileHandleProtocol`` by making system calls to interact with the local file system.
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
public struct FileHandle: FileHandleProtocol, Sendable {
|
||||
internal let systemFileHandle: SystemFileHandle
|
||||
|
||||
internal init(wrapping handle: SystemFileHandle) {
|
||||
self.systemFileHandle = handle
|
||||
}
|
||||
|
||||
public func info() async throws -> FileInfo {
|
||||
try await self.systemFileHandle.info()
|
||||
}
|
||||
|
||||
public func replacePermissions(_ permissions: FilePermissions) async throws {
|
||||
try await self.systemFileHandle.replacePermissions(permissions)
|
||||
}
|
||||
|
||||
public func addPermissions(_ permissions: FilePermissions) async throws -> FilePermissions {
|
||||
try await self.systemFileHandle.addPermissions(permissions)
|
||||
}
|
||||
|
||||
public func removePermissions(_ permissions: FilePermissions) async throws -> FilePermissions {
|
||||
try await self.systemFileHandle.removePermissions(permissions)
|
||||
}
|
||||
|
||||
public func attributeNames() async throws -> [String] {
|
||||
try await self.systemFileHandle.attributeNames()
|
||||
}
|
||||
|
||||
public func valueForAttribute(_ name: String) async throws -> [UInt8] {
|
||||
try await self.systemFileHandle.valueForAttribute(name)
|
||||
}
|
||||
|
||||
public func updateValueForAttribute(
|
||||
_ bytes: some (Sendable & RandomAccessCollection<UInt8>),
|
||||
attribute name: String
|
||||
) async throws {
|
||||
try await self.systemFileHandle.updateValueForAttribute(bytes, attribute: name)
|
||||
}
|
||||
|
||||
public func removeValueForAttribute(_ name: String) async throws {
|
||||
try await self.systemFileHandle.removeValueForAttribute(name)
|
||||
}
|
||||
|
||||
public func synchronize() async throws {
|
||||
try await self.systemFileHandle.synchronize()
|
||||
}
|
||||
|
||||
public func withUnsafeDescriptor<R: Sendable>(
|
||||
_ execute: @Sendable @escaping (FileDescriptor) throws -> R
|
||||
) async throws -> R {
|
||||
try await self.systemFileHandle.withUnsafeDescriptor {
|
||||
try execute($0)
|
||||
}
|
||||
}
|
||||
|
||||
public func detachUnsafeFileDescriptor() throws -> FileDescriptor {
|
||||
try self.systemFileHandle.detachUnsafeFileDescriptor()
|
||||
}
|
||||
|
||||
public func close() async throws {
|
||||
try await self.systemFileHandle.close()
|
||||
}
|
||||
|
||||
public func setTimes(
|
||||
lastAccess: FileInfo.Timespec?,
|
||||
lastDataModification: FileInfo.Timespec?
|
||||
) async throws {
|
||||
try await self.systemFileHandle.setTimes(
|
||||
lastAccess: lastAccess,
|
||||
lastDataModification: lastDataModification
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Implements ``ReadableFileHandleProtocol`` by making system calls to interact with the local
|
||||
/// file system.
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
public struct ReadFileHandle: ReadableFileHandleProtocol, _HasFileHandle, Sendable {
|
||||
public let fileHandle: FileHandle
|
||||
|
||||
internal init(wrapping systemFileHandle: SystemFileHandle) {
|
||||
self.fileHandle = FileHandle(wrapping: systemFileHandle)
|
||||
}
|
||||
|
||||
public func readChunk(
|
||||
fromAbsoluteOffset offset: Int64,
|
||||
length: ByteCount
|
||||
) async throws -> ByteBuffer {
|
||||
try await self.fileHandle.systemFileHandle.readChunk(
|
||||
fromAbsoluteOffset: offset,
|
||||
length: length
|
||||
)
|
||||
}
|
||||
|
||||
public func readChunks(in range: Range<Int64>, chunkLength: ByteCount) -> FileChunks {
|
||||
self.fileHandle.systemFileHandle.readChunks(in: range, chunkLength: chunkLength)
|
||||
}
|
||||
|
||||
public func setTimes(
|
||||
lastAccess: FileInfo.Timespec?,
|
||||
lastDataModification: FileInfo.Timespec?
|
||||
) async throws {
|
||||
try await self.fileHandle.systemFileHandle.setTimes(
|
||||
lastAccess: lastAccess,
|
||||
lastDataModification: lastDataModification
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Implements ``WritableFileHandleProtocol`` by making system calls to interact with the local
|
||||
/// file system.
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
public struct WriteFileHandle: WritableFileHandleProtocol, _HasFileHandle, Sendable {
|
||||
public let fileHandle: FileHandle
|
||||
|
||||
internal init(wrapping systemFileHandle: SystemFileHandle) {
|
||||
self.fileHandle = FileHandle(wrapping: systemFileHandle)
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
public func write(
|
||||
contentsOf bytes: some (Sequence<UInt8> & Sendable),
|
||||
toAbsoluteOffset offset: Int64
|
||||
) async throws -> Int64 {
|
||||
try await self.fileHandle.systemFileHandle.write(
|
||||
contentsOf: bytes,
|
||||
toAbsoluteOffset: offset
|
||||
)
|
||||
}
|
||||
|
||||
public func resize(to size: ByteCount) async throws {
|
||||
try await self.fileHandle.systemFileHandle.resize(to: size)
|
||||
}
|
||||
|
||||
public func close(makeChangesVisible: Bool) async throws {
|
||||
try await self.fileHandle.systemFileHandle.close(makeChangesVisible: makeChangesVisible)
|
||||
}
|
||||
|
||||
public func setTimes(
|
||||
lastAccess: FileInfo.Timespec?,
|
||||
lastDataModification: FileInfo.Timespec?
|
||||
) async throws {
|
||||
try await self.fileHandle.systemFileHandle.setTimes(
|
||||
lastAccess: lastAccess,
|
||||
lastDataModification: lastDataModification
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Implements ``ReadableAndWritableFileHandleProtocol`` by making system calls to interact with the
|
||||
/// local file system.
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
public struct ReadWriteFileHandle: ReadableAndWritableFileHandleProtocol, _HasFileHandle, Sendable {
|
||||
public let fileHandle: FileHandle
|
||||
|
||||
internal init(wrapping systemFileHandle: SystemFileHandle) {
|
||||
self.fileHandle = FileHandle(wrapping: systemFileHandle)
|
||||
}
|
||||
|
||||
public func readChunk(
|
||||
fromAbsoluteOffset offset: Int64,
|
||||
length: ByteCount
|
||||
) async throws -> ByteBuffer {
|
||||
try await self.fileHandle.systemFileHandle.readChunk(
|
||||
fromAbsoluteOffset: offset,
|
||||
length: length
|
||||
)
|
||||
}
|
||||
|
||||
public func readChunks(in offset: Range<Int64>, chunkLength: ByteCount) -> FileChunks {
|
||||
self.fileHandle.systemFileHandle.readChunks(in: offset, chunkLength: chunkLength)
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
public func write(
|
||||
contentsOf bytes: some (Sequence<UInt8> & Sendable),
|
||||
toAbsoluteOffset offset: Int64
|
||||
) async throws -> Int64 {
|
||||
try await self.fileHandle.systemFileHandle.write(
|
||||
contentsOf: bytes,
|
||||
toAbsoluteOffset: offset
|
||||
)
|
||||
}
|
||||
|
||||
public func resize(to size: ByteCount) async throws {
|
||||
try await self.fileHandle.systemFileHandle.resize(to: size)
|
||||
}
|
||||
|
||||
public func close(makeChangesVisible: Bool) async throws {
|
||||
try await self.fileHandle.systemFileHandle.close(makeChangesVisible: makeChangesVisible)
|
||||
}
|
||||
|
||||
public func setTimes(
|
||||
lastAccess: FileInfo.Timespec?,
|
||||
lastDataModification: FileInfo.Timespec?
|
||||
) async throws {
|
||||
try await self.fileHandle.systemFileHandle.setTimes(
|
||||
lastAccess: lastAccess,
|
||||
lastDataModification: lastDataModification
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Implements ``DirectoryFileHandleProtocol`` by making system calls to interact with the local
|
||||
/// file system.
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
public struct DirectoryFileHandle: DirectoryFileHandleProtocol, _HasFileHandle, Sendable {
|
||||
public let fileHandle: FileHandle
|
||||
|
||||
internal init(wrapping systemFileHandle: SystemFileHandle) {
|
||||
self.fileHandle = FileHandle(wrapping: systemFileHandle)
|
||||
}
|
||||
|
||||
public func listContents(recursive: Bool) -> DirectoryEntries {
|
||||
self.fileHandle.systemFileHandle.listContents(recursive: recursive)
|
||||
}
|
||||
|
||||
public func openFile(
|
||||
forReadingAt path: FilePath,
|
||||
options: OpenOptions.Read
|
||||
) async throws -> ReadFileHandle {
|
||||
let systemFileHandle = try await self.fileHandle.systemFileHandle.openFile(
|
||||
forReadingAt: path,
|
||||
options: options
|
||||
)
|
||||
return ReadFileHandle(wrapping: systemFileHandle)
|
||||
}
|
||||
|
||||
public func openFile(
|
||||
forWritingAt path: FilePath,
|
||||
options: OpenOptions.Write
|
||||
) async throws -> WriteFileHandle {
|
||||
let systemFileHandle = try await self.fileHandle.systemFileHandle.openFile(
|
||||
forWritingAt: path,
|
||||
options: options
|
||||
)
|
||||
return WriteFileHandle(wrapping: systemFileHandle)
|
||||
}
|
||||
|
||||
public func openFile(
|
||||
forReadingAndWritingAt path: FilePath,
|
||||
options: OpenOptions.Write
|
||||
) async throws -> ReadWriteFileHandle {
|
||||
let systemFileHandle = try await self.fileHandle.systemFileHandle.openFile(
|
||||
forReadingAndWritingAt: path,
|
||||
options: options
|
||||
)
|
||||
return ReadWriteFileHandle(wrapping: systemFileHandle)
|
||||
}
|
||||
|
||||
public func openDirectory(
|
||||
atPath path: FilePath,
|
||||
options: OpenOptions.Directory
|
||||
) async throws -> DirectoryFileHandle {
|
||||
let systemFileHandle = try await self.fileHandle.systemFileHandle.openDirectory(
|
||||
atPath: path,
|
||||
options: options
|
||||
)
|
||||
return DirectoryFileHandle(wrapping: systemFileHandle)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,769 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2025 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
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
|
||||
|
||||
/// Sets the file's last access and last data modification times to the given values.
|
||||
///
|
||||
/// If **either** time is `nil`, the current value will not be changed.
|
||||
/// If **both** times are `nil`, then both times will be set to the current time.
|
||||
///
|
||||
/// > Important: Times are only considered valid if their nanoseconds components are one of the following:
|
||||
/// > - `UTIME_NOW` (you can use ``FileInfo/Timespec/now`` to get a Timespec set to this value),
|
||||
/// > - `UTIME_OMIT` (you can use ``FileInfo/Timespec/omit`` to get a Timespec set to this value),
|
||||
/// > - Greater than zero and no larger than 1000 million: if outside of this range, the value will be clamped to the closest valid value.
|
||||
/// > The seconds component must also be positive: if it's not, zero will be used as the value instead.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - lastAccess: The new value of the file's last access time, as time elapsed since the Epoch.
|
||||
/// - lastDataModification: The new value of the file's last data modification time, as time elapsed since the Epoch.
|
||||
///
|
||||
/// - Throws: If there's an error updating the times. If this happens, the original values won't be modified.
|
||||
func setTimes(
|
||||
lastAccess: FileInfo.Timespec?,
|
||||
lastDataModification: FileInfo.Timespec?
|
||||
) 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.
|
||||
/// - 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 {
|
||||
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.
|
||||
/// - 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 {
|
||||
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.
|
||||
/// - 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.
|
||||
/// - 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.
|
||||
/// - 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.
|
||||
/// - 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 {
|
||||
self.readChunks(in: 0..<Int64.max, chunkLength: chunkLength)
|
||||
}
|
||||
|
||||
/// Returns an asynchronous sequence of chunks read from the file.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - chunkLength: The length of chunks to read, defaults to 128 KiB.
|
||||
/// - SeeAlso: ``ReadableFileHandleProtocol/readChunks(in:chunkLength:)-2dz6``.
|
||||
/// - Returns: An `AsyncSequence` of chunks read from the file.
|
||||
public func readChunks(
|
||||
chunkLength: ByteCount = .kibibytes(128)
|
||||
) -> FileChunks {
|
||||
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 `maximumSizeAllowed` is more than can be written to `ByteBuffer`. Or if there are more bytes to read than
|
||||
/// `maximumBytesAllowed`.
|
||||
public func readToEnd(
|
||||
fromAbsoluteOffset offset: Int64 = 0,
|
||||
maximumSizeAllowed: ByteCount
|
||||
) async throws -> ByteBuffer {
|
||||
let maximumSizeAllowed = maximumSizeAllowed == .unlimited ? .byteBufferCapacity : maximumSizeAllowed
|
||||
let info = try await self.info()
|
||||
let fileSize = Int64(info.size)
|
||||
let readSize = max(Int(fileSize - offset), 0)
|
||||
|
||||
if maximumSizeAllowed > .byteBufferCapacity {
|
||||
throw FileSystemError(
|
||||
code: .resourceExhausted,
|
||||
message: """
|
||||
The maximum size allowed (\(maximumSizeAllowed)) is more than the maximum \
|
||||
amount of bytes that can be written to ByteBuffer \
|
||||
(\(ByteCount.byteBufferCapacity)). You can read the file in smaller chunks by \
|
||||
calling readChunks().
|
||||
""",
|
||||
cause: nil,
|
||||
location: .here()
|
||||
)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
extension WritableFileHandleProtocol {
|
||||
/// Write the readable bytes of the `ByteBuffer` 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:
|
||||
/// - buffer: 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
|
||||
public func write(
|
||||
contentsOf buffer: ByteBuffer,
|
||||
toAbsoluteOffset offset: Int64
|
||||
) async throws -> Int64 {
|
||||
try await self.write(contentsOf: buffer.readableBytesView, toAbsoluteOffset: offset)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - File times modifiers
|
||||
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
extension FileHandleProtocol {
|
||||
/// Sets the file's last access time to the given time.
|
||||
///
|
||||
/// - Parameter time: The time to which the file's last access time should be set.
|
||||
///
|
||||
/// - Throws: If there's an error updating the time. If this happens, the original value won't be modified.
|
||||
public func setLastAccessTime(to time: FileInfo.Timespec) async throws {
|
||||
try await self.setTimes(lastAccess: time, lastDataModification: nil)
|
||||
}
|
||||
|
||||
/// Sets the file's last data modification time to the given time.
|
||||
///
|
||||
/// - Parameter time: The time to which the file's last data modification time should be set.
|
||||
///
|
||||
/// - Throws: If there's an error updating the time. If this happens, the original value won't be modified.
|
||||
public func setLastDataModificationTime(to time: FileInfo.Timespec) async throws {
|
||||
try await self.setTimes(lastAccess: nil, lastDataModification: time)
|
||||
}
|
||||
|
||||
/// Sets the file's last access and last data modification times to the current time.
|
||||
///
|
||||
/// - Throws: If there's an error updating the times. If this happens, the original values won't be modified.
|
||||
public func touch() async throws {
|
||||
try await self.setTimes(lastAccess: nil, lastDataModification: nil)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
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 ``DirectoryFileHandleProtocol/withFileHandle(forWritingAt:options:execute:)-36f0k``
|
||||
/// and ``DirectoryFileHandleProtocol/withFileHandle(forReadingAndWritingAt:options:execute:)-5j0f3``,
|
||||
/// 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<Result>(
|
||||
forReadingAt path: FilePath,
|
||||
options: OpenOptions.Read = OpenOptions.Read(),
|
||||
execute body: (_ read: ReadFileHandle) async throws -> Result
|
||||
) async throws -> Result {
|
||||
let handle = try await self.openFile(forReadingAt: path, options: options)
|
||||
|
||||
return try await withUncancellableTearDown {
|
||||
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 ``DirectoryFileHandleProtocol/withFileHandle(forReadingAt:options:execute:)-52xsn`` and
|
||||
/// ``DirectoryFileHandleProtocol/withFileHandle(forReadingAndWritingAt:options:execute:)-5j0f3``,
|
||||
/// 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<Result>(
|
||||
forWritingAt path: FilePath,
|
||||
options: OpenOptions.Write = .newFile(replaceExisting: false),
|
||||
execute body: (_ write: WriteFileHandle) async throws -> Result
|
||||
) async throws -> Result {
|
||||
let handle = try await self.openFile(forWritingAt: path, options: options)
|
||||
|
||||
return try await withUncancellableTearDown {
|
||||
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 ``DirectoryFileHandleProtocol/withFileHandle(forReadingAt:options:execute:)-52xsn`` and
|
||||
/// ``DirectoryFileHandleProtocol/withFileHandle(forWritingAt:options:execute:)-36f0k``, 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<Result>(
|
||||
forReadingAndWritingAt path: FilePath,
|
||||
options: OpenOptions.Write = .newFile(replaceExisting: false),
|
||||
execute body: (_ readWrite: ReadWriteFileHandle) async throws -> Result
|
||||
) async throws -> Result {
|
||||
let handle = try await self.openFile(forReadingAndWritingAt: path, options: options)
|
||||
|
||||
return try await withUncancellableTearDown {
|
||||
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.
|
||||
/// - options: How the directory should be opened.
|
||||
/// - 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<Result>(
|
||||
atPath path: FilePath,
|
||||
options: OpenOptions.Directory = OpenOptions.Directory(),
|
||||
execute body: (_ directory: Self) async throws -> Result
|
||||
) async throws -> Result {
|
||||
let handle = try await self.openDirectory(atPath: path, options: options)
|
||||
|
||||
return try await withUncancellableTearDown {
|
||||
try await body(handle)
|
||||
} tearDown: { _ in
|
||||
try await handle.close()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import SystemPackage
|
||||
|
||||
#if canImport(Darwin)
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
@preconcurrency import Glibc
|
||||
import CNIOLinux
|
||||
#elseif canImport(Musl)
|
||||
@preconcurrency import Musl
|
||||
import CNIOLinux
|
||||
#elseif canImport(Android)
|
||||
@preconcurrency import Android
|
||||
import CNIOLinux
|
||||
#endif
|
||||
|
||||
/// Information about a file system object.
|
||||
///
|
||||
/// The information available for a file depends on the platform, ``FileInfo`` provides
|
||||
/// convenient access to a common subset of properties. Using these properties ensures that
|
||||
/// code is portable. If available, the platform specific information is made available via
|
||||
/// ``FileInfo/platformSpecificStatus``. However users should take care to ensure their
|
||||
/// code uses the correct platform checks when using it to ensure their code is portable.
|
||||
public struct FileInfo: Hashable, Sendable {
|
||||
/// Wraps `CInterop.Stat` providing `Hashable` and `Equatable` conformance.
|
||||
private var _platformSpecificStatus: Stat?
|
||||
|
||||
/// The information about the file returned from the filesystem, if available.
|
||||
///
|
||||
/// This value is platform specific: you should be careful when using
|
||||
/// it as some of its fields vary across platforms. In most cases prefer
|
||||
/// using other properties on this type instead.
|
||||
///
|
||||
/// See also: the manual pages for 'stat' (`man 2 stat`)
|
||||
public var platformSpecificStatus: CInterop.Stat? {
|
||||
get { self._platformSpecificStatus?.stat }
|
||||
set { self._platformSpecificStatus = newValue.map { Stat($0) } }
|
||||
}
|
||||
|
||||
/// The type of the file.
|
||||
public var type: FileType
|
||||
|
||||
/// Permissions currently set on the file.
|
||||
public var permissions: FilePermissions
|
||||
|
||||
/// The size of the file in bytes.
|
||||
public var size: Int64
|
||||
|
||||
/// User ID of the file.
|
||||
public var userID: UserID
|
||||
|
||||
/// Group ID of the file.
|
||||
public var groupID: GroupID
|
||||
|
||||
/// The last time the file was accessed.
|
||||
public var lastAccessTime: Timespec
|
||||
|
||||
/// The last time the files data was last changed.
|
||||
public var lastDataModificationTime: Timespec
|
||||
|
||||
/// The last time the status of the file was changed.
|
||||
public var lastStatusChangeTime: Timespec
|
||||
|
||||
/// Creates a ``FileInfo`` by deriving values from a platform-specific value.
|
||||
public init(platformSpecificStatus: CInterop.Stat) {
|
||||
self._platformSpecificStatus = Stat(platformSpecificStatus)
|
||||
self.type = FileType(platformSpecificMode: CInterop.Mode(platformSpecificStatus.st_mode))
|
||||
self.permissions = FilePermissions(masking: CInterop.Mode(platformSpecificStatus.st_mode))
|
||||
self.size = Int64(platformSpecificStatus.st_size)
|
||||
self.userID = UserID(rawValue: platformSpecificStatus.st_uid)
|
||||
self.groupID = GroupID(rawValue: platformSpecificStatus.st_gid)
|
||||
|
||||
#if canImport(Darwin)
|
||||
self.lastAccessTime = Timespec(platformSpecificStatus.st_atimespec)
|
||||
self.lastDataModificationTime = Timespec(platformSpecificStatus.st_mtimespec)
|
||||
self.lastStatusChangeTime = Timespec(platformSpecificStatus.st_ctimespec)
|
||||
#elseif canImport(Glibc) || canImport(Musl) || canImport(Android)
|
||||
self.lastAccessTime = Timespec(platformSpecificStatus.st_atim)
|
||||
self.lastDataModificationTime = Timespec(platformSpecificStatus.st_mtim)
|
||||
self.lastStatusChangeTime = Timespec(platformSpecificStatus.st_ctim)
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Creates a ``FileInfo`` from the provided values.
|
||||
///
|
||||
/// If you have a platform specific status value prefer calling
|
||||
/// ``init(platformSpecificStatus:)``.
|
||||
public init(
|
||||
type: FileType,
|
||||
permissions: FilePermissions,
|
||||
size: Int64,
|
||||
userID: UserID,
|
||||
groupID: GroupID,
|
||||
lastAccessTime: Timespec,
|
||||
lastDataModificationTime: Timespec,
|
||||
lastStatusChangeTime: Timespec
|
||||
) {
|
||||
self._platformSpecificStatus = nil
|
||||
self.type = type
|
||||
self.permissions = permissions
|
||||
self.size = size
|
||||
self.userID = userID
|
||||
self.groupID = groupID
|
||||
self.lastAccessTime = lastAccessTime
|
||||
self.lastDataModificationTime = lastDataModificationTime
|
||||
self.lastStatusChangeTime = lastStatusChangeTime
|
||||
}
|
||||
}
|
||||
|
||||
extension FileInfo {
|
||||
/// The numeric ID of a user.
|
||||
public struct UserID: Hashable, Sendable, CustomStringConvertible {
|
||||
public var rawValue: UInt32
|
||||
|
||||
public init(rawValue: UInt32) {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
public var description: String {
|
||||
String(describing: self.rawValue)
|
||||
}
|
||||
}
|
||||
|
||||
/// The numeric ID of a group.
|
||||
public struct GroupID: Hashable, Sendable, CustomStringConvertible {
|
||||
public var rawValue: UInt32
|
||||
|
||||
public init(rawValue: UInt32) {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
public var description: String {
|
||||
String(describing: self.rawValue)
|
||||
}
|
||||
}
|
||||
|
||||
/// A time interval consisting of whole seconds and nanoseconds.
|
||||
public struct Timespec: Hashable, Sendable {
|
||||
#if canImport(Darwin)
|
||||
private static let utimeOmit = Int(UTIME_OMIT)
|
||||
private static let utimeNow = Int(UTIME_NOW)
|
||||
#elseif canImport(Glibc) || canImport(Musl) || canImport(Android)
|
||||
private static let utimeOmit = Int(CNIOLinux_UTIME_OMIT)
|
||||
private static let utimeNow = Int(CNIOLinux_UTIME_NOW)
|
||||
#endif
|
||||
|
||||
/// A timespec where the seconds are set to zero and the nanoseconds set to `UTIME_OMIT`.
|
||||
/// In syscalls such as `futimens`, this means the time component set to this value will be ignored.
|
||||
public static let omit = Self(
|
||||
seconds: 0,
|
||||
nanoseconds: Self.utimeOmit
|
||||
)
|
||||
|
||||
/// A timespec where the seconds are set to zero and the nanoseconds set to `UTIME_NOW`.
|
||||
/// In syscalls such as `futimens`, this means the time component set to this value will be
|
||||
/// be set to the current time or the largest value supported by the platform, whichever is smaller.
|
||||
public static let now = Self(
|
||||
seconds: 0,
|
||||
nanoseconds: Self.utimeNow
|
||||
)
|
||||
|
||||
/// The number of seconds.
|
||||
public var seconds: Int
|
||||
|
||||
/// The number of nanoseconds.
|
||||
public var nanoseconds: Int
|
||||
|
||||
init(_ timespec: timespec) {
|
||||
self.seconds = timespec.tv_sec
|
||||
self.nanoseconds = timespec.tv_nsec
|
||||
}
|
||||
|
||||
public init(seconds: Int, nanoseconds: Int) {
|
||||
self.seconds = seconds
|
||||
self.nanoseconds = nanoseconds
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A wrapper providing `Hashable` and `Equatable` conformance for `CInterop.Stat`.
|
||||
private struct Stat: Hashable {
|
||||
var stat: CInterop.Stat
|
||||
|
||||
init(_ stat: CInterop.Stat) {
|
||||
self.stat = stat
|
||||
}
|
||||
|
||||
func hash(into hasher: inout Hasher) {
|
||||
let stat = self.stat
|
||||
// Different platforms have different values; these are
|
||||
// common between Darwin and Glibc.
|
||||
hasher.combine(stat.st_dev)
|
||||
hasher.combine(stat.st_mode)
|
||||
hasher.combine(stat.st_nlink)
|
||||
hasher.combine(stat.st_ino)
|
||||
hasher.combine(stat.st_uid)
|
||||
hasher.combine(stat.st_gid)
|
||||
hasher.combine(stat.st_rdev)
|
||||
hasher.combine(stat.st_size)
|
||||
hasher.combine(stat.st_blocks)
|
||||
hasher.combine(stat.st_blksize)
|
||||
|
||||
#if canImport(Darwin)
|
||||
hasher.combine(FileInfo.Timespec(stat.st_atimespec))
|
||||
hasher.combine(FileInfo.Timespec(stat.st_mtimespec))
|
||||
hasher.combine(FileInfo.Timespec(stat.st_ctimespec))
|
||||
hasher.combine(FileInfo.Timespec(stat.st_birthtimespec))
|
||||
hasher.combine(stat.st_flags)
|
||||
hasher.combine(stat.st_gen)
|
||||
#elseif canImport(Glibc) || canImport(Musl) || canImport(Android)
|
||||
hasher.combine(FileInfo.Timespec(stat.st_atim))
|
||||
hasher.combine(FileInfo.Timespec(stat.st_mtim))
|
||||
hasher.combine(FileInfo.Timespec(stat.st_ctim))
|
||||
#endif
|
||||
|
||||
}
|
||||
|
||||
static func == (lhs: Stat, rhs: Stat) -> Bool {
|
||||
let lStat = lhs.stat
|
||||
let rStat = rhs.stat
|
||||
|
||||
// Different platforms have different values; these are
|
||||
// common between Darwin and Glibc.
|
||||
var isEqual = lStat.st_dev == rStat.st_dev
|
||||
isEqual = isEqual && lStat.st_mode == rStat.st_mode
|
||||
isEqual = isEqual && lStat.st_nlink == rStat.st_nlink
|
||||
isEqual = isEqual && lStat.st_ino == rStat.st_ino
|
||||
isEqual = isEqual && lStat.st_uid == rStat.st_uid
|
||||
isEqual = isEqual && lStat.st_gid == rStat.st_gid
|
||||
isEqual = isEqual && lStat.st_rdev == rStat.st_rdev
|
||||
isEqual = isEqual && lStat.st_size == rStat.st_size
|
||||
isEqual = isEqual && lStat.st_blocks == rStat.st_blocks
|
||||
isEqual = isEqual && lStat.st_blksize == rStat.st_blksize
|
||||
|
||||
#if canImport(Darwin)
|
||||
isEqual =
|
||||
isEqual
|
||||
&& FileInfo.Timespec(lStat.st_atimespec) == FileInfo.Timespec(rStat.st_atimespec)
|
||||
isEqual =
|
||||
isEqual
|
||||
&& FileInfo.Timespec(lStat.st_mtimespec) == FileInfo.Timespec(rStat.st_mtimespec)
|
||||
isEqual =
|
||||
isEqual
|
||||
&& FileInfo.Timespec(lStat.st_ctimespec) == FileInfo.Timespec(rStat.st_ctimespec)
|
||||
isEqual =
|
||||
isEqual
|
||||
&& FileInfo.Timespec(lStat.st_birthtimespec)
|
||||
== FileInfo.Timespec(rStat.st_birthtimespec)
|
||||
isEqual = isEqual && lStat.st_flags == rStat.st_flags
|
||||
isEqual = isEqual && lStat.st_gen == rStat.st_gen
|
||||
#elseif canImport(Glibc) || canImport(Musl) || canImport(Android)
|
||||
isEqual = isEqual && FileInfo.Timespec(lStat.st_atim) == FileInfo.Timespec(rStat.st_atim)
|
||||
isEqual = isEqual && FileInfo.Timespec(lStat.st_mtim) == FileInfo.Timespec(rStat.st_mtim)
|
||||
isEqual = isEqual && FileInfo.Timespec(lStat.st_ctim) == FileInfo.Timespec(rStat.st_ctim)
|
||||
#endif
|
||||
|
||||
return isEqual
|
||||
}
|
||||
}
|
||||
|
||||
extension FilePermissions {
|
||||
internal init(masking rawValue: CInterop.Mode) {
|
||||
self = .init(rawValue: rawValue & ~S_IFMT)
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,280 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import SystemPackage
|
||||
|
||||
/// An error thrown as a result of interaction with the file system.
|
||||
///
|
||||
/// All errors have a high-level ``FileSystemError/Code-swift.struct`` which identifies the domain
|
||||
/// of the error. For example an operation performed on a ``FileHandleProtocol`` which has already been
|
||||
/// closed will result in a ``FileSystemError/Code-swift.struct/closed`` error code. Errors also
|
||||
/// include a message describing what went wrong and how to remedy it (if applicable). The
|
||||
/// ``FileSystemError/message`` is not static and may include dynamic information such as the path
|
||||
/// of the file for which the operation failed, for example.
|
||||
///
|
||||
/// Errors may have a ``FileSystemError/cause``, an error which caused the operation to
|
||||
/// fail which may be platform specific.
|
||||
public struct FileSystemError: Error, Sendable {
|
||||
/// A high-level error code to provide broad a classification.
|
||||
public var code: Code
|
||||
|
||||
/// A message describing what went wrong and how it may be remedied.
|
||||
public var message: String
|
||||
|
||||
/// An error which caused the operation to fail. This may include additional details
|
||||
/// about the root cause of the failure.
|
||||
public var cause: Error?
|
||||
|
||||
/// The location from which this error was thrown.
|
||||
public var location: SourceLocation
|
||||
|
||||
public init(
|
||||
code: Code,
|
||||
message: String,
|
||||
cause: Error?,
|
||||
location: SourceLocation
|
||||
) {
|
||||
self.code = code
|
||||
self.message = message
|
||||
self.cause = cause
|
||||
self.location = location
|
||||
}
|
||||
|
||||
/// Creates a ``FileSystemError`` by wrapping the given `cause` and its location and code.
|
||||
internal init(message: String, wrapping cause: FileSystemError) {
|
||||
self.init(code: cause.code, message: message, cause: cause, location: cause.location)
|
||||
}
|
||||
}
|
||||
|
||||
extension FileSystemError: CustomStringConvertible {
|
||||
public var description: String {
|
||||
if let cause = self.cause {
|
||||
return "\(self.code): \(self.message) (\(cause))"
|
||||
} else {
|
||||
return "\(self.code): \(self.message)"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension FileSystemError: CustomDebugStringConvertible {
|
||||
public var debugDescription: String {
|
||||
if let cause = self.cause {
|
||||
return """
|
||||
\(String(reflecting: self.code)): \(String(reflecting: self.message)) \
|
||||
(\(String(reflecting: cause)))
|
||||
"""
|
||||
} else {
|
||||
return "\(String(reflecting: self.code)): \(String(reflecting: self.message))"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension FileSystemError {
|
||||
private func detailedDescriptionLines() -> [String] {
|
||||
// Build up a tree-like description of the error. This allows nested causes to be formatted
|
||||
// correctly, especially when they are also FileSystemErrors.
|
||||
//
|
||||
// An example is:
|
||||
//
|
||||
// FileSystemError: Closed
|
||||
// ├─ Reason: Unable to open file at path 'foo.swift', the descriptor is closed.
|
||||
// ├─ Cause: 'openat' system call failed with '(9) Bad file descriptor'.
|
||||
// └─ Source location: openFile(forReadingAt:_:) (FileSystem.swift:314)
|
||||
var lines = [
|
||||
"FileSystemError: \(self.code)",
|
||||
"├─ Reason: \(self.message)",
|
||||
]
|
||||
|
||||
if let error = self.cause as? FileSystemError {
|
||||
lines.append("├─ Cause:")
|
||||
let causeLines = error.detailedDescriptionLines()
|
||||
// We know this will never be empty.
|
||||
lines.append("│ └─ \(causeLines.first!)")
|
||||
lines.append(contentsOf: causeLines.dropFirst().map { "│ \($0)" })
|
||||
} else if let error = self.cause {
|
||||
lines.append("├─ Cause: \(String(reflecting: error))")
|
||||
}
|
||||
|
||||
lines.append(
|
||||
"└─ Source location: \(self.location.function) (\(self.location.file):\(self.location.line))"
|
||||
)
|
||||
|
||||
return lines
|
||||
}
|
||||
|
||||
/// A detailed multi-line description of the error.
|
||||
///
|
||||
/// - Returns: A multi-line description of the error.
|
||||
public func detailedDescription() -> String {
|
||||
self.detailedDescriptionLines().joined(separator: "\n")
|
||||
}
|
||||
}
|
||||
|
||||
extension FileSystemError {
|
||||
/// A high level indication of the kind of error being thrown.
|
||||
public struct Code: Hashable, Sendable, CustomStringConvertible {
|
||||
private enum Wrapped: Hashable, Sendable, CustomStringConvertible {
|
||||
case closed
|
||||
case invalidArgument
|
||||
case io
|
||||
case permissionDenied
|
||||
case notEmpty
|
||||
case notFound
|
||||
case resourceExhausted
|
||||
case unavailable
|
||||
case unknown
|
||||
case unsupported
|
||||
case fileAlreadyExists
|
||||
|
||||
var description: String {
|
||||
switch self {
|
||||
case .closed:
|
||||
return "Closed"
|
||||
case .invalidArgument:
|
||||
return "Invalid argument"
|
||||
case .io:
|
||||
return "I/O error"
|
||||
case .permissionDenied:
|
||||
return "Permission denied"
|
||||
case .resourceExhausted:
|
||||
return "Resource exhausted"
|
||||
case .notEmpty:
|
||||
return "Not empty"
|
||||
case .notFound:
|
||||
return "Not found"
|
||||
case .unavailable:
|
||||
return "Unavailable"
|
||||
case .unknown:
|
||||
return "Unknown"
|
||||
case .unsupported:
|
||||
return "Unsupported"
|
||||
case .fileAlreadyExists:
|
||||
return "File already exists"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public var description: String {
|
||||
String(describing: self.code)
|
||||
}
|
||||
|
||||
private var code: Wrapped
|
||||
private init(_ code: Wrapped) {
|
||||
self.code = code
|
||||
}
|
||||
|
||||
/// An operation on the file could not be performed because the file is closed
|
||||
/// (or detached).
|
||||
public static var closed: Self {
|
||||
Self(.closed)
|
||||
}
|
||||
|
||||
/// A provided argument was not valid for the operation.
|
||||
public static var invalidArgument: Self {
|
||||
Self(.invalidArgument)
|
||||
}
|
||||
|
||||
/// An I/O error occurred.
|
||||
public static var io: Self {
|
||||
Self(.io)
|
||||
}
|
||||
|
||||
/// The caller did not have sufficient permission to perform the operation.
|
||||
public static var permissionDenied: Self {
|
||||
Self(.permissionDenied)
|
||||
}
|
||||
|
||||
/// A required resource was exhausted.
|
||||
public static var resourceExhausted: Self {
|
||||
Self(.resourceExhausted)
|
||||
}
|
||||
|
||||
/// The directory wasn't empty.
|
||||
public static var notEmpty: Self {
|
||||
Self(.notEmpty)
|
||||
}
|
||||
|
||||
/// The file could not be found.
|
||||
public static var notFound: Self {
|
||||
Self(.notFound)
|
||||
}
|
||||
|
||||
/// The file system is not currently available, for example if the executor
|
||||
/// is not running.
|
||||
public static var unavailable: Self {
|
||||
Self(.unavailable)
|
||||
}
|
||||
|
||||
/// The error is not known or may not have an appropriate classification. See
|
||||
/// ``FileSystemError/cause`` for more information about the error.
|
||||
public static var unknown: Self {
|
||||
Self(.unknown)
|
||||
}
|
||||
|
||||
/// The operation is not supported or is not enabled.
|
||||
public static var unsupported: Self {
|
||||
Self(.unsupported)
|
||||
}
|
||||
|
||||
/// The file already exists.
|
||||
public static var fileAlreadyExists: Self {
|
||||
Self(.fileAlreadyExists)
|
||||
}
|
||||
}
|
||||
|
||||
/// A location within source code.
|
||||
public struct SourceLocation: Sendable, Hashable {
|
||||
/// The function in which the error was thrown.
|
||||
public var function: String
|
||||
|
||||
/// The file in which the error was thrown.
|
||||
public var file: String
|
||||
|
||||
/// The line on which the error was thrown.
|
||||
public var line: Int
|
||||
|
||||
public init(function: String, file: String, line: Int) {
|
||||
self.function = function
|
||||
self.file = file
|
||||
self.line = line
|
||||
}
|
||||
|
||||
internal static func here(
|
||||
function: String = #function,
|
||||
file: String = #fileID,
|
||||
line: Int = #line
|
||||
) -> Self {
|
||||
SourceLocation(function: function, file: file, line: line)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension FileSystemError {
|
||||
/// An error resulting from a system call.
|
||||
public struct SystemCallError: Error, Hashable, CustomStringConvertible {
|
||||
/// The name of the system call which produced the error.
|
||||
public var systemCall: String
|
||||
/// The errno set by the system call.
|
||||
public var errno: Errno
|
||||
|
||||
public init(systemCall: String, errno: Errno) {
|
||||
self.systemCall = systemCall
|
||||
self.errno = errno
|
||||
}
|
||||
|
||||
public var description: String {
|
||||
"'\(self.systemCall)' system call failed with '(\(self.errno.rawValue)) \(self.errno)'."
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,721 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2025 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import SystemPackage
|
||||
|
||||
/// The interface for interacting with a file system.
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
public protocol FileSystemProtocol: Sendable {
|
||||
/// 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
|
||||
|
||||
/// The type of ``DirectoryFileHandleProtocol`` to return when opening directories.
|
||||
associatedtype DirectoryFileHandle: DirectoryFileHandleProtocol
|
||||
where
|
||||
DirectoryFileHandle.ReadFileHandle == ReadFileHandle,
|
||||
DirectoryFileHandle.ReadWriteFileHandle == ReadWriteFileHandle,
|
||||
DirectoryFileHandle.WriteFileHandle == WriteFileHandle
|
||||
|
||||
// MARK: - File access
|
||||
|
||||
/// Opens the file at `path` for reading and returns a handle to it.
|
||||
///
|
||||
/// The file being opened must exist otherwise this function will throw a ``FileSystemError``
|
||||
/// with code ``FileSystemError/Code-swift.struct/notFound``.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The path of the file to open.
|
||||
/// - options: How the file should be opened.
|
||||
/// - Returns: A readable 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.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The path of the file to open relative to the open file.
|
||||
/// - options: How the file should be opened.
|
||||
/// - Returns: A writable 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.
|
||||
///
|
||||
/// - 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.
|
||||
/// Use ``createDirectory(at:withIntermediateDirectories:permissions:)`` to create directories.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The path of the directory to open.
|
||||
/// - options: How the directory should be opened.
|
||||
/// - Returns: A handle to the opened directory.
|
||||
func openDirectory(
|
||||
atPath path: FilePath,
|
||||
options: OpenOptions.Directory
|
||||
) async throws -> DirectoryFileHandle
|
||||
|
||||
/// Create a directory at the given path.
|
||||
///
|
||||
/// If a directory (or file) already exists at `path` then an error will be thrown. If
|
||||
/// `createIntermediateDirectories` is `false` then the full prefix of `path` must already
|
||||
/// exist. If set to `true` then all intermediate directories will be created.
|
||||
///
|
||||
/// Related system calls: `mkdir(2)`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The directory to create.
|
||||
/// - createIntermediateDirectories: Whether intermediate directories should be created.
|
||||
/// - permissions: The permissions to set on the new directory; default permissions will be
|
||||
/// used if not specified.
|
||||
func createDirectory(
|
||||
at path: FilePath,
|
||||
withIntermediateDirectories createIntermediateDirectories: Bool,
|
||||
permissions: FilePermissions?
|
||||
) async throws
|
||||
|
||||
// MARK: - Common directories
|
||||
|
||||
/// Returns the current working directory.
|
||||
var currentWorkingDirectory: FilePath { get async throws }
|
||||
|
||||
/// Returns the path of the temporary directory.
|
||||
var temporaryDirectory: FilePath { get async throws }
|
||||
|
||||
/// Create a temporary directory at the given path, from a template.
|
||||
///
|
||||
/// The template for the path of the temporary directory must end in at least
|
||||
/// three 'X's, which will be replaced with a unique alphanumeric combination.
|
||||
/// The template can contain intermediary directories which will be created
|
||||
/// if they do not exist already.
|
||||
///
|
||||
/// Related system calls: `mkdir(2)`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - template: The template for the path of the temporary directory.
|
||||
/// - Returns:
|
||||
/// - The path to the new temporary directory.
|
||||
func createTemporaryDirectory(
|
||||
template: FilePath
|
||||
) async throws -> FilePath
|
||||
|
||||
// MARK: - File information
|
||||
|
||||
/// Returns information about the file at the given path, if it exists; nil otherwise.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The path to get information about.
|
||||
/// - infoAboutSymbolicLink: If the file is a symbolic link and this parameter is `true` then
|
||||
/// information about the link will be returned, otherwise information about the
|
||||
/// destination of the symbolic link is returned.
|
||||
/// - Returns: Information about the file at the given path or `nil` if no file exists.
|
||||
func info(
|
||||
forFileAt path: FilePath,
|
||||
infoAboutSymbolicLink: Bool
|
||||
) async throws -> FileInfo?
|
||||
|
||||
// MARK: - Symbolic links
|
||||
|
||||
/// Creates a symbolic link that points to the destination.
|
||||
///
|
||||
/// If a file or directory exists at `path` then an error is thrown.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The path at which to create the symbolic link.
|
||||
/// - destinationPath: The path that contains the item that the symbolic link points to.`
|
||||
func createSymbolicLink(
|
||||
at path: FilePath,
|
||||
withDestination destinationPath: FilePath
|
||||
) async throws
|
||||
|
||||
/// Returns the path of the item pointed to by a symbolic link.
|
||||
///
|
||||
/// - Parameter path: The path of a file or directory.
|
||||
/// - Returns: The path of the file or directory to which the symbolic link points to.
|
||||
func destinationOfSymbolicLink(
|
||||
at path: FilePath
|
||||
) async throws -> FilePath
|
||||
|
||||
// MARK: - File copying, removal, and moving
|
||||
|
||||
/// Copies the item at the specified path to a new location.
|
||||
///
|
||||
/// The following error codes may be thrown:
|
||||
/// - ``FileSystemError/Code-swift.struct/notFound`` if the item at `sourcePath` does not exist,
|
||||
/// - ``FileSystemError/Code-swift.struct/invalidArgument`` if an item at `destinationPath`
|
||||
/// exists prior to the copy or its parent directory does not exist.
|
||||
///
|
||||
/// Note that other errors may also be thrown.
|
||||
///
|
||||
/// If `sourcePath` is a symbolic link then only the link is copied. The copied file will
|
||||
/// preserve permissions and any extended attributes (if supported by the file system).
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - sourcePath: The path to the item to copy.
|
||||
/// - destinationPath: The path at which to place the copy.
|
||||
/// - copyStrategy: How to deal with concurrent aspects of the copy, only relevant to directories.
|
||||
/// - shouldProceedAfterError: A closure which is executed to determine whether to continue
|
||||
/// copying files if an error is encountered during the operation. See Errors section for full details.
|
||||
/// - shouldCopyItem: A closure which is executed before each copy to determine whether each
|
||||
/// item should be copied. See Filtering section for full details
|
||||
///
|
||||
/// #### Errors
|
||||
///
|
||||
/// No errors should be throw by implementors without first calling `shouldProceedAfterError`,
|
||||
/// if that returns without throwing this is taken as permission to continue and the error is swallowed.
|
||||
/// If instead the closure throws then ``copyItem(at:to:strategy:shouldProceedAfterError:shouldCopyItem:)``
|
||||
/// will throw and copying will stop, though the precise semantics of this can depend on the `strategy`.
|
||||
///
|
||||
/// if using ``CopyStrategy/parallel(maxDescriptors:)``
|
||||
/// Already started work may continue for an indefinite period of time. In particular, after throwing an error
|
||||
/// it is possible that invocations of `shouldCopyItem` may continue to occur!
|
||||
///
|
||||
/// If using ``CopyStrategy/sequential`` only one invocation of any of the `should*` closures will occur at a time,
|
||||
/// and an error will immediately stop further activity.
|
||||
///
|
||||
/// The specific error thrown from copyItem is undefined, it does not have to be the same error thrown from
|
||||
/// `shouldProceedAfterError`.
|
||||
/// In the event of any errors (ignored or otherwise) implementations are under no obbligation to
|
||||
/// attempt to 'tidy up' after themselves. The state of the file system within `destinationPath`
|
||||
/// after an aborted copy should is undefined.
|
||||
///
|
||||
/// When calling `shouldProceedAfterError` implementations of this method
|
||||
/// MUST:
|
||||
/// - Do so once and only once per item.
|
||||
/// - Not hold any locks when doing so.
|
||||
/// MAY:
|
||||
/// - invoke the function multiple times concurrently (except when using ``CopyStrategy/sequential``)
|
||||
///
|
||||
/// #### Filtering
|
||||
///
|
||||
/// When invoking `shouldCopyItem` implementations of this method
|
||||
/// MUST:
|
||||
/// - Do so once and only once per item.
|
||||
/// - Do so before attempting any operations related to the copy (including determining if they can do so).
|
||||
/// - Not hold any locks when doing so.
|
||||
/// - Check parent directories *before* items within them,
|
||||
/// * if a parent is ignored no items within it should be considered or checked
|
||||
/// - Skip all contents of a directory which is filtered out.
|
||||
/// - Invoke it for the `sourcePath` itself.
|
||||
/// MAY:
|
||||
/// - invoke the function multiple times concurrently (except when using ``CopyStrategy/sequential``)
|
||||
/// - invoke the function an arbitrary point before actually trying to copy the file
|
||||
func copyItem(
|
||||
at sourcePath: FilePath,
|
||||
to destinationPath: FilePath,
|
||||
strategy copyStrategy: CopyStrategy,
|
||||
shouldProceedAfterError: @escaping @Sendable (
|
||||
_ source: DirectoryEntry,
|
||||
_ error: Error
|
||||
) async throws -> Void,
|
||||
shouldCopyItem: @escaping @Sendable (
|
||||
_ source: DirectoryEntry,
|
||||
_ destination: FilePath
|
||||
) async -> Bool
|
||||
) async throws
|
||||
|
||||
/// Deletes the file or directory (and its contents) at `path`.
|
||||
///
|
||||
/// The item to be removed must be a regular file, symbolic link or directory. If no file exists
|
||||
/// at the given path then this function returns zero.
|
||||
///
|
||||
/// If the item at the `path` is a directory and `removeItemRecursively` is `true` then the
|
||||
/// contents of all of its subdirectories will be removed recursively before the directory at
|
||||
/// `path`. Symbolic links are removed (but their targets are not deleted).
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The path to delete.
|
||||
/// - removalStrategy: Whether to delete files sequentially (one-by-one), or perform a
|
||||
/// concurrent scan of the tree at `path` and delete files when they are found. Ignored if
|
||||
/// the item being removed isn't a directory.
|
||||
/// - removeItemRecursively: If the item being removed is a directory, remove it by
|
||||
/// recursively removing its children. Setting this to `true` is synonymous with calling
|
||||
/// `rm -r`, setting this false is synonymous to calling `rmdir`. Ignored if the item
|
||||
/// being removed isn't a directory.
|
||||
/// - Returns: The number of deleted items which may be zero if `path` did not exist.
|
||||
@discardableResult
|
||||
func removeItem(
|
||||
at path: FilePath,
|
||||
strategy removalStrategy: RemovalStrategy,
|
||||
recursively removeItemRecursively: Bool
|
||||
) async throws -> Int
|
||||
|
||||
/// Moves the file or directory at the specified path to a new location.
|
||||
///
|
||||
/// The following error codes may be thrown:
|
||||
/// - ``FileSystemError/Code-swift.struct/notFound`` if the item at `sourcePath` does not exist,
|
||||
/// - ``FileSystemError/Code-swift.struct/invalidArgument`` if an item at `destinationPath`
|
||||
/// exists prior to the copy or its parent directory does not exist.
|
||||
///
|
||||
/// Note that other errors may also be thrown.
|
||||
///
|
||||
/// If the file at `sourcePath` is a symbolic link then only the link is moved to the new path.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - sourcePath: The path to the item to move.
|
||||
/// - destinationPath: The path at which to place the item.
|
||||
func moveItem(at sourcePath: FilePath, to destinationPath: FilePath) async throws
|
||||
|
||||
/// Replaces the item at `destinationPath` with the item at `existingPath`.
|
||||
///
|
||||
/// The following error codes may be thrown:
|
||||
/// - ``FileSystemError/Code-swift.struct/notFound`` if the item at `existingPath` does
|
||||
/// not exist,
|
||||
/// - ``FileSystemError/Code-swift.struct/io`` if the file at `existingPath` was successfully
|
||||
/// copied to `destinationPath` but an error occurred while removing it from `existingPath.`
|
||||
///
|
||||
/// Note that other errors may also be thrown.
|
||||
///
|
||||
/// The item at `destinationPath` is not required to exist. Note that it is possible to replace
|
||||
/// a file with a directory and vice versa. After the file or directory at `destinationPath`
|
||||
/// has been replaced, the item at `existingPath` will be removed.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - destinationPath: The path of the file or directory to replace.
|
||||
/// - existingPath: The path of the existing file or directory.
|
||||
func replaceItem(at destinationPath: FilePath, withItemAt existingPath: FilePath) async throws
|
||||
}
|
||||
|
||||
// MARK: - Open existing files/directories
|
||||
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
extension FileSystemProtocol {
|
||||
/// Opens the file at the given path and provides scoped read-only 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-write or write-only
|
||||
/// mode by calling ``FileSystemProtocol/withFileHandle(forReadingAndWritingAt:options:execute:)-9nqu3`` and
|
||||
/// ``FileSystemProtocol/withFileHandle(forWritingAt:options:execute:)-1p6ka``.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The path of the file to open for reading.
|
||||
/// - options: How the file should be opened.
|
||||
/// - execute: 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<Result>(
|
||||
forReadingAt path: FilePath,
|
||||
options: OpenOptions.Read = OpenOptions.Read(),
|
||||
execute: (_ read: ReadFileHandle) async throws -> Result
|
||||
) async throws -> Result {
|
||||
let handle = try await self.openFile(forReadingAt: path, options: options)
|
||||
return try await withUncancellableTearDown {
|
||||
try await execute(handle)
|
||||
} tearDown: { _ in
|
||||
try await handle.close()
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens the file at the given path and provides scoped write-only 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-write or read-only
|
||||
/// mode by calling ``FileSystemProtocol/withFileHandle(forReadingAndWritingAt:options:execute:)-9nqu3`` and
|
||||
/// ``FileSystemProtocol/withFileHandle(forReadingAt:options:execute:)-nsue``.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The path of the file to open for reading.
|
||||
/// - options: How the file should be opened.
|
||||
/// - execute: 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<Result>(
|
||||
forWritingAt path: FilePath,
|
||||
options: OpenOptions.Write = .newFile(replaceExisting: false),
|
||||
execute: (_ write: WriteFileHandle) async throws -> Result
|
||||
) async throws -> Result {
|
||||
let handle = try await self.openFile(forWritingAt: path, options: options)
|
||||
return try await withUncancellableTearDown {
|
||||
try await execute(handle)
|
||||
} tearDown: { result in
|
||||
switch result {
|
||||
case .success:
|
||||
try await handle.close()
|
||||
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 function returns. Files may also be opened in read-only or
|
||||
/// write-only mode by with ``FileSystemProtocol/withFileHandle(forReadingAt:options:execute:)-nsue`` and
|
||||
/// ``FileSystemProtocol/withFileHandle(forWritingAt:options:execute:)-1p6ka``.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The path of the file to open for reading and writing.
|
||||
/// - options: How the file should be opened.
|
||||
/// - execute: 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<Result>(
|
||||
forReadingAndWritingAt path: FilePath,
|
||||
options: OpenOptions.Write = .newFile(replaceExisting: false),
|
||||
execute: (_ readWrite: ReadWriteFileHandle) async throws -> Result
|
||||
) async throws -> Result {
|
||||
let handle = try await self.openFile(forReadingAndWritingAt: path, options: options)
|
||||
return try await withUncancellableTearDown {
|
||||
try await execute(handle)
|
||||
} tearDown: { _ in
|
||||
try await handle.close()
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens the directory at the given path and provides scoped access to it.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The path of the directory to open.
|
||||
/// - options: How the file should be opened.
|
||||
/// - execute: 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<Result>(
|
||||
atPath path: FilePath,
|
||||
options: OpenOptions.Directory = OpenOptions.Directory(),
|
||||
execute: (_ directory: DirectoryFileHandle) async throws -> Result
|
||||
) async throws -> Result {
|
||||
let handle = try await self.openDirectory(atPath: path, options: options)
|
||||
return try await withUncancellableTearDown {
|
||||
try await execute(handle)
|
||||
} tearDown: { _ in
|
||||
try await handle.close()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
extension FileSystemProtocol {
|
||||
/// Opens the file at `path` for reading and returns a handle to it.
|
||||
///
|
||||
/// The file being opened must exist otherwise this function will throw a ``FileSystemError``
|
||||
/// with code ``FileSystemError/Code-swift.struct/notFound``.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The path of the file to open.
|
||||
/// - Returns: A readable handle to the opened file.
|
||||
public func openFile(
|
||||
forReadingAt path: FilePath
|
||||
) async throws -> ReadFileHandle {
|
||||
try await self.openFile(forReadingAt: path, options: OpenOptions.Read())
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// Use ``createDirectory(at:withIntermediateDirectories:permissions:)`` to create directories.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The path of the directory to open.
|
||||
/// - Returns: A handle to the opened directory.
|
||||
public func openDirectory(
|
||||
atPath path: FilePath
|
||||
) async throws -> DirectoryFileHandle {
|
||||
try await self.openDirectory(atPath: path, options: OpenOptions.Directory())
|
||||
}
|
||||
|
||||
/// Returns information about the file at the given path, if it exists; nil otherwise.
|
||||
///
|
||||
/// Calls ``info(forFileAt:infoAboutSymbolicLink:)`` setting `infoAboutSymbolicLink` to `false`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The path to get information about.
|
||||
/// - Returns: Information about the file at the given path or `nil` if no file exists.
|
||||
public func info(forFileAt path: FilePath) async throws -> FileInfo? {
|
||||
try await self.info(forFileAt: path, infoAboutSymbolicLink: false)
|
||||
}
|
||||
|
||||
/// Copies the item at the specified path to a new location.
|
||||
///
|
||||
/// The following error codes may be thrown:
|
||||
/// - ``FileSystemError/Code-swift.struct/notFound`` if the item at `sourcePath` does not exist,
|
||||
/// - ``FileSystemError/Code-swift.struct/invalidArgument`` if an item at `destinationPath`
|
||||
/// exists prior to the copy or its parent directory does not exist.
|
||||
///
|
||||
/// Note that other errors may also be thrown. If any error is encountered during the copy
|
||||
/// then the copy is aborted. You can modify the behaviour with the `shouldProceedAfterError`
|
||||
/// parameter of ``FileSystemProtocol/copyItem(at:to:strategy:shouldProceedAfterError:shouldCopyItem:)``.
|
||||
///
|
||||
/// If the file at `sourcePath` is a symbolic link then only the link is copied to the new path.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - sourcePath: The path to the item to copy.
|
||||
/// - destinationPath: The path at which to place the copy.
|
||||
/// - copyStrategy: This controls the concurrency used if the file at `sourcePath` is a directory.
|
||||
public func copyItem(
|
||||
at sourcePath: FilePath,
|
||||
to destinationPath: FilePath,
|
||||
strategy copyStrategy: CopyStrategy = .platformDefault
|
||||
) async throws {
|
||||
try await self.copyItem(at: sourcePath, to: destinationPath, strategy: copyStrategy) { path, error in
|
||||
throw error
|
||||
} shouldCopyItem: { source, destination in
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// Copies the item at the specified path to a new location.
|
||||
///
|
||||
/// The item to be copied must be a:
|
||||
/// - regular file,
|
||||
/// - symbolic link, or
|
||||
/// - directory.
|
||||
///
|
||||
/// If `sourcePath` is a symbolic link then only the link is copied. The copied file will
|
||||
/// preserve permissions and any extended attributes (if supported by the file system).
|
||||
///
|
||||
/// #### Errors
|
||||
///
|
||||
/// Error codes thrown include:
|
||||
/// - ``FileSystemError/Code-swift.struct/notFound`` if `sourcePath` doesn't exist.
|
||||
/// - ``FileSystemError/Code-swift.struct/fileAlreadyExists`` if `destinationPath` exists.
|
||||
///
|
||||
/// #### Backward Compatibility details
|
||||
///
|
||||
/// This is implemented in terms of ``copyItem(at:to:strategy:shouldProceedAfterError:shouldCopyItem:)``
|
||||
/// using ``CopyStrategy/sequential`` to avoid changing the concurrency semantics of the should callbacks
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - sourcePath: The path to the item to copy.
|
||||
/// - destinationPath: The path at which to place the copy.
|
||||
/// - shouldProceedAfterError: Determines whether to continue copying files if an error is
|
||||
/// thrown during the operation. This error does not have to match the error passed
|
||||
/// to the closure.
|
||||
/// - shouldCopyFile: A closure which is executed before each file to determine whether the
|
||||
/// file should be copied.
|
||||
@available(*, deprecated, message: "please use copyItem overload taking CopyStrategy")
|
||||
public func copyItem(
|
||||
at sourcePath: FilePath,
|
||||
to destinationPath: FilePath,
|
||||
shouldProceedAfterError: @escaping @Sendable (
|
||||
_ entry: DirectoryEntry,
|
||||
_ error: Error
|
||||
) async throws -> Void,
|
||||
shouldCopyFile: @escaping @Sendable (
|
||||
_ source: FilePath,
|
||||
_ destination: FilePath
|
||||
) async -> Bool
|
||||
) async throws {
|
||||
try await self.copyItem(
|
||||
at: sourcePath,
|
||||
to: destinationPath,
|
||||
strategy: .sequential,
|
||||
shouldProceedAfterError: shouldProceedAfterError,
|
||||
shouldCopyItem: { (source, destination) in
|
||||
await shouldCopyFile(source.path, destination)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
/// Copies the item at the specified path to a new location.
|
||||
///
|
||||
/// The following error codes may be thrown:
|
||||
/// - ``FileSystemError/Code-swift.struct/notFound`` if the item at `sourcePath` does not exist,
|
||||
/// - ``FileSystemError/Code-swift.struct/invalidArgument`` if an item at `destinationPath`
|
||||
/// exists prior to the copy or its parent directory does not exist.
|
||||
///
|
||||
/// Note that other errors may also be thrown.
|
||||
///
|
||||
/// If `sourcePath` is a symbolic link then only the link is copied. The copied file will
|
||||
/// preserve permissions and any extended attributes (if supported by the file system).
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - sourcePath: The path to the item to copy.
|
||||
/// - destinationPath: The path at which to place the copy.
|
||||
/// - shouldProceedAfterError: A closure which is executed to determine whether to continue
|
||||
/// copying files if an error is encountered during the operation. See Errors section for full details.
|
||||
/// - shouldCopyItem: A closure which is executed before each copy to determine whether each
|
||||
/// item should be copied. See Filtering section for full details
|
||||
///
|
||||
/// #### Parallelism
|
||||
///
|
||||
/// This overload uses ``CopyStrategy/platformDefault`` which is likely to result in multiple concurrency domains being used
|
||||
/// in the event of copying a directory.
|
||||
/// See the detailed description on ``copyItem(at:to:strategy:shouldProceedAfterError:shouldCopyItem:)``
|
||||
/// for the implications of this with respect to the `shouldProceedAfterError` and `shouldCopyItem` callbacks
|
||||
public func copyItem(
|
||||
at sourcePath: FilePath,
|
||||
to destinationPath: FilePath,
|
||||
shouldProceedAfterError: @escaping @Sendable (
|
||||
_ source: DirectoryEntry,
|
||||
_ error: Error
|
||||
) async throws -> Void,
|
||||
shouldCopyItem: @escaping @Sendable (
|
||||
_ source: DirectoryEntry,
|
||||
_ destination: FilePath
|
||||
) async -> Bool
|
||||
) async throws {
|
||||
try await self.copyItem(
|
||||
at: sourcePath,
|
||||
to: destinationPath,
|
||||
strategy: .platformDefault,
|
||||
shouldProceedAfterError: shouldProceedAfterError,
|
||||
shouldCopyItem: shouldCopyItem
|
||||
)
|
||||
}
|
||||
|
||||
/// Deletes the file or directory (and its contents) at `path`.
|
||||
///
|
||||
/// The item to be removed must be a regular file, symbolic link or directory. If no file exists
|
||||
/// at the given path then this function returns zero.
|
||||
///
|
||||
/// If the item at the `path` is a directory then the contents of all of its subdirectories will
|
||||
/// be removed recursively before the directory at `path`. Symbolic links are removed (but their
|
||||
/// targets are not deleted).
|
||||
///
|
||||
/// The strategy for deletion will be determined automatically depending on the discovered
|
||||
/// platform.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The path to delete.
|
||||
/// - Returns: The number of deleted items which may be zero if `path` did not exist.
|
||||
@discardableResult
|
||||
public func removeItem(
|
||||
at path: FilePath
|
||||
) async throws -> Int {
|
||||
try await self.removeItem(at: path, strategy: .platformDefault, recursively: true)
|
||||
}
|
||||
|
||||
/// Deletes the file or directory (and its contents) at `path`.
|
||||
///
|
||||
/// The item to be removed must be a regular file, symbolic link or directory. If no file exists
|
||||
/// at the given path then this function returns zero.
|
||||
///
|
||||
/// If the item at the `path` is a directory then the contents of all of its subdirectories will
|
||||
/// be removed recursively before the directory at `path`. Symbolic links are removed (but their
|
||||
/// targets are not deleted).
|
||||
///
|
||||
/// The strategy for deletion will be determined automatically depending on the discovered
|
||||
/// platform.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The path to delete.
|
||||
/// - removeItemRecursively: If the item being removed is a directory, remove it by
|
||||
/// recursively removing its children. Setting this to `true` is synonymous with calling
|
||||
/// `rm -r`, setting this false is synonymous to calling `rmdir`. Ignored if the item
|
||||
/// being removed isn't a directory.
|
||||
/// - Returns: The number of deleted items which may be zero if `path` did not exist.
|
||||
@discardableResult
|
||||
public func removeItem(
|
||||
at path: FilePath,
|
||||
recursively removeItemRecursively: Bool
|
||||
) async throws -> Int {
|
||||
try await self.removeItem(at: path, strategy: .platformDefault, recursively: removeItemRecursively)
|
||||
}
|
||||
|
||||
/// Deletes the file or directory (and its contents) at `path`.
|
||||
///
|
||||
/// The item to be removed must be a regular file, symbolic link or directory. If no file exists
|
||||
/// at the given path then this function returns zero.
|
||||
///
|
||||
/// If the item at the `path` is a directory then the contents of all of its subdirectories will
|
||||
/// be removed recursively before the directory at `path`. Symbolic links are removed (but their
|
||||
/// targets are not deleted).
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The path to delete.
|
||||
/// - removalStrategy: Whether to delete files sequentially (one-by-one), or perform a
|
||||
/// concurrent scan of the tree at `path` and delete files when they are found.
|
||||
/// - Returns: The number of deleted items which may be zero if `path` did not exist.
|
||||
@discardableResult
|
||||
public func removeItem(
|
||||
at path: FilePath,
|
||||
strategy removalStrategy: RemovalStrategy
|
||||
) async throws -> Int {
|
||||
try await self.removeItem(at: path, strategy: removalStrategy, recursively: true)
|
||||
}
|
||||
|
||||
/// Create a directory at the given path.
|
||||
///
|
||||
/// If a directory (or file) already exists at `path` then an error will be thrown. If
|
||||
/// `createIntermediateDirectories` is `false` then the full prefix of `path` must already
|
||||
/// exist. If set to `true` then all intermediate directories will be created.
|
||||
///
|
||||
/// New directories will be given read-write-execute owner permissions and read-execute group
|
||||
/// and other permissions.
|
||||
///
|
||||
/// Related system calls: `mkdir(2)`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The directory to create.
|
||||
/// - createIntermediateDirectories: Whether intermediate directories should be created.
|
||||
public func createDirectory(
|
||||
at path: FilePath,
|
||||
withIntermediateDirectories createIntermediateDirectories: Bool
|
||||
) async throws {
|
||||
try await self.createDirectory(
|
||||
at: path,
|
||||
withIntermediateDirectories: createIntermediateDirectories,
|
||||
permissions: .defaultsForDirectory
|
||||
)
|
||||
}
|
||||
|
||||
/// Create a temporary directory and removes it once the function returns.
|
||||
///
|
||||
/// You can use `prefix` to specify the directory in which the temporary directory should
|
||||
/// be created. If `prefix` is `nil` then the value of ``temporaryDirectory`` is used as
|
||||
/// the prefix.
|
||||
///
|
||||
/// The temporary directory, and all of its contents, is removed once `execute` returns.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - prefix: The prefix to use for the path of the temporary directory.
|
||||
/// - options: Options used to create the directory.
|
||||
/// - execute: A closure which provides access to the directory and its path.
|
||||
/// - Returns: The result of `execute`.
|
||||
public func withTemporaryDirectory<Result>(
|
||||
prefix: FilePath? = nil,
|
||||
options: OpenOptions.Directory = OpenOptions.Directory(),
|
||||
execute: (_ directory: DirectoryFileHandle, _ path: FilePath) async throws -> Result
|
||||
) async throws -> Result {
|
||||
let template: FilePath
|
||||
|
||||
if let prefix = prefix {
|
||||
template = prefix.appending("XXXXXXXX")
|
||||
} else {
|
||||
template = try await self.temporaryDirectory.appending("XXXXXXXX")
|
||||
}
|
||||
|
||||
let directory = try await self.createTemporaryDirectory(template: template)
|
||||
return try await withUncancellableTearDown {
|
||||
try await withDirectoryHandle(atPath: directory, options: options) { handle in
|
||||
try await execute(handle, directory)
|
||||
}
|
||||
} tearDown: { _ in
|
||||
try await self.removeItem(at: directory, strategy: .platformDefault, recursively: true)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import SystemPackage
|
||||
|
||||
#if canImport(Darwin)
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
@preconcurrency import Glibc
|
||||
#elseif canImport(Musl)
|
||||
@preconcurrency import Musl
|
||||
#elseif canImport(Android)
|
||||
@preconcurrency import Android
|
||||
#endif
|
||||
|
||||
/// The type of a file system object.
|
||||
public struct FileType: Hashable, Sendable {
|
||||
internal enum Wrapped: Hashable, Sendable, CaseIterable {
|
||||
case regular
|
||||
case block
|
||||
case character
|
||||
case fifo
|
||||
case directory
|
||||
case symlink
|
||||
case socket
|
||||
case whiteout
|
||||
case unknown
|
||||
}
|
||||
|
||||
internal let wrapped: Wrapped
|
||||
private init(_ wrapped: Wrapped) {
|
||||
self.wrapped = wrapped
|
||||
}
|
||||
}
|
||||
|
||||
extension FileType {
|
||||
/// Regular file.
|
||||
public static var regular: Self { Self(.regular) }
|
||||
|
||||
/// Directory.
|
||||
public static var directory: Self { Self(.directory) }
|
||||
|
||||
/// Symbolic link.
|
||||
public static var symlink: Self { Self(.symlink) }
|
||||
|
||||
/// Hardware block device.
|
||||
public static var block: Self { Self(.block) }
|
||||
|
||||
/// Hardware character device.
|
||||
public static var character: Self { Self(.character) }
|
||||
|
||||
/// FIFO (or named pipe).
|
||||
public static var fifo: Self { Self(.fifo) }
|
||||
|
||||
/// Socket.
|
||||
public static var socket: Self { Self(.socket) }
|
||||
|
||||
/// Whiteout file.
|
||||
public static var whiteout: Self { Self(.whiteout) }
|
||||
|
||||
/// A file of unknown type.
|
||||
public static var unknown: Self { Self(.unknown) }
|
||||
}
|
||||
|
||||
extension FileType: CustomStringConvertible {
|
||||
public var description: String {
|
||||
switch self.wrapped {
|
||||
case .regular:
|
||||
return "regular"
|
||||
case .block:
|
||||
return "block"
|
||||
case .character:
|
||||
return "character"
|
||||
case .fifo:
|
||||
return "fifo"
|
||||
case .directory:
|
||||
return "directory"
|
||||
case .symlink:
|
||||
return "symlink"
|
||||
case .socket:
|
||||
return "socket"
|
||||
case .whiteout:
|
||||
return "whiteout"
|
||||
case .unknown:
|
||||
return "unknown"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension FileType: CaseIterable {
|
||||
public static var allCases: [FileType] {
|
||||
Self.Wrapped.allCases.map { FileType($0) }
|
||||
}
|
||||
}
|
||||
|
||||
extension FileType {
|
||||
/// Initializes a file type from a `CInterop.Mode`.
|
||||
///
|
||||
/// Note: an appropriate mask is applied to `mode`.
|
||||
public init(platformSpecificMode: CInterop.Mode) {
|
||||
// See: `man 2 stat`
|
||||
switch platformSpecificMode & S_IFMT {
|
||||
case S_IFIFO:
|
||||
self = .fifo
|
||||
case S_IFCHR:
|
||||
self = .character
|
||||
case S_IFDIR:
|
||||
self = .directory
|
||||
case S_IFBLK:
|
||||
self = .block
|
||||
case S_IFREG:
|
||||
self = .regular
|
||||
case S_IFLNK:
|
||||
self = .symlink
|
||||
case S_IFSOCK:
|
||||
self = .socket
|
||||
#if canImport(Darwin)
|
||||
case S_IFWHT:
|
||||
self = .whiteout
|
||||
#endif
|
||||
default:
|
||||
self = .unknown
|
||||
}
|
||||
}
|
||||
|
||||
/// Initializes a file type from the `d_type` from `dirent`.
|
||||
@_spi(Testing)
|
||||
public init(direntType: UInt8) {
|
||||
#if canImport(Darwin) || canImport(Musl) || os(Android)
|
||||
let value = Int32(direntType)
|
||||
#elseif canImport(Glibc)
|
||||
let value = Int(direntType)
|
||||
#endif
|
||||
|
||||
switch value {
|
||||
case DT_FIFO:
|
||||
self = .fifo
|
||||
case DT_CHR:
|
||||
self = .character
|
||||
case DT_DIR:
|
||||
self = .directory
|
||||
case DT_BLK:
|
||||
self = .block
|
||||
case DT_REG:
|
||||
self = .regular
|
||||
case DT_LNK:
|
||||
self = .symlink
|
||||
case DT_SOCK:
|
||||
self = .socket
|
||||
#if canImport(Darwin)
|
||||
case DT_WHT:
|
||||
self = .whiteout
|
||||
#endif
|
||||
case DT_UNKNOWN:
|
||||
self = .unknown
|
||||
default:
|
||||
self = .unknown
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2024 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// How many file descriptors to open when performing I/O operations.
|
||||
enum IOStrategy: Hashable, Sendable {
|
||||
// platformDefault is reified into one of the concrete options below:
|
||||
case sequential
|
||||
case parallel(_ maxDescriptors: Int)
|
||||
|
||||
// These selections are relatively arbitrary but the rationale is as follows:
|
||||
//
|
||||
// - Never exceed the default OS limits even if 4 such operations were happening at once.
|
||||
// - Sufficient to enable significant speed up from parallelism
|
||||
// - Not wasting effort by pushing contention to the storage device. Further we
|
||||
// assume an SSD or similar storage tech. Users on spinning rust need to account
|
||||
// for that themselves anyway.
|
||||
//
|
||||
// That said, empirical testing for this has not been performed, suggestions welcome.
|
||||
//
|
||||
// Note: The directory scan is modelled after a copy strategy needing two handles: during the
|
||||
// creation of the destination directory we hold the handle while copying attributes. A much
|
||||
// more complex internal state machine could allow doing two of these if desired. This may not
|
||||
// result in a faster copy though so things are left simple.
|
||||
internal static func determinePlatformDefault() -> Self {
|
||||
#if os(macOS) || os(Linux) || os(Windows)
|
||||
// Eight file descriptors allow for four concurrent file copies/directory scans. Avoiding
|
||||
// storage system contention is of utmost importance.
|
||||
//
|
||||
// Testing was performed on an SSD, while copying objects (a dense directory of small files
|
||||
// and subdirectories of similar shape) to the same volume, totalling 12GB. Results showed
|
||||
// improvements in elapsed time for (expected) increases in CPU time up to parallel(8).
|
||||
// Beyond this, the increases in CPU led to only moderate gains.
|
||||
//
|
||||
// Anyone tuning this is encouraged to cover worst case scenarios.
|
||||
return .parallel(8)
|
||||
#elseif (canImport(Darwin) && !os(macOS)) || os(Android)
|
||||
// Reduced maximum descriptors in embedded world. This is chosen based on biasing towards
|
||||
// safety, not empirical testing.
|
||||
return .parallel(4)
|
||||
#else
|
||||
// Safety first. If we do not know what system we run on, we keep it simple.
|
||||
return .sequential
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
/// How to perform copies. Currently only relevant to directory level copies when using
|
||||
/// ``FileSystemProtocol/copyItem(at:to:strategy:shouldProceedAfterError:shouldCopyItem:)`` or other
|
||||
/// overloads that use the default behaviour.
|
||||
public struct CopyStrategy: Hashable, Sendable {
|
||||
internal let wrapped: IOStrategy
|
||||
private init(_ strategy: IOStrategy) {
|
||||
switch strategy {
|
||||
case .sequential:
|
||||
self.wrapped = .sequential
|
||||
case let .parallel(maxDescriptors):
|
||||
self.wrapped = .parallel(maxDescriptors)
|
||||
}
|
||||
}
|
||||
|
||||
// A copy fundamentally can't work without two descriptors unless you copy everything into
|
||||
// memory which is infeasible/inefficient for large copies.
|
||||
private static let minDescriptorsAllowed = 2
|
||||
|
||||
/// Operate in whatever manner is deemed a reasonable default for the platform. This will limit
|
||||
/// the maximum file descriptors usage based on reasonable defaults.
|
||||
///
|
||||
/// Current assumptions (which are subject to change):
|
||||
/// - Only one copy operation would be performed at once
|
||||
/// - The copy operation is not intended to be the primary activity on the device
|
||||
public static let platformDefault: Self = Self(IOStrategy.determinePlatformDefault())
|
||||
|
||||
/// The copy is done asynchronously, but only one operation will occur at a time. This is the
|
||||
/// only way to guarantee only one callback to the `shouldCopyItem` will happen at a time.
|
||||
public static let sequential: Self = Self(.sequential)
|
||||
|
||||
/// Allow multiple I/O operations to run concurrently, including file copies/directory creation
|
||||
/// and scanning.
|
||||
///
|
||||
/// - Parameter maxDescriptors: a conservative limit on the number of concurrently open file
|
||||
/// descriptors involved in the copy. This number must be >= 2 though, if you are using a
|
||||
/// value that low you should use ``sequential``
|
||||
///
|
||||
/// - Throws: ``FileSystemError/Code-swift.struct/invalidArgument`` if `maxDescriptors` is less
|
||||
/// than 2.
|
||||
///
|
||||
public static func parallel(maxDescriptors: Int) throws -> Self {
|
||||
guard maxDescriptors >= Self.minDescriptorsAllowed else {
|
||||
// 2 is not quite the same as sequential, you could have two concurrent directory
|
||||
// listings for example less than 2 and you can't actually do a _copy_ though so it's
|
||||
// non-sensical.
|
||||
throw FileSystemError(
|
||||
code: .invalidArgument,
|
||||
message: "Can't do a copy operation without at least 2 file descriptors '\(maxDescriptors)' is illegal",
|
||||
cause: nil,
|
||||
location: .here()
|
||||
)
|
||||
}
|
||||
return .init(.parallel(maxDescriptors))
|
||||
}
|
||||
}
|
||||
|
||||
extension CopyStrategy: CustomStringConvertible {
|
||||
public var description: String {
|
||||
switch self.wrapped {
|
||||
case .sequential:
|
||||
return "sequential"
|
||||
case let .parallel(maxDescriptors):
|
||||
return "parallel with max \(maxDescriptors) descriptors"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How to perform file deletions. Currently only relevant to directory level deletions when using
|
||||
/// ``FileSystemProtocol/removeItem(at:strategy:recursively:)`` or other overloads that use the
|
||||
/// default behaviour.
|
||||
public struct RemovalStrategy: Hashable, Sendable {
|
||||
internal let wrapped: IOStrategy
|
||||
private init(_ strategy: IOStrategy) {
|
||||
switch strategy {
|
||||
case .sequential:
|
||||
self.wrapped = .sequential
|
||||
case let .parallel(maxDescriptors):
|
||||
self.wrapped = .parallel(maxDescriptors)
|
||||
}
|
||||
}
|
||||
|
||||
// A deletion requires no file descriptors. We only consume a file descriptor while scanning the
|
||||
// contents of a directory, so the minimum is 1.
|
||||
private static let minRequiredDescriptors = 1
|
||||
|
||||
/// Operate in whatever manner is deemed a reasonable default for the platform. This will limit
|
||||
/// the maximum file descriptors usage based on reasonable defaults.
|
||||
///
|
||||
/// Current assumptions (which are subject to change):
|
||||
/// - Only one delete operation would be performed at once
|
||||
/// - The delete operation is not intended to be the primary activity on the device
|
||||
public static let platformDefault: Self = Self(IOStrategy.determinePlatformDefault())
|
||||
|
||||
/// Traversal of directories and removal of files will be done sequentially without any
|
||||
/// parallelization.
|
||||
public static let sequential: Self = Self(.sequential)
|
||||
|
||||
/// Allow for one or more directory scans to run at the same time. Removal of files will happen
|
||||
/// on asynchronous tasks in parallel.
|
||||
///
|
||||
/// Setting `maxDescriptors` to 1, will limit the speed of directory discovery. Deletion of
|
||||
/// files within that directory will run in parallel, but discovery of subdirectories will be
|
||||
/// limited to one at a time.
|
||||
public static func parallel(maxDescriptors: Int) throws -> Self {
|
||||
guard maxDescriptors >= Self.minRequiredDescriptors else {
|
||||
throw FileSystemError(
|
||||
code: .invalidArgument,
|
||||
message:
|
||||
"Can't do a remove operation without at least one file descriptor '\(maxDescriptors)' is illegal",
|
||||
cause: nil,
|
||||
location: .here()
|
||||
)
|
||||
}
|
||||
return .init(.parallel(maxDescriptors))
|
||||
}
|
||||
}
|
||||
|
||||
extension RemovalStrategy: CustomStringConvertible {
|
||||
public var description: String {
|
||||
switch self.wrapped {
|
||||
case .sequential:
|
||||
return "sequential"
|
||||
case let .parallel(maxDescriptors):
|
||||
return "parallel with max \(maxDescriptors) descriptors"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import NIOCore
|
||||
|
||||
/// Wraps a ``NIOThrowingAsyncSequenceProducer<Element>`` or ``AnyAsyncSequence<Element>``.
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
internal enum BufferedOrAnyStream<Element: Sendable, Delegate: NIOAsyncSequenceProducerDelegate>: Sendable {
|
||||
typealias AsyncSequenceProducer = NIOThrowingAsyncSequenceProducer<
|
||||
Element, Error, NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark, Delegate
|
||||
>
|
||||
|
||||
case nioThrowingAsyncSequenceProducer(AsyncSequenceProducer)
|
||||
case anyAsyncSequence(AnyAsyncSequence<Element>)
|
||||
|
||||
internal init(wrapping stream: AsyncSequenceProducer) {
|
||||
self = .nioThrowingAsyncSequenceProducer(stream)
|
||||
}
|
||||
|
||||
internal init<S: AsyncSequence & Sendable>(wrapping stream: S)
|
||||
where S.Element == Element, S.AsyncIterator: _NIOFileSystemSendableMetatype {
|
||||
self = .anyAsyncSequence(AnyAsyncSequence(wrapping: stream))
|
||||
}
|
||||
|
||||
internal func makeAsyncIterator() -> AsyncIterator {
|
||||
switch self {
|
||||
case let .nioThrowingAsyncSequenceProducer(stream):
|
||||
return AsyncIterator(wrapping: stream.makeAsyncIterator())
|
||||
case let .anyAsyncSequence(stream):
|
||||
return AsyncIterator(wrapping: stream.makeAsyncIterator())
|
||||
}
|
||||
}
|
||||
|
||||
internal enum AsyncIterator: AsyncIteratorProtocol {
|
||||
case bufferedStream(AsyncSequenceProducer.AsyncIterator)
|
||||
case anyAsyncSequence(AnyAsyncSequence<Element>.AsyncIterator)
|
||||
|
||||
internal mutating func next() async throws -> Element? {
|
||||
let element: Element?
|
||||
switch self {
|
||||
case let .bufferedStream(iterator):
|
||||
defer { self = .bufferedStream(iterator) }
|
||||
element = try await iterator.next()
|
||||
case var .anyAsyncSequence(iterator):
|
||||
defer { self = .anyAsyncSequence(iterator) }
|
||||
element = try await iterator.next()
|
||||
}
|
||||
return element
|
||||
}
|
||||
|
||||
internal init(wrapping iterator: AsyncSequenceProducer.AsyncIterator) {
|
||||
self = .bufferedStream(iterator)
|
||||
}
|
||||
|
||||
internal init(wrapping iterator: AnyAsyncSequence<Element>.AsyncIterator) {
|
||||
self = .anyAsyncSequence(iterator)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
internal struct AnyAsyncSequence<Element>: AsyncSequence, Sendable {
|
||||
private let _makeAsyncIterator: @Sendable () -> AsyncIterator
|
||||
|
||||
internal init<S: AsyncSequence & Sendable>(wrapping sequence: S)
|
||||
where S.Element == Element, S.AsyncIterator: _NIOFileSystemSendableMetatype {
|
||||
self._makeAsyncIterator = {
|
||||
AsyncIterator(wrapping: sequence.makeAsyncIterator())
|
||||
}
|
||||
}
|
||||
|
||||
internal func makeAsyncIterator() -> AsyncIterator {
|
||||
self._makeAsyncIterator()
|
||||
}
|
||||
|
||||
internal struct AsyncIterator: AsyncIteratorProtocol, _NIOFileSystemSendableMetatype {
|
||||
private var iterator: any AsyncIteratorProtocol
|
||||
|
||||
init<I: AsyncIteratorProtocol>(wrapping iterator: I) where I.Element == Element {
|
||||
self.iterator = iterator
|
||||
}
|
||||
|
||||
internal mutating func next() async throws -> Element? {
|
||||
try await self.iterator.next() as? Element
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,54 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// Executes the closure and masks cancellation.
|
||||
@_spi(Testing)
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
public func withoutCancellation<R: Sendable>(
|
||||
_ execute: @escaping () async throws -> R
|
||||
) async throws -> R {
|
||||
// Okay as we immediately wait for the result of the task.
|
||||
let unsafeExecute = UnsafeTransfer(execute)
|
||||
let t = Task {
|
||||
try await unsafeExecute.wrappedValue()
|
||||
}
|
||||
return try await t.value
|
||||
}
|
||||
|
||||
/// Executes `fn` and then `tearDown`, which cannot be cancelled.
|
||||
@_spi(Testing)
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
public func withUncancellableTearDown<R>(
|
||||
_ fn: () async throws -> R,
|
||||
tearDown: @escaping (Result<Void, Error>) async throws -> Void
|
||||
) async throws -> R {
|
||||
let result: Result<R, Error>
|
||||
do {
|
||||
result = .success(try await fn())
|
||||
} catch {
|
||||
result = .failure(error)
|
||||
}
|
||||
|
||||
let errorOnlyResult: Result<Void, Error> = result.map { _ in () }
|
||||
let tearDownResult: Result<Void, Error> = try await withoutCancellation {
|
||||
do {
|
||||
return .success(try await tearDown(errorOnlyResult))
|
||||
} catch {
|
||||
return .failure(error)
|
||||
}
|
||||
}
|
||||
|
||||
try tearDownResult.get()
|
||||
return try result.get()
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2024 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift open source project
|
||||
//
|
||||
// Copyright (c) 2023 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 the list of Swift project authors
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import DequeModule
|
||||
import NIOConcurrencyHelpers
|
||||
|
||||
/// Type modeled after a "token bucket" pattern, which is similar to a semaphore, but is built with
|
||||
/// Swift Concurrency primitives.
|
||||
///
|
||||
/// This is an adaptation of the TokenBucket found in Swift Package Manager.
|
||||
/// Instead of using an ``actor``, we define a class and limit access through
|
||||
/// ``NIOLock``.
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
final class TokenBucket: @unchecked Sendable {
|
||||
private var tokens: Int
|
||||
private var waiters: Deque<CheckedContinuation<Void, Never>>
|
||||
private let lock: NIOLock
|
||||
|
||||
init(tokens: Int) {
|
||||
precondition(tokens >= 1, "Need at least one token!")
|
||||
self.tokens = tokens
|
||||
self.waiters = Deque()
|
||||
self.lock = NIOLock()
|
||||
}
|
||||
|
||||
/// Executes an `async` closure immediately when a token is available.
|
||||
/// Only the same number of closures will be executed concurrently as the number
|
||||
/// of `tokens` passed to ``TokenBucket/init(tokens:)``, all subsequent
|
||||
/// invocations of `withToken` will suspend until a "free" token is available.
|
||||
/// - Parameter body: The closure to invoke when a token is available.
|
||||
/// - Returns: Resulting value returned by `body`.
|
||||
func withToken<ReturnType>(
|
||||
_ body: @Sendable () async throws -> ReturnType
|
||||
) async rethrows -> ReturnType {
|
||||
await self.getToken()
|
||||
defer { self.returnToken() }
|
||||
return try await body()
|
||||
}
|
||||
|
||||
private func getToken() async {
|
||||
self.lock.lock()
|
||||
if self.tokens > 0 {
|
||||
self.tokens -= 1
|
||||
self.lock.unlock()
|
||||
return
|
||||
}
|
||||
|
||||
await withCheckedContinuation {
|
||||
self.waiters.append($0)
|
||||
self.lock.unlock()
|
||||
}
|
||||
}
|
||||
|
||||
private func returnToken() {
|
||||
if let waiter = self.lock.withLock({ () -> CheckedContinuation<Void, Never>? in
|
||||
if let nextWaiter = self.waiters.popFirst() {
|
||||
return nextWaiter
|
||||
}
|
||||
|
||||
self.tokens += 1
|
||||
return nil
|
||||
}) {
|
||||
waiter.resume()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
@usableFromInline
|
||||
struct UnsafeTransfer<Value>: @unchecked Sendable {
|
||||
@usableFromInline
|
||||
var wrappedValue: Value
|
||||
|
||||
@inlinable
|
||||
init(_ wrappedValue: Value) {
|
||||
self.wrappedValue = wrappedValue
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2024 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import NIOCore
|
||||
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
extension FileSystem {
|
||||
/// Iterative implementation of a recursive parallel copy of the directory from `sourcePath` to
|
||||
/// `destinationPath`.
|
||||
///
|
||||
/// The parallelism is solely at the level of individual items (files, symbolic links and
|
||||
/// directories). A larger file is not 'split' into concurrent reads or writes.
|
||||
///
|
||||
/// If a symbolic link is encountered, then only the link is copied. If supported by the file
|
||||
/// system, the copied items will preserve permissions and any extended attributes.
|
||||
///
|
||||
/// Note: `maxConcurrentOperations` is used as a hard (conservative) limit on the number of open
|
||||
/// file descriptors at any point. Operations are assumed to consume 2 descriptors, so the
|
||||
/// maximum open descriptors are `maxConcurrentOperations * 2`
|
||||
@usableFromInline
|
||||
func copyDirectoryParallel(
|
||||
from sourcePath: FilePath,
|
||||
to destinationPath: FilePath,
|
||||
maxConcurrentOperations: Int,
|
||||
shouldProceedAfterError: @escaping @Sendable (
|
||||
_ entry: DirectoryEntry,
|
||||
_ error: Error
|
||||
) async throws -> Void,
|
||||
shouldCopyItem: @escaping @Sendable (
|
||||
_ source: DirectoryEntry,
|
||||
_ destination: FilePath
|
||||
) async -> Bool
|
||||
) async throws {
|
||||
// Implemented with NIOAsyncSequenceProducer rather than AsyncStream. It is approximately
|
||||
// the same speed in the best case, but has significantly less variance.
|
||||
// NIOAsyncSequenceProducer also enforces a multi-producer, single-consumer access pattern.
|
||||
let copyRequiredQueue = NIOAsyncSequenceProducer.makeSequence(
|
||||
elementType: DirCopyItem.self,
|
||||
backPressureStrategy: NoBackPressureStrategy(),
|
||||
finishOnDeinit: false,
|
||||
delegate: DirCopyDelegate()
|
||||
)
|
||||
|
||||
// We ignore the result of yield in all cases, because we are not implementing back
|
||||
// pressure, and cancellation is dealt with separately.
|
||||
@Sendable func yield(_ contentsOf: [DirCopyItem]) {
|
||||
_ = copyRequiredQueue.source.yield(contentsOf: contentsOf)
|
||||
}
|
||||
|
||||
// Kick-start the procees by enqueuing the root entry. The calling function already
|
||||
// validated the root needed copying, so it is safe to force unwrap the value.
|
||||
_ = copyRequiredQueue.source.yield(
|
||||
.toCopy(from: .init(path: sourcePath, type: .directory)!, to: destinationPath)
|
||||
)
|
||||
|
||||
// The processing of the very first item (the root) will increment this counter. Processing
|
||||
// will finish when the counter hits zero again.
|
||||
//
|
||||
// This does not need to be a ManagedAtomic or similar because:
|
||||
// - All state maintenance is done within the withThrowingTaskGroup closure
|
||||
// - All actual file system work is done by tasks created on the `taskGroup`
|
||||
var activeDirCount = 0
|
||||
|
||||
// Despite there being no 'result' for each operation, we cannot use a discarding task group,
|
||||
// because we use the 'drain results' queue as a concurrency limiting side effect.
|
||||
try await withThrowingTaskGroup(of: Void.self) { taskGroup in
|
||||
// Process each item in the current task.
|
||||
//
|
||||
// Side Effects:
|
||||
// - Updates activeDirCount and finishes the stream if required.
|
||||
// - Might add a task to `taskGroup`.
|
||||
//
|
||||
// Returns true if it added a task, false otherwise.
|
||||
func onNextItem(_ item: DirCopyItem) -> Bool {
|
||||
switch item {
|
||||
case .endOfDir:
|
||||
activeDirCount -= 1
|
||||
if activeDirCount == 0 {
|
||||
copyRequiredQueue.source.finish()
|
||||
}
|
||||
return false
|
||||
case let .toCopy(from: from, to: to):
|
||||
if from.type == .directory {
|
||||
activeDirCount += 1
|
||||
}
|
||||
taskGroup.addTask {
|
||||
try await copySelfAndEnqueueChildren(
|
||||
from: from,
|
||||
to: to,
|
||||
yield: yield,
|
||||
shouldProceedAfterError: shouldProceedAfterError,
|
||||
shouldCopyItem: shouldCopyItem
|
||||
)
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
let iter = copyRequiredQueue.sequence.makeAsyncIterator()
|
||||
|
||||
// inProgress counts the number of tasks we have added to the task group.
|
||||
// Get up to the maximum concurrency first.
|
||||
// We haven't started monitoring for task completion, so inProgress is 'worst case'.
|
||||
var inProgress = 0
|
||||
while inProgress <= maxConcurrentOperations {
|
||||
let item = await iter.next()
|
||||
if let item = item {
|
||||
if onNextItem(item) {
|
||||
inProgress += 1
|
||||
}
|
||||
} else {
|
||||
// Either we completed things before we hit the limit or we were cancelled. In
|
||||
// the latter case we choose to propagate the cancellation clearly. This makes
|
||||
// testing for it more reliable.
|
||||
try Task.checkCancellation()
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// One in (finish) -> one out (start another), but only for items that trigger a task.
|
||||
while let _ = try await taskGroup.next() {
|
||||
var keepConsuming = true
|
||||
while keepConsuming {
|
||||
let item = await iter.next()
|
||||
if let item = item {
|
||||
keepConsuming = !onNextItem(item)
|
||||
} else {
|
||||
// We must check here, to accurately propagate the cancellation.
|
||||
try Task.checkCancellation()
|
||||
keepConsuming = false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An 'always ask for more' no back-pressure strategy for a ``NIOAsyncSequenceProducer``.
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
private struct NoBackPressureStrategy: NIOAsyncSequenceProducerBackPressureStrategy {
|
||||
mutating func didYield(bufferDepth: Int) -> Bool { true }
|
||||
|
||||
mutating func didConsume(bufferDepth: Int) -> Bool { true }
|
||||
}
|
||||
|
||||
/// We ignore back pressure, the inherent handle limiting in copyDirectoryParallel means it is unnecessary.
|
||||
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
private struct DirCopyDelegate: NIOAsyncSequenceProducerDelegate, Sendable {
|
||||
@inlinable
|
||||
func produceMore() {}
|
||||
|
||||
@inlinable
|
||||
func didTerminate() {}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2024 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import NIOCore
|
||||
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
extension FileSystem {
|
||||
/// Recursively walk all objects found in `path`. Call ourselves recursively
|
||||
/// on each directory that we find, as soon as the file descriptor for
|
||||
/// `path` has been closed; also delete all files that we come across.
|
||||
func discoverAndRemoveItemsInTree(
|
||||
at path: FilePath,
|
||||
_ bucket: TokenBucket
|
||||
) async throws -> Int {
|
||||
// Discover current directory and find all files/directories. Free up
|
||||
// the handle as fast as possible.
|
||||
let (directoriesToRecurseInto, itemsToDelete) = try await bucket.withToken {
|
||||
try await self.withDirectoryHandle(atPath: path) { directory in
|
||||
var subdirectories: [FilePath] = []
|
||||
var itemsInDirectory: [FilePath] = []
|
||||
|
||||
for try await batch in directory.listContents().batched() {
|
||||
for entry in batch {
|
||||
switch entry.type {
|
||||
case .directory:
|
||||
subdirectories.append(entry.path)
|
||||
default:
|
||||
itemsInDirectory.append(entry.path)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (subdirectories, itemsInDirectory)
|
||||
}
|
||||
}
|
||||
|
||||
return try await withThrowingTaskGroup(of: Int.self) { group in
|
||||
// Delete all items we found in the current directory.
|
||||
for item in itemsToDelete {
|
||||
group.addTask {
|
||||
try await self.removeOneItem(at: item)
|
||||
}
|
||||
}
|
||||
|
||||
// Recurse into all newly found subdirectories.
|
||||
for directory in directoriesToRecurseInto {
|
||||
group.addTask {
|
||||
try await self.discoverAndRemoveItemsInTree(at: directory, bucket)
|
||||
}
|
||||
}
|
||||
|
||||
// Await task groups to finish and sum all items deleted so far.
|
||||
var numberOfDeletedItems = try await group.reduce(0, +)
|
||||
|
||||
// Remove top level directory.
|
||||
numberOfDeletedItems += try await self.removeOneItem(at: path)
|
||||
|
||||
return numberOfDeletedItems
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension String {
|
||||
@inlinable
|
||||
init(
|
||||
backportUnsafeUninitializedCapacity capacity: Int,
|
||||
initializingUTF8With initializer: (_ buffer: UnsafeMutableBufferPointer<UInt8>) throws -> Int
|
||||
) rethrows {
|
||||
// The buffer will store zero terminated C string
|
||||
let buffer = UnsafeMutableBufferPointer<UInt8>.allocate(capacity: capacity + 1)
|
||||
defer {
|
||||
buffer.deallocate()
|
||||
}
|
||||
|
||||
let initializedCount = try initializer(buffer)
|
||||
precondition(initializedCount <= capacity, "Overran buffer in initializer!")
|
||||
|
||||
// add zero termination
|
||||
buffer[initializedCount] = 0
|
||||
|
||||
self = String(cString: buffer.baseAddress!)
|
||||
}
|
||||
}
|
||||
|
||||
// Frustratingly, Swift 5.3 shipped before the macOS 11 SDK did, so we cannot gate the availability of
|
||||
// this declaration on having the 5.3 compiler. This has caused a number of build issues. While updating
|
||||
// to newer Xcodes does work, we can save ourselves some hassle and just wait until 5.4 to get this
|
||||
// enhancement on Apple platforms.
|
||||
extension String {
|
||||
@inlinable
|
||||
init(
|
||||
customUnsafeUninitializedCapacity capacity: Int,
|
||||
initializingUTF8With initializer: (
|
||||
_ buffer: UnsafeMutableBufferPointer<UInt8>
|
||||
) throws -> Int
|
||||
) rethrows {
|
||||
if #available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *) {
|
||||
try self.init(
|
||||
unsafeUninitializedCapacity: capacity,
|
||||
initializingUTF8With: initializer
|
||||
)
|
||||
} else {
|
||||
try self.init(
|
||||
backportUnsafeUninitializedCapacity: capacity,
|
||||
initializingUTF8With: initializer
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import SystemPackage
|
||||
|
||||
#if canImport(Darwin)
|
||||
import Darwin
|
||||
import CNIODarwin
|
||||
#elseif canImport(Glibc)
|
||||
@preconcurrency import Glibc
|
||||
import CNIOLinux
|
||||
#elseif canImport(Musl)
|
||||
@preconcurrency import Musl
|
||||
import CNIOLinux
|
||||
#elseif canImport(Android)
|
||||
@preconcurrency import Android
|
||||
import CNIOLinux
|
||||
#endif
|
||||
|
||||
/// Aliases for platform-dependent types used for system calls.
|
||||
extension CInterop {
|
||||
#if canImport(Darwin)
|
||||
public typealias Stat = Darwin.stat
|
||||
#elseif canImport(Glibc)
|
||||
public typealias Stat = Glibc.stat
|
||||
#elseif canImport(Musl)
|
||||
public typealias Stat = Musl.stat
|
||||
#elseif canImport(Android)
|
||||
public typealias Stat = Android.stat
|
||||
#endif
|
||||
|
||||
#if canImport(Darwin)
|
||||
@_spi(Testing)
|
||||
public static let maxPathLength = Darwin.PATH_MAX
|
||||
#elseif canImport(Glibc)
|
||||
@_spi(Testing)
|
||||
public static let maxPathLength = Glibc.PATH_MAX
|
||||
#elseif canImport(Musl)
|
||||
@_spi(Testing)
|
||||
public static let maxPathLength = Musl.PATH_MAX
|
||||
#elseif canImport(Android)
|
||||
@_spi(Testing)
|
||||
public static let maxPathLength = Android.PATH_MAX
|
||||
#endif
|
||||
|
||||
#if canImport(Darwin)
|
||||
typealias DirPointer = UnsafeMutablePointer<Darwin.DIR>
|
||||
#elseif canImport(Glibc) || canImport(Musl) || canImport(Android)
|
||||
typealias DirPointer = OpaquePointer
|
||||
#endif
|
||||
|
||||
#if canImport(Darwin)
|
||||
typealias DirEnt = Darwin.dirent
|
||||
#elseif canImport(Glibc)
|
||||
typealias DirEnt = Glibc.dirent
|
||||
#elseif canImport(Musl)
|
||||
typealias DirEnt = Musl.dirent
|
||||
#elseif canImport(Android)
|
||||
typealias DirEnt = Android.dirent
|
||||
#endif
|
||||
|
||||
#if canImport(Darwin)
|
||||
typealias FTS = CNIODarwin.FTS
|
||||
typealias FTSEnt = CNIODarwin.FTSENT
|
||||
#elseif canImport(Glibc) || canImport(Musl) || canImport(Android)
|
||||
typealias FTS = CNIOLinux.FTS
|
||||
typealias FTSEnt = CNIOLinux.FTSENT
|
||||
#endif
|
||||
|
||||
typealias FTSPointer = UnsafeMutablePointer<FTS>
|
||||
typealias FTSEntPointer = UnsafeMutablePointer<CInterop.FTSEnt>
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import SystemPackage
|
||||
|
||||
#if canImport(Darwin)
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
@preconcurrency import Glibc
|
||||
#elseif canImport(Musl)
|
||||
@preconcurrency import Musl
|
||||
#elseif canImport(Android)
|
||||
@preconcurrency import Android
|
||||
#endif
|
||||
|
||||
extension Errno {
|
||||
@_spi(Testing)
|
||||
public static var _current: Errno {
|
||||
get {
|
||||
#if canImport(Darwin)
|
||||
return Errno(rawValue: Darwin.errno)
|
||||
#elseif canImport(Glibc)
|
||||
return Errno(rawValue: Glibc.errno)
|
||||
#elseif canImport(Musl)
|
||||
return Errno(rawValue: Musl.errno)
|
||||
#elseif canImport(Android)
|
||||
return Errno(rawValue: Android.errno)
|
||||
#endif
|
||||
}
|
||||
set {
|
||||
#if canImport(Darwin)
|
||||
Darwin.errno = newValue.rawValue
|
||||
#elseif canImport(Glibc)
|
||||
Glibc.errno = newValue.rawValue
|
||||
#elseif canImport(Musl)
|
||||
Musl.errno = newValue.rawValue
|
||||
#elseif canImport(Android)
|
||||
Android.errno = newValue.rawValue
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate static func clear() {
|
||||
#if canImport(Darwin)
|
||||
Darwin.errno = 0
|
||||
#elseif canImport(Glibc)
|
||||
Glibc.errno = 0
|
||||
#elseif canImport(Musl)
|
||||
Musl.errno = 0
|
||||
#elseif canImport(Android)
|
||||
Android.errno = 0
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a `Result` representing the value returned from the given closure
|
||||
/// or an `Errno` if that value was -1.
|
||||
///
|
||||
/// If desired this function can call the closure in a loop until it does not
|
||||
/// result in `Errno` being `.interrupted`.
|
||||
@_spi(Testing)
|
||||
public func valueOrErrno<I: FixedWidthInteger>(
|
||||
retryOnInterrupt: Bool = true,
|
||||
_ fn: () -> I
|
||||
) -> Result<I, Errno> {
|
||||
while true {
|
||||
Errno.clear()
|
||||
let result = fn()
|
||||
if result == -1 {
|
||||
let errno = Errno._current
|
||||
if errno == .interrupted, retryOnInterrupt {
|
||||
continue
|
||||
} else {
|
||||
return .failure(errno)
|
||||
}
|
||||
} else {
|
||||
return .success(result)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// As `valueOrErrno` but discards the success value.
|
||||
@_spi(Testing)
|
||||
public func nothingOrErrno<I: FixedWidthInteger>(
|
||||
retryOnInterrupt: Bool = true,
|
||||
_ fn: () -> I
|
||||
) -> Result<Void, Errno> {
|
||||
valueOrErrno(retryOnInterrupt: retryOnInterrupt, fn).map { _ in }
|
||||
}
|
||||
|
||||
/// Returns a `Result` representing the value returned from the given closure
|
||||
/// or an `Errno` if that value was `nil`.
|
||||
///
|
||||
/// If desired this function can call the closure in a loop until it does not
|
||||
/// result in `Errno` being `.interrupted`. `Errno` is only checked if the
|
||||
/// closure returns `nil`.
|
||||
@_spi(Testing)
|
||||
public func optionalValueOrErrno<R>(
|
||||
retryOnInterrupt: Bool = true,
|
||||
_ fn: () -> R?
|
||||
) -> Result<R?, Errno> {
|
||||
while true {
|
||||
Errno.clear()
|
||||
if let result = fn() {
|
||||
return .success(result)
|
||||
} else {
|
||||
let errno = Errno._current
|
||||
if errno == .interrupted, retryOnInterrupt {
|
||||
continue
|
||||
} else if errno.rawValue == 0 {
|
||||
return .success(nil)
|
||||
} else {
|
||||
return .failure(errno)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// As `valueOrErrno` but unconditionally checks the current `Errno`.
|
||||
@_spi(Testing)
|
||||
public func valueOrErrno<R>(
|
||||
retryOnInterrupt: Bool = true,
|
||||
_ fn: () -> R
|
||||
) -> Result<R, Errno> {
|
||||
while true {
|
||||
Errno.clear()
|
||||
let value = fn()
|
||||
let errno = Errno._current
|
||||
if errno.rawValue == 0 {
|
||||
return .success(value)
|
||||
} else if errno == .interrupted, retryOnInterrupt {
|
||||
continue
|
||||
} else {
|
||||
return .failure(errno)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,326 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import NIOCore
|
||||
import SystemPackage
|
||||
|
||||
#if canImport(Darwin)
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
@preconcurrency import Glibc
|
||||
import CNIOLinux
|
||||
#elseif canImport(Musl)
|
||||
@preconcurrency import Musl
|
||||
import CNIOLinux
|
||||
#elseif canImport(Bionic)
|
||||
@preconcurrency import Bionic
|
||||
import CNIOLinux
|
||||
#endif
|
||||
|
||||
extension FileDescriptor {
|
||||
/// Opens or creates a file for reading or writing.
|
||||
///
|
||||
/// The corresponding C function is `fdopenat`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The location of the file to open. If the path is relative then the file is opened
|
||||
/// relative to the descriptor.
|
||||
/// - mode: The read and write access to use.
|
||||
/// - options: The behavior for opening the file.
|
||||
/// - permissions: The file permissions to use for created files.
|
||||
/// - retryOnInterrupt: Whether to retry the operation if it throws `Errno.interrupted`. The
|
||||
/// default is true. Pass false to try only once and throw an error upon interruption.
|
||||
/// - Returns: A file descriptor for the open file.
|
||||
@_spi(Testing)
|
||||
public func `open`(
|
||||
atPath path: FilePath,
|
||||
mode: FileDescriptor.AccessMode,
|
||||
options: FileDescriptor.OpenOptions,
|
||||
permissions: FilePermissions?,
|
||||
retryOnInterrupt: Bool = true
|
||||
) -> Result<FileDescriptor, Errno> {
|
||||
let oFlag = mode.rawValue | options.rawValue
|
||||
let rawValue = valueOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
path.withPlatformString {
|
||||
if let permissions = permissions {
|
||||
return system_fdopenat(self.rawValue, $0, oFlag, permissions.rawValue)
|
||||
} else {
|
||||
precondition(!options.contains(.create), "Create must be given permissions")
|
||||
return system_fdopenat(self.rawValue, $0, oFlag)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return rawValue.map { FileDescriptor(rawValue: $0) }
|
||||
}
|
||||
|
||||
/// Returns information about the status of the open file.
|
||||
///
|
||||
/// The corresponding C function is `fstat`.
|
||||
///
|
||||
/// - Returns: Information about the open file.
|
||||
@_spi(Testing)
|
||||
public func status() -> Result<CInterop.Stat, Errno> {
|
||||
var status = CInterop.Stat()
|
||||
return nothingOrErrno(retryOnInterrupt: false) {
|
||||
system_fstat(self.rawValue, &status)
|
||||
}.map { status }
|
||||
}
|
||||
|
||||
/// Sets the permission bits of the open file.
|
||||
///
|
||||
/// The corresponding C function is `fchmod`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - mode: The permissions to set on the file.
|
||||
/// - retryOnInterrupt: Whether to retry the operation if it throws `Errno.interrupted`. The
|
||||
/// default is true. Pass false to try only once and throw an error upon interruption.
|
||||
@_spi(Testing)
|
||||
public func changeMode(
|
||||
_ mode: FilePermissions,
|
||||
retryOnInterrupt: Bool = true
|
||||
) -> Result<Void, Errno> {
|
||||
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_fchmod(self.rawValue, mode.rawValue)
|
||||
}
|
||||
}
|
||||
|
||||
/// List the names of extended attributes.
|
||||
///
|
||||
/// The corresponding C function is `flistxattr`.
|
||||
///
|
||||
/// - Parameter buffer: The buffer into which names are written. Names are written are NULL
|
||||
/// terminated UTF-8 strings and are returned in an arbitrary order. There is no padding
|
||||
/// between strings. If `buffer` is `nil` then the return value is the size of the buffer
|
||||
/// required to list all extended attributes. If there is not enough space in the `buffer`
|
||||
/// then `Errno.outOfRange` is returned.
|
||||
/// - Returns: The size of the extended attribute list.
|
||||
@_spi(Testing)
|
||||
public func listExtendedAttributes(
|
||||
_ buffer: UnsafeMutableBufferPointer<CChar>?
|
||||
) -> Result<Int, Errno> {
|
||||
valueOrErrno(retryOnInterrupt: false) {
|
||||
system_flistxattr(self.rawValue, buffer?.baseAddress, buffer?.count ?? 0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the value of the named extended attribute.
|
||||
///
|
||||
/// The corresponding C function is `fgetxattr`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - name: The name of the extended attribute.
|
||||
/// - buffer: The buffer into which the value is written. If `buffer` is `nil` then the return
|
||||
/// value is the size of the buffer required to read the value. If there is not enough
|
||||
/// space in the `buffer` then `Errno.outOfRange` is returned.
|
||||
/// - Returns: The size of the extended attribute value.
|
||||
@_spi(Testing)
|
||||
public func getExtendedAttribute(
|
||||
named name: String,
|
||||
buffer: UnsafeMutableRawBufferPointer?
|
||||
) -> Result<Int, Errno> {
|
||||
valueOrErrno(retryOnInterrupt: false) {
|
||||
name.withPlatformString {
|
||||
system_fgetxattr(self.rawValue, $0, buffer?.baseAddress, buffer?.count ?? 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the value of the named extended attribute.
|
||||
///
|
||||
/// The corresponding C function is `fsetxattr`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - name: The name of the extended attribute.
|
||||
/// - value: The data to set for the attribute.
|
||||
@_spi(Testing)
|
||||
public func setExtendedAttribute(
|
||||
named name: String,
|
||||
to value: UnsafeRawBufferPointer?
|
||||
) -> Result<Void, Errno> {
|
||||
nothingOrErrno(retryOnInterrupt: false) {
|
||||
name.withPlatformString { namePointer in
|
||||
system_fsetxattr(self.rawValue, namePointer, value?.baseAddress, value?.count ?? 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove the value for the named extended attribute.
|
||||
///
|
||||
/// The corresponding C function is `fremovexattr`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - name: The name of the extended attribute.
|
||||
@_spi(Testing)
|
||||
public func removeExtendedAttribute(_ name: String) -> Result<Void, Errno> {
|
||||
nothingOrErrno(retryOnInterrupt: false) {
|
||||
name.withPlatformString {
|
||||
system_fremovexattr(self.rawValue, $0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronize modified data and metadata to a permanent storage device.
|
||||
///
|
||||
/// The corresponding C functions is `fsync`.
|
||||
///
|
||||
/// - Parameter retryOnInterrupt: Whether the call should be retried on `Errno.interrupted`.
|
||||
@_spi(Testing)
|
||||
public func synchronize(retryOnInterrupt: Bool = true) -> Result<Void, Errno> {
|
||||
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_fsync(self.rawValue)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a pointer to a directory structure.
|
||||
///
|
||||
/// The corresponding C function is `fdopendir`
|
||||
///
|
||||
/// - Important: Calling this function cedes ownership of the file descriptor to the system. The
|
||||
/// caller should not modify the descriptor or close the descriptor via `close()`. Once
|
||||
/// directory iteration has been completed then `Libc.closdir(_:)` must be called.
|
||||
internal func opendir() -> Result<CInterop.DirPointer, Errno> {
|
||||
valueOrErrno(retryOnInterrupt: false) {
|
||||
libc_fdopendir(self.rawValue)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension FileDescriptor {
|
||||
func listExtendedAttributes() -> Result<[String], Errno> {
|
||||
// Required capacity is returned if a no buffer is passed to flistxattr.
|
||||
self.listExtendedAttributes(nil).flatMap { capacity in
|
||||
guard capacity > 0 else {
|
||||
// Required capacity is zero: no attributes to read.
|
||||
return .success([])
|
||||
}
|
||||
|
||||
// Read and decode.
|
||||
var buffer = [CChar](repeating: 0, count: capacity)
|
||||
return buffer.withUnsafeMutableBufferPointer { pointer in
|
||||
self.listExtendedAttributes(pointer)
|
||||
}.map { size in
|
||||
// The buffer contains null terminated C-strings.
|
||||
var attributes = [String]()
|
||||
var slice = buffer.prefix(size)
|
||||
while let index = slice.firstIndex(of: 0) {
|
||||
// TODO: can we do this more cheaply?
|
||||
let prefix = slice[...index]
|
||||
attributes.append(String(cString: Array(prefix)))
|
||||
slice = slice.dropFirst(prefix.count)
|
||||
}
|
||||
|
||||
return attributes
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func readExtendedAttribute(named name: String) -> Result<[UInt8], Errno> {
|
||||
// Required capacity is returned if a no buffer is passed to fgetxattr.
|
||||
self.getExtendedAttribute(named: name, buffer: nil).flatMap { capacity in
|
||||
guard capacity > 0 else {
|
||||
// Required capacity is zero: no values to read.
|
||||
return .success([])
|
||||
}
|
||||
|
||||
// Read and decode.
|
||||
var buffer = [UInt8](repeating: 0, count: capacity)
|
||||
return buffer.withUnsafeMutableBytes { bytes in
|
||||
self.getExtendedAttribute(named: name, buffer: bytes)
|
||||
}.map { size in
|
||||
// Remove any trailing zeros.
|
||||
buffer.removeLast(buffer.count - size)
|
||||
return buffer
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension FileDescriptor {
|
||||
func readChunk(fromAbsoluteOffset offset: Int64, length: Int64) -> Result<ByteBuffer, Error> {
|
||||
self._readChunk(fromAbsoluteOffset: offset, length: length)
|
||||
}
|
||||
|
||||
func readChunk(length: Int64) -> Result<ByteBuffer, Error> {
|
||||
self._readChunk(fromAbsoluteOffset: nil, length: length)
|
||||
}
|
||||
|
||||
private func _readChunk(
|
||||
fromAbsoluteOffset offset: Int64?,
|
||||
length: Int64
|
||||
) -> Result<ByteBuffer, Error> {
|
||||
// This is used by the `FileChunks` and means we allocate for every chunk that we read for
|
||||
// the file. That's fine for now because the syscall cost is likely to be the dominant
|
||||
// factor here. However we should investigate whether it's possible to have a pool of
|
||||
// buffers which we can reuse. This would need to be at least as large as the high watermark
|
||||
// of the chunked file for it to be useful.
|
||||
Result {
|
||||
var buffer = ByteBuffer()
|
||||
try buffer.writeWithUnsafeMutableBytes(minimumWritableBytes: Int(length)) { buffer in
|
||||
let bufferPointer: UnsafeMutableRawBufferPointer
|
||||
|
||||
// Don't vend a buffer which is larger than `length`; we can read less but we must
|
||||
// not read more.
|
||||
if length < buffer.count {
|
||||
bufferPointer = UnsafeMutableRawBufferPointer(
|
||||
start: buffer.baseAddress,
|
||||
count: Int(length)
|
||||
)
|
||||
} else {
|
||||
bufferPointer = buffer
|
||||
}
|
||||
|
||||
if let offset {
|
||||
return try self.read(fromAbsoluteOffset: offset, into: bufferPointer)
|
||||
} else {
|
||||
return try self.read(into: bufferPointer)
|
||||
}
|
||||
}
|
||||
return buffer
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension FileDescriptor {
|
||||
func write(
|
||||
contentsOf bytes: some Sequence<UInt8>,
|
||||
toAbsoluteOffset offset: Int64
|
||||
) -> Result<Int64, Error> {
|
||||
Result {
|
||||
Int64(try self.writeAll(toAbsoluteOffset: offset, bytes))
|
||||
}
|
||||
}
|
||||
|
||||
func write(
|
||||
contentsOf bytes: some Sequence<UInt8>
|
||||
) -> Result<Int64, Error> {
|
||||
Result {
|
||||
Int64(try self.writeAll(bytes))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if canImport(Glibc) || canImport(Musl) || canImport(Bionic)
|
||||
extension FileDescriptor.OpenOptions {
|
||||
static var temporaryFile: Self {
|
||||
Self(rawValue: CNIOLinux_O_TMPFILE)
|
||||
}
|
||||
}
|
||||
|
||||
extension FileDescriptor {
|
||||
static var currentWorkingDirectory: Self {
|
||||
Self(rawValue: AT_FDCWD)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,380 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// This source file is part of the Swift System open source project//
|
||||
// Copyright (c) 2020 Apple Inc. and the Swift System project authors
|
||||
// Licensed under Apache License v2.0 with Runtime Library Exception//
|
||||
// See https://swift.org/LICENSE.txt for license information
|
||||
|
||||
import SystemPackage
|
||||
|
||||
#if canImport(Darwin)
|
||||
import Darwin
|
||||
#elseif canImport(Glibc)
|
||||
@preconcurrency import Glibc
|
||||
import CNIOLinux
|
||||
#elseif canImport(Musl)
|
||||
@preconcurrency import Musl
|
||||
import CNIOLinux
|
||||
#elseif canImport(Android)
|
||||
@preconcurrency import Android
|
||||
import CNIOLinux
|
||||
#endif
|
||||
|
||||
// Syscall mocking support.
|
||||
//
|
||||
// NOTE: This is currently the bare minimum needed for System's testing purposes, though we do
|
||||
// eventually want to expose some solution to users.
|
||||
//
|
||||
// Mocking is contextual, accessible through MockingDriver.withMockingEnabled. Mocking
|
||||
// state, including whether it is enabled, is stored in thread-local storage. Mocking is only
|
||||
// enabled in testing builds of System currently, to minimize runtime overhead of release builds.
|
||||
//
|
||||
|
||||
#if ENABLE_MOCKING
|
||||
@_spi(Testing)
|
||||
public struct Trace {
|
||||
@_spi(Testing)
|
||||
public struct Entry {
|
||||
@_spi(Testing)
|
||||
public var name: String
|
||||
@_spi(Testing)
|
||||
public var arguments: [AnyHashable]
|
||||
|
||||
@_spi(Testing)
|
||||
public init(name: String, _ arguments: [AnyHashable]) {
|
||||
self.name = name
|
||||
self.arguments = arguments
|
||||
}
|
||||
}
|
||||
|
||||
private var entries: [Entry] = []
|
||||
private var firstEntry: Int = 0
|
||||
|
||||
@_spi(Testing)
|
||||
public var isEmpty: Bool { firstEntry >= entries.count }
|
||||
|
||||
@_spi(Testing)
|
||||
public mutating func dequeue() -> Entry? {
|
||||
guard !self.isEmpty else { return nil }
|
||||
defer { firstEntry += 1 }
|
||||
return entries[firstEntry]
|
||||
}
|
||||
|
||||
fileprivate mutating func add(_ e: Entry) {
|
||||
entries.append(e)
|
||||
}
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
extension Trace: Sendable {}
|
||||
|
||||
@available(*, unavailable)
|
||||
extension Trace.Entry: Sendable {}
|
||||
|
||||
@_spi(Testing)
|
||||
public enum ForceErrno: Equatable, Sendable {
|
||||
case none
|
||||
case always(errno: CInt)
|
||||
|
||||
case counted(errno: CInt, count: Int)
|
||||
}
|
||||
|
||||
// Provide access to the driver, context, and trace stack of mocking
|
||||
@_spi(Testing)
|
||||
public final class MockingDriver {
|
||||
// Record syscalls and their arguments
|
||||
@_spi(Testing)
|
||||
public var trace = Trace()
|
||||
|
||||
// Mock errors inside syscalls
|
||||
@_spi(Testing)
|
||||
public var forceErrno = ForceErrno.none
|
||||
|
||||
// Whether we should pretend to be Windows for syntactic operations
|
||||
// inside FilePath
|
||||
fileprivate var forceWindowsSyntaxForPaths = false
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
extension MockingDriver: Sendable {}
|
||||
|
||||
private let driverKey: _PlatformTLSKey = { makeTLSKey() }()
|
||||
|
||||
internal var currentMockingDriver: MockingDriver? {
|
||||
#if !ENABLE_MOCKING
|
||||
fatalError("Contextual mocking in non-mocking build")
|
||||
#endif
|
||||
guard let rawPtr = getTLS(driverKey) else { return nil }
|
||||
|
||||
return Unmanaged<MockingDriver>.fromOpaque(rawPtr).takeUnretainedValue()
|
||||
}
|
||||
|
||||
extension MockingDriver {
|
||||
/// Enables mocking for the duration of `f` with a clean trace queue
|
||||
/// Restores prior mocking status and trace queue after execution
|
||||
@_spi(Testing)
|
||||
public static func withMockingEnabled(
|
||||
_ f: (MockingDriver) throws -> Void
|
||||
) rethrows {
|
||||
let priorMocking = currentMockingDriver
|
||||
let driver = MockingDriver()
|
||||
|
||||
defer {
|
||||
if let object = priorMocking {
|
||||
setTLS(driverKey, Unmanaged.passUnretained(object).toOpaque())
|
||||
} else {
|
||||
setTLS(driverKey, nil)
|
||||
}
|
||||
_fixLifetime(driver)
|
||||
}
|
||||
|
||||
setTLS(driverKey, Unmanaged.passUnretained(driver).toOpaque())
|
||||
return try f(driver)
|
||||
}
|
||||
}
|
||||
|
||||
// Check TLS for mocking
|
||||
@inline(never)
|
||||
private var contextualMockingEnabled: Bool {
|
||||
currentMockingDriver != nil
|
||||
}
|
||||
|
||||
extension MockingDriver {
|
||||
@_spi(Testing)
|
||||
public static var enabled: Bool { mockingEnabled }
|
||||
|
||||
@_spi(Testing)
|
||||
public static var forceWindowsPaths: Bool {
|
||||
currentMockingDriver?.forceWindowsSyntaxForPaths ?? false
|
||||
}
|
||||
}
|
||||
|
||||
#endif // ENABLE_MOCKING
|
||||
|
||||
@inline(__always)
|
||||
internal var mockingEnabled: Bool {
|
||||
// Fast constant-foldable check for release builds
|
||||
#if ENABLE_MOCKING
|
||||
return contextualMockingEnabled
|
||||
#else
|
||||
return false
|
||||
#endif
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
internal var forceWindowsPaths: Bool {
|
||||
#if !ENABLE_MOCKING
|
||||
return false
|
||||
#else
|
||||
return MockingDriver.forceWindowsPaths
|
||||
#endif
|
||||
}
|
||||
|
||||
#if ENABLE_MOCKING
|
||||
// Strip the mock_system prefix and the arg list suffix
|
||||
private func originalSyscallName(_ function: String) -> String {
|
||||
// `function` must be of format `system_<name>(<parameters>)`
|
||||
for `prefix` in ["system_", "libc_"] {
|
||||
if function.starts(with: `prefix`) {
|
||||
return String(function.dropFirst(`prefix`.count).prefix { $0 != "(" })
|
||||
}
|
||||
}
|
||||
preconditionFailure("\(function) must start with 'system_' or 'libc_'")
|
||||
}
|
||||
|
||||
private func mockImpl(syscall name: String, args: [AnyHashable]) -> CInt {
|
||||
precondition(mockingEnabled)
|
||||
let origName = originalSyscallName(name)
|
||||
guard let driver = currentMockingDriver else {
|
||||
fatalError("Mocking requested from non-mocking context")
|
||||
}
|
||||
|
||||
driver.trace.add(Trace.Entry(name: origName, args))
|
||||
|
||||
switch driver.forceErrno {
|
||||
case .none: break
|
||||
case .always(let e):
|
||||
system_errno = e
|
||||
return -1
|
||||
case .counted(let e, let count):
|
||||
assert(count >= 1)
|
||||
system_errno = e
|
||||
driver.forceErrno = count > 1 ? .counted(errno: e, count: count - 1) : .none
|
||||
return -1
|
||||
}
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
private func reinterpret(_ args: [AnyHashable?]) -> [AnyHashable] {
|
||||
args.map { arg in
|
||||
switch arg {
|
||||
case let charPointer as UnsafePointer<CInterop.PlatformChar>:
|
||||
return String(_errorCorrectingPlatformString: charPointer)
|
||||
case is UnsafeMutablePointer<CInterop.PlatformChar>:
|
||||
return "<buffer>"
|
||||
case is UnsafeMutableRawPointer:
|
||||
return "<buffer>"
|
||||
case is UnsafeRawPointer:
|
||||
return "<buffer>"
|
||||
case .none:
|
||||
return "nil"
|
||||
case let .some(arg):
|
||||
return arg
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func mock(
|
||||
syscall name: String = #function,
|
||||
_ args: AnyHashable?...
|
||||
) -> CInt {
|
||||
mockImpl(syscall: name, args: reinterpret(args))
|
||||
}
|
||||
|
||||
func mockInt(
|
||||
syscall name: String = #function,
|
||||
_ args: AnyHashable?...
|
||||
) -> Int {
|
||||
Int(mockImpl(syscall: name, args: reinterpret(args)))
|
||||
}
|
||||
|
||||
#endif // ENABLE_MOCKING
|
||||
|
||||
// Force paths to be treated as Windows syntactically if `enabled` is
|
||||
// true.
|
||||
@_spi(Testing)
|
||||
public func _withWindowsPaths(enabled: Bool, _ body: () -> Void) {
|
||||
#if ENABLE_MOCKING
|
||||
guard enabled else {
|
||||
body()
|
||||
return
|
||||
}
|
||||
MockingDriver.withMockingEnabled { driver in
|
||||
driver.forceWindowsSyntaxForPaths = true
|
||||
body()
|
||||
}
|
||||
#else
|
||||
body()
|
||||
#endif
|
||||
}
|
||||
|
||||
// Internal wrappers and typedefs which help reduce #if littering in System's
|
||||
// code base.
|
||||
|
||||
// TODO: Should CSystem just include all the header files we need?
|
||||
|
||||
internal typealias _COffT = off_t
|
||||
|
||||
// MARK: syscalls and variables
|
||||
|
||||
#if canImport(Darwin)
|
||||
internal var system_errno: CInt {
|
||||
get { Darwin.errno }
|
||||
set { Darwin.errno = newValue }
|
||||
}
|
||||
#elseif canImport(Glibc)
|
||||
internal var system_errno: CInt {
|
||||
get { Glibc.errno }
|
||||
set { Glibc.errno = newValue }
|
||||
}
|
||||
#elseif canImport(Musl)
|
||||
internal var system_errno: CInt {
|
||||
get { Musl.errno }
|
||||
set { Musl.errno = newValue }
|
||||
}
|
||||
#elseif canImport(Android)
|
||||
internal var system_errno: CInt {
|
||||
get { Android.errno }
|
||||
set { Android.errno = newValue }
|
||||
}
|
||||
#endif
|
||||
|
||||
// MARK: C stdlib decls
|
||||
|
||||
// Convention: `system_foo` is system's wrapper for `foo`.
|
||||
|
||||
internal func system_strerror(_ __errnum: Int32) -> UnsafeMutablePointer<Int8>! {
|
||||
strerror(__errnum)
|
||||
}
|
||||
|
||||
internal func system_strlen(_ s: UnsafePointer<CChar>) -> Int {
|
||||
strlen(s)
|
||||
}
|
||||
internal func system_strlen(_ s: UnsafeMutablePointer<CChar>) -> Int {
|
||||
strlen(s)
|
||||
}
|
||||
|
||||
// Convention: `system_platform_foo` is a
|
||||
// platform-representation-abstracted wrapper around `foo`-like functionality.
|
||||
// Type and layout differences such as the `char` vs `wchar` are abstracted.
|
||||
//
|
||||
|
||||
// strlen for the platform string
|
||||
internal func system_platform_strlen(_ s: UnsafePointer<CInterop.PlatformChar>) -> Int {
|
||||
strlen(s)
|
||||
}
|
||||
|
||||
// memset for raw buffers
|
||||
// FIXME: Do we really not have something like this in the stdlib already?
|
||||
internal func system_memset(
|
||||
_ buffer: UnsafeMutableRawBufferPointer,
|
||||
to byte: UInt8
|
||||
) {
|
||||
guard buffer.count > 0 else { return }
|
||||
memset(buffer.baseAddress!, CInt(byte), buffer.count)
|
||||
}
|
||||
|
||||
// Interop between String and platfrom string
|
||||
extension String {
|
||||
internal func _withPlatformString<Result>(
|
||||
_ body: (UnsafePointer<CInterop.PlatformChar>) throws -> Result
|
||||
) rethrows -> Result {
|
||||
// Need to #if because CChar may be signed
|
||||
try withCString(body)
|
||||
}
|
||||
|
||||
internal init?(_platformString platformString: UnsafePointer<CInterop.PlatformChar>) {
|
||||
// Need to #if because CChar may be signed
|
||||
self.init(validatingUTF8: platformString)
|
||||
}
|
||||
|
||||
internal init(
|
||||
_errorCorrectingPlatformString platformString: UnsafePointer<CInterop.PlatformChar>
|
||||
) {
|
||||
// Need to #if because CChar may be signed
|
||||
self.init(cString: platformString)
|
||||
}
|
||||
}
|
||||
|
||||
internal typealias _PlatformTLSKey = pthread_key_t
|
||||
|
||||
internal func makeTLSKey() -> _PlatformTLSKey {
|
||||
var raw = pthread_key_t()
|
||||
guard 0 == pthread_key_create(&raw, nil) else {
|
||||
fatalError("Unable to create key")
|
||||
}
|
||||
return raw
|
||||
}
|
||||
|
||||
internal func setTLS(_ key: _PlatformTLSKey, _ p: UnsafeMutableRawPointer?) {
|
||||
guard 0 == pthread_setspecific(key, p) else {
|
||||
fatalError("Unable to set TLS")
|
||||
}
|
||||
}
|
||||
|
||||
internal func getTLS(_ key: _PlatformTLSKey) -> UnsafeMutableRawPointer? {
|
||||
pthread_getspecific(key)
|
||||
}
|
||||
@@ -0,0 +1,437 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import SystemPackage
|
||||
|
||||
#if canImport(Darwin)
|
||||
import Darwin
|
||||
import CNIODarwin
|
||||
#elseif canImport(Glibc)
|
||||
@preconcurrency import Glibc
|
||||
import CNIOLinux
|
||||
#elseif canImport(Musl)
|
||||
@preconcurrency import Musl
|
||||
import CNIOLinux
|
||||
#elseif canImport(Bionic)
|
||||
@preconcurrency import Bionic
|
||||
import CNIOLinux
|
||||
#endif
|
||||
|
||||
@_spi(Testing)
|
||||
public enum Syscall: Sendable {
|
||||
@_spi(Testing)
|
||||
public static func stat(path: FilePath) -> Result<CInterop.Stat, Errno> {
|
||||
path.withPlatformString { platformPath in
|
||||
var status = CInterop.Stat()
|
||||
return valueOrErrno(retryOnInterrupt: false) {
|
||||
system_stat(platformPath, &status)
|
||||
}.map { _ in
|
||||
status
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@_spi(Testing)
|
||||
public static func lstat(path: FilePath) -> Result<CInterop.Stat, Errno> {
|
||||
path.withPlatformString { platformPath in
|
||||
var status = CInterop.Stat()
|
||||
return valueOrErrno(retryOnInterrupt: false) {
|
||||
system_lstat(platformPath, &status)
|
||||
}.map { _ in
|
||||
status
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@_spi(Testing)
|
||||
public static func mkdir(at path: FilePath, permissions: FilePermissions) -> Result<Void, Errno> {
|
||||
nothingOrErrno(retryOnInterrupt: false) {
|
||||
path.withPlatformString { p in
|
||||
system_mkdir(p, permissions.rawValue)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@_spi(Testing)
|
||||
public static func rename(from old: FilePath, to new: FilePath) -> Result<Void, Errno> {
|
||||
nothingOrErrno(retryOnInterrupt: false) {
|
||||
old.withPlatformString { oldPath in
|
||||
new.withPlatformString { newPath in
|
||||
system_rename(oldPath, newPath)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if canImport(Darwin)
|
||||
@_spi(Testing)
|
||||
public static func rename(
|
||||
from old: FilePath,
|
||||
to new: FilePath,
|
||||
options: RenameOptions
|
||||
) -> Result<Void, Errno> {
|
||||
nothingOrErrno(retryOnInterrupt: false) {
|
||||
old.withPlatformString { oldPath in
|
||||
new.withPlatformString { newPath in
|
||||
system_renamex_np(oldPath, newPath, options.rawValue)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@_spi(Testing)
|
||||
public struct RenameOptions: OptionSet, Sendable {
|
||||
public var rawValue: CUnsignedInt
|
||||
|
||||
public init(rawValue: CUnsignedInt) {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
public static var exclusive: Self {
|
||||
Self(rawValue: UInt32(bitPattern: RENAME_EXCL))
|
||||
}
|
||||
|
||||
public static var swap: Self {
|
||||
Self(rawValue: UInt32(bitPattern: RENAME_SWAP))
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#if canImport(Glibc) || canImport(Musl) || canImport(Bionic)
|
||||
@_spi(Testing)
|
||||
public static func rename(
|
||||
from old: FilePath,
|
||||
relativeTo oldFD: FileDescriptor,
|
||||
to new: FilePath,
|
||||
relativeTo newFD: FileDescriptor,
|
||||
flags: RenameAtFlags
|
||||
) -> Result<Void, Errno> {
|
||||
nothingOrErrno(retryOnInterrupt: false) {
|
||||
old.withPlatformString { oldPath in
|
||||
new.withPlatformString { newPath in
|
||||
system_renameat2(
|
||||
oldFD.rawValue,
|
||||
oldPath,
|
||||
newFD.rawValue,
|
||||
newPath,
|
||||
flags.rawValue
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@_spi(Testing)
|
||||
public struct RenameAtFlags: OptionSet {
|
||||
public var rawValue: CUnsignedInt
|
||||
|
||||
public init(rawValue: CUnsignedInt) {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
public static var exclusive: Self {
|
||||
Self(rawValue: CNIOLinux_RENAME_NOREPLACE)
|
||||
}
|
||||
|
||||
public static var swap: Self {
|
||||
Self(rawValue: CNIOLinux_RENAME_EXCHANGE)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#if canImport(Glibc) || canImport(Musl) || canImport(Bionic)
|
||||
@_spi(Testing)
|
||||
public struct LinkAtFlags: OptionSet {
|
||||
@_spi(Testing)
|
||||
public var rawValue: CInt
|
||||
|
||||
@_spi(Testing)
|
||||
public init(rawValue: CInt) {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
@_spi(Testing)
|
||||
public static var emptyPath: Self {
|
||||
Self(rawValue: CNIOLinux_AT_EMPTY_PATH)
|
||||
}
|
||||
|
||||
@_spi(Testing)
|
||||
public static var followSymbolicLinks: Self {
|
||||
Self(rawValue: AT_SYMLINK_FOLLOW)
|
||||
}
|
||||
}
|
||||
|
||||
@_spi(Testing)
|
||||
public static func linkAt(
|
||||
from source: FilePath,
|
||||
relativeTo sourceFD: FileDescriptor,
|
||||
to destination: FilePath,
|
||||
relativeTo destinationFD: FileDescriptor,
|
||||
flags: LinkAtFlags
|
||||
) -> Result<Void, Errno> {
|
||||
nothingOrErrno(retryOnInterrupt: false) {
|
||||
source.withPlatformString { src in
|
||||
destination.withPlatformString { dst in
|
||||
system_linkat(
|
||||
sourceFD.rawValue,
|
||||
src,
|
||||
destinationFD.rawValue,
|
||||
dst,
|
||||
flags.rawValue
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@_spi(Testing)
|
||||
public static func link(
|
||||
from source: FilePath,
|
||||
to destination: FilePath
|
||||
) -> Result<Void, Errno> {
|
||||
nothingOrErrno(retryOnInterrupt: false) {
|
||||
source.withPlatformString { src in
|
||||
destination.withPlatformString { dst in
|
||||
system_link(src, dst)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@_spi(Testing)
|
||||
public static func unlink(path: FilePath) -> Result<Void, Errno> {
|
||||
nothingOrErrno(retryOnInterrupt: false) {
|
||||
path.withPlatformString { ptr in
|
||||
system_unlink(ptr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@_spi(Testing)
|
||||
public static func symlink(
|
||||
to destination: FilePath,
|
||||
from source: FilePath
|
||||
) -> Result<Void, Errno> {
|
||||
nothingOrErrno(retryOnInterrupt: false) {
|
||||
source.withPlatformString { src in
|
||||
destination.withPlatformString { dst in
|
||||
system_symlink(dst, src)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@_spi(Testing)
|
||||
public static func readlink(at path: FilePath) -> Result<FilePath, Errno> {
|
||||
do {
|
||||
let resolved = try path.withPlatformString { p in
|
||||
try String(customUnsafeUninitializedCapacity: Int(CInterop.maxPathLength)) { pointer in
|
||||
let result = pointer.withMemoryRebound(to: CInterop.PlatformChar.self) { ptr in
|
||||
valueOrErrno(retryOnInterrupt: false) {
|
||||
system_readlink(p, ptr.baseAddress!, ptr.count)
|
||||
}
|
||||
}
|
||||
return try result.get()
|
||||
}
|
||||
}
|
||||
return .success(FilePath(resolved))
|
||||
} catch let error as Errno {
|
||||
return .failure(error)
|
||||
} catch {
|
||||
// Shouldn't happen: we deal in Result types and only ever with Errno.
|
||||
fatalError("Unexpected error '\(error)' caught")
|
||||
}
|
||||
}
|
||||
|
||||
#if canImport(Glibc) || canImport(Musl) || canImport(Bionic)
|
||||
@_spi(Testing)
|
||||
public static func sendfile(
|
||||
to output: FileDescriptor,
|
||||
from input: FileDescriptor,
|
||||
offset: Int,
|
||||
size: Int
|
||||
) -> Result<Int, Errno> {
|
||||
valueOrErrno(retryOnInterrupt: false) {
|
||||
system_sendfile(output.rawValue, input.rawValue, off_t(offset), size)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@_spi(Testing)
|
||||
public static func futimens(
|
||||
fileDescriptor fd: FileDescriptor,
|
||||
times: UnsafePointer<timespec>?
|
||||
) -> Result<Void, Errno> {
|
||||
nothingOrErrno(retryOnInterrupt: false) {
|
||||
system_futimens(fd.rawValue, times)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@_spi(Testing)
|
||||
public enum Libc: Sendable {
|
||||
static func readdir(
|
||||
_ dir: CInterop.DirPointer
|
||||
) -> Result<UnsafeMutablePointer<CInterop.DirEnt>?, Errno> {
|
||||
optionalValueOrErrno(retryOnInterrupt: false) {
|
||||
libc_readdir(dir)
|
||||
}
|
||||
}
|
||||
|
||||
static func closedir(
|
||||
_ dir: CInterop.DirPointer
|
||||
) -> Result<Void, Errno> {
|
||||
nothingOrErrno(retryOnInterrupt: false) {
|
||||
libc_closedir(dir)
|
||||
}
|
||||
}
|
||||
|
||||
#if canImport(Darwin)
|
||||
@_spi(Testing)
|
||||
public static func fcopyfile(
|
||||
from source: FileDescriptor,
|
||||
to destination: FileDescriptor,
|
||||
state: copyfile_state_t?,
|
||||
flags: copyfile_flags_t
|
||||
) -> Result<Void, Errno> {
|
||||
nothingOrErrno(retryOnInterrupt: false) {
|
||||
libc_fcopyfile(source.rawValue, destination.rawValue, state, flags)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#if canImport(Darwin)
|
||||
@_spi(Testing)
|
||||
public static func copyfile(
|
||||
from source: FilePath,
|
||||
to destination: FilePath,
|
||||
state: copyfile_state_t?,
|
||||
flags: copyfile_flags_t
|
||||
) -> Result<Void, Errno> {
|
||||
source.withPlatformString { sourcePath in
|
||||
destination.withPlatformString { destinationPath in
|
||||
nothingOrErrno(retryOnInterrupt: false) {
|
||||
libc_copyfile(sourcePath, destinationPath, state, flags)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@_spi(Testing)
|
||||
public static func remove(
|
||||
_ path: FilePath
|
||||
) -> Result<Void, Errno> {
|
||||
nothingOrErrno(retryOnInterrupt: false) {
|
||||
path.withPlatformString {
|
||||
libc_remove($0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static func getcwd() -> Result<FilePath, Errno> {
|
||||
var buffer = [CInterop.PlatformChar](
|
||||
repeating: 0,
|
||||
count: Int(CInterop.maxPathLength)
|
||||
)
|
||||
|
||||
return optionalValueOrErrno(retryOnInterrupt: false) {
|
||||
buffer.withUnsafeMutableBufferPointer { pointer in
|
||||
libc_getcwd(pointer.baseAddress!, pointer.count)
|
||||
}
|
||||
}.map { ptr in
|
||||
// 'ptr' is just the input pointer, we should ignore it and just rely on the bytes
|
||||
// in buffer.
|
||||
//
|
||||
// At this point 'ptr' must be non-nil, because if it were 'nil' we should be on the
|
||||
// error path.
|
||||
precondition(ptr != nil)
|
||||
return FilePath(platformString: buffer)
|
||||
}
|
||||
}
|
||||
|
||||
#if !os(Android)
|
||||
static func constr(_ name: CInt) -> Result<String, Errno> {
|
||||
var buffer = [CInterop.PlatformChar](repeating: 0, count: 128)
|
||||
|
||||
repeat {
|
||||
let result = valueOrErrno(retryOnInterrupt: false) {
|
||||
buffer.withUnsafeMutableBufferPointer { pointer in
|
||||
libc_confstr(name, pointer.baseAddress!, pointer.count)
|
||||
}
|
||||
}
|
||||
|
||||
switch result {
|
||||
case let .success(length):
|
||||
if length <= buffer.count {
|
||||
return .success(String(cString: buffer))
|
||||
} else {
|
||||
// The buffer wasn't long enough. Double and try again.
|
||||
buffer.append(contentsOf: repeatElement(0, count: buffer.capacity))
|
||||
}
|
||||
case let .failure(errno):
|
||||
return .failure(errno)
|
||||
}
|
||||
} while true
|
||||
}
|
||||
#endif
|
||||
|
||||
static func ftsOpen(_ path: FilePath, options: FTSOpenOptions) -> Result<CInterop.FTSPointer, Errno> {
|
||||
// 'fts_open' needs an unsafe mutable pointer to the C-string, `FilePath` doesn't offer this
|
||||
// so copy out its bytes.
|
||||
var pathBytes = path.withPlatformString { pointer in
|
||||
// Length excludes the null terminator, so add it back.
|
||||
let bufferPointer = UnsafeBufferPointer(start: pointer, count: path.length + 1)
|
||||
return Array(bufferPointer)
|
||||
}
|
||||
|
||||
return valueOrErrno {
|
||||
pathBytes.withUnsafeMutableBufferPointer { pointer in
|
||||
// The array must be terminated with a nil.
|
||||
libc_fts_open([pointer.baseAddress, nil], options.rawValue)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Options passed to 'fts_open'.
|
||||
struct FTSOpenOptions: OptionSet {
|
||||
var rawValue: CInt
|
||||
|
||||
/// Don't change directory while walking the filesystem hierarchy.
|
||||
static var noChangeDir: Self { Self(rawValue: FTS_NOCHDIR) }
|
||||
|
||||
/// Return FTS entries for symbolic links rather than their targets.
|
||||
static var physical: Self { Self(rawValue: FTS_PHYSICAL) }
|
||||
|
||||
/// Return FTS entries for the targets of symbolic links.
|
||||
static var logical: Self { Self(rawValue: FTS_LOGICAL) }
|
||||
}
|
||||
|
||||
static func ftsRead(
|
||||
_ pointer: CInterop.FTSPointer
|
||||
) -> Result<UnsafeMutablePointer<CInterop.FTSEnt>?, Errno> {
|
||||
optionalValueOrErrno {
|
||||
libc_fts_read(pointer)
|
||||
}
|
||||
}
|
||||
|
||||
static func ftsClose(
|
||||
_ pointer: CInterop.FTSPointer
|
||||
) -> Result<Void, Errno> {
|
||||
nothingOrErrno {
|
||||
libc_fts_close(pointer)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,481 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import SystemPackage
|
||||
|
||||
#if canImport(Darwin)
|
||||
import Darwin
|
||||
import CNIODarwin
|
||||
#elseif canImport(Glibc)
|
||||
@preconcurrency import Glibc
|
||||
import CNIOLinux
|
||||
#elseif canImport(Musl)
|
||||
@preconcurrency import Musl
|
||||
import CNIOLinux
|
||||
#elseif canImport(Android)
|
||||
@preconcurrency import Android
|
||||
import CNIOLinux
|
||||
#endif
|
||||
|
||||
// MARK: - system
|
||||
|
||||
/// openat(2): Open or create a file for reading or writing
|
||||
func system_fdopenat(
|
||||
_ fd: FileDescriptor.RawValue,
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ oflag: Int32
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled {
|
||||
return mock(fd, path, oflag)
|
||||
}
|
||||
#endif
|
||||
return openat(fd, path, oflag)
|
||||
}
|
||||
|
||||
/// openat(2): Open or create a file for reading or writing
|
||||
func system_fdopenat(
|
||||
_ fd: FileDescriptor.RawValue,
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ oflag: Int32,
|
||||
_ mode: CInterop.Mode
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled {
|
||||
return mock(fd, path, oflag, mode)
|
||||
}
|
||||
#endif
|
||||
return openat(fd, path, oflag, mode)
|
||||
}
|
||||
|
||||
/// stat(2): Get file status
|
||||
func system_stat(
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ info: inout CInterop.Stat
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled {
|
||||
return mock(path)
|
||||
}
|
||||
#endif
|
||||
return stat(path, &info)
|
||||
}
|
||||
|
||||
/// lstat(2): Get file status
|
||||
internal func system_lstat(
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ info: inout CInterop.Stat
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled {
|
||||
return mock(path)
|
||||
}
|
||||
#endif
|
||||
return lstat(path, &info)
|
||||
}
|
||||
|
||||
/// fstat(2): Get file status
|
||||
internal func system_fstat(
|
||||
_ fd: FileDescriptor.RawValue,
|
||||
_ info: inout CInterop.Stat
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled {
|
||||
return mock(fd)
|
||||
}
|
||||
#endif
|
||||
return fstat(fd, &info)
|
||||
}
|
||||
|
||||
/// fchmod(2): Change mode of file
|
||||
internal func system_fchmod(
|
||||
_ fd: FileDescriptor.RawValue,
|
||||
_ mode: CInterop.Mode
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled {
|
||||
return mock(fd, mode)
|
||||
}
|
||||
#endif
|
||||
return fchmod(fd, mode)
|
||||
}
|
||||
|
||||
/// fsync(2): Synchronize modifications to a file to permanent storage
|
||||
internal func system_fsync(
|
||||
_ fd: FileDescriptor.RawValue
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled {
|
||||
return mock(fd)
|
||||
}
|
||||
#endif
|
||||
return fsync(fd)
|
||||
}
|
||||
|
||||
/// mkdir(2): Make a directory file
|
||||
internal func system_mkdir(
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ mode: CInterop.Mode
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled {
|
||||
return mock(path, mode)
|
||||
}
|
||||
#endif
|
||||
return mkdir(path, mode)
|
||||
}
|
||||
|
||||
/// symlink(2): Make symolic link to a file
|
||||
internal func system_symlink(
|
||||
_ destination: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ source: UnsafePointer<CInterop.PlatformChar>
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled {
|
||||
return mock(destination, source)
|
||||
}
|
||||
#endif
|
||||
return symlink(destination, source)
|
||||
}
|
||||
|
||||
/// readlink(2): Read value of a symolic link
|
||||
internal func system_readlink(
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ buffer: UnsafeMutablePointer<CInterop.PlatformChar>,
|
||||
_ bufferSize: Int
|
||||
) -> Int {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled {
|
||||
return mockInt(path, buffer, bufferSize)
|
||||
}
|
||||
#endif
|
||||
return readlink(path, buffer, bufferSize)
|
||||
}
|
||||
|
||||
/// flistxattr(2): List extended attribute names
|
||||
internal func system_flistxattr(
|
||||
_ fd: FileDescriptor.RawValue,
|
||||
_ namebuf: UnsafeMutablePointer<CChar>?,
|
||||
_ size: Int
|
||||
) -> Int {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled {
|
||||
return mockInt(fd, namebuf, size)
|
||||
}
|
||||
#endif
|
||||
#if canImport(Darwin)
|
||||
// The final parameter is 'options'; there is no equivalent on Linux.
|
||||
return flistxattr(fd, namebuf, size, 0)
|
||||
#elseif canImport(Glibc) || canImport(Musl) || canImport(Android)
|
||||
return flistxattr(fd, namebuf, size)
|
||||
#endif
|
||||
}
|
||||
|
||||
/// fgetxattr(2): Get an extended attribute value
|
||||
internal func system_fgetxattr(
|
||||
_ fd: FileDescriptor.RawValue,
|
||||
_ name: UnsafePointer<CChar>,
|
||||
_ value: UnsafeMutableRawPointer?,
|
||||
_ size: Int
|
||||
) -> Int {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled {
|
||||
return mockInt(fd, name, value, size)
|
||||
}
|
||||
#endif
|
||||
|
||||
#if canImport(Darwin)
|
||||
// Penultimate parameter is position which is reserved and should be zero.
|
||||
// The final parameter is 'options'; there is no equivalent on Linux.
|
||||
return fgetxattr(fd, name, value, size, 0, 0)
|
||||
#elseif canImport(Glibc) || canImport(Musl) || canImport(Android)
|
||||
return fgetxattr(fd, name, value, size)
|
||||
#endif
|
||||
}
|
||||
|
||||
/// fsetxattr(2): Set an extended attribute value
|
||||
internal func system_fsetxattr(
|
||||
_ fd: FileDescriptor.RawValue,
|
||||
_ name: UnsafePointer<CChar>,
|
||||
_ value: UnsafeRawPointer?,
|
||||
_ size: Int
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled {
|
||||
return mock(fd, name, value, size)
|
||||
}
|
||||
#endif
|
||||
|
||||
// The final parameter is 'options'/'flags' on Darwin/Linux respectively.
|
||||
#if canImport(Darwin)
|
||||
// Penultimate parameter is position which is reserved and should be zero.
|
||||
return fsetxattr(fd, name, value, size, 0, 0)
|
||||
#elseif canImport(Glibc) || canImport(Musl) || canImport(Android)
|
||||
return fsetxattr(fd, name, value, size, 0)
|
||||
#endif
|
||||
}
|
||||
|
||||
/// fremovexattr(2): Remove an extended attribute value
|
||||
internal func system_fremovexattr(
|
||||
_ fd: FileDescriptor.RawValue,
|
||||
_ name: UnsafePointer<CChar>
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled {
|
||||
return mock(fd, name)
|
||||
}
|
||||
#endif
|
||||
|
||||
#if canImport(Darwin)
|
||||
// The final parameter is 'options'; there is no equivalent on Linux.
|
||||
return fremovexattr(fd, name, 0)
|
||||
#elseif canImport(Glibc) || canImport(Musl) || canImport(Android)
|
||||
return fremovexattr(fd, name)
|
||||
#endif
|
||||
}
|
||||
|
||||
/// rename(2): Change the name of a file
|
||||
internal func system_rename(
|
||||
_ old: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ new: UnsafePointer<CInterop.PlatformChar>
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled {
|
||||
return mock(old, new)
|
||||
}
|
||||
#endif
|
||||
return rename(old, new)
|
||||
}
|
||||
|
||||
#if canImport(Darwin)
|
||||
internal func system_renamex_np(
|
||||
_ old: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ new: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ flags: CUnsignedInt
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled {
|
||||
return mock(old, new, flags)
|
||||
}
|
||||
#endif
|
||||
return renamex_np(old, new, flags)
|
||||
}
|
||||
#endif
|
||||
|
||||
#if canImport(Glibc) || canImport(Musl) || canImport(Android)
|
||||
internal func system_renameat2(
|
||||
_ oldFD: FileDescriptor.RawValue,
|
||||
_ old: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ newFD: FileDescriptor.RawValue,
|
||||
_ new: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ flags: CUnsignedInt
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled {
|
||||
return mock(oldFD, old, newFD, new, flags)
|
||||
}
|
||||
#endif
|
||||
return CNIOLinux_renameat2(oldFD, old, newFD, new, flags)
|
||||
}
|
||||
#endif
|
||||
|
||||
/// link(2): Creates a new link for a file.
|
||||
#if canImport(Glibc) || canImport(Musl) || canImport(Android)
|
||||
internal func system_linkat(
|
||||
_ oldFD: FileDescriptor.RawValue,
|
||||
_ old: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ newFD: FileDescriptor.RawValue,
|
||||
_ new: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ flags: CInt
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled {
|
||||
return mock(oldFD, old, newFD, new, flags)
|
||||
}
|
||||
#endif
|
||||
return linkat(oldFD, old, newFD, new, flags)
|
||||
}
|
||||
#endif
|
||||
|
||||
/// link(2): Creates a new link for a file.
|
||||
internal func system_link(
|
||||
_ old: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ new: UnsafePointer<CInterop.PlatformChar>
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled {
|
||||
return mock(old, new)
|
||||
}
|
||||
#endif
|
||||
return link(old, new)
|
||||
}
|
||||
|
||||
/// unlink(2): Remove a directory entry.
|
||||
internal func system_unlink(
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled {
|
||||
return mock(path)
|
||||
}
|
||||
#endif
|
||||
return unlink(path)
|
||||
}
|
||||
|
||||
#if canImport(Glibc) || canImport(Musl) || canImport(Android)
|
||||
/// sendfile(2): Transfer data between descriptors
|
||||
internal func system_sendfile(
|
||||
_ outFD: CInt,
|
||||
_ inFD: CInt,
|
||||
_ offset: off_t,
|
||||
_ count: Int
|
||||
) -> Int {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled {
|
||||
return mockInt(outFD, inFD, offset, count)
|
||||
}
|
||||
#endif
|
||||
var offset = offset
|
||||
return sendfile(outFD, inFD, &offset, count)
|
||||
}
|
||||
#endif
|
||||
|
||||
internal func system_futimens(
|
||||
_ fd: CInt,
|
||||
_ times: UnsafePointer<timespec>?
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled {
|
||||
return mock(fd, times)
|
||||
}
|
||||
#endif
|
||||
return futimens(fd, times)
|
||||
}
|
||||
|
||||
// MARK: - libc
|
||||
|
||||
/// fdopendir(3): Opens a directory stream for the file descriptor
|
||||
internal func libc_fdopendir(
|
||||
_ fd: FileDescriptor.RawValue
|
||||
) -> CInterop.DirPointer {
|
||||
fdopendir(fd)!
|
||||
}
|
||||
|
||||
/// readdir(3): Returns a pointer to the next directory entry
|
||||
internal func libc_readdir(
|
||||
_ dir: CInterop.DirPointer
|
||||
) -> UnsafeMutablePointer<CInterop.DirEnt>? {
|
||||
readdir(dir)
|
||||
}
|
||||
|
||||
/// readdir(3): Closes the directory stream and frees associated structures
|
||||
internal func libc_closedir(
|
||||
_ dir: CInterop.DirPointer
|
||||
) -> CInt {
|
||||
closedir(dir)
|
||||
}
|
||||
|
||||
/// remove(3): Remove directory entry
|
||||
internal func libc_remove(
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled {
|
||||
return mock(path)
|
||||
}
|
||||
#endif
|
||||
return remove(path)
|
||||
}
|
||||
|
||||
#if canImport(Darwin)
|
||||
/// fcopyfile(3): Copy a file from one file to another.
|
||||
internal func libc_fcopyfile(
|
||||
_ from: CInt,
|
||||
_ to: CInt,
|
||||
_ state: copyfile_state_t?,
|
||||
_ flags: copyfile_flags_t
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled {
|
||||
return mock(from, to, state, flags)
|
||||
}
|
||||
#endif
|
||||
return fcopyfile(from, to, state, flags)
|
||||
}
|
||||
#endif
|
||||
|
||||
#if canImport(Darwin)
|
||||
/// copyfile(3): Copy a file from one file to another.
|
||||
internal func libc_copyfile(
|
||||
_ from: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ to: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ state: copyfile_state_t?,
|
||||
_ flags: copyfile_flags_t
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled {
|
||||
return mock(from, to, state, flags)
|
||||
}
|
||||
#endif
|
||||
return copyfile(from, to, state, flags)
|
||||
}
|
||||
#endif
|
||||
|
||||
/// getcwd(3): Get working directory pathname
|
||||
internal func libc_getcwd(
|
||||
_ buffer: UnsafeMutablePointer<CInterop.PlatformChar>,
|
||||
_ size: Int
|
||||
) -> UnsafeMutablePointer<CInterop.PlatformChar>? {
|
||||
getcwd(buffer, size)
|
||||
}
|
||||
|
||||
/// confstr(3)
|
||||
#if !os(Android)
|
||||
internal func libc_confstr(
|
||||
_ name: CInt,
|
||||
_ buffer: UnsafeMutablePointer<CInterop.PlatformChar>,
|
||||
_ size: Int
|
||||
) -> Int {
|
||||
confstr(name, buffer, size)
|
||||
}
|
||||
#endif
|
||||
|
||||
/// fts(3)
|
||||
internal func libc_fts_open(
|
||||
_ path: [UnsafeMutablePointer<CInterop.PlatformChar>?],
|
||||
_ options: CInt
|
||||
) -> UnsafeMutablePointer<CInterop.FTS> {
|
||||
#if os(Android)
|
||||
// This branch is a workaround for incorrect nullability annotations in the Android SDK.
|
||||
// They were added in https://android.googlesource.com/platform/bionic/+/dec8efd72a6ad8b807a15a614ae1519487cfa456,
|
||||
// and lasted for more than a year: https://android.googlesource.com/platform/bionic/+/da81ec4d1cbd0279014feb60535bf38defcd9346.
|
||||
CNIOLinux_fts_open(path, options, nil)!
|
||||
#else
|
||||
fts_open(path, options, nil)!
|
||||
#endif
|
||||
}
|
||||
|
||||
/// fts(3)
|
||||
internal func libc_fts_read(
|
||||
_ fts: UnsafeMutablePointer<CInterop.FTS>
|
||||
) -> UnsafeMutablePointer<CInterop.FTSEnt>? {
|
||||
fts_read(fts)
|
||||
}
|
||||
|
||||
/// fts(3)
|
||||
internal func libc_fts_close(
|
||||
_ fts: UnsafeMutablePointer<CInterop.FTS>
|
||||
) -> CInt {
|
||||
fts_close(fts)
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,48 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import SystemPackage
|
||||
|
||||
@usableFromInline
|
||||
internal final class Ref<Value> {
|
||||
@usableFromInline
|
||||
var value: Value
|
||||
@inlinable
|
||||
init(_ value: Value) {
|
||||
self.value = value
|
||||
}
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
extension Ref: Sendable {}
|
||||
|
||||
extension String {
|
||||
init(randomAlphaNumericOfLength length: Int) {
|
||||
precondition(length > 0)
|
||||
|
||||
let characters = (0..<length).lazy.map {
|
||||
_ in Array.alphaNumericValues.randomElement()!
|
||||
}
|
||||
self = String(decoding: characters, as: UTF8.self)
|
||||
}
|
||||
}
|
||||
|
||||
extension Array where Element == UInt8 {
|
||||
fileprivate static let alphaNumericValues: [UInt8] = {
|
||||
var alphaNumericValues = Array(UInt8(ascii: "a")...UInt8(ascii: "z"))
|
||||
alphaNumericValues.append(contentsOf: UInt8(ascii: "A")...UInt8(ascii: "Z"))
|
||||
alphaNumericValues.append(contentsOf: UInt8(ascii: "0")...UInt8(ascii: "9"))
|
||||
return alphaNumericValues
|
||||
}()
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2025 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import SystemPackage
|
||||
|
||||
#if canImport(System)
|
||||
import System
|
||||
#endif
|
||||
|
||||
/// `NIOFilePath` is a type for representing a file path. It is backed by `SystemPackage`'s `FilePath` type.
|
||||
///
|
||||
/// You can create a `NIOFilePath` from a string literal:
|
||||
///
|
||||
/// ```swift
|
||||
/// let path: NIOFilePath = "/home/user/report.txt"
|
||||
/// ```
|
||||
///
|
||||
/// To interact with the underlying filepath using `SystemPackage.FilePath`'s API, you can initialize a `SystemPackage.FilePath` instance from a
|
||||
/// `NIOFilePath` instance (and vice-versa).
|
||||
public struct NIOFilePath: Equatable, Hashable, Sendable, ExpressibleByStringLiteral, CustomStringConvertible,
|
||||
CustomDebugStringConvertible
|
||||
{
|
||||
/// The underlying `SystemPackage.FilePath` instance that ``NIOFilePath`` uses.
|
||||
var underlying: SystemPackage.FilePath
|
||||
|
||||
/// Creates a ``NIOFilePath`` given an underlying `SystemPackage.FilePath` instance.
|
||||
///
|
||||
/// - Parameter underlying: The `SystemPackage.FilePath` to use as the underlying backing for ``NIOFilePath``.
|
||||
public init(_ underlying: SystemPackage.FilePath) {
|
||||
self.underlying = underlying
|
||||
}
|
||||
|
||||
#if canImport(System)
|
||||
/// Creates a ``NIOFilePath`` given an underlying `System.FilePath` instance.
|
||||
///
|
||||
/// - Parameter underlying: The `System.FilePath` instance to use to create this ``NIOFilePath`` instance.
|
||||
@available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)
|
||||
public init(_ underlying: System.FilePath) {
|
||||
self.underlying = underlying.withPlatformString {
|
||||
SystemPackage.FilePath(platformString: $0)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Creates an instance representing an empty and null-terminated filepath.
|
||||
public init() {
|
||||
self.underlying = .init()
|
||||
}
|
||||
|
||||
/// Creates an instance corresponding to the file path represented by the provided string.
|
||||
///
|
||||
/// - Parameter string: A string whose Unicode encoded contents to use as the contents of the path
|
||||
public init(_ string: String) {
|
||||
self.underlying = .init(string)
|
||||
}
|
||||
|
||||
/// Creates an instance from a string literal.
|
||||
///
|
||||
/// - Parameter stringLiteral: A string literal whose Unicode encoded contents to use as the contents of the path.
|
||||
public init(stringLiteral: String) {
|
||||
self.init(stringLiteral)
|
||||
}
|
||||
|
||||
/// A textual representation of the file path.
|
||||
///
|
||||
/// If the content of the path isn't a well-formed Unicode string, this replaces invalid bytes with U+FFFD. See `String.init(decoding:)`
|
||||
public var description: String {
|
||||
self.underlying.description
|
||||
}
|
||||
|
||||
/// A textual representation of the file path, suitable for debugging.
|
||||
///
|
||||
/// If the content of the path isn't a well-formed Unicode string, this replaces invalid bytes with U+FFFD. See `String.init(decoding:)`
|
||||
public var debugDescription: String {
|
||||
self.underlying.debugDescription
|
||||
}
|
||||
}
|
||||
|
||||
extension SystemPackage.FilePath {
|
||||
/// Creates a `SystemPackage.FilePath` from a ``NIOFilePath`` instance.
|
||||
public init(_ filePath: NIOFilePath) {
|
||||
self = filePath.underlying
|
||||
}
|
||||
}
|
||||
|
||||
#if canImport(System)
|
||||
@available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)
|
||||
extension System.FilePath {
|
||||
/// Creates a `System.FilePath` from a ``NIOFilePath`` instance.
|
||||
public init(_ filePath: NIOFilePath) {
|
||||
self = filePath.underlying.withPlatformString {
|
||||
System.FilePath(platformString: $0)
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,19 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2025 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 compiler(>=6.2)
|
||||
public typealias _NIOFileSystemSendableMetatype = SendableMetatype
|
||||
#else
|
||||
public typealias _NIOFileSystemSendableMetatype = Any
|
||||
#endif
|
||||
@@ -0,0 +1,297 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2025 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import SystemPackage
|
||||
|
||||
/// Options for opening file handles.
|
||||
public enum OpenOptions: Sendable {
|
||||
/// Options for opening a file for reading.
|
||||
public struct Read: Hashable, Sendable {
|
||||
/// If the last path component is a symbolic link then this flag determines whether the
|
||||
/// link is followed. If `false` and the last path component is a symbolic link then an
|
||||
/// error is thrown.
|
||||
public var followSymbolicLinks: Bool
|
||||
|
||||
/// Marks the descriptor of the opened file as 'close-on-exec'.
|
||||
public var closeOnExec: Bool
|
||||
|
||||
/// Creates a new set of options for opening a file for reading.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - followSymbolicLinks: Whether symbolic links should be followed, defaults to `true`.
|
||||
/// - closeOnExec: Whether the descriptor should be marked as closed-on-exec, defaults
|
||||
/// to `false`.
|
||||
public init(
|
||||
followSymbolicLinks: Bool = true,
|
||||
closeOnExec: Bool = false
|
||||
) {
|
||||
self.followSymbolicLinks = followSymbolicLinks
|
||||
self.closeOnExec = closeOnExec
|
||||
}
|
||||
}
|
||||
|
||||
/// Options for opening a directory.
|
||||
public struct Directory: Hashable, Sendable {
|
||||
/// If the last path component is a symbolic link then this flag determines whether the
|
||||
/// link is followed. If `false` and the last path component is a symbolic link then an
|
||||
/// error is thrown.
|
||||
public var followSymbolicLinks: Bool
|
||||
|
||||
/// Marks the descriptor of the opened file as 'close-on-exec'.
|
||||
public var closeOnExec: Bool
|
||||
|
||||
/// Creates a new set of options for opening a directory.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - followSymbolicLinks: Whether symbolic links should be followed, defaults to `true`.
|
||||
/// - closeOnExec: Whether the descriptor should be marked as closed-on-exec, defaults
|
||||
/// to `false`.
|
||||
public init(
|
||||
followSymbolicLinks: Bool = true,
|
||||
closeOnExec: Bool = false
|
||||
) {
|
||||
self.followSymbolicLinks = followSymbolicLinks
|
||||
self.closeOnExec = closeOnExec
|
||||
}
|
||||
}
|
||||
|
||||
/// Options for opening a file for writing (or reading and writing).
|
||||
///
|
||||
/// You can use the following methods to create commonly used sets of options:
|
||||
/// - ``newFile(replaceExisting:permissions:)`` to create a new file, optionally replacing
|
||||
/// one which already exists.
|
||||
/// - ``modifyFile(createIfNecessary:permissions:)`` to modify an existing file, optionally
|
||||
/// creating it if it doesn't exist.
|
||||
public struct Write: Hashable, Sendable {
|
||||
/// The behavior for opening an existing file.
|
||||
public var existingFile: OpenOptions.ExistingFile
|
||||
|
||||
/// The creation options for a new file, if one should be created. `nil` means that no
|
||||
/// file should be created.
|
||||
public var newFile: OpenOptions.NewFile?
|
||||
|
||||
/// If the last path component is a symbolic link then this flag determines whether the
|
||||
/// link is followed. If `false` and the last path component is a symbolic link then an
|
||||
/// error is thrown.
|
||||
public var followSymbolicLinks: Bool
|
||||
|
||||
/// Marks the descriptor of the opened file as 'close-on-exec'.
|
||||
public var closeOnExec: Bool
|
||||
|
||||
/// Creates a new set of options for opening a directory.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - existingFile: Options for handling an existing file.
|
||||
/// - newFile: Options for creating a new file.
|
||||
/// - followSymbolicLinks: Whether symbolic links should be followed, defaults to `true`.
|
||||
/// - closeOnExec: Whether the descriptor should be marked as closed-on-exec, defaults
|
||||
/// to `false`.
|
||||
public init(
|
||||
existingFile: OpenOptions.ExistingFile,
|
||||
newFile: OpenOptions.NewFile?,
|
||||
followSymbolicLinks: Bool = true,
|
||||
closeOnExec: Bool = false
|
||||
) {
|
||||
self.existingFile = existingFile
|
||||
self.newFile = newFile
|
||||
self.followSymbolicLinks = followSymbolicLinks
|
||||
self.closeOnExec = closeOnExec
|
||||
}
|
||||
|
||||
/// Create a new file for writing to.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - replaceExisting: Whether any existing file of the same name is replaced. If
|
||||
/// this is `true` then any existing file of the same name will be replaced with the
|
||||
/// new file. If this is `false` and a file already exists an error is thrown.
|
||||
/// - permissions: The permissions to apply to the newly created file. Default permissions
|
||||
/// (read-write owner permissions and read permissions for everyone else) are applied
|
||||
/// if `nil`.
|
||||
/// - Returns: Options for creating a new file for writing.
|
||||
public static func newFile(
|
||||
replaceExisting: Bool,
|
||||
permissions: FilePermissions? = nil
|
||||
) -> Self {
|
||||
Write(
|
||||
existingFile: replaceExisting ? .truncate : .none,
|
||||
newFile: NewFile(permissions: permissions)
|
||||
)
|
||||
}
|
||||
|
||||
/// Opens a file for modifying.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - createIfNecessary: Whether a file should be created if one doesn't exist. If
|
||||
/// `false` and a file doesn't exist then an error is thrown.
|
||||
/// - permissions: The permissions to apply to the newly created file. Default permissions
|
||||
/// (read-write owner permissions and read permissions for everyone else) are applied
|
||||
/// if `nil`. Ignored if `createIfNonExistent` is `false`.
|
||||
/// - Returns: Options for modifying an existing file for writing.
|
||||
public static func modifyFile(
|
||||
createIfNecessary: Bool,
|
||||
permissions: FilePermissions? = nil
|
||||
) -> Self {
|
||||
Write(
|
||||
existingFile: .open,
|
||||
newFile: createIfNecessary ? NewFile(permissions: permissions) : nil
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension OpenOptions {
|
||||
/// Options for opening an existing file.
|
||||
public enum ExistingFile: Sendable, Hashable {
|
||||
/// Indicates that no file exists. If a file does exist then an error is thrown when
|
||||
/// opening the file.
|
||||
case none
|
||||
|
||||
/// Any existing file should be opened without modification.
|
||||
case open
|
||||
|
||||
/// Truncate the existing file.
|
||||
///
|
||||
/// Setting this is equivalent to opening a file with `O_TRUNC`.
|
||||
case truncate
|
||||
}
|
||||
|
||||
/// Options for creating a new file.
|
||||
public struct NewFile: Sendable, Hashable {
|
||||
/// The permissions to apply to the new file. `nil` implies default permissions
|
||||
/// should be applied.
|
||||
public var permissions: FilePermissions?
|
||||
|
||||
/// Whether the file should be created and updated as a single transaction, if
|
||||
/// applicable.
|
||||
///
|
||||
/// When this option is set and applied the newly created file will only materialize
|
||||
/// on the file system when the file is closed. When used in conjunction with
|
||||
/// ``FileSystemProtocol/withFileHandle(forWritingAt:options:execute:)-1p6ka`` and
|
||||
/// ``FileSystemProtocol/withFileHandle(forReadingAndWritingAt:options:execute:)-9nqu3`` the
|
||||
/// file will only materialize when the file is closed and no errors have been thrown.
|
||||
///
|
||||
/// - Important: This flag is only applied if ``OpenOptions/Write/existingFile`` is
|
||||
/// ``OpenOptions/ExistingFile/none``.
|
||||
public var transactionalCreation: Bool
|
||||
|
||||
public init(
|
||||
permissions: FilePermissions? = nil,
|
||||
transactionalCreation: Bool = true
|
||||
) {
|
||||
self.permissions = permissions
|
||||
self.transactionalCreation = transactionalCreation
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension OpenOptions.Write {
|
||||
@_spi(Testing)
|
||||
public var permissionsForRegularFile: FilePermissions? {
|
||||
if let newFile = self.newFile {
|
||||
return newFile.permissions ?? .defaultsForRegularFile
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
var descriptorOptions: FileDescriptor.OpenOptions {
|
||||
var options = FileDescriptor.OpenOptions()
|
||||
|
||||
if !self.followSymbolicLinks {
|
||||
options.insert(.noFollow)
|
||||
}
|
||||
|
||||
if self.closeOnExec {
|
||||
options.insert(.closeOnExec)
|
||||
}
|
||||
|
||||
if self.newFile != nil {
|
||||
options.insert(.create)
|
||||
}
|
||||
|
||||
switch self.existingFile {
|
||||
case .none:
|
||||
options.insert(.exclusiveCreate)
|
||||
case .open:
|
||||
()
|
||||
case .truncate:
|
||||
options.insert(.truncate)
|
||||
}
|
||||
|
||||
return options
|
||||
}
|
||||
}
|
||||
|
||||
extension OpenOptions.Read {
|
||||
var descriptorOptions: FileDescriptor.OpenOptions {
|
||||
var options = FileDescriptor.OpenOptions()
|
||||
|
||||
if !self.followSymbolicLinks {
|
||||
options.insert(.noFollow)
|
||||
}
|
||||
|
||||
if self.closeOnExec {
|
||||
options.insert(.closeOnExec)
|
||||
}
|
||||
|
||||
return options
|
||||
}
|
||||
}
|
||||
|
||||
extension OpenOptions.Directory {
|
||||
var descriptorOptions: FileDescriptor.OpenOptions {
|
||||
var options = FileDescriptor.OpenOptions([.directory])
|
||||
|
||||
if !self.followSymbolicLinks {
|
||||
options.insert(.noFollow)
|
||||
}
|
||||
|
||||
if self.closeOnExec {
|
||||
options.insert(.closeOnExec)
|
||||
}
|
||||
|
||||
return options
|
||||
}
|
||||
}
|
||||
|
||||
extension FileDescriptor.OpenOptions {
|
||||
public init(_ options: OpenOptions.Read) {
|
||||
self = options.descriptorOptions
|
||||
}
|
||||
|
||||
public init(_ options: OpenOptions.Write) {
|
||||
self = options.descriptorOptions
|
||||
}
|
||||
|
||||
public init(_ options: OpenOptions.Directory) {
|
||||
self = options.descriptorOptions
|
||||
}
|
||||
}
|
||||
|
||||
extension FilePermissions {
|
||||
/// Default permissions for regular files; owner read-write, group read, other read.
|
||||
internal static let defaultsForRegularFile: FilePermissions = [
|
||||
.ownerReadWrite,
|
||||
.groupRead,
|
||||
.otherRead,
|
||||
]
|
||||
|
||||
/// Default permissions for directories; owner read-write-execute, group read-execute, other
|
||||
/// read-execute.
|
||||
internal static let defaultsForDirectory: FilePermissions = [
|
||||
.ownerReadWriteExecute,
|
||||
.groupReadExecute,
|
||||
.otherReadExecute,
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>NSPrivacyTracking</key>
|
||||
<false/>
|
||||
<key>NSPrivacyAccessedAPITypes</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>NSPrivacyAccessedAPITypeReasons</key>
|
||||
<array>
|
||||
<string>0A2A.1</string>
|
||||
</array>
|
||||
<key>NSPrivacyAccessedAPIType</key>
|
||||
<string>NSPrivacyAccessedAPICategoryFileTimestamp</string>
|
||||
</dict>
|
||||
</array>
|
||||
<key>NSPrivacyCollectedDataTypes</key>
|
||||
<array/>
|
||||
<key>NSPrivacyTrackingDomains</key>
|
||||
<array/>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,56 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2025 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import NIOCore
|
||||
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
extension String {
|
||||
/// Reads the contents of the file at the path into a String.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The path of the file to read.
|
||||
/// - maximumSizeAllowed: The maximum size of file which can be read, in bytes, as a ``ByteCount``. If the file is larger than this, an error is thrown.
|
||||
/// - fileSystem: The ``FileSystemProtocol`` instance to use to read the file.
|
||||
///
|
||||
/// - Throws: If the file is larger than `maximumSizeAllowed`, an ``FileSystemError/Code-swift.struct/resourceExhausted`` error will be thrown.
|
||||
public init(
|
||||
contentsOf path: FilePath,
|
||||
maximumSizeAllowed: ByteCount,
|
||||
fileSystem: some FileSystemProtocol
|
||||
) async throws {
|
||||
let byteBuffer = try await fileSystem.withFileHandle(forReadingAt: path) { handle in
|
||||
try await handle.readToEnd(maximumSizeAllowed: maximumSizeAllowed)
|
||||
}
|
||||
|
||||
self = Self(buffer: byteBuffer)
|
||||
}
|
||||
|
||||
/// Reads the contents of the file at the path using ``FileSystem``.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The path of the file to read.
|
||||
/// - maximumSizeAllowed: The maximum size of file which can be read, in bytes, as a ``ByteCount``. If the file is larger than this, an error is thrown.
|
||||
///
|
||||
/// - Throws: If the file is larger than `maximumSizeAllowed`, an ``FileSystemError/Code-swift.struct/resourceExhausted`` error will be thrown.
|
||||
public init(
|
||||
contentsOf path: FilePath,
|
||||
maximumSizeAllowed: ByteCount
|
||||
) async throws {
|
||||
self = try await Self(
|
||||
contentsOf: path,
|
||||
maximumSizeAllowed: maximumSizeAllowed,
|
||||
fileSystem: .shared
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2025 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 canImport(Darwin) || os(Linux) || os(Android)
|
||||
import _NIOFileSystem
|
||||
import NIOCore
|
||||
import NIOFoundationCompat
|
||||
import struct Foundation.Data
|
||||
|
||||
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
|
||||
extension Data {
|
||||
/// Reads the contents of the file at the path.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The path of the file to read.
|
||||
/// - maximumSizeAllowed: The maximum size of file which can be read, in bytes, as a ``ByteCount``.
|
||||
/// - fileSystem: The ``FileSystemProtocol`` instance to use to read the file.
|
||||
public init(
|
||||
contentsOf path: FilePath,
|
||||
maximumSizeAllowed: ByteCount,
|
||||
fileSystem: some FileSystemProtocol
|
||||
) async throws {
|
||||
let byteBuffer = try await fileSystem.withFileHandle(forReadingAt: path) { handle in
|
||||
try await handle.readToEnd(maximumSizeAllowed: maximumSizeAllowed)
|
||||
}
|
||||
|
||||
self = Data(buffer: byteBuffer)
|
||||
}
|
||||
|
||||
/// Reads the contents of the file at the path using ``FileSystem``.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - path: The path of the file to read.
|
||||
/// - maximumSizeAllowed: The maximum size of file which can be read, as a ``ByteCount``.
|
||||
public init(
|
||||
contentsOf path: FilePath,
|
||||
maximumSizeAllowed: ByteCount
|
||||
) async throws {
|
||||
self = try await Self(
|
||||
contentsOf: path,
|
||||
maximumSizeAllowed: maximumSizeAllowed,
|
||||
fileSystem: .shared
|
||||
)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,31 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import _NIOFileSystem
|
||||
|
||||
import struct Foundation.Date
|
||||
|
||||
extension Date {
|
||||
public init(timespec: FileInfo.Timespec) {
|
||||
let timeInterval = Double(timespec.seconds) + Double(timespec.nanoseconds) / 1_000_000_000
|
||||
self = Date(timeIntervalSince1970: timeInterval)
|
||||
}
|
||||
}
|
||||
|
||||
extension FileInfo.Timespec {
|
||||
/// The UTC time of the timestamp.
|
||||
public var date: Date {
|
||||
Date(timespec: self)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user