khive_graph_diff/
parse.rs1use std::collections::BTreeMap;
2
3use khive_types::ParseIdError;
4use serde_json::Value;
5
6use crate::{Id128, Records, Substrate};
7
8#[derive(Debug, thiserror::Error)]
10pub enum DiffInputError {
11 #[error("{substrate} line {line}: invalid JSON: {source}")]
12 InvalidJson {
13 substrate: Substrate,
14 line: usize,
15 #[source]
16 source: serde_json::Error,
17 },
18 #[error("{substrate} line {line}: expected a JSON object")]
19 NotObject { substrate: Substrate, line: usize },
20 #[error("{substrate} line {line}: missing identity field {field}")]
21 MissingIdentity {
22 substrate: Substrate,
23 line: usize,
24 field: &'static str,
25 },
26 #[error("{substrate} line {line}: identity field {field} must be a string")]
27 NonStringIdentity {
28 substrate: Substrate,
29 line: usize,
30 field: &'static str,
31 },
32 #[error("{substrate} line {line}: invalid identity: {source}")]
33 InvalidIdentity {
34 substrate: Substrate,
35 line: usize,
36 #[source]
37 source: ParseIdError,
38 },
39 #[error("{substrate} line {line}: duplicate identity {id}")]
40 DuplicateIdentity {
41 substrate: Substrate,
42 line: usize,
43 id: Id128,
44 },
45}
46
47pub(crate) fn records(input: &str, substrate: Substrate) -> Result<Records, DiffInputError> {
48 let mut records = Records::new();
49 for (offset, text) in input.lines().enumerate() {
50 if text.trim().is_empty() {
51 continue;
52 }
53 let line = offset + 1;
54 let value: Value =
55 serde_json::from_str(text).map_err(|source| DiffInputError::InvalidJson {
56 substrate,
57 line,
58 source,
59 })?;
60 let Value::Object(mut fields) = value else {
61 return Err(DiffInputError::NotObject { substrate, line });
62 };
63 let field = substrate.identity_field();
64 let identity = fields
65 .remove(field)
66 .ok_or(DiffInputError::MissingIdentity {
67 substrate,
68 line,
69 field,
70 })?;
71 let Value::String(identity) = identity else {
72 return Err(DiffInputError::NonStringIdentity {
73 substrate,
74 line,
75 field,
76 });
77 };
78 let id = identity
79 .parse()
80 .map_err(|source| DiffInputError::InvalidIdentity {
81 substrate,
82 line,
83 source,
84 })?;
85 if records.contains_key(&id) {
86 return Err(DiffInputError::DuplicateIdentity {
87 substrate,
88 line,
89 id,
90 });
91 }
92 records.insert(
93 id,
94 fields
95 .into_iter()
96 .map(|(key, value)| (key, canonical_value(value)))
97 .collect(),
98 );
99 }
100 Ok(records)
101}
102
103fn canonical_value(value: Value) -> Value {
106 match value {
107 Value::Object(fields) => {
108 let sorted: BTreeMap<_, _> = fields.into_iter().collect();
109 Value::Object(
110 sorted
111 .into_iter()
112 .map(|(key, value)| (key, canonical_value(value)))
113 .collect(),
114 )
115 }
116 Value::Array(values) => Value::Array(values.into_iter().map(canonical_value).collect()),
117 scalar => scalar,
118 }
119}