|
| 1 | +//===----------------------------------------------------------------------===// |
| 2 | +// |
| 3 | +// This source file is part of the Swift open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2023-2024 Apple Inc. and the Swift project authors |
| 6 | +// Licensed under Apache License v2.0 with Runtime Library Exception |
| 7 | +// |
| 8 | +// See https://swift.org/LICENSE.txt for license information |
| 9 | +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors |
| 10 | +// |
| 11 | +//===----------------------------------------------------------------------===// |
| 12 | + |
| 13 | +import Foundation |
| 14 | +@preconcurrency package import SystemPackage |
| 15 | + |
| 16 | +public actor OSFileSystem: AsyncFileSystem { |
| 17 | + public static let defaultChunkSize = 512 * 1024 |
| 18 | + |
| 19 | + let readChunkSize: Int |
| 20 | + private let ioQueue = DispatchQueue(label: "org.swift.sdk-generator-io") |
| 21 | + |
| 22 | + package init(readChunkSize: Int = defaultChunkSize) { |
| 23 | + self.readChunkSize = readChunkSize |
| 24 | + } |
| 25 | + |
| 26 | + package func withOpenReadableFile<T: Sendable>( |
| 27 | + _ path: FilePath, |
| 28 | + _ body: (OpenReadableFile) async throws -> T |
| 29 | + ) async throws -> T { |
| 30 | + let fd = try FileDescriptor.open(path, .readOnly) |
| 31 | + // Can't use ``FileDescriptor//closeAfter` here, as that doesn't support async closures. |
| 32 | + do { |
| 33 | + let result = try await body(.init(chunkSize: readChunkSize, fileHandle: .real(fd, self.ioQueue))) |
| 34 | + try fd.close() |
| 35 | + return result |
| 36 | + } catch { |
| 37 | + try fd.close() |
| 38 | + throw error.attach(path) |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + package func withOpenWritableFile<T: Sendable>( |
| 43 | + _ path: FilePath, |
| 44 | + _ body: (OpenWritableFile) async throws -> T |
| 45 | + ) async throws -> T { |
| 46 | + let fd = try FileDescriptor.open( |
| 47 | + path, |
| 48 | + .writeOnly, |
| 49 | + options: [.create, .truncate], |
| 50 | + permissions: [ |
| 51 | + .groupRead, |
| 52 | + .otherRead, |
| 53 | + .ownerReadWrite |
| 54 | + ] |
| 55 | + ) |
| 56 | + do { |
| 57 | + let result = try await body(.init(storage: .real(fd, self.ioQueue), path: path)) |
| 58 | + try fd.close() |
| 59 | + return result |
| 60 | + } catch { |
| 61 | + try fd.close() |
| 62 | + throw error.attach(path) |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + package func exists(_ path: SystemPackage.FilePath) async -> Bool { |
| 67 | + FileManager.default.fileExists(atPath: path.string) |
| 68 | + } |
| 69 | +} |
0 commit comments