Debian Codegraph @

cmd/jsonnet.cpp

raw
1 /*
2 Copyright 2015 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 <sstream>
27 #include <string>
28 #include <vector>
29
30 #include "utils.h"
31
32 extern "C" {
33 #include <libjsonnet.h>
34 }
35
36 #ifdef _WIN32
37 const char PATH_SEP = ';';
38 #else
39 const char PATH_SEP = ':';
40 #endif
41
42 void version(std::ostream &o)
43 {
44 o << "Jsonnet commandline interpreter " << jsonnet_version() << std::endl;
45 }
46
47 void usage(std::ostream &o)
48 {
49 version(o);
50 o << "\n";
51 o << "jsonnet {<option>} <filename>\n";
52 o << "\n";
53 o << "Available options:\n";
54 o << " -h / --help This message\n";
55 o << " -e / --exec Treat filename as code\n";
56 o << " -J / --jpath <dir> Specify an additional library search dir (right-most wins)\n";
57 o << " -o / --output-file <file> Write to the output file rather than stdout\n";
58 o << " -m / --multi <dir> Write multiple files to the directory, list files on stdout\n";
59 o << " -y / --yaml-stream Write output as a YAML stream of JSON documents\n";
60 o << " -S / --string Expect a string, manifest as plain text\n";
61 o << " --no-trailing-newline Do not add a trailing newline to the output\n";
62 o << " -s / --max-stack <n> Number of allowed stack frames\n";
63 o << " -t / --max-trace <n> Max length of stack trace before cropping\n";
64 o << " --gc-min-objects <n> Do not run garbage collector until this many\n";
65 o << " --gc-growth-trigger <n> Run garbage collector after this amount of object growth\n";
66 o << " --version Print version\n";
67 o << "Available options for specifying values of 'external' variables:\n";
68 o << "Provide the value as a string:\n";
69 o << " -V / --ext-str <var>[=<val>] If <val> is omitted, get from environment var <var>\n";
70 o << " --ext-str-file <var>=<file> Read the string from the file\n";
71 o << "Provide a value as Jsonnet code:\n";
72 o << " --ext-code <var>[=<code>] If <code> is omitted, get from environment var <var>\n";
73 o << " --ext-code-file <var>=<file> Read the code from the file\n";
74 o << "Available options for specifying values of 'top-level arguments':\n";
75 o << "Provide the value as a string:\n";
76 o << " -A / --tla-str <var>[=<val>] If <val> is omitted, get from environment var <var>\n";
77 o << " --tla-str-file <var>=<file> Read the string from the file\n";
78 o << "Provide a value as Jsonnet code:\n";
79 o << " --tla-code <var>[=<code>] If <code> is omitted, get from environment var <var>\n";
80 o << " --tla-code-file <var>=<file> Read the code from the file\n";
81 o << "Environment variables:\n";
82 o << "JSONNET_PATH is a colon (semicolon on Windows) separated list of directories added\n";
83 o << "in reverse order before the paths specified by --jpath (i.e. left-most wins)\n";
84 o << "E.g. JSONNET_PATH=a:b jsonnet -J c -J d is equivalent to:\n";
85 o << "JSONNET_PATH=d:c:a:b jsonnet\n";
86 o << "jsonnet -J b -J a -J c -J d\n";
87 o << "\n";
88 o << "In all cases:\n";
89 o << "<filename> can be - (stdin)\n";
90 o << "Multichar options are expanded e.g. -abc becomes -a -b -c.\n";
91 o << "The -- option suppresses option processing for subsequent arguments.\n";
92 o << "Note that since filenames and jsonnet programs can begin with -, it is advised to\n";
93 o << "use -- if the argument is unknown, e.g. jsonnet -- \"$FILENAME\".";
94 o << std::endl;
95 }
96
97 /** Class for representing configuration read from command line flags. */
98 struct JsonnetConfig {
99 std::vector<std::string> inputFiles;
100 std::string outputFile;
101 bool filenameIsCode;
102
103 // EVAL flags
104 bool evalMulti;
105 bool evalStream;
106 std::string evalMultiOutputDir;
107
108 JsonnetConfig()
109 : filenameIsCode(false),
110 evalMulti(false),
111 evalStream(false)
112 {
113 }
114 };
115
116 bool get_var_val(const std::string &var_val, std::string &var, std::string &val)
117 {
118 size_t eq_pos = var_val.find_first_of('=', 0);
119 if (eq_pos == std::string::npos) {
120 var = var_val;
121 const char *val_cstr = ::getenv(var.c_str());
122 if (val_cstr == nullptr) {
123 std::cerr << "ERROR: environment variable " << var << " was undefined." << std::endl;
124 return false;
125 }
126 val = val_cstr;
127 } else {
128 var = var_val.substr(0, eq_pos);
129 val = var_val.substr(eq_pos + 1, std::string::npos);
130 }
131 return true;
132 }
133
134 bool get_var_file(const std::string &var_file, const std::string &imp, std::string &var, std::string &val)
135 {
136 size_t eq_pos = var_file.find_first_of('=', 0);
137 if (eq_pos == std::string::npos) {
138 std::cerr << "ERROR: argument not in form <var>=<file> \"" << var_file << "\"."
139 << std::endl;
140 return false;
141 }
142 var = var_file.substr(0, eq_pos);
143 const std::string path = var_file.substr(eq_pos + 1, std::string::npos);
144
145 size_t b, e;
146 val.erase().append(imp).append(" @'");
147 // duplicate all the single quotes in @path to make a quoted string
148 for (b = 0; (e = path.find("'", b)) != std::string::npos; b = e + 1) {
149 val.append(path.substr(b, e - b + 1)).push_back('\'');
150 }
151 val.append(path.substr(b)).push_back('\'');
152
153 return true;
154 }
155
156 enum ArgStatus {
157 ARG_CONTINUE,
158 ARG_SUCCESS,
159 ARG_FAILURE,
160 };
161
162 /** Parse the command line arguments, configuring the Jsonnet VM context and
163 * populating the JsonnetConfig.
164 */
165 static ArgStatus process_args(int argc, const char **argv, JsonnetConfig *config, JsonnetVm *vm)
166 {
167 auto args = simplify_args(argc, argv);
168 std::vector<std::string> remaining_args;
169
170 unsigned i = 0;
171 bool trailing_newline = true;
172
173 for (; i < args.size(); ++i) {
174 const std::string &arg = args[i];
175 if (arg == "-h" || arg == "--help") {
176 usage(std::cout);
177 return ARG_SUCCESS;
178 } else if (arg == "-v" || arg == "--version") {
179 version(std::cout);
180 return ARG_SUCCESS;
181 } else if (arg == "-e" || arg == "--exec") {
182 config->filenameIsCode = true;
183 } else if (arg == "-o" || arg == "--output-file") {
184 std::string output_file = next_arg(i, args);
185 if (output_file.length() == 0) {
186 std::cerr << "ERROR: -o argument was empty string" << std::endl;
187 return ARG_FAILURE;
188 }
189 config->outputFile = output_file;
190 } else if (arg == "--") {
191 // All subsequent args are not options.
192 while ((++i) < args.size())
193 remaining_args.push_back(args[i]);
194 break;
195 } else if (arg == "-s" || arg == "--max-stack") {
196 long l = strtol_check(next_arg(i, args));
197 if (l < 1) {
198 std::cerr << "ERROR: invalid --max-stack value: " << l << std::endl;
199 return ARG_FAILURE;
200 }
201 jsonnet_max_stack(vm, l);
202 } else if (arg == "-J" || arg == "--jpath") {
203 std::string dir = next_arg(i, args);
204 if (dir.length() == 0) {
205 std::cerr << "ERROR: -J argument was empty string" << std::endl;
206 return ARG_FAILURE;
207 }
208 if (dir[dir.length() - 1] != '/') {
209 dir += '/';
210 }
211 jsonnet_jpath_add(vm, dir.c_str());
212 } else if (arg == "-V" || arg == "--ext-str") {
213 std::string var, val;
214 if (!get_var_val(next_arg(i, args), var, val))
215 return ARG_FAILURE;
216 jsonnet_ext_var(vm, var.c_str(), val.c_str());
217 } else if (arg == "-E" || arg == "--var" || arg == "--env") {
218 // TODO(dcunnin): Delete this in a future release.
219 std::cerr << "WARNING: jsonnet eval -E, --var and --env are deprecated,"
220 << " please use -V or --ext-str." << std::endl;
221 std::string var, val;
222 if (!get_var_val(next_arg(i, args), var, val))
223 return ARG_FAILURE;
224 jsonnet_ext_var(vm, var.c_str(), val.c_str());
225 } else if (arg == "--ext-str-file") {
226 std::string var, val;
227 if (!get_var_file(next_arg(i, args), "importstr", var, val))
228 return ARG_FAILURE;
229 jsonnet_ext_code(vm, var.c_str(), val.c_str());
230 } else if (arg == "-F" || arg == "--file") {
231 // TODO(dcunnin): Delete this in a future release.
232 std::cerr << "WARNING: jsonnet eval -F and --file are deprecated,"
233 << " please use --ext-str-file." << std::endl;
234 std::string var, val;
235 if (!get_var_file(next_arg(i, args), "importstr", var, val))
236 return ARG_FAILURE;
237 jsonnet_ext_code(vm, var.c_str(), val.c_str());
238 } else if (arg == "--ext-code") {
239 std::string var, val;
240 if (!get_var_val(next_arg(i, args), var, val))
241 return ARG_FAILURE;
242 jsonnet_ext_code(vm, var.c_str(), val.c_str());
243 } else if (arg == "--code-var" || arg == "--code-env") {
244 // TODO(dcunnin): Delete this in a future release.
245 std::cerr << "WARNING: jsonnet eval --code-var and --code-env are deprecated,"
246 << " please use --ext-code." << std::endl;
247 std::string var, val;
248 if (!get_var_val(next_arg(i, args), var, val))
249 return ARG_FAILURE;
250 jsonnet_ext_code(vm, var.c_str(), val.c_str());
251 } else if (arg == "--ext-code-file") {
252 std::string var, val;
253 if (!get_var_file(next_arg(i, args), "import", var, val))
254 return ARG_FAILURE;
255 jsonnet_ext_code(vm, var.c_str(), val.c_str());
256 } else if (arg == "--code-file") {
257 // TODO(dcunnin): Delete this in a future release.
258 std::cerr << "WARNING: jsonnet eval --code-file is deprecated,"
259 << " please use --ext-code-file." << std::endl;
260 std::string var, val;
261 if (!get_var_file(next_arg(i, args), "import", var, val))
262 return ARG_FAILURE;
263 jsonnet_ext_code(vm, var.c_str(), val.c_str());
264 } else if (arg == "-A" || arg == "--tla-str") {
265 std::string var, val;
266 if (!get_var_val(next_arg(i, args), var, val))
267 return ARG_FAILURE;
268 jsonnet_tla_var(vm, var.c_str(), val.c_str());
269 } else if (arg == "--tla-str-file") {
270 std::string var, val;
271 if (!get_var_file(next_arg(i, args), "importstr", var, val))
272 return ARG_FAILURE;
273 jsonnet_tla_code(vm, var.c_str(), val.c_str());
274 } else if (arg == "--tla-code") {
275 std::string var, val;
276 if (!get_var_val(next_arg(i, args), var, val))
277 return ARG_FAILURE;
278 jsonnet_tla_code(vm, var.c_str(), val.c_str());
279 } else if (arg == "--tla-code-file") {
280 std::string var, val;
281 if (!get_var_file(next_arg(i, args), "import", var, val))
282 return ARG_FAILURE;
283 jsonnet_tla_code(vm, var.c_str(), val.c_str());
284
285 } else if (arg == "--gc-min-objects") {
286 long l = strtol_check(next_arg(i, args));
287 if (l < 0) {
288 std::cerr << "ERROR: invalid --gc-min-objects value: " << l << std::endl;
289 return ARG_FAILURE;
290 }
291 jsonnet_gc_min_objects(vm, l);
292 } else if (arg == "-t" || arg == "--max-trace") {
293 long l = strtol_check(next_arg(i, args));
294 if (l < 0) {
295 std::cerr << "ERROR: invalid --max-trace value: " << l << std::endl;
296 return ARG_FAILURE;
297 }
298 jsonnet_max_trace(vm, l);
299 } else if (arg == "--gc-growth-trigger") {
300 std::string num = next_arg(i, args);
301 char *ep;
302 double v = std::strtod(num.c_str(), &ep);
303 if (*ep != '\0' || num.length() == 0) {
304 std::cerr << "ERROR: invalid number \"" << num << "\"" << std::endl;
305 return ARG_FAILURE;
306 }
307 if (v < 0) {
308 std::cerr << "ERROR: invalid --gc-growth-trigger \"" << num << "\""
309 << std::endl;
310 return ARG_FAILURE;
311 }
312 jsonnet_gc_growth_trigger(vm, v);
313 } else if (arg == "-m" || arg == "--multi") {
314 config->evalMulti = true;
315 std::string output_dir = next_arg(i, args);
316 if (output_dir.length() == 0) {
317 std::cerr << "ERROR: -m argument was empty string" << std::endl;
318 return ARG_FAILURE;
319 }
320 if (output_dir[output_dir.length() - 1] != '/') {
321 output_dir += '/';
322 }
323 config->evalMultiOutputDir = output_dir;
324 } else if (arg == "-y" || arg == "--yaml-stream") {
325 config->evalStream = true;
326 } else if (arg == "-S" || arg == "--string") {
327 jsonnet_string_output(vm, 1);
328 } else if (arg == "--no-trailing-newline") {
329 // Keep track so we can check for mutually incompatible args.
330 trailing_newline = false;
331 jsonnet_set_trailing_newline(vm, 0);
332 } else if (arg.length() > 1 && arg[0] == '-') {
333 std::cerr << "ERROR: unrecognized argument: " << arg << std::endl;
334 return ARG_FAILURE;
335 } else {
336 remaining_args.push_back(args[i]);
337 }
338 }
339
340 if (config->evalStream && !trailing_newline) {
341 std::cerr << "ERROR: cannot use --no-trailing-newline with --yaml-stream" << std::endl;
342 usage(std::cerr);
343 return ARG_FAILURE;
344 }
345
346 const char *want = config->filenameIsCode ? "code" : "filename";
347 if (remaining_args.size() == 0) {
348 std::cerr << "ERROR: must give " << want << "\n" << std::endl;
349 usage(std::cerr);
350 return ARG_FAILURE;
351 }
352
353 if (remaining_args.size() > 1) {
354 std::string filename = remaining_args[0];
355 std::cerr << "ERROR: only one " << want << " is allowed\n" << std::endl;
356 return ARG_FAILURE;
357 }
358 config->inputFiles = remaining_args;
359 return ARG_CONTINUE;
360 }
361
362 /** Writes output files for multiple file output */
363 static bool write_multi_output_files(JsonnetVm *vm, char *output, const std::string &output_dir,
364 const std::string &output_file)
365 {
366 // If multiple file output is used, then iterate over each string from
367 // the sequence of strings returned by jsonnet_evaluate_snippet_multi,
368 // construct pairs of filename and content, and write each output file.
369 std::map<std::string, std::string> r;
370 for (const char *c = output; *c != '\0';) {
371 const char *filename = c;
372 const char *c2 = c;
373 while (*c2 != '\0')
374 ++c2;
375 ++c2;
376 const char *json = c2;
377 while (*c2 != '\0')
378 ++c2;
379 ++c2;
380 c = c2;
381 r[filename] = json;
382 }
383 jsonnet_realloc(vm, output, 0);
384
385 std::ostream *o;
386 std::ofstream f;
387
388 if (output_file.empty()) {
389 o = &std::cout;
390 } else {
391 f.open(output_file.c_str());
392 if (!f.good()) {
393 std::string msg = "Writing to output file: " + output_file;
394 perror(msg.c_str());
395 return false;
396 }
397 o = &f;
398 }
399
400 for (const auto &pair : r) {
401 const std::string &new_content = pair.second;
402 const std::string &filename = output_dir + pair.first;
403 (*o) << filename << std::endl;
404 {
405 std::ifstream exists(filename.c_str());
406 if (exists.good()) {
407 std::string existing_content;
408 existing_content.assign(std::istreambuf_iterator<char>(exists),
409 std::istreambuf_iterator<char>());
410 if (existing_content == new_content) {
411 // Do not bump the timestamp on the file if its content is
412 // the same. This may trigger other tools (e.g. make) to do
413 // unnecessary work.
414 continue;
415 }
416 }
417 }
418 std::ofstream f;
419 f.open(filename.c_str());
420 if (!f.good()) {
421 std::string msg = "Opening output file: " + filename;
422 perror(msg.c_str());
423 return false;
424 }
425 f << new_content;
426 f.close();
427 if (!f.good()) {
428 std::string msg = "Writing to output file: " + filename;
429 perror(msg.c_str());
430 return false;
431 }
432 }
433
434 if (output_file.empty()) {
435 std::cout.flush();
436 } else {
437 f.close();
438 if (!f.good()) {
439 std::string msg = "Writing to output file: " + output_file;
440 perror(msg.c_str());
441 return false;
442 }
443 }
444 return true;
445 }
446
447 /** Writes output files for YAML stream output */
448 static bool write_output_stream(JsonnetVm *vm, char *output, const std::string &output_file)
449 {
450 std::ostream *o;
451 std::ofstream f;
452
453 if (output_file.empty()) {
454 o = &std::cout;
455 } else {
456 f.open(output_file.c_str());
457 if (!f.good()) {
458 std::string msg = "Writing to output file: " + output_file;
459 perror(msg.c_str());
460 return false;
461 }
462 o = &f;
463 }
464
465 // If YAML stream output is used, then iterate over each string from
466 // the sequence of strings returned by jsonnet_evaluate_snippet_stream,
467 // and add the --- and ... as defined by the YAML spec.
468 std::vector<std::string> r;
469 for (const char *c = output; *c != '\0';) {
470 const char *json = c;
471 while (*c != '\0')
472 ++c;
473 ++c;
474 r.emplace_back(json);
475 }
476 jsonnet_realloc(vm, output, 0);
477 for (const auto &str : r) {
478 (*o) << "---\n";
479 (*o) << str;
480 }
481 if (r.size() > 0)
482 (*o) << "...\n";
483 o->flush();
484
485 if (output_file.empty()) {
486 std::cout.flush();
487 } else {
488 f.close();
489 if (!f.good()) {
490 std::string msg = "Writing to output file: " + output_file;
491 perror(msg.c_str());
492 return false;
493 }
494 }
495
496 return true;
497 }
498
499 int main(int argc, const char **argv)
500 {
501 try {
502 JsonnetVm *vm = jsonnet_make();
503 JsonnetConfig config;
504 if (const char *jsonnet_path_env = getenv("JSONNET_PATH")) {
505 std::list<std::string> jpath;
506 std::istringstream iss(jsonnet_path_env);
507 std::string path;
508 while (std::getline(iss, path, PATH_SEP)) {
509 jpath.push_front(path);
510 }
511 for (const std::string &path : jpath) {
512 jsonnet_jpath_add(vm, path.c_str());
513 }
514 }
515 ArgStatus arg_status = process_args(argc, argv, &config, vm);
516 if (arg_status != ARG_CONTINUE) {
517 jsonnet_destroy(vm);
518 return arg_status == ARG_SUCCESS ? EXIT_SUCCESS : EXIT_FAILURE;
519 }
520
521 // Evaluate input Jsonnet and handle any errors from Jsonnet VM.
522 int error;
523 char *output;
524 assert(config.inputFiles.size() == 1);
525
526 // Read input file.
527 std::string input;
528 if (!read_input(config.filenameIsCode, &config.inputFiles[0], &input)) {
529 jsonnet_destroy(vm);
530 return EXIT_FAILURE;
531 }
532
533 if (config.evalMulti) {
534 output = jsonnet_evaluate_snippet_multi(
535 vm, config.inputFiles[0].c_str(), input.c_str(), &error);
536 } else if (config.evalStream) {
537 output = jsonnet_evaluate_snippet_stream(
538 vm, config.inputFiles[0].c_str(), input.c_str(), &error);
539 } else {
540 output = jsonnet_evaluate_snippet(
541 vm, config.inputFiles[0].c_str(), input.c_str(), &error);
542 }
543
544 if (error) {
545 std::cerr << output;
546 jsonnet_realloc(vm, output, 0);
547 jsonnet_destroy(vm);
548 return EXIT_FAILURE;
549 }
550
551 // Write output JSON.
552 if (config.evalMulti) {
553 if (!write_multi_output_files(
554 vm, output, config.evalMultiOutputDir, config.outputFile)) {
555 jsonnet_destroy(vm);
556 return EXIT_FAILURE;
557 }
558 } else if (config.evalStream) {
559 if (!write_output_stream(vm, output, config.outputFile)) {
560 jsonnet_destroy(vm);
561 return EXIT_FAILURE;
562 }
563 } else {
564 bool successful = write_output_file(output, config.outputFile);
565 jsonnet_realloc(vm, output, 0);
566 if (!successful) {
567 jsonnet_destroy(vm);
568 return EXIT_FAILURE;
569 }
570 }
571
572 jsonnet_destroy(vm);
573 return EXIT_SUCCESS;
574
575 } catch (const std::bad_alloc &) {
576 // Avoid further allocation attempts
577 fputs("Internal out-of-memory error (please report this)\n", stderr);
578 } catch (const std::exception &e) {
579 std::cerr << "Internal error (please report this): " << e.what() << std::endl;
580 } catch (...) {
581 std::cerr << "An unknown exception occurred (please report this)." << std::endl;
582 }
583 return EXIT_FAILURE;
584 }