Files
swift-hpa/Sources/ConfigurationClient/File.swift
Michael Housh faa28749bc
All checks were successful
CI / Run Tests (push) Successful in 2m43s
feat: Merges dev
2024-12-17 15:55:36 -05:00

66 lines
1.7 KiB
Swift

import FileClient
import Foundation
/// Represents a file location and type on disk for a configuration file.
///
/// Currently the supported formats are `json` or `toml`. Toml is the default /
/// preferred format because it allows comments in the file and is easy to understand.
///
public enum File: Equatable, Sendable {
case json(URL)
case toml(URL)
/// Attempts to create a file with the given url.
///
/// ## NOTE: There are no checks on if a file / path actually exists or not.
///
/// If the file does not have a suffix of `json` or `toml` then
/// we will return `nil`.
public init?(_ url: URL) {
if url.cleanFilePath.hasSuffix("json") {
self = .json(url)
} else if url.cleanFilePath.hasSuffix("toml") {
self = .toml(url)
} else {
return nil
}
}
/// Attempts to create a file with the given path.
///
/// ## NOTE: There are no checks on if a file / path actually exists or not.
///
/// If the file does not have a suffix of `json` or `toml` then
/// we will return `nil`.
public init?(_ path: String) {
self.init(URL(filePath: path))
}
/// Get the url of the file.
public var url: URL {
switch self {
case let .json(url): return url
case let .toml(url): return url
}
}
/// Get the path string of the file.
public var path: String {
url.cleanFilePath
}
/// Represents the default file path for a user's configuration.
///
/// Which is `~/.config/hpa/config.toml`
public static var `default`: Self {
let fileUrl = FileManager.default
.homeDirectoryForCurrentUser
.appending(path: ".config")
.appending(path: HPAKey.configDirName)
.appending(path: HPAKey.defaultFileName)
return .toml(fileUrl)
}
}