Shamrock 2025.10.0
Astrophysical Code
Loading...
Searching...
No Matches
json_print_diff.hpp
Go to the documentation of this file.
1// -------------------------------------------------------//
2//
3// SHAMROCK code for hydrodynamics
4// Copyright (c) 2021-2026 Timothée David--Cléris <tim.shamrock@proton.me>
5// SPDX-License-Identifier: CeCILL Free Software License Agreement v2.1
6// Shamrock is licensed under the CeCILL 2.1 License, see LICENSE for more information
7//
8// -------------------------------------------------------//
9
10#pragma once
11
19#include "shambase/string.hpp"
21#include <nlohmann/json.hpp>
22#include <optional>
23#include <sstream>
24
25namespace shamrock {
26
27 inline std::string json_diff_str(const nlohmann::json &j1, const nlohmann::json &j2) {
28 auto v1 = shambase::split_str(j1.dump(4), "\n");
29 auto v2 = shambase::split_str(j2.dump(4), "\n");
30
31 // Equivalent to diff since the json entries are sorted
32 auto it1 = v1.begin();
33 auto it2 = v2.begin();
34
38
39 // Helper lambda to check if two strings differ only by a trailing character
40 auto differ_by_trailing_char = [](const std::string &s1, const std::string &s2) -> bool {
41 if (s1 == s2)
42 return false;
43 size_t len1 = s1.length();
44 size_t len2 = s2.length();
45
46 // Check if s1 equals s2 with last char removed
47 if (len1 == len2 + 1 && s1.substr(0, len2) == s2)
48 return true;
49
50 // Check if s2 equals s1 with last char removed
51 if (len2 == len1 + 1 && s2.substr(0, len1) == s1)
52 return true;
53
54 return false;
55 };
56
57 std::stringstream ss;
58
59 while (it1 != v1.end() || it2 != v2.end()) {
60 if (it1 == v1.end()) {
61 ss << shambase::format("{}+ | {}{}\n", green, *it2++, reset);
62 } else if (it2 == v2.end()) {
63 ss << shambase::format("{}- | {}{}\n", red, *it1++, reset);
64 } else if (differ_by_trailing_char(*it1, *it2)) {
65 auto &longest = (*it1).length() > (*it2).length() ? *it1 : *it2;
66 ss << shambase::format(" | {}\n", longest); // unchanged
67 ++it1;
68 ++it2;
69 } else if (*it1 < *it2) {
70 ss << shambase::format("{}- | {}{}\n", red, *it1++, reset);
71 } else if (*it2 < *it1) {
72 ss << shambase::format("{}+ | {}{}\n", green, *it2++, reset);
73 } else {
74 ss << shambase::format(" | {}\n", *it1); // unchanged
75 ++it1;
76 ++it2;
77 }
78 }
79
80 return ss.str();
81 }
82} // namespace shamrock
std::vector< std::string > split_str(std::string s, std::string delimiter)
Splits a string into a vector of substrings according to a delimiter.
Definition string.hpp:290
namespace for the main framework
Definition __init__.py:1
const std::string reset()
Get the reset terminal escape char.
const std::string col8b_green()
Get the green terminal escape char.
const std::string col8b_red()
Get the red terminal escape char.