This commit is contained in:
71
Sources/CliClient/EnvironmentDependency.swift
Normal file
71
Sources/CliClient/EnvironmentDependency.swift
Normal file
@@ -0,0 +1,71 @@
|
||||
import Dependencies
|
||||
import DependenciesMacros
|
||||
import DotEnv
|
||||
import Foundation
|
||||
import Models
|
||||
|
||||
@_spi(Internal)
|
||||
public extension DependencyValues {
|
||||
var environment: EnvironmentDependency {
|
||||
get { self[EnvironmentDependency.self] }
|
||||
set { self[EnvironmentDependency.self] = newValue }
|
||||
}
|
||||
}
|
||||
|
||||
/// Responsible for loading environment variables and files.
|
||||
///
|
||||
///
|
||||
@_spi(Internal)
|
||||
@DependencyClient
|
||||
public struct EnvironmentDependency: Sendable {
|
||||
|
||||
/// Load the variables based on the request.
|
||||
public var load: @Sendable (FileType) async throws -> [String: String] = { _ in [:] }
|
||||
|
||||
public var processInfo: @Sendable () -> [String: String] = { [:] }
|
||||
|
||||
public enum FileType: Equatable {
|
||||
case dotEnv(path: String)
|
||||
case json(path: String)
|
||||
|
||||
init?(path: String) {
|
||||
let strings = path.split(separator: ".")
|
||||
guard let ext = strings.last else {
|
||||
return nil
|
||||
}
|
||||
switch ext {
|
||||
case "env":
|
||||
self = .dotEnv(path: path)
|
||||
case "json":
|
||||
self = .json(path: path)
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@_spi(Internal)
|
||||
extension EnvironmentDependency: DependencyKey {
|
||||
|
||||
public static let testValue: EnvironmentDependency = Self()
|
||||
|
||||
public static let liveValue: EnvironmentDependency = Self(
|
||||
load: { file in
|
||||
switch file {
|
||||
case let .dotEnv(path: path):
|
||||
let file = try DotEnv.read(path: path)
|
||||
return file.lines.reduce(into: [String: String]()) { partialResult, line in
|
||||
partialResult[line.key] = line.value
|
||||
}
|
||||
case let .json(path: path):
|
||||
let url = URL(filePath: path)
|
||||
return try JSONDecoder().decode(
|
||||
[String: String].self,
|
||||
from: Data(contentsOf: url)
|
||||
)
|
||||
}
|
||||
},
|
||||
processInfo: { ProcessInfo.processInfo.environment }
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user