File: jsonnetfmt.cpp

package info (click to toggle)
jsonnet 0.20.0%2Bds-3.1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 16,776 kB
  • sloc: cpp: 23,318; python: 1,788; javascript: 1,003; ansic: 885; sh: 745; makefile: 194; java: 140
file content (328 lines) | stat: -rw-r--r-- 12,255 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
/*
Copyright 2019 Google Inc. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

#include <cassert>
#include <cstdlib>
#include <cstring>

#include <exception>
#include <fstream>
#include <iostream>
#include <list>
#include <map>
#include <string>
#include <vector>

#include "utils.h"

extern "C" {
#include <libjsonnet.h>
#include <libjsonnet_fmt.h>
}

void version(std::ostream &o)
{
    o << "Jsonnet reformatter " << jsonnet_version() << std::endl;
}

void usage(std::ostream &o)
{
    version(o);
    o << "\n";
    o << "jsonnetfmt {<option>} { <filename> }\n";
    o << "\n";
    o << "Available options:\n";
    o << "  -h / --help             This message\n";
    o << "  -e / --exec             Treat filename as code\n";
    o << "  -o / --output-file <file> Write to the output file rather than stdout\n";
    o << "  -i / --in-place         Update the Jsonnet file(s) in place.\n";
    o << "  --test                  Exit with failure if reformatting changed the file(s).\n";
    o << "  -n / --indent <n>       Number of spaces to indent by (default 2, 0 means no change)\n";
    o << "  --max-blank-lines <n>   Max vertical spacing, 0 means no change (default 2)\n";
    o << "  --string-style <d|s|l>  Enforce double, single (default) quotes or 'leave'\n";
    o << "  --comment-style <h|s|l> # (h), // (s)(default), or 'leave'; never changes she-bang\n";
    o << "  --[no-]pretty-field-names Use syntax sugar for fields and indexing (on by default)\n";
    o << "  --[no-]pad-arrays       [ 1, 2, 3 ] instead of [1, 2, 3]\n";
    o << "  --[no-]pad-objects      { x: 1, y: 2 } instead of {x: 1, y: 2} (on by default)\n";
    o << "  --[no-]sort-imports     Sorting of imports (on by default)\n";
    o << "  --debug-desugaring      Unparse the desugared AST without executing it\n";
    o << "  --version               Print version\n";
    o << "\n";
    o << "In all cases:\n";
    o << "<filename> can be - (stdin)\n";
    o << "Multichar options are expanded e.g. -abc becomes -a -b -c.\n";
    o << "The -- option suppresses option processing for subsequent arguments.\n";
    o << "Note that since filenames and jsonnet programs can begin with -, it is advised to\n";
    o << "use -- if the argument is unknown, e.g. jsonnet -- \"$FILENAME\".";
    o << std::endl;
}

/** Class for representing configuration read from command line flags.  */
struct JsonnetConfig {
    std::vector<std::string> inputFiles;
    std::string outputFile;
    bool filenameIsCode;

    bool fmtInPlace;
    bool fmtTest;

    JsonnetConfig()
        : filenameIsCode(false),
          fmtInPlace(false),
          fmtTest(false)
    {
    }
};

enum ArgStatus {
    ARG_CONTINUE,
    ARG_SUCCESS,
    ARG_FAILURE,
};

/** Parse the command line arguments, configuring the Jsonnet VM context and
 * populating the JsonnetConfig.
 */
static ArgStatus process_args(int argc, const char **argv, JsonnetConfig *config, JsonnetVm *vm)
{
    auto args = simplify_args(argc, argv);
    std::vector<std::string> remaining_args;

    unsigned i = 0;

    for (; i < args.size(); ++i) {
        const std::string &arg = args[i];
        if (arg == "-h" || arg == "--help") {
            usage(std::cout);
            return ARG_SUCCESS;
        } else if (arg == "-v" || arg == "--version") {
            version(std::cout);
            return ARG_SUCCESS;
        } else if (arg == "-e" || arg == "--exec") {
            config->filenameIsCode = true;
        } else if (arg == "-o" || arg == "--output-file") {
            std::string output_file = next_arg(i, args);
            if (output_file.length() == 0) {
                std::cerr << "ERROR: -o argument was empty string" << std::endl;
                return ARG_FAILURE;
            }
            config->outputFile = output_file;
        } else if (arg == "--") {
            // All subsequent args are not options.
            while ((++i) < args.size())
                remaining_args.push_back(args[i]);          
            break;  
        } else if (arg == "-i" || arg == "--in-place") {
            config->fmtInPlace = true;
        } else if (arg == "--test") {
            config->fmtTest = true;
        } else if (arg == "-n" || arg == "--indent") {
            long l = strtol_check(next_arg(i, args));
            if (l < 0) {
                std::cerr << "ERROR: invalid --indent value: " << l << std::endl;
                return ARG_FAILURE;
            }
            jsonnet_fmt_indent(vm, l);
        } else if (arg == "--max-blank-lines") {
            long l = strtol_check(next_arg(i, args));
            if (l < 0) {
                std::cerr << "ERROR: invalid --max-blank-lines value: " << l << ""
                            << std::endl;
                return ARG_FAILURE;
            }
            jsonnet_fmt_max_blank_lines(vm, l);
        } else if (arg == "--comment-style") {
            const std::string val = next_arg(i, args);
            if (val == "h") {
                jsonnet_fmt_comment(vm, 'h');
            } else if (val == "s") {
                jsonnet_fmt_comment(vm, 's');
            } else if (val == "l") {
                jsonnet_fmt_comment(vm, 'l');
            } else {
                std::cerr << "ERROR: invalid --comment-style value: " << val
                            << std::endl;
                return ARG_FAILURE;
            }
        } else if (arg == "--string-style") {
            const std::string val = next_arg(i, args);
            if (val == "d") {
                jsonnet_fmt_string(vm, 'd');
            } else if (val == "s") {
                jsonnet_fmt_string(vm, 's');
            } else if (val == "l") {
                jsonnet_fmt_string(vm, 'l');
            } else {
                std::cerr << "ERROR: invalid --string-style value: " << val
                            << std::endl;
                return ARG_FAILURE;
            }
        } else if (arg == "--pad-arrays") {
            jsonnet_fmt_pad_arrays(vm, true);
        } else if (arg == "--no-pad-arrays") {
            jsonnet_fmt_pad_arrays(vm, false);
        } else if (arg == "--pad-objects") {
            jsonnet_fmt_pad_objects(vm, true);
        } else if (arg == "--no-pad-objects") {
            jsonnet_fmt_pad_objects(vm, false);
        } else if (arg == "--pretty-field-names") {
            jsonnet_fmt_pretty_field_names(vm, true);
        } else if (arg == "--no-pretty-field-names") {
            jsonnet_fmt_pretty_field_names(vm, false);
        } else if (arg == "--sort-imports") {
            jsonnet_fmt_sort_imports(vm, true);
        } else if (arg == "--no-sort-imports") {
            jsonnet_fmt_sort_imports(vm, false);
        } else if (arg == "--debug-desugaring") {
            jsonnet_fmt_debug_desugaring(vm, true);
        } else if (arg.length() > 1 && arg[0] == '-') {
            std::cerr << "ERROR: unrecognized argument: " << arg << std::endl;
            return ARG_FAILURE;
        } else {
            remaining_args.push_back(args[i]);
        }
    }

    const char *want = config->filenameIsCode ? "code" : "filename";
    if (remaining_args.size() == 0) {
        std::cerr << "ERROR: must give " << want << "\n" << std::endl;
        usage(std::cerr);
        return ARG_FAILURE;
    }

    if (!config->fmtTest && !config->fmtInPlace) {
        if (remaining_args.size() > 1) {
            std::string filename = remaining_args[0];
            std::cerr << "ERROR: only one " << want << " is allowed\n" << std::endl;
            return ARG_FAILURE;
        }
    }
    config->inputFiles = remaining_args;
    return ARG_CONTINUE;
}

int main(int argc, const char **argv)
{
    try {
        JsonnetVm *vm = jsonnet_make();
        JsonnetConfig config;
        ArgStatus arg_status = process_args(argc, argv, &config, vm);
        if (arg_status != ARG_CONTINUE) {
            jsonnet_destroy(vm);
            return arg_status == ARG_SUCCESS ? EXIT_SUCCESS : EXIT_FAILURE;
        }

        // Evaluate input Jsonnet and handle any errors from Jsonnet VM.
        int error;
        char *output;
        std::string output_file = config.outputFile;

        if (config.fmtInPlace || config.fmtTest) {
            assert(config.inputFiles.size() >= 1);
            for (std::string &inputFile : config.inputFiles) {
                if (config.fmtInPlace) {
                    output_file = inputFile;

                    if (inputFile == "-") {
                        std::cerr << "ERROR: cannot use --in-place with stdin" << std::endl;
                        jsonnet_destroy(vm);
                        return EXIT_FAILURE;
                    }
                    if (config.filenameIsCode) {
                        std::cerr << "ERROR: cannot use --in-place with --exec"
                                    << std::endl;
                        jsonnet_destroy(vm);
                        return EXIT_FAILURE;
                    }
                }

                std::string input;
                if (!read_input(config.filenameIsCode, &inputFile, &input)) {
                    jsonnet_destroy(vm);
                    return EXIT_FAILURE;
                }

                output = jsonnet_fmt_snippet(vm, inputFile.c_str(), input.c_str(), &error);

                if (error) {
                    std::cerr << output;
                    jsonnet_realloc(vm, output, 0);
                    jsonnet_destroy(vm);
                    return EXIT_FAILURE;
                }

                if (config.fmtTest) {
                    // Check the output matches the input.
                    bool ok = output == input;
                    jsonnet_realloc(vm, output, 0);
                    if (!ok) {
                        jsonnet_destroy(vm);
                        return 2;
                    }
                } else {
                    // Write output Jsonnet only if there is a difference between input and output
                    bool different = output != input;
                    if (different) {
                        bool successful = write_output_file(output, output_file);
                        jsonnet_realloc(vm, output, 0);
                        if (!successful) {
                            jsonnet_destroy(vm);
                            return EXIT_FAILURE;
                        }
                    }
                }
            }
        } else {
            assert(config.inputFiles.size() == 1);
            // Read input file.
            std::string input;
            if (!read_input(config.filenameIsCode, &config.inputFiles[0], &input)) {
                jsonnet_destroy(vm);
                return EXIT_FAILURE;
            }

            output = jsonnet_fmt_snippet(
                vm, config.inputFiles[0].c_str(), input.c_str(), &error);

            if (error) {
                std::cerr << output;
                jsonnet_realloc(vm, output, 0);
                jsonnet_destroy(vm);
                return EXIT_FAILURE;
            }

            // Write output Jsonnet.
            bool successful = write_output_file(output, output_file);
            jsonnet_realloc(vm, output, 0);
            if (!successful) {
                jsonnet_destroy(vm);
                return EXIT_FAILURE;
            }
        }

        jsonnet_destroy(vm);
        return EXIT_SUCCESS;

    } catch (const std::bad_alloc &) {
        // Avoid further allocation attempts
        fputs("Internal out-of-memory error (please report this)\n", stderr);
    } catch (const std::exception &e) {
        std::cerr << "Internal error (please report this): " << e.what() << std::endl;
    } catch (...) {
        std::cerr << "An unknown exception occurred (please report this)." << std::endl;
    }
    return EXIT_FAILURE;
}