45 lines
1.7 KiB
Swift
45 lines
1.7 KiB
Swift
import Foundation
|
|
import HelderCore
|
|
|
|
public protocol ConfigServicing: Sendable {
|
|
/// Rewrites `config.default.json`, re-reads `config.json`, and returns the effective config.
|
|
@discardableResult
|
|
func resolve() async -> HelderConfig
|
|
/// The last resolved config; the defaults before the first `resolve()`.
|
|
func current() async -> HelderConfig
|
|
}
|
|
|
|
public actor ConfigService: ConfigServicing {
|
|
public nonisolated let root: URL
|
|
private var config = HelderConfig.defaults
|
|
|
|
public init(root: URL) {
|
|
self.root = root
|
|
}
|
|
|
|
public nonisolated var folder: URL { root.appendingPathComponent(HelderConfig.folderName) }
|
|
public nonisolated var overridesURL: URL { folder.appendingPathComponent(HelderConfig.overridesFileName) }
|
|
|
|
/// A read-only or missing project folder yields the defaults instead of an error.
|
|
@discardableResult
|
|
public func resolve() async -> HelderConfig {
|
|
let fm = FileManager.default
|
|
do {
|
|
try fm.createDirectory(at: folder, withIntermediateDirectories: true)
|
|
try HelderConfig.defaultsJSON().write(to: folder.appendingPathComponent(HelderConfig.defaultsFileName))
|
|
let gitignore = folder.appendingPathComponent(".gitignore")
|
|
if (try? String(contentsOf: gitignore, encoding: .utf8)) != HelderConfig.gitignoreBody {
|
|
try Data(HelderConfig.gitignoreBody.utf8).write(to: gitignore)
|
|
}
|
|
} catch {
|
|
Log.warn("config", "cannot write \(folder.path): \(error.localizedDescription)")
|
|
}
|
|
config = HelderConfig.resolved(overrides: try? Data(contentsOf: overridesURL))
|
|
return config
|
|
}
|
|
|
|
public func current() async -> HelderConfig {
|
|
config
|
|
}
|
|
}
|