1use indexmap::IndexMap;
4use serde_json::{Map, Value};
5
6use crate::tree::{Flat, detach, entry_mut, flatten, place};
7
8pub type Changes = IndexMap<String, Option<Value>>;
10
11#[derive(Debug, Clone, PartialEq)]
12pub enum Record {
13 Remove,
14 Upsert {
15 created: bool,
17 parent: Option<Option<String>>,
20 position: usize,
22 changes: Changes,
23 },
24}
25
26pub type Journal = IndexMap<String, Record>;
28
29pub fn diff_options(legacy: &Value, options: &Value) -> Changes {
30 let empty = Map::new();
31 let (legacy, options) = (legacy.as_object().unwrap_or(&empty), options.as_object().unwrap_or(&empty));
32 let mut changes = Changes::new();
33 for key in legacy.keys().chain(options.keys()) {
34 if key == "id" || changes.contains_key(key) || legacy.get(key) == options.get(key) {
35 continue;
36 }
37 changes.insert(key.clone(), options.get(key).cloned());
38 }
39 changes
40}
41
42pub fn merge_records(older: Option<Record>, newer: Record) -> Option<Record> {
44 let Some(older) = older else { return Some(newer) };
45 match (older, newer) {
46 (Record::Upsert { created: true, .. }, Record::Remove) => None,
48 (_, Record::Remove) => Some(Record::Remove),
49 (Record::Remove, Record::Upsert { parent, position, changes, .. }) => {
50 Some(Record::Upsert { created: false, parent, position, changes })
51 }
52 (
53 Record::Upsert { created, parent: old_parent, position: old_position, changes: mut merged },
54 Record::Upsert { parent, position, changes, .. },
55 ) => {
56 merged.extend(changes);
57 let (parent, position) = if parent.is_some() { (parent, position) } else { (old_parent, old_position) };
58 Some(Record::Upsert { created, parent, position, changes: merged })
59 }
60 }
61}
62
63pub fn merge(journal: &mut Journal, id: &str, record: Record) {
64 if let Some(merged) = merge_records(journal.shift_remove(id), record) {
65 journal.insert(id.to_string(), merged);
66 }
67}
68
69pub fn record(
72 journal: &mut Journal,
73 id: &str,
74 options: Option<&Value>,
75 legacy: Option<&Value>,
76 moved: bool,
77 parent: Option<String>,
78 position: usize,
79) {
80 let record = match (options, legacy) {
81 (None, _) => Record::Remove,
82 (Some(options), None) => {
83 let changes = options
84 .as_object()
85 .into_iter()
86 .flatten()
87 .filter(|(key, _)| *key != "id")
88 .map(|(key, value)| (key.clone(), Some(value.clone())))
89 .collect();
90 Record::Upsert { created: true, parent: Some(parent), position, changes }
91 }
92 (Some(options), Some(legacy)) => Record::Upsert {
93 created: false,
94 parent: moved.then_some(parent),
95 position,
96 changes: diff_options(legacy, options),
97 },
98 };
99 merge(journal, id, record);
100}
101
102pub fn apply_changes(options: &mut Value, changes: &Changes, mut filter: impl FnMut(&str) -> bool) {
103 let Some(map) = options.as_object_mut() else { return };
104 for (key, value) in changes {
105 if !filter(key) {
106 continue;
107 }
108 match value {
109 None => {
110 map.shift_remove(key);
111 }
112 Some(value) => {
113 map.insert(key.clone(), value.clone());
114 }
115 }
116 }
117}
118
119pub fn apply_journal(
122 mut data: Vec<Value>,
123 journal: &Journal,
124 filter: impl Fn(&str, Option<&str>) -> bool,
125 warn: &dyn Fn(String),
126) -> Vec<Value> {
127 for (id, record) in journal {
128 if !filter(id, None) {
129 continue;
130 }
131 let Record::Upsert { parent, position, changes, .. } = record else {
132 detach(&mut data, id);
133 continue;
134 };
135 let Some(flat) = flatten(&data).shift_remove(id) else {
136 let mut options = Value::Object(Map::from_iter([("id".to_string(), Value::String(id.clone()))]));
137 apply_changes(&mut options, changes, |key| filter(id, Some(key)));
138 let parent = parent.clone().flatten();
139 if !place(&mut data, options, parent.as_deref(), *position) {
140 warn(format!("cannot place entry {id}: group {} not found", parent.unwrap_or_default()));
141 }
142 continue;
143 };
144 if let Some(options) = entry_mut(&mut data, id) {
145 apply_changes(options, changes, |key| filter(id, Some(key)));
146 }
147 if let Some(target) = parent
148 && *target != flat.parent
149 {
150 let options = detach(&mut data, id).expect("found above");
151 if !place(&mut data, options.clone(), target.as_deref(), *position) {
152 warn(format!("cannot move entry {id}: group {} not found", target.clone().unwrap_or_default()));
153 place(&mut data, options, flat.parent.as_deref(), flat.position);
154 }
155 }
156 }
157 data
158}
159
160#[derive(Debug, Clone, PartialEq, Eq)]
161pub struct Conflict {
162 pub id: String,
163 pub reason: String,
164}
165
166pub fn reconcile(
171 journal: &mut Journal,
172 base: &IndexMap<String, Flat>,
173 theirs: &IndexMap<String, Flat>,
174 file_owned: impl Fn(&str, Option<&str>) -> bool,
175) -> Vec<Conflict> {
176 let mut conflicts = Vec::new();
177 let mut conflict = |id: &str, reason: String| conflicts.push(Conflict { id: id.to_string(), reason });
178 let ids: Vec<String> = journal.keys().cloned().collect();
179 for id in ids {
180 if !file_owned(&id, None) {
181 continue;
182 }
183 let (b, t) = (base.get(&id), theirs.get(&id));
184 let record = journal.get_mut(&id).expect("listed above");
185 let Record::Upsert { created, parent, changes, .. } = record else {
186 match (b, t) {
187 (_, None) => {}
188 (Some(b), Some(t)) if b.options == t.options => continue,
189 (b, Some(_)) => {
190 let reason = if b.is_some() {
191 "modified in file, removed at runtime"
192 } else {
193 "added in file, removed at runtime"
194 };
195 conflict(&id, reason.into());
196 }
197 }
198 journal.shift_remove(&id);
199 continue;
200 };
201 let Some(t) = t else {
202 if b.is_some() {
203 conflict(&id, "removed in file, modified at runtime".into());
204 journal.shift_remove(&id);
205 }
206 continue;
208 };
209 *created = false;
210 let keys: Vec<String> = changes.keys().cloned().collect();
211 for key in keys {
212 if !file_owned(&id, Some(&key)) {
213 continue;
214 }
215 let base_value = b.and_then(|b| b.options.get(&key));
216 let their_value = t.options.get(&key);
217 if base_value == their_value || their_value == changes[&key].as_ref() {
218 continue;
219 }
220 conflict(&id, format!("key \"{key}\" modified both in file and at runtime"));
221 changes.shift_remove(&key);
222 }
223 if let (Some(target), Some(b)) = (parent.as_ref(), b)
224 && t.parent != b.parent
225 && t.parent != *target
226 {
227 conflict(&id, "moved both in file and at runtime".into());
228 *parent = None;
229 }
230 let moved = parent.as_ref().is_some_and(|target| *target != t.parent);
231 if changes.is_empty() && !moved {
232 journal.shift_remove(&id);
233 }
234 }
235 conflicts
236}
237
238#[cfg(test)]
239mod tests {
240 use serde_json::json;
241
242 use super::*;
243
244 fn upsert(changes: Value, parent: Option<Option<&str>>, created: bool) -> Record {
245 let changes =
246 changes.as_object().unwrap().iter().map(|(k, v)| (k.clone(), (!v.is_null()).then(|| v.clone()))).collect();
247 Record::Upsert { created, parent: parent.map(|p| p.map(String::from)), position: 0, changes }
248 }
249
250 #[test]
251 fn merges_records() {
252 assert_eq!(merge_records(Some(upsert(json!({}), Some(None), true)), Record::Remove), None);
253 assert_eq!(merge_records(Some(upsert(json!({}), None, false)), Record::Remove), Some(Record::Remove));
254 assert_eq!(
255 merge_records(Some(Record::Remove), upsert(json!({ "a": 1 }), None, true)),
256 Some(upsert(json!({ "a": 1 }), None, false))
257 );
258 assert_eq!(
259 merge_records(
260 Some(upsert(json!({ "a": 1, "b": 1 }), Some(Some("g")), true)),
261 upsert(json!({ "b": 2 }), None, false)
262 ),
263 Some(upsert(json!({ "a": 1, "b": 2 }), Some(Some("g")), true))
264 );
265 }
266
267 #[test]
268 fn applies_a_journal() {
269 let data = vec![
270 json!({ "id": "a", "name": "foo" }),
271 json!({ "id": "g", "name": "group", "group": true, "config": [] }),
272 ];
273 let mut journal = Journal::new();
274 journal.insert("a".into(), upsert(json!({ "config": { "x": 1 } }), Some(Some("g")), false));
275 journal.insert("b".into(), upsert(json!({ "name": "bar" }), Some(None), true));
276 let result = apply_journal(data, &journal, |_, _| true, &|_| {});
277 assert_eq!(
278 result,
279 vec![
280 json!({ "id": "b", "name": "bar" }),
281 json!({ "id": "g", "name": "group", "group": true, "config": [{ "id": "a", "name": "foo", "config": { "x": 1 } }] }),
282 ]
283 );
284 }
285
286 #[test]
287 fn the_file_wins_conflicts() {
288 let base = flatten(&[json!({ "id": "a", "name": "foo", "config": 1 }), json!({ "id": "b", "name": "foo" })]);
289 let theirs = flatten(&[json!({ "id": "a", "name": "foo", "config": 2 })]);
290 let mut journal = Journal::new();
291 journal.insert("a".into(), upsert(json!({ "config": 3, "disabled": true }), None, false));
292 journal.insert("b".into(), upsert(json!({ "config": 3 }), None, false));
293 journal.insert("c".into(), upsert(json!({ "name": "new" }), Some(None), true));
294 let conflicts = reconcile(&mut journal, &base, &theirs, |_, _| true);
295 let reasons: Vec<_> = conflicts.iter().map(|c| format!("{}: {}", c.id, c.reason)).collect();
296 assert_eq!(
297 reasons,
298 vec!["a: key \"config\" modified both in file and at runtime", "b: removed in file, modified at runtime"]
299 );
300 assert_eq!(journal.keys().collect::<Vec<_>>(), vec!["a", "c"]);
301 assert_eq!(journal["a"], upsert(json!({ "disabled": true }), None, false));
302 }
303}