Caps-Server/Sources/App/Config.swift

74 lines
2.1 KiB
Swift
Raw Normal View History

import Foundation
struct Config: Codable {
2023-01-11 18:26:53 +01:00
/// The port where the server runs
let port: Int
/// The maximum size of the request body
let maxBodySize: String
2023-02-06 21:31:12 +01:00
/// The path to the folder where the metric logs are stored
2023-11-22 10:35:47 +01:00
///
/// If no path is provided, then a folder `logs` in the resources directory is created
/// If the path is relative, then it is assumed relative to the resources directory
let logPath: String?
2022-05-27 09:25:41 +02:00
/// Serve files in the Public directory using Vapor
let serveFiles: Bool
2022-05-27 09:25:41 +02:00
/// Authentication tokens for remotes allowed to write
let writers: [String]
2023-11-22 10:35:47 +01:00
2023-12-25 19:05:27 +01:00
/**
The folder where the data should be stored.
If the folder is set to `nil`, then the `Resources` folder is used.
*/
2023-12-25 14:35:01 +01:00
let dataDirectory: String?
func customDataDirectory(or publicDirectory: String) -> URL {
guard let dataDirectory else {
return URL(fileURLWithPath: publicDirectory)
}
return URL(fileURLWithPath: dataDirectory)
}
2023-11-22 10:35:47 +01:00
func logURL(possiblyRelativeTo resourcesDirectory: URL) -> URL {
guard let logPath else {
return resourcesDirectory.appendingPathComponent("logs")
}
guard !logPath.hasPrefix("/") else {
return .init(fileURLWithPath: logPath)
}
2023-11-22 11:49:39 +01:00
return resourcesDirectory.appendingPathComponent(logPath)
}
2023-01-11 18:26:53 +01:00
}
extension Config {
private static func file(in directory: URL) -> URL {
directory.appendingPathComponent("config.json")
}
init(loadFrom directory: URL) {
let configFileUrl = Config.file(in: directory)
2023-05-07 21:07:30 +02:00
guard FileManager.default.fileExists(atPath: configFileUrl.path) else {
print("No configuration found at \(configFileUrl.path)")
exit(-1)
2023-01-11 18:26:53 +01:00
}
2023-05-07 21:07:30 +02:00
self.init(loadAt: configFileUrl)
2023-01-11 18:26:53 +01:00
}
private init(loadAt url: URL) {
do {
let configData = try Data(contentsOf: url)
self = try JSONDecoder().decode(Config.self, from: configData)
} catch {
print("Failed to load configuration from \(url.path): \(error)")
2023-05-07 21:07:30 +02:00
exit(-1)
2023-01-11 18:26:53 +01:00
}
}
}