71 lines
1.9 KiB
Swift
71 lines
1.9 KiB
Swift
import Dependencies
|
|
import Foundation
|
|
import ShellClient
|
|
|
|
@_spi(Internal)
|
|
public func findConfigurationFiles(
|
|
env: [String: String] = ProcessInfo.processInfo.environment
|
|
) throws -> URL {
|
|
@Dependency(\.logger) var logger
|
|
@Dependency(\.fileClient) var fileClient
|
|
|
|
logger.debug("Begin find configuration files.")
|
|
logger.trace("Env: \(env)")
|
|
|
|
let homeDir = fileClient.homeDir()
|
|
|
|
// Check for environment variable pointing to a directory that the
|
|
// the configuration lives.
|
|
if let configHome = env["HPA_CONFIG_HOME"] {
|
|
let url = URL(filePath: configHome).appending(path: "config")
|
|
|
|
if fileClient.isReadable(url) {
|
|
logger.debug("Found configuration from hpa config home env var.")
|
|
return url
|
|
}
|
|
}
|
|
|
|
// Check home directory for a `.hparc` file.
|
|
let url = homeDir.appending(path: ".hparc")
|
|
if fileClient.isReadable(url) {
|
|
logger.debug("Found configuration in home directory")
|
|
return url
|
|
}
|
|
|
|
// Check for environment variable pointing to a directory that the
|
|
// the configuration lives.
|
|
if let pwd = env["PWD"] {
|
|
let url = URL(filePath: "\(pwd)").appending(path: ".hparc")
|
|
if fileClient.isReadable(url) {
|
|
logger.debug("Found configuration in current working directory.")
|
|
return url
|
|
}
|
|
}
|
|
|
|
// Check in xdg config home, under an hpa-playbook directory.
|
|
if let xdgConfigHome = env["XDG_CONFIG_HOME"] {
|
|
logger.debug("XDG Config Home: \(xdgConfigHome)")
|
|
|
|
let url = URL(filePath: "\(xdgConfigHome)")
|
|
.appending(path: "hpa-playbook")
|
|
.appending(path: "config")
|
|
|
|
logger.debug("XDG Config url: \(url.absoluteString)")
|
|
|
|
if fileClient.isReadable(url) {
|
|
return url
|
|
}
|
|
}
|
|
|
|
// We could not find configuration in any usual places.
|
|
throw ConfigurationError.configurationNotFound
|
|
}
|
|
|
|
func path(for url: URL) -> String {
|
|
url.absoluteString.replacing("file://", with: "")
|
|
}
|
|
|
|
enum ConfigurationError: Error {
|
|
case configurationNotFound
|
|
}
|