Files
json-serializer/main.cpp
T
2026-08-10 08:21:31 +02:00

299 lines
8.5 KiB
C++

#include <cstdint>
#include <fstream>
#include <ios>
#include <sys/stat.h>
#include <cmath>
#include <cstddef>
#include <cstdio>
#include <filesystem>
#include <iostream>
#include <map>
#include <optional>
#include <sstream>
#include <string>
#include <sys/types.h>
#include <type_traits>
#include <variant>
#include <vector>
struct TreeNode {
std::filesystem::file_type type;
int inode;
std::string name;
int parent;
int mode;
int owner;
int group;
int mtime;
int ctime;
int atime;
std::optional<std::vector<uint8_t>> content;
std::vector<TreeNode> children;
};
TreeNode parse(const std::filesystem::path& p, int& next_inode, int& parent_inode);
TreeNode parse_tree(const std::filesystem::path& p) {
int next_inode = 0;
int parent_inode = 0;
TreeNode root = parse(p, next_inode, parent_inode);
root.parent = 0;
return root;
}
TreeNode parse(const std::filesystem::path& p, int& next_inode, int& parent_inode) {
TreeNode node;
node.inode = next_inode++;
node.name = p.filename().string();
node.type = std::filesystem::status(p).type();
struct stat buf;
if(stat(p.c_str(), &buf) == 0) {
node.mode = buf.st_mode & 0777;
node.owner = buf.st_uid;
node.group = buf.st_gid;
node.parent = parent_inode;
node.mtime = static_cast<int64_t>(buf.st_mtime);
node.atime = static_cast<int64_t>(buf.st_atime);
node.ctime = static_cast<int64_t>(buf.st_ctime);
}
if(node.type == std::filesystem::file_type::directory) {
for(const auto& entry : std::filesystem::directory_iterator(p)) {
TreeNode child = parse(entry.path(), next_inode, node.inode);
child.parent = node.inode;
node.children.push_back(std::move(child));
}
}
if(node.type == std::filesystem::file_type::regular) {
std::ifstream file(p, std::ios::binary | std::ios::ate);
if(file.good()) {
std::streamsize size = file.tellg();
file.seekg(0, std::ios::beg);
std::vector<uint8_t> buffer(size);
if(file.read(reinterpret_cast<char*>(buffer.data()), size)) {
node.content = std::move(buffer);
}
}
}
return node;
}
class JsonValue;
using JsonNull = std::nullptr_t;
using JsonObject = std::map<std::string, JsonValue>;
using JsonArray = std::vector<JsonValue>;
using JsonVariant = std::variant<
JsonNull,
bool,
int,
double,
std::string,
JsonArray,
JsonObject>;
class JsonValue {
public:
JsonVariant value;
JsonValue() : value(nullptr) {}
JsonValue(std::nullptr_t): value(nullptr) {}
JsonValue(bool b) : value(b) {}
JsonValue(int i) : value(i) {}
JsonValue(double n) : value(n) {}
JsonValue(const std::string& s) : value(s) {}
JsonValue(const char* s) : value(std::string(s)) {}
JsonValue(JsonArray arr) : value(std::move(arr)) {}
JsonValue(JsonObject obj) : value(std::move(obj)) {}
};
std::string number_to_string(double);
std::string escape_string(const std::string&);
std::string serialize_array(const JsonArray&, const std::string&, const std::string&);
std::string serialize_object(const JsonObject&, const std::string&, const std::string&);
std::string serialize(const JsonValue& val,
const std::string& indent = "",
const std::string& current_indent = "")
{
return std::visit([&](const auto& v) -> std::string {
using T = std::decay_t<decltype(v)>;
if constexpr (std::is_same_v<T, JsonNull>) {
return "null";
} else if constexpr (std::is_same_v<T, bool>) {
return v ? "true" : "false";
} else if constexpr (std::is_same_v<T, int>) {
return number_to_string(static_cast<double>(v));
} else if constexpr (std::is_same_v<T, double>) {
return number_to_string(v);
} else if constexpr (std::is_same_v<T, std::string>) {
return escape_string(v);
} else if constexpr (std::is_same_v<T, JsonArray>) {
return serialize_array(v, indent, current_indent);
} else if constexpr (std::is_same_v<T, JsonObject>) {
return serialize_object(v, indent, current_indent);
}
}, val.value);
}
std::string number_to_string(double num) {
if(std::isnan(num) || std::isinf(num)) return "null";
std::ostringstream oss;
oss.precision(17);
oss << num;
std::string str = oss.str();
if(str.find('.') != std::string::npos && str.find('e') == std::string::npos) {
while (str.back() == '0')
str.pop_back();
if(str.back() == '.') str.pop_back();
}
return str;
}
std::string escape_string(const std::string& s) {
std::string result = "\"";
for(char c : s) {
switch(c) {
case '"': result += "\\\""; break;
case '\\': result += "\\\\"; break;
case '\n': result += "\\n"; break;
case '\t': result += "\\t"; break;
case '\r': result += "\\r"; break;
case '\f': result += "\\f"; break;
case '\b': result += "\\b"; break;
default:
if(static_cast<unsigned char>(c) < 0x20) {
char buf[7];
snprintf(buf, sizeof buf, "\\u%04x", static_cast<unsigned char>(c));
result += buf;
} else {
result += c;
}
}
}
result += '"';
return result;
}
std::string serialize_array(const JsonArray& arr, const std::string& indent, const std::string& current_indent) {
if(arr.empty()) return "[]";
std::string next_indent = current_indent + indent;
std::string result;
if(indent.empty()) {
result = "[";
}
else result = "[\n";
for(size_t i = 0; i < arr.size(); i++) {
result += next_indent + serialize(arr[i], indent, next_indent);
if(i!= arr.size() - 1) result += ',';
if(!indent.empty()) result += '\n';
}
result += current_indent + "]";
return result;
}
std::string serialize_object(const JsonObject& obj, const std::string& indent, const std::string& current_indent) {
if(obj.empty()) return "{}";
std::string next_indent = current_indent + indent;
std::string result;
if(indent.empty()) {
result = "{";
}
else result = "{\n";
size_t count = 0;
for(const auto& [key, value] : obj) {
result += next_indent + escape_string(key) + ": " + serialize(value, indent, next_indent);
if(++count != obj.size()) result += ',';
if(!indent.empty()) result += '\n';
}
result += current_indent + "}";
return result;
}
std::string file_type_to_string(std::filesystem::file_type t) {
using std::filesystem::file_type;
switch (t) {
case file_type::none: return "none";
case file_type::not_found: return "not_found";
case file_type::regular: return "regular";
case file_type::directory: return "directory";
case file_type::symlink: return "symlink";
case file_type::block: return "block";
case file_type::character: return "character";
case file_type::fifo: return "fifo";
case file_type::socket: return "socket";
default: return "unknown";
}
}
JsonValue to_json(const TreeNode& node) {
JsonObject obj;
obj["type"] = file_type_to_string(node.type);
obj["inode"] = node.inode;
obj["name"] = node.name;
obj["parent"] = node.parent;
obj["mode"] = node.mode;
obj["owner"] = node.owner;
obj["group"] = node.group;
obj["mtime"] = node.mtime;
obj["ctime"] = node.ctime;
obj["atime"] = node.atime;
if(node.content.has_value()) {
JsonArray arr;
for(uint8_t byte : node.content.value()) {
arr.push_back(byte);
}
obj["content"] = arr;
} else {
obj["content"] = nullptr;
}
JsonArray childrenArray;
for(const auto& child : node.children) {
childrenArray.push_back(to_json(child));
}
obj["children"] = std::move(childrenArray);
return obj;
}
int main(int argc, char* argv[]) {
if(argc != 2) {
std::cerr << "Wrong number of arguments passed\n";
return 1;
}
if(!std::filesystem::exists(argv[1])) {
std::cerr << "The path doesnt exist\n";
return 1;
}
const std::filesystem::path rootPath = argv[1];
TreeNode root = parse_tree(rootPath);
JsonValue json = to_json(root);
std::string json_str = serialize(json, " ");
std::cout << json_str << "\n";
return 0;
}