adds schema view and schema generating command
This commit is contained in:
@@ -0,0 +1,145 @@
|
||||
import Foundation
|
||||
import HelderCore
|
||||
|
||||
/// Finds the php binary: Laravel Herd's first, then the search path.
|
||||
public struct PHPLocator: Sendable {
|
||||
public var herdPath: String
|
||||
public var locator: ExecutableLocator
|
||||
|
||||
public init(herdPath: String = PHPLocator.defaultHerdPath, locator: ExecutableLocator = .standard) {
|
||||
self.herdPath = herdPath
|
||||
self.locator = locator
|
||||
}
|
||||
|
||||
public static var defaultHerdPath: String {
|
||||
FileManager.default.homeDirectoryForCurrentUser
|
||||
.appendingPathComponent("Library/Application Support/Herd/bin/php").path
|
||||
}
|
||||
|
||||
public func locate() -> URL? {
|
||||
if FileManager.default.isExecutableFile(atPath: herdPath) { return URL(fileURLWithPath: herdPath) }
|
||||
return locator.locate("php")
|
||||
}
|
||||
}
|
||||
|
||||
public struct SchemaService: SchemaServicing {
|
||||
public let root: URL
|
||||
private let runner: ProcessRunning
|
||||
private let php: PHPLocator
|
||||
private let timeout: TimeInterval
|
||||
|
||||
public static let notFoundMessage = "php not found. Install Laravel Herd or put php on PATH."
|
||||
public static let arguments = ["artisan", "helder:schema", "--no-ansi", "--no-interaction"]
|
||||
|
||||
public init(root: URL, runner: ProcessRunning = ProcessRunner(), php: PHPLocator = PHPLocator(), timeout: TimeInterval = 120) {
|
||||
self.root = root
|
||||
self.runner = runner
|
||||
self.php = php
|
||||
self.timeout = timeout
|
||||
}
|
||||
|
||||
public func isLaravelApp() async -> Bool {
|
||||
isFile(SchemaPaths.artisanFile)
|
||||
}
|
||||
|
||||
public func hasCommand() async -> Bool {
|
||||
isFile(SchemaPaths.commandFile)
|
||||
}
|
||||
|
||||
public func readDump() async throws -> SchemaModel? {
|
||||
let url = root.appendingPathComponent(SchemaPaths.dumpFile)
|
||||
guard FileManager.default.fileExists(atPath: url.path) else { return nil }
|
||||
let data: Data
|
||||
do {
|
||||
data = try Data(contentsOf: url)
|
||||
} catch {
|
||||
throw SchemaDumpError.corrupt(reason: error.localizedDescription)
|
||||
}
|
||||
return SchemaModel(dump: try SchemaDump.decode(data))
|
||||
}
|
||||
|
||||
public func dumpModificationDate() async -> Date? {
|
||||
let path = root.appendingPathComponent(SchemaPaths.dumpFile).path
|
||||
return (try? FileManager.default.attributesOfItem(atPath: path))?[.modificationDate] as? Date
|
||||
}
|
||||
|
||||
/// The found php's folder goes first on the child's PATH, so `php` called from the app's own scripts is the same one.
|
||||
public func runDump(onLine: @escaping @Sendable (_ line: String, _ isError: Bool) -> Void) async -> Int32 {
|
||||
guard let binary = php.locate() else {
|
||||
onLine(Self.notFoundMessage, true)
|
||||
return -1
|
||||
}
|
||||
var environment = ProcessInfo.processInfo.environment
|
||||
let folder = binary.deletingLastPathComponent().path
|
||||
environment["PATH"] = [folder, environment["PATH"]].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: ":")
|
||||
let runner = self.runner, root = self.root, timeout = self.timeout
|
||||
|
||||
let outcome = await withTaskGroup(of: Outcome?.self) { group -> Outcome? in
|
||||
group.addTask {
|
||||
do {
|
||||
let result = try await runner.stream(binary.path, arguments: Self.arguments, in: root,
|
||||
environment: environment, onLine: onLine)
|
||||
return .finished(result.exitCode)
|
||||
} catch is CancellationError {
|
||||
return nil
|
||||
} catch let ProcessRunnerError.executableNotFound(name) {
|
||||
return .failed("\(name) not found")
|
||||
} catch let ProcessRunnerError.launchFailed(reason) {
|
||||
return .failed(reason)
|
||||
} catch {
|
||||
return .failed("\(error)")
|
||||
}
|
||||
}
|
||||
group.addTask {
|
||||
try? await Task.sleep(nanoseconds: UInt64(max(0, timeout) * 1_000_000_000))
|
||||
return Task.isCancelled ? nil : .failed("timed out after \(Self.seconds(timeout))s")
|
||||
}
|
||||
let first = await group.next() ?? nil
|
||||
group.cancelAll()
|
||||
return first
|
||||
}
|
||||
switch outcome {
|
||||
case let .finished(code):
|
||||
return code
|
||||
case let .failed(reason):
|
||||
onLine(reason, true)
|
||||
return -1
|
||||
case nil:
|
||||
return -1
|
||||
}
|
||||
}
|
||||
|
||||
private enum Outcome: Sendable {
|
||||
case finished(Int32)
|
||||
case failed(String)
|
||||
}
|
||||
|
||||
private func isFile(_ relative: String) -> Bool {
|
||||
var isDirectory: ObjCBool = false
|
||||
let exists = FileManager.default.fileExists(atPath: root.appendingPathComponent(relative).path, isDirectory: &isDirectory)
|
||||
return exists && !isDirectory.boolValue
|
||||
}
|
||||
|
||||
/// "5" for whole seconds, "0.5" otherwise.
|
||||
private static func seconds(_ value: TimeInterval) -> String {
|
||||
value == value.rounded() ? String(Int(value)) : String(value)
|
||||
}
|
||||
}
|
||||
|
||||
/// Never throws: positions that cannot be read are empty, ones that cannot be written are skipped.
|
||||
public struct UserDefaultsSchemaLayoutStore: SchemaLayoutPersisting, @unchecked Sendable {
|
||||
private let defaults: UserDefaults
|
||||
|
||||
public init(defaults: UserDefaults = .standard) {
|
||||
self.defaults = defaults
|
||||
}
|
||||
|
||||
public func loadPositions(root: String) -> [String: SchemaPoint] {
|
||||
defaults.data(forKey: SchemaLayout.defaultsKey(root: root))
|
||||
.flatMap { try? JSONDecoder().decode([String: SchemaPoint].self, from: $0) } ?? [:]
|
||||
}
|
||||
|
||||
public func savePositions(_ positions: [String: SchemaPoint], root: String) {
|
||||
if let data = try? JSONEncoder().encode(positions) { defaults.set(data, forKey: SchemaLayout.defaultsKey(root: root)) }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user