Skip to content

Commit 931d153

Browse files
committed
Add another command for printing out JSON
1 parent a391190 commit 931d153

File tree

1 file changed

+44
-1
lines changed

1 file changed

+44
-1
lines changed

Sources/CLI/CLI.swift

+44-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ struct Tool: ParsableCommand {
77
static var configuration = CommandConfiguration(
88
commandName: "dotenvy-tool",
99
abstract: "Tool for working with dotenv files",
10-
subcommands: [Check.self]
10+
subcommands: [Check.self, JSON.self]
1111
)
1212
}
1313

@@ -43,6 +43,49 @@ struct Check: ParsableCommand {
4343
}
4444
}
4545

46+
struct JSON: ParsableCommand {
47+
static var configuration
48+
= CommandConfiguration(
49+
abstract: "Convert input to JSON.",
50+
discussion: """
51+
The input is converted to a JSON object.
52+
53+
In case of a syntax error, the error is printed to standard error and the
54+
command exits with failure code \(ExitCode.failure.rawValue).
55+
56+
If there are no problems reading the input, the JSON value is printed to
57+
standard output and the command exits with \(ExitCode.success.rawValue).
58+
"""
59+
)
60+
61+
@Argument(help: "Input file. Standard input is used if omitted")
62+
var file: FileURL?
63+
64+
@Flag(help: "Pretty print JSON")
65+
var pretty: Bool = false
66+
67+
func validate() throws {
68+
_ = try self.file?.url.checkResourceIsReachable()
69+
}
70+
71+
func run() throws {
72+
let string = try readInput(self.file)
73+
do {
74+
let values = try DotEnvironment.parse(string: string)
75+
let json = try JSONSerialization.data(
76+
withJSONObject: values,
77+
options: self.pretty ? [.prettyPrinted, .sortedKeys] : []
78+
)
79+
FileHandle.standardOutput.write(json)
80+
FileHandle.standardOutput.write(Data("\n".utf8))
81+
} catch let error as ParseErrorWithLocation {
82+
FileHandle.standardError.write(Data(error.formatError(source: string).utf8))
83+
FileHandle.standardError.write(Data("\n".utf8))
84+
throw ExitCode.failure
85+
}
86+
}
87+
}
88+
4689
struct FileURL: ExpressibleByArgument {
4790
var url: URL
4891

0 commit comments

Comments
 (0)