Debian Codegraph @

cmd/jsonnetfmt.cpp

raw
1 /*
2 Copyright 2019 Google Inc. All rights reserved.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 #include <cassert>
18 #include <cstdlib>
19 #include <cstring>
20
21 #include <exception>
22 #include <fstream>
23 #include <iostream>
24 #include <list>
25 #include <map>
26 #include <string>
27 #include <vector>
28
29 #include "utils.h"
30
31 extern "C" {
32 #include <libjsonnet.h>
33 #include <libjsonnet_fmt.h>
34 }
35
36 void version(std::ostream &o)
37 {
38 o << "Jsonnet reformatter " << jsonnet_version() << std::endl;
39 }
40
41 void usage(std::ostream &o)
42 {
43 version(o);
44 o << "\n";
45 o << "jsonnetfmt {<option>} { <filename> }\n";
46 o << "\n";
47 o << "Available options:\n";
48 o << " -h / --help This message\n";
49 o << " -e / --exec Treat filename as code\n";
50 o << " -o / --output-file <file> Write to the output file rather than stdout\n";
51 o << " -i / --in-place Update the Jsonnet file(s) in place.\n";
52 o << " --test Exit with failure if reformatting changed the file(s).\n";
53 o << " -n / --indent <n> Number of spaces to indent by (default 2, 0 means no change)\n";
54 o << " --max-blank-lines <n> Max vertical spacing, 0 means no change (default 2)\n";
55 o << " --string-style <d|s|l> Enforce double, single (default) quotes or 'leave'\n";
56 o << " --comment-style <h|s|l> # (h), // (s)(default), or 'leave'; never changes she-bang\n";
57 o << " --[no-]pretty-field-names Use syntax sugar for fields and indexing (on by default)\n";
58 o << " --[no-]pad-arrays [ 1, 2, 3 ] instead of [1, 2, 3]\n";
59 o << " --[no-]pad-objects { x: 1, y: 2 } instead of {x: 1, y: 2} (on by default)\n";
60 o << " --[no-]sort-imports Sorting of imports (on by default)\n";
61 o << " --debug-desugaring Unparse the desugared AST without executing it\n";
62 o << " --version Print version\n";
63 o << "\n";
64 o << "In all cases:\n";
65 o << "<filename> can be - (stdin)\n";
66 o << "Multichar options are expanded e.g. -abc becomes -a -b -c.\n";
67 o << "The -- option suppresses option processing for subsequent arguments.\n";
68 o << "Note that since filenames and jsonnet programs can begin with -, it is advised to\n";
69 o << "use -- if the argument is unknown, e.g. jsonnet -- \"$FILENAME\".";
70 o << std::endl;
71 }
72
73 /** Class for representing configuration read from command line flags. */
74 struct JsonnetConfig {
75 std::vector<std::string> inputFiles;
76 std::string outputFile;
77 bool filenameIsCode;
78
79 bool fmtInPlace;
80 bool fmtTest;
81
82 JsonnetConfig()
83 : filenameIsCode(false),
84 fmtInPlace(false),
85 fmtTest(false)
86 {
87 }
88 };
89
90 enum ArgStatus {
91 ARG_CONTINUE,
92 ARG_SUCCESS,
93 ARG_FAILURE,
94 };
95
96 /** Parse the command line arguments, configuring the Jsonnet VM context and
97 * populating the JsonnetConfig.
98 */
99 static ArgStatus process_args(int argc, const char **argv, JsonnetConfig *config, JsonnetVm *vm)
100 {
101 auto args = simplify_args(argc, argv);
102 std::vector<std::string> remaining_args;
103
104 unsigned i = 0;
105
106 for (; i < args.size(); ++i) {
107 const std::string &arg = args[i];
108 if (arg == "-h" || arg == "--help") {
109 usage(std::cout);
110 return ARG_SUCCESS;
111 } else if (arg == "-v" || arg == "--version") {
112 version(std::cout);
113 return ARG_SUCCESS;
114 } else if (arg == "-e" || arg == "--exec") {
115 config->filenameIsCode = true;
116 } else if (arg == "-o" || arg == "--output-file") {
117 std::string output_file = next_arg(i, args);
118 if (output_file.length() == 0) {
119 std::cerr << "ERROR: -o argument was empty string" << std::endl;
120 return ARG_FAILURE;
121 }
122 config->outputFile = output_file;
123 } else if (arg == "--") {
124 // All subsequent args are not options.
125 while ((++i) < args.size())
126 remaining_args.push_back(args[i]);
127 break;
128 } else if (arg == "-i" || arg == "--in-place") {
129 config->fmtInPlace = true;
130 } else if (arg == "--test") {
131 config->fmtTest = true;
132 } else if (arg == "-n" || arg == "--indent") {
133 long l = strtol_check(next_arg(i, args));
134 if (l < 0) {
135 std::cerr << "ERROR: invalid --indent value: " << l << std::endl;
136 return ARG_FAILURE;
137 }
138 jsonnet_fmt_indent(vm, l);
139 } else if (arg == "--max-blank-lines") {
140 long l = strtol_check(next_arg(i, args));
141 if (l < 0) {
142 std::cerr << "ERROR: invalid --max-blank-lines value: " << l << ""
143 << std::endl;
144 return ARG_FAILURE;
145 }
146 jsonnet_fmt_max_blank_lines(vm, l);
147 } else if (arg == "--comment-style") {
148 const std::string val = next_arg(i, args);
149 if (val == "h") {
150 jsonnet_fmt_comment(vm, 'h');
151 } else if (val == "s") {
152 jsonnet_fmt_comment(vm, 's');
153 } else if (val == "l") {
154 jsonnet_fmt_comment(vm, 'l');
155 } else {
156 std::cerr << "ERROR: invalid --comment-style value: " << val
157 << std::endl;
158 return ARG_FAILURE;
159 }
160 } else if (arg == "--string-style") {
161 const std::string val = next_arg(i, args);
162 if (val == "d") {
163 jsonnet_fmt_string(vm, 'd');
164 } else if (val == "s") {
165 jsonnet_fmt_string(vm, 's');
166 } else if (val == "l") {
167 jsonnet_fmt_string(vm, 'l');
168 } else {
169 std::cerr << "ERROR: invalid --string-style value: " << val
170 << std::endl;
171 return ARG_FAILURE;
172 }
173 } else if (arg == "--pad-arrays") {
174 jsonnet_fmt_pad_arrays(vm, true);
175 } else if (arg == "--no-pad-arrays") {
176 jsonnet_fmt_pad_arrays(vm, false);
177 } else if (arg == "--pad-objects") {
178 jsonnet_fmt_pad_objects(vm, true);
179 } else if (arg == "--no-pad-objects") {
180 jsonnet_fmt_pad_objects(vm, false);
181 } else if (arg == "--pretty-field-names") {
182 jsonnet_fmt_pretty_field_names(vm, true);
183 } else if (arg == "--no-pretty-field-names") {
184 jsonnet_fmt_pretty_field_names(vm, false);
185 } else if (arg == "--sort-imports") {
186 jsonnet_fmt_sort_imports(vm, true);
187 } else if (arg == "--no-sort-imports") {
188 jsonnet_fmt_sort_imports(vm, false);
189 } else if (arg == "--debug-desugaring") {
190 jsonnet_fmt_debug_desugaring(vm, true);
191 } else if (arg.length() > 1 && arg[0] == '-') {
192 std::cerr << "ERROR: unrecognized argument: " << arg << std::endl;
193 return ARG_FAILURE;
194 } else {
195 remaining_args.push_back(args[i]);
196 }
197 }
198
199 const char *want = config->filenameIsCode ? "code" : "filename";
200 if (remaining_args.size() == 0) {
201 std::cerr << "ERROR: must give " << want << "\n" << std::endl;
202 usage(std::cerr);
203 return ARG_FAILURE;
204 }
205
206 if (!config->fmtTest && !config->fmtInPlace) {
207 if (remaining_args.size() > 1) {
208 std::string filename = remaining_args[0];
209 std::cerr << "ERROR: only one " << want << " is allowed\n" << std::endl;
210 return ARG_FAILURE;
211 }
212 }
213 config->inputFiles = remaining_args;
214 return ARG_CONTINUE;
215 }
216
217 int main(int argc, const char **argv)
218 {
219 try {
220 JsonnetVm *vm = jsonnet_make();
221 JsonnetConfig config;
222 ArgStatus arg_status = process_args(argc, argv, &config, vm);
223 if (arg_status != ARG_CONTINUE) {
224 jsonnet_destroy(vm);
225 return arg_status == ARG_SUCCESS ? EXIT_SUCCESS : EXIT_FAILURE;
226 }
227
228 // Evaluate input Jsonnet and handle any errors from Jsonnet VM.
229 int error;
230 char *output;
231 std::string output_file = config.outputFile;
232
233 if (config.fmtInPlace || config.fmtTest) {
234 bool changed_files = false;
235 assert(config.inputFiles.size() >= 1);
236 for (std::string &inputFile : config.inputFiles) {
237 const bool input_stdin = inputFile == "-";
238 if (config.fmtInPlace) {
239 output_file = inputFile;
240
241 if (input_stdin) {
242 std::cerr << "ERROR: cannot use --in-place with stdin" << std::endl;
243 jsonnet_destroy(vm);
244 return EXIT_FAILURE;
245 }
246 if (config.filenameIsCode) {
247 std::cerr << "ERROR: cannot use --in-place with --exec"
248 << std::endl;
249 jsonnet_destroy(vm);
250 return EXIT_FAILURE;
251 }
252 }
253
254 std::string input;
255 if (!read_input(config.filenameIsCode, &inputFile, &input)) {
256 jsonnet_destroy(vm);
257 return EXIT_FAILURE;
258 }
259
260 output = jsonnet_fmt_snippet(vm, inputFile.c_str(), input.c_str(), &error);
261
262 if (error) {
263 std::cerr << output;
264 jsonnet_realloc(vm, output, 0);
265 jsonnet_destroy(vm);
266 return EXIT_FAILURE;
267 }
268
269 // Write output Jsonnet only if there is a difference between input and output
270 bool different = output != input;
271 if (config.fmtInPlace && different) {
272 bool successful = write_output_file(output, output_file);
273 jsonnet_realloc(vm, output, 0);
274 if (!successful) {
275 jsonnet_destroy(vm);
276 return EXIT_FAILURE;
277 }
278 } else {
279 jsonnet_realloc(vm, output, 0);
280 }
281
282 // If we're not processing stdin or some other unnamed thing, then
283 // print the names of any changed or unclean files.
284 if (different) {
285 changed_files = true;
286 if (!input_stdin && !config.filenameIsCode) {
287 std::cout << inputFile << std::endl;
288 }
289 }
290 }
291
292 if (config.fmtTest && changed_files) {
293 jsonnet_destroy(vm);
294 return 2;
295 }
296 } else {
297 assert(config.inputFiles.size() == 1);
298 // Read input file.
299 std::string input;
300 if (!read_input(config.filenameIsCode, &config.inputFiles[0], &input)) {
301 jsonnet_destroy(vm);
302 return EXIT_FAILURE;
303 }
304
305 output = jsonnet_fmt_snippet(
306 vm, config.inputFiles[0].c_str(), input.c_str(), &error);
307
308 if (error) {
309 std::cerr << output;
310 jsonnet_realloc(vm, output, 0);
311 jsonnet_destroy(vm);
312 return EXIT_FAILURE;
313 }
314
315 // Write output Jsonnet.
316 bool successful = write_output_file(output, output_file);
317 jsonnet_realloc(vm, output, 0);
318 if (!successful) {
319 jsonnet_destroy(vm);
320 return EXIT_FAILURE;
321 }
322 }
323
324 jsonnet_destroy(vm);
325 return EXIT_SUCCESS;
326
327 } catch (const std::bad_alloc &) {
328 // Avoid further allocation attempts
329 fputs("Internal out-of-memory error (please report this)\n", stderr);
330 } catch (const std::exception &e) {
331 std::cerr << "Internal error (please report this): " << e.what() << std::endl;
332 } catch (...) {
333 std::cerr << "An unknown exception occurred (please report this)." << std::endl;
334 }
335 return EXIT_FAILURE;
336 }