Files

73 lines
2.7 KiB
Swift

import Foundation
import HelderCore
import HelderServices
/// A scripted `runDump`: the lines it streams (`isError` for stderr), its exit code, and the dump it leaves behind.
struct FakeSchemaRun {
var exitCode: Int32 = 0
var lines: [(text: String, isError: Bool)] = []
/// Becomes the dump `readDump` returns once the run ends; nil keeps the current one.
var writes: SchemaModel?
/// How long the run takes after its lines.
var delay: Duration = .zero
static let success = FakeSchemaRun()
}
/// A project's schema state in memory; `runDump` plays the scripted run and counts the calls.
final class FakeSchema: SchemaServicing, @unchecked Sendable {
private struct State {
var isLaravelApp = true
var hasCommand = false
var dump: SchemaModel?
var dumpDate: Date?
var readError: Error?
var run = FakeSchemaRun.success
var runs = 0
var reads = 0
}
private let state: Locked<State>
init(hasCommand: Bool = false, dump: SchemaModel? = nil) {
state = Locked(State(hasCommand: hasCommand, dump: dump, dumpDate: dump == nil ? nil : Date()))
}
var runs: Int { state.current.runs }
var reads: Int { state.current.reads }
func setLaravelApp(_ value: Bool) { state.mutate { $0.isLaravelApp = value } }
func setHasCommand(_ value: Bool) { state.mutate { $0.hasCommand = value } }
func setDump(_ model: SchemaModel?, date: Date? = Date()) { state.mutate { $0.dump = model; $0.dumpDate = model == nil ? nil : date } }
/// Makes every `readDump` throw this error, or read normally again with nil.
func setReadError(_ error: Error?) { state.mutate { $0.readError = error } }
func setRun(_ run: FakeSchemaRun) { state.mutate { $0.run = run } }
func isLaravelApp() async -> Bool { state.current.isLaravelApp }
func hasCommand() async -> Bool { state.current.hasCommand }
func readDump() async throws -> SchemaModel? {
let (dump, error) = state.mutate { state in
state.reads += 1
return (state.dump, state.readError)
}
if let error { throw error }
return dump
}
func dumpModificationDate() async -> Date? { state.current.dumpDate }
func runDump(onLine: @escaping @Sendable (String, Bool) -> Void) async -> Int32 {
let run = state.mutate { state in
state.runs += 1
return state.run
}
for line in run.lines { onLine(line.text, line.isError) }
if run.delay > .zero { try? await Task.sleep(for: run.delay) }
if let written = run.writes {
state.mutate { $0.dump = written; $0.dumpDate = Date() }
}
return run.exitCode
}
}