@@ -7,7 +7,7 @@ struct Tool: ParsableCommand {
7
7
static var configuration = CommandConfiguration (
8
8
commandName: " dotenvy-tool " ,
9
9
abstract: " Tool for working with dotenv files " ,
10
- subcommands: [ Check . self]
10
+ subcommands: [ Check . self, JSON . self ]
11
11
)
12
12
}
13
13
@@ -43,6 +43,49 @@ struct Check: ParsableCommand {
43
43
}
44
44
}
45
45
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
+
46
89
struct FileURL : ExpressibleByArgument {
47
90
var url : URL
48
91
0 commit comments