Exit if configuration is not found

This commit is contained in:
Christoph Hagen 2023-05-07 21:07:30 +02:00
parent 76a68f9d03
commit 7152346a86

View File

@ -31,12 +31,11 @@ extension Config {
init(loadFrom directory: URL) {
let configFileUrl = Config.file(in: directory)
if FileManager.default.fileExists(atPath: configFileUrl.path) {
self.init(loadAt: configFileUrl)
} else {
self.init(standardIn: directory)
write(to: configFileUrl)
guard FileManager.default.fileExists(atPath: configFileUrl.path) else {
print("No configuration found at \(configFileUrl.path)")
exit(-1)
}
self.init(loadAt: configFileUrl)
}
private init(loadAt url: URL) {
@ -45,23 +44,7 @@ extension Config {
self = try JSONDecoder().decode(Config.self, from: configData)
} catch {
print("Failed to load configuration from \(url.path): \(error)")
print("Using default configuration")
self.init(standardIn: url.deletingLastPathComponent())
}
}
private init(standardIn directory: URL) {
let defaultLogPath = directory.appendingPathComponent("logs").path
self.init(port: 8000, maxBodySize: "2mb", logPath: defaultLogPath, serveFiles: true, writers: [])
}
private func write(to url: URL) {
do {
let configData = try JSONEncoder().encode(self)
try configData.write(to: url)
print("Configuration written at \(url.path)")
} catch {
print("Failed to write default configuration to \(url.path)")
exit(-1)
}
}
}