Debian Codegraph @

script/json-schema-eval

raw
1 #!/usr/bin/perl
2 # vim: set ts=8 sts=2 sw=2 tw=100 et :
3 # PODNAME: json-schema-eval
4 # ABSTRACT: A command-line interface to JSON::Schema::Modern::evaluate()
5 use 5.020; # for fc, unicode_strings features
6 use strictures 2;
7 use stable 0.031 'postderef';
8 use experimental 'signatures';
9 no autovivification warn => qw(fetch store exists delete);
10 use if "$]" >= 5.022, experimental => 're_strict';
11 no if "$]" >= 5.031009, feature => 'indirect';
12 no if "$]" >= 5.033001, feature => 'multidimensional';
13 no if "$]" >= 5.033006, feature => 'bareword_filehandles';
14 use open ':std', ':encoding(UTF-8)'; # force stdin, stdout, stderr into utf8
15
16 use if -d '.git', 'Test::File::ShareDir', -share => { -dist => { 'JSON-Schema-Modern' => 'share' } };
17 use Getopt::Long::Descriptive;
18 use Mojo::File 'path';
19 use Feature::Compat::Try;
20 use List::Util 'max';
21 use builtin::compat 'blessed';
22 use JSON::Schema::Modern;
23
24 local $| = 1; # do not buffer stdout
25
26 my ($opt, $usage) = Getopt::Long::Descriptive::describe_options(
27 "$0 %o",
28 ['help|usage|?|h', 'print usage information and exit', { shortcircuit => 1 } ],
29 [],
30 ['specification-version|version=s', 'which version of the JSON Schema specification to use'],
31 ['output-format=s', 'output format (flag, basic, terse)'],
32 ['short-circuit', 'return early in any execution path as soon as the outcome can be determined'],
33 ['max-traversal-depth=i', 'the maximum number of levels deep a schema traversal may go'],
34 ['validate-formats', 'treat the "format" keyword as an assertion, not merely an annotation'],
35 ['validate-content-schemas', 'treat the "contentMediaType" and "contentSchema" keywords as assertions'],
36 ['collect-annotations', 'collect annotations'],
37 ['strict', 'disallow unknown keywords'],
38 # scalarref-booleans, stringy-numbers make no sense in json-encoded data
39 ['dump-identifiers', 'print a list of all identifiers found in the schema'],
40 ['with-defaults', 'include list of defaults for missing data'],
41 [],
42 ['validate-schema:s@', 'validate the provided schema against its meta-schema and the specification. do not provide --data or --schema; can be used more than once' ],
43 ['add-schema=s@', 'the filename of an extra schema to load, so it can be used by $ref; can be used more than once' ],
44 ['data=s@', 'the filename to use for the instance data (if not provided, STDIN is used); can be used more than once'],
45 ['schema=s', 'the filename to use for the schema (if not provided, STDIN is used)'],
46 );
47
48 print($usage->text), exit if $opt->help;
49
50 die '--validate-schema and --data should not be used together' if defined $opt->data and defined $opt->validate_schema;
51 die '--validate-schema and --schema should not be used together' if defined $opt->schema and defined $opt->validate_schema;
52
53 my $js = JSON::Schema::Modern->new(%$opt);
54
55
56 foreach my $add_schema_file (($opt->add_schema//[])->@*) {
57 try {
58 my $schema = parse_input(path($add_schema_file)->slurp('UTF-8'));
59 die "this looks like an OpenAPI file: try 'openapi-validate' (install OpenAPI::Modern), instead\n"
60 if ref $schema eq 'HASH' and $schema->{openapi};
61 $js->add_schema('file://'.$add_schema_file => $schema);
62 }
63 catch ($e) {
64 say blessed($e) && $e->isa('JSON::Schema::Modern::Result') ? $e->dump: '"'.$e.'"';
65 exit 2;
66 }
67 }
68
69 my $exit_val = 0;
70
71 if (defined $opt->validate_schema) {
72 my $encoded_schema;
73
74 foreach my $schema_filename ($opt->validate_schema->@*) {
75 # boolean flag is passed as ''; some other value = filename
76 if (length $schema_filename) {
77 $encoded_schema = path($schema_filename)->slurp('UTF-8');
78 }
79 else {
80 say 'enter schema, followed by ^D:';
81 local $/;
82 $encoded_schema = <STDIN>;
83 say '';
84 }
85
86 my $schema = parse_input($encoded_schema);
87 die "this looks like an OpenAPI file: try 'openapi-validate' (install OpenAPI::Modern), instead\n"
88 if ref $schema eq 'HASH' and $schema->{openapi};
89
90 my $result = $js->validate_schema($schema);
91 $js->add_schema($schema) if $opt->dump_identifiers;
92
93 $exit_val = max($exit_val, $result->valid ? 0 : $result->exception ? 2 : 1);
94
95 # possible FIXME: can output_format ever be data_only here? it does not jsonify
96 say encode($opt->validate_schema->@* > 1 ? { $schema_filename => $result } : $result);
97 }
98 }
99 else {
100 my @encoded_data;
101 foreach my $data_filename (($opt->data//[''])->@*) {
102 if (length $data_filename) {
103 push @encoded_data, [ $data_filename => path($data_filename)->slurp('UTF-8') ];
104 }
105 else {
106 say 'enter data instance, followed by ^D:';
107 local $/;
108 push @encoded_data, [ '' => <STDIN> ];
109 STDIN->clearerr;
110 }
111 }
112
113 my ($schema_filename, $encoded_schema);
114 if (defined $opt->schema) {
115 $encoded_schema = path($schema_filename = $opt->schema)->slurp('UTF-8');
116 }
117 else {
118 say 'enter schema, followed by ^D:';
119 local $/;
120 $encoded_schema = <STDIN>;
121 say '';
122 }
123
124 # if there is no $id within the document, the filename will be used instead
125 my $schema = parse_input($encoded_schema);
126 die "this looks like an OpenAPI file: try 'openapi-validate' (install OpenAPI::Modern), instead\n"
127 if ref $schema eq 'HASH' and $schema->{openapi};
128 $js->add_schema(my $uri = 'file://'.$schema_filename, $schema) if length $schema_filename;
129
130 foreach my $encoded_data (@encoded_data) { # [ filename, data string ]
131 my $data = parse_input($encoded_data->[1]);
132
133 my $result = $js->evaluate($data, $uri // $schema);
134 $exit_val = max($exit_val, $result->valid ? 0 : $result->exception ? 2 : 1);
135
136 # possible FIXME: can output_format ever be data_only here? it does not jsonify
137 say encode(($opt->data//[])->@* > 1 ? { $encoded_data->[0] => $result } : $result);
138 }
139 }
140
141
142 if ($opt->dump_identifiers) {
143 my %identifiers = map +(
144 $_->[0] => {
145 canonical_uri => $_->[1]{canonical_uri},
146 document_base => $_->[1]{document}->canonical_uri,
147 document_path => $_->[1]{path},
148 }
149 ),
150 grep $_->[0] !~ m{^https?://json-schema.org/},
151 $js->_resource_pairs;
152
153 say encode({identifiers => \%identifiers });
154 }
155
156 exit $exit_val;
157
158 ### END
159
160 sub parse_input ($input) {
161 if ($input =~ /^(\{|\[\|["0-9]|true\b|false\b|null\b)/) {
162 # this looks like json
163 state $json_decoder = JSON::Schema::Modern::_JSON_BACKEND()->new->allow_nonref(1)->utf8(0);
164 return $json_decoder->decode($input);
165 }
166 else {
167 # well I suppose it must be yaml
168 require YAML::PP;
169 state $yaml_decoder = YAML::PP->new(boolean => 'JSON::PP');
170 return $yaml_decoder->load_string($input);
171 }
172 }
173
174 sub encode ($input) {
175 my $encoder = JSON::Schema::Modern::_JSON_BACKEND()->new
176 ->convert_blessed(1)
177 ->utf8(0)
178 ->canonical(1)
179 ->pretty(1)
180 ->space_before(0);
181 $encoder->indent_length(2) if $encoder->can('indent_length');
182 $encoder->encode($input);
183 }
184
185 __END__
186
187 =pod
188
189 =encoding UTF-8
190
191 =head1 NAME
192
193 json-schema-eval - A command-line interface to JSON::Schema::Modern::evaluate()
194
195 =head1 VERSION
196
197 version 0.650
198
199 I use a linearly-increasing version numbering scheme. No meaning should be
200 presumed or inferred from the version being less than 1.0.
201
202 =head1 SYNOPSIS
203
204 json-schema-eval --help
205
206 json-schema-eval \
207 [ --specification-version|version <version> ] \
208 [ --output-format <format> ] \
209 [ --short-circuit ] \
210 [ --max-traversal-depth <depth> ] \
211 [ --validate-formats ] \
212 [ --validate-content-schemas ] \
213 [ --collect-annotations ] \
214 [ --strict ] \
215 [ --dump-identifiers ] \
216 [ --with-defaults ] \
217 [ --validate-schema [ <filename> ] [ ... ] ] \
218 [ --add-schema [ <filename> ] [ ... ] ] \
219 [ --data [ <filename> ] [ ... ] ] \
220 [ --schema [ <filename> ] ]
221
222 =head1 DESCRIPTION
223
224 A command-line interface to L<JSON::Schema::Modern/evaluate>.
225
226 F<data.json> contains:
227
228 {"hello": 42.1}
229
230 F<schema.json> contains:
231
232 {"properties": {"hello": {"type": ["string", "integer"]}}}
233
234 Run:
235
236 json-schema-eval --data data.json --schema schema.json
237
238 produces output:
239
240 {
241 "errors" : [
242 {
243 "error" : "got number, not one of string, integer",
244 "instanceLocation" : "/hello",
245 "keywordLocation" : "/properties/hello/type"
246 },
247 {
248 "error" : "not all properties are valid",
249 "instanceLocation" : "",
250 "keywordLocation" : "/properties"
251 }
252 ],
253 "valid" : false
254 }
255
256 Or run:
257
258 json-schema-eval --validate-schema schema.json
259
260 produces output:
261
262 {
263 "valid": true
264 }
265
266 The exit value (C<$?>) is 0 when the result is valid, 1 when it is invalid,
267 and some other non-zero value if an exception occurred.
268
269 =head1 OPTIONS
270
271 =for stopwords schemas
272
273 All boolean and string options used as L<constructors to
274 JSON::Schema::Modern|JSON::Schema::Modern/CONFIGURATION OPTIONS> are available.
275
276 Additionally, C<--data> is used to provide the filename containing a JSON- or YAML-encoded data
277 instance, and C<--schema> provides the filename containing a JSON- or YAML-encoded schema.
278 You can use the C<--data> option more than once to validate multiple data instances against the same
279 schema.
280
281 If either or both of these are not provided, STDIN is used as input.
282
283 Both JSON- and YAML-encoded data and schemas are supported, using heuristics based on the
284 content of the first line of the data.
285
286 Alternatively, you can use C<--validate-schema> and either provide a filename containing a
287 JSON-encoded schema, or omit the argument to read a schema from STDIN. The schema
288 will be evaluated against its meta-schema for the corresponding specification version.
289 You can use this option more than once to validate multiple schemas in the same runtime instance.
290
291 Additional schemas, that you wish to use via the C<$ref> keyword, can be added with
292 C<< --add-schema <filename> >>. The actual filename is insignificant: Make sure you use an C<$id>
293 keyword within that schema that matches the value you use in the C<$ref>. This option can be used
294 more than once.
295
296 =for stopwords OpenAPI
297
298 =head1 AVAILABILITY
299
300 This executable is available on modern Debian versions (via C<apt-get>) as the
301 C<libjson-schema-modern-perl> package.
302
303 =head1 GIVING THANKS
304
305 =for stopwords MetaCPAN GitHub
306
307 If you found this module to be useful, please show your appreciation by
308 adding a +1 in L<MetaCPAN|https://metacpan.org/dist/JSON-Schema-Modern>
309 and a star in L<GitHub|https://github.com/karenetheridge/JSON-Schema-Modern>.
310
311 =head1 SUPPORT
312
313 Bugs may be submitted through L<https://github.com/karenetheridge/JSON-Schema-Modern/issues>.
314
315 I am also usually active on irc, as 'ether' at C<irc.perl.org> and C<irc.libera.chat>.
316
317 =for stopwords OpenAPI
318
319 You can also find me on the L<JSON Schema Slack server|https://json-schema.slack.com> and L<OpenAPI Slack
320 server|https://open-api.slack.com>, which are also great resources for finding help.
321
322 =head1 AUTHOR
323
324 Karen Etheridge <[email protected]>
325
326 =head1 COPYRIGHT AND LICENCE
327
328 This software is copyright (c) 2020 by Karen Etheridge.
329
330 This is free software; you can redistribute it and/or modify it under
331 the same terms as the Perl 5 programming language system itself.
332
333 Some schema files have their own licence, in share/LICENSE.
334
335 =cut