Skip to content

Commit

Permalink
Add another command for printing out JSON
Browse files Browse the repository at this point in the history
  • Loading branch information
juri committed May 12, 2024
1 parent a391190 commit 931d153
Showing 1 changed file with 44 additions and 1 deletion.
45 changes: 44 additions & 1 deletion Sources/CLI/CLI.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ struct Tool: ParsableCommand {
static var configuration = CommandConfiguration(
commandName: "dotenvy-tool",
abstract: "Tool for working with dotenv files",
subcommands: [Check.self]
subcommands: [Check.self, JSON.self]
)
}

Expand Down Expand Up @@ -43,6 +43,49 @@ struct Check: ParsableCommand {
}
}

struct JSON: ParsableCommand {
static var configuration
= CommandConfiguration(
abstract: "Convert input to JSON.",
discussion: """
The input is converted to a JSON object.
In case of a syntax error, the error is printed to standard error and the
command exits with failure code \(ExitCode.failure.rawValue).
If there are no problems reading the input, the JSON value is printed to
standard output and the command exits with \(ExitCode.success.rawValue).
"""
)

@Argument(help: "Input file. Standard input is used if omitted")
var file: FileURL?

@Flag(help: "Pretty print JSON")
var pretty: Bool = false

func validate() throws {
_ = try self.file?.url.checkResourceIsReachable()
}

func run() throws {
let string = try readInput(self.file)
do {
let values = try DotEnvironment.parse(string: string)
let json = try JSONSerialization.data(
withJSONObject: values,
options: self.pretty ? [.prettyPrinted, .sortedKeys] : []
)
FileHandle.standardOutput.write(json)
FileHandle.standardOutput.write(Data("\n".utf8))
} catch let error as ParseErrorWithLocation {
FileHandle.standardError.write(Data(error.formatError(source: string).utf8))
FileHandle.standardError.write(Data("\n".utf8))
throw ExitCode.failure
}
}
}

struct FileURL: ExpressibleByArgument {
var url: URL

Expand Down

0 comments on commit 931d153

Please sign in to comment.