feat: Adds generate-config as json file.

This commit is contained in:
2024-11-29 22:25:50 -05:00
parent 505f7d8013
commit ed3f752694
6 changed files with 97 additions and 36 deletions

View File

@@ -16,7 +16,7 @@ public struct CliClient: Sendable {
public var encoder: @Sendable () -> JSONEncoder = { .init() }
public var loadConfiguration: @Sendable () throws -> Configuration
public var runCommand: @Sendable ([String], Bool, ShellCommand.Shell) async throws -> Void
public var createConfiguration: @Sendable (String) throws -> Void
public var createConfiguration: @Sendable (_ path: String, _ json: Bool) throws -> Void
public func runCommand(
quiet: Bool,
@@ -50,16 +50,14 @@ extension CliClient: DependencyKey {
} encoder: {
encoder
} loadConfiguration: {
let urls = try findConfigurationFiles(env: env)
let url = try findConfigurationFiles(env: env)
var env = env
logger.trace("Loading configuration from: \(urls)")
for url in urls {
try fileClient.loadFile(url, &env, decoder)
}
logger.trace("Loading configuration from: \(url)")
try fileClient.loadFile(url, &env, decoder)
return try .fromEnv(env, encoder: encoder, decoder: decoder)
} runCommand: { args, quiet, shell in
@Dependency(\.asyncShellClient) var shellClient
if !quiet {
@@ -76,8 +74,27 @@ extension CliClient: DependencyKey {
in: nil,
args
))
} createConfiguration: { path in
try fileClient.write(path, Data(Configuration.fileTemplate.utf8))
} createConfiguration: { path, json in
// Early out if a file exists at the path already.
guard !fileClient.fileExists(path) else {
throw CliClientError.fileExistsAtPath(path)
}
var path = path
let data: Data
if !json {
// Write the default env template.
data = Data(Configuration.fileTemplate.utf8)
} else {
if !path.contains(".json") {
path += ".json"
}
data = try jsonEncoder.encode(Configuration.mock)
}
try fileClient.write(path, data)
}
}
@@ -87,3 +104,13 @@ extension CliClient: DependencyKey {
public static let testValue: CliClient = Self()
}
enum CliClientError: Error {
case fileExistsAtPath(String)
}
private let jsonEncoder: JSONEncoder = {
var encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .withoutEscapingSlashes]
return encoder
}()