import Foundation import HelderCore import HelderServices /// An in-memory project: a tree for the Explorer and file texts for the editor. Records every disk change. final class FakeFiles: FileServicing, @unchecked Sendable { private struct State { var tree: FileNode var contents: [String: String] var images: [String: Data] = [:] var binary: Set = [] var treeLoads = 0 var childReads: [String] = [] var writes: [(path: String, text: String)] = [] var created: [String] = [] var createdDirectories: [String] = [] var renamed: [(String, String)] = [] var deleted: [String] = [] var failWrites = false } let root: URL private let state: Locked private let gates = Locked([String: [ReadGate]]()) init(tree: FileNode = FileNode(name: "project", kind: .directory, path: "", children: []), contents: [String: String] = [:], root: URL = URL(fileURLWithPath: "/fake")) { self.root = root state = Locked(State(tree: tree, contents: contents)) } var treeLoads: Int { state.current.treeLoads } var childReads: [String] { state.current.childReads } var writes: [(path: String, text: String)] { state.current.writes } var created: [String] { state.current.created } var createdDirectories: [String] { state.current.createdDirectories } var renamed: [(String, String)] { state.current.renamed } var deleted: [String] { state.current.deleted } /// Makes every write, create, rename and delete throw. var failWrites: Bool { get { state.current.failWrites } set { state.mutate { $0.failWrites = newValue } } } func setTree(_ tree: FileNode) { state.mutate { $0.tree = tree } } func set(_ path: String, _ text: String) { state.mutate { $0.contents[path] = text } } func setImage(_ path: String, _ data: Data) { state.mutate { $0.images[path] = data } } /// Makes a path read as binary, as a file with NUL bytes does. func setBinary(_ path: String) { state.mutate { $0.binary.insert(path) } } func current(_ path: String) -> String? { state.current.contents[path] } /// The file disappears from disk, as when another program deletes it. func remove(_ path: String) { state.mutate { $0.contents[path] = nil } } /// The next read of `path` takes the contents it finds at once but returns only when the gate opens. func holdNextRead(_ path: String) -> ReadGate { let gate = ReadGate() gates.mutate { $0[path, default: []].append(gate) } return gate } func tree() async -> FileNode { state.mutate { state in state.treeLoads += 1 return state.tree } } func children(of directory: String) async -> [FileNode] { state.mutate { state in state.childReads.append(directory) return FileTree.find(directory, in: state.tree)?.children ?? [] } } func read(_ path: String) async throws -> String { let text = state.current.contents[path] let gate: ReadGate? = gates.mutate { gates in guard var waiting = gates[path], !waiting.isEmpty else { return nil } let first = waiting.removeFirst() gates[path] = waiting return first } await gate?.wait() guard let text else { throw CocoaError(.fileNoSuchFile) } return text } func readText(_ path: String) async throws -> FileContents { if state.current.binary.contains(path) { return .binary } return .text(try await read(path)) } func readImage(_ path: String) async -> Data? { state.current.images[path] } func write(_ path: String, contents text: String) async throws { try change { state in state.contents[path] = text state.writes.append((path, text)) } } func createFile(_ path: String) async throws { try change { $0.created.append(path) } } func createDirectory(_ path: String) async throws { try change { $0.createdDirectories.append(path) } } func rename(_ path: String, to name: String) async throws -> String { try change { $0.renamed.append((path, name)) } return PathUtils.join(PathUtils.dirname(path), name) } func delete(_ path: String) async throws { try change { $0.deleted.append(path) } } private func change(_ apply: (inout State) -> Void) throws { try state.mutate { state in if state.failWrites { throw FakeError() } apply(&state) } } } func dir(_ path: String, _ children: [FileNode] = []) -> FileNode { FileNode(name: PathUtils.basename(path), kind: .directory, path: path, children: children) } func file(_ path: String) -> FileNode { FileNode(name: PathUtils.basename(path), kind: .file, path: path) } /// root/ ├ .github/ci.yml ├ src/ (Http/Kernel.php, app.php) ├ empty/ ├ .env └ README.md func sampleTree() -> FileNode { FileNode(name: "project", kind: .directory, path: "", children: [ dir(".github", [file(".github/ci.yml")]), dir("src", [dir("src/Http", [file("src/Http/Kernel.php")]), file("src/app.php")]), dir("empty"), file(".env"), file("README.md"), ]) } /// Holds one read until the test opens it, so a slower read can be made to land last. final class ReadGate: @unchecked Sendable { private let stream: AsyncStream private let continuation: AsyncStream.Continuation private let started = Locked(false) init() { (stream, continuation) = AsyncStream.makeStream() } /// True once a read is waiting on the gate. var isWaiting: Bool { started.current } func open() { continuation.yield() continuation.finish() } func wait() async { started.mutate { $0 = true } for await _ in stream { break } } }