Created
September 22, 2020 20:56
-
-
Save saethlin/a323c4aa20cbd0750b2b5a9f63a1de8f to your computer and use it in GitHub Desktop.
Order-resistant JSON diffing cargo script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env run-cargo-script | |
| //! ```cargo | |
| //! [package] | |
| //! edition = "2018" | |
| //! | |
| //! [dependencies] | |
| //! serde = "1.0" | |
| //! serde_json = "1.0" | |
| //! ``` | |
| use serde_json::Value; | |
| use std::{ | |
| fs::File, | |
| io::{BufRead, BufReader}, | |
| }; | |
| fn main() { | |
| let old_file = std::env::args().nth(1).unwrap(); | |
| let new_file = std::env::args().nth(2).unwrap(); | |
| for (old_line, new_line) in BufReader::new(File::open(&old_file).unwrap()) | |
| .lines() | |
| .zip(BufReader::new(File::open(&new_file).unwrap()).lines()) | |
| { | |
| let mut old_json = serde_json::from_str::<Value>(&old_line.unwrap()).unwrap(); | |
| let mut new_json = serde_json::from_str::<Value>(&new_line.unwrap()).unwrap(); | |
| sort_arrays(&mut old_json); | |
| sort_arrays(&mut new_json); | |
| if new_json != old_json { | |
| println!("Match fail between {} and {}", new_file, old_file); | |
| std::process::exit(-1); | |
| } | |
| } | |
| } | |
| fn sort_arrays(this: &mut Value) { | |
| match this { | |
| Value::Array(arr) => { | |
| arr.sort_by(|a, b| a.to_string().cmp(&b.to_string())); | |
| for value in arr { | |
| sort_arrays(value); | |
| } | |
| } | |
| Value::Object(map) => { | |
| for value in map.values_mut() { | |
| sort_arrays(value); | |
| } | |
| } | |
| _ => {} | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment