Skip to content

Improve API for library usage #5

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
[package]
name = "json_diff_ng"
version = "0.5.0"
version = "0.6.0-RC1"
authors = ["ksceriath", "ChrisRega"]
edition = "2021"
license = "Unlicense"
description = "A small diff tool utility for comparing jsons. Forked from ksceriath and improved for usage as a library and with good support for array diffs."
description = "A small diff tool utility for comparing jsons. Forked from ksceriath and improved for usage as a library and with proper support for array diffs."
readme = "README.md"
homepage = "https://github.com/ChrisRega/json-diff"
repository = "https://github.com/ChrisRega/json-diff"
Expand Down
81 changes: 35 additions & 46 deletions src/ds/key_node.rs
Original file line number Diff line number Diff line change
@@ -1,65 +1,54 @@
use crate::enums::ValueType;
use serde_json::Value;
use std::collections::HashMap;

use serde_json::Value;

use crate::enums::{DiffEntry, PathElement};

#[derive(Debug, PartialEq)]
pub enum KeyNode {
Nil,
Value(Value, Value),
Node(HashMap<String, KeyNode>),
}

fn truncate(s: &str, max_chars: usize) -> String {
match s.char_indices().nth(max_chars) {
None => String::from(s),
Some((idx, _)) => {
let shorter = &s[..idx];
let snip = "//SNIP//";
let new_s = format!("{}{}", shorter, snip);
new_s
}
}
Array(Vec<(usize, KeyNode)>),
}

impl KeyNode {
pub fn absolute_keys_to_vec(&self, max_display_length: Option<usize>) -> Vec<ValueType> {
let mut vec = Vec::new();
self.absolute_keys(&mut vec, None, max_display_length);
vec
pub fn get_diffs(&self) -> Vec<DiffEntry> {
let mut buf = Vec::new();
self.follow_path(&mut buf, &[]);
buf
}

pub fn absolute_keys(
&self,
keys: &mut Vec<ValueType>,
key_from_root: Option<String>,
max_display_length: Option<usize>,
) {
let max_display_length = max_display_length.unwrap_or(4000);
let val_key = |key: Option<String>| {
key.map(|mut s| {
s.push_str("->");
s
})
.unwrap_or_default()
};
pub fn follow_path(&self, diffs: &mut Vec<DiffEntry>, offset: &[PathElement]) {
match self {
KeyNode::Nil => {
if let Some(key) = key_from_root {
keys.push(ValueType::new_key(key))
let is_map_child = offset
.last()
.map(|o| matches!(o, PathElement::Object(_)))
.unwrap_or_default();
if is_map_child {
diffs.push(DiffEntry {
path: offset.to_vec(),
values: None,
});
}
}
KeyNode::Value(l, r) => diffs.push(DiffEntry {
path: offset.to_vec(),
values: Some((l.to_string(), r.to_string())),
}),
KeyNode::Node(o) => {
for (k, v) in o {
let mut new_offset = offset.to_vec();
new_offset.push(PathElement::Object(k.clone()));
v.follow_path(diffs, &new_offset);
}
}
KeyNode::Value(a, b) => keys.push(ValueType::new_value(
val_key(key_from_root),
truncate(a.to_string().as_str(), max_display_length),
truncate(b.to_string().as_str(), max_display_length),
)),
KeyNode::Node(map) => {
for (key, value) in map {
value.absolute_keys(
keys,
Some(format!("{}{}", val_key(key_from_root.clone()), key)),
Some(max_display_length),
)
KeyNode::Array(v) => {
for (l, k) in v {
let mut new_offset = offset.to_vec();
new_offset.push(PathElement::ArrayEntry(*l));
k.follow_path(diffs, &new_offset);
}
}
}
Expand Down
15 changes: 6 additions & 9 deletions src/ds/mismatch.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::ds::key_node::KeyNode;
use crate::enums::{DiffType, ValueType};
use crate::enums::{DiffEntry, DiffType};

#[derive(Debug, PartialEq)]
pub struct Mismatch {
Expand Down Expand Up @@ -31,24 +31,20 @@ impl Mismatch {
&& self.right_only_keys == KeyNode::Nil
}

pub fn all_diffs(&self) -> Vec<(DiffType, ValueType)> {
self.all_diffs_trunc(None)
}

pub fn all_diffs_trunc(&self, truncation_length: Option<usize>) -> Vec<(DiffType, ValueType)> {
pub fn all_diffs(&self) -> Vec<(DiffType, DiffEntry)> {
let both = self
.keys_in_both
.absolute_keys_to_vec(truncation_length)
.get_diffs()
.into_iter()
.map(|k| (DiffType::Mismatch, k));
let left = self
.left_only_keys
.absolute_keys_to_vec(truncation_length)
.get_diffs()
.into_iter()
.map(|k| (DiffType::LeftExtra, k));
let right = self
.right_only_keys
.absolute_keys_to_vec(truncation_length)
.get_diffs()
.into_iter()
.map(|k| (DiffType::RightExtra, k));

Expand All @@ -59,6 +55,7 @@ impl Mismatch {
#[cfg(test)]
mod test {
use super::*;

#[test]
fn empty_diffs() {
let empty = Mismatch::empty();
Expand Down
58 changes: 28 additions & 30 deletions src/enums.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use std::fmt::{Display, Formatter};

use thiserror::Error;
use vg_errortools::FatIOError;

Expand Down Expand Up @@ -30,45 +31,42 @@ impl Display for DiffType {
}
}

pub enum ValueType {
Key(String),
Value {
key: String,
value_left: String,
value_right: String,
},
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum PathElement {
Object(String),
ArrayEntry(usize),
}

impl ValueType {
pub fn new_value(key: String, value_left: String, value_right: String) -> Self {
Self::Value {
value_right,
value_left,
key,
}
}
pub fn new_key(key: String) -> Self {
Self::Key(key)
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct DiffEntry {
pub path: Vec<PathElement>,
pub values: Option<(String, String)>,
}

pub fn get_key(&self) -> &str {
match self {
ValueType::Value { key, .. } => key.as_str(),
ValueType::Key(key) => key.as_str(),
impl Display for DiffEntry {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
for element in &self.path {
write!(f, ".{element}")?;
}
if let Some((l, r)) = &self.values {
if l != r {
write!(f, ".({l} != {r})")?;
} else {
write!(f, ".({l})")?;
}
}
Ok(())
}
}

impl Display for ValueType {
impl Display for PathElement {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
ValueType::Key(key) => write!(f, "{key}"),
ValueType::Value {
value_left,
key,
value_right,
} => {
write!(f, "{key}{{{value_left}!={value_right}}}")
PathElement::Object(o) => {
write!(f, "{o}")
}
PathElement::ArrayEntry(l) => {
write!(f, "[{l}]")
}
}
}
Expand Down
Loading
Loading