|
8 | 8 | using namespace nlohmann; |
9 | 9 | using namespace nlohmann::json_schema; |
10 | 10 |
|
11 | | -int main(int argc, char *argv[]) |
| 11 | +class main_cli : public CLI::App |
12 | 12 | { |
13 | 13 | std::ifstream schema_input; |
14 | 14 | std::ifstream object_input; |
| 15 | + // TODO: Export this as a built-in loader |
| 16 | + static void loader(const json_uri &uri, json &schema) |
| 17 | + { |
| 18 | + std::string filename = "./" + uri.path(); |
| 19 | + std::ifstream lf(filename); |
| 20 | + if (!lf.good()) |
| 21 | + throw std::invalid_argument("could not open " + uri.url() + " tried with " + filename); |
| 22 | + try { |
| 23 | + lf >> schema; |
| 24 | + } catch (const std::exception &e) { |
| 25 | + throw e; |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | +public: |
| 30 | + json schema; |
| 31 | + json object; |
| 32 | + json_validator validator; |
| 33 | + main_cli() |
| 34 | + : CLI::App{"Json schema validator", "json-validator"}, |
| 35 | + validator{loader, default_string_format_check} |
| 36 | + { |
| 37 | + // TODO: Move to a generated header file |
| 38 | + set_version_flag("--version", "2.2.0"); |
| 39 | + add_option("schema", schema_input, "JSON schema of the object") |
| 40 | + ->check(CLI::ExistingFile); |
| 41 | + add_option("object", object_input, "JSON object to validate") |
| 42 | + ->check(CLI::ExistingFile); |
| 43 | + } |
| 44 | + void validate() |
| 45 | + { |
| 46 | + validator.set_root_schema(schema); |
| 47 | + validator.validate(object); |
| 48 | + } |
| 49 | +}; |
15 | 50 |
|
16 | | - CLI::App app{"Json schema validator", "json-validator"}; |
17 | | - // TODO: Move to a generated header file |
18 | | - app.set_version_flag("--version", "2.2.0"); |
19 | | - app.add_option("schema", schema_input, "JSON schema of the object") |
20 | | - ->check(CLI::ExistingFile); |
21 | | - app.add_option("object", "JSON object to validate") |
22 | | - ->check(CLI::ExistingFile); |
| 51 | +int main(int argc, char *argv[]) |
| 52 | +{ |
| 53 | + main_cli app{}; |
23 | 54 |
|
24 | 55 | try { |
25 | 56 | app.parse(argc, argv); |
26 | 57 | } catch (const CLI::ParseError &e) { |
27 | 58 | return app.exit(e); |
28 | 59 | } |
29 | 60 |
|
30 | | - json schema{}; |
31 | | - json object{}; |
32 | | - if (!schema_input.good()) |
33 | | - throw std::invalid_argument("could not read schema"); |
34 | | - if (!object_input.good()) |
35 | | - throw std::invalid_argument("could not read object"); |
36 | | - schema_input >> schema; |
37 | | - object_input >> object; |
| 61 | + app.validate(); |
| 62 | + |
38 | 63 | return 0; |
39 | 64 | } |
0 commit comments