43 lines
1.4 KiB
Swift
43 lines
1.4 KiB
Swift
import Foundation
|
|
import TOML
|
|
|
|
extension PHConfig {
|
|
/// Load the configuration from the resolved config directory (see `PHPaths`).
|
|
/// If the file doesn't exist or fails to parse, the execution is interrupted.
|
|
static func load() throws -> PHConfig {
|
|
let url = PHPaths.configFile
|
|
|
|
if FileManager.default.fileExists(atPath: url.relativePath) {
|
|
return try load(from: url)
|
|
} else {
|
|
let config = url.lastPathComponent
|
|
throw PHBar.Error(
|
|
"""
|
|
Configuration file not found.
|
|
Make sure to have a file named `\(config)` inside the
|
|
directory: `\(PHPaths.configDirectory.relativePath)`
|
|
|
|
Tip: If you've never used phbar before, run the `phbar install` command
|
|
to automatically generate the required configuration files.
|
|
"""
|
|
)
|
|
}
|
|
}
|
|
|
|
/// Load the configuration from the file at URL.
|
|
/// If the file doesn't exist or fails to parse, the execution is interrupted.
|
|
static private func load(from url: URL) throws -> PHConfig {
|
|
do {
|
|
let data = try Data(contentsOf: url)
|
|
guard let contents = String(data: data, encoding: .utf8) else {
|
|
throw PHBar.Error("content is not UTF8 encoded.")
|
|
}
|
|
let decoder = TOMLDecoder()
|
|
let configFile = contents.expanded(from: ProcessInfo.processInfo.environment)
|
|
return try decoder.decode(PHConfig.self, from: configFile)
|
|
} catch {
|
|
throw PHBar.Error("Configuration file not readable", underlyingError: error)
|
|
}
|
|
}
|
|
}
|