|
| 1 | +#include <cppcson.hpp> |
| 2 | +#include <fstream> |
| 3 | +#include <iostream> |
| 4 | + |
| 5 | +static void print(const cppcson::Value &value, bool isRoot, int32_t indent) { |
| 6 | + if (value.isNull()) { |
| 7 | + std::cout << "null"; |
| 8 | + } else if (value.isBool()) { |
| 9 | + std::cout << value.asBool(); |
| 10 | + } else if (value.isInt()) { |
| 11 | + std::cout << value.asInt(); |
| 12 | + } else if (value.isFloat()) { |
| 13 | + std::cout << value.asFloat(); |
| 14 | + } else if (value.isString()) { |
| 15 | + std::cout << cppcson::escape(value.asString()); |
| 16 | + } else if (value.isArray()) { |
| 17 | + std::cout << "["; |
| 18 | + |
| 19 | + indent += 2; |
| 20 | + for (auto &item : value) { |
| 21 | + std::cout << std::endl << std::string(indent, ' '); |
| 22 | + print(item, false, indent); |
| 23 | + } |
| 24 | + indent -= 2; |
| 25 | + |
| 26 | + std::cout << std::endl << std::string(indent, ' ') << "]"; |
| 27 | + } else if (value.isObject()) { |
| 28 | + if (!isRoot) { |
| 29 | + indent += 2; |
| 30 | + } |
| 31 | + |
| 32 | + auto skipNewline = isRoot; |
| 33 | + |
| 34 | + for (auto &key : value.keys()) { |
| 35 | + if (skipNewline) { |
| 36 | + skipNewline = false; |
| 37 | + } else { |
| 38 | + std::cout << std::endl; |
| 39 | + } |
| 40 | + |
| 41 | + std::cout << std::string(indent, ' ') << cppcson::escapeKey(key) << ": "; |
| 42 | + print(value.item(key), false, indent); |
| 43 | + } |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +static void print(const cppcson::Value &value) { |
| 48 | + print(value, true, 0); |
| 49 | + std::cout << std::endl; |
| 50 | +} |
| 51 | + |
| 52 | +int main(int argc, char const *const *argv) { |
| 53 | + if (argc != 2) { |
| 54 | + std::cout << "Error: Please pass a path to a cson file" << std::endl; |
| 55 | + return 1; |
| 56 | + } |
| 57 | + |
| 58 | + std::string path(argv[1]); |
| 59 | + std::ifstream stream(path); |
| 60 | + |
| 61 | + if (stream.fail()) { |
| 62 | + std::cout << "Error: File " << path << " could not be read" << std::endl; |
| 63 | + return 2; |
| 64 | + } |
| 65 | + |
| 66 | + try { |
| 67 | + auto root = cppcson::parse(stream); |
| 68 | + |
| 69 | + print(root); |
| 70 | + return 0; |
| 71 | + } catch (const cppcson::Error &e) { |
| 72 | + std::cout << "Error: The file " << path << " could not be parsed as cson" |
| 73 | + << std::endl |
| 74 | + << "Details:" << std::endl |
| 75 | + << e.getLocation() << std::endl |
| 76 | + << e.what() << std::endl; |
| 77 | + return 3; |
| 78 | + } |
| 79 | +} |
0 commit comments