Skip to main content

crisol_core/spec/
patch.rs

1//! JSON-pointer patches that update a spec without rebuilding the UI.
2//!
3//! ```
4//! use crisol_core::spec::patch;
5//! ```
6
7use serde::{Deserialize, Serialize};
8use serde_json::Value;
9
10/// One host patch.
11#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
12#[serde(tag = "op", rename_all = "snake_case")]
13#[non_exhaustive]
14/// # Example
15///
16/// ```
17/// use crisol_core::spec::Patch;
18/// ```
19pub enum Patch {
20    /// Set an existing value (or create a missing object key).
21    Set {
22        /// JSON pointer such as `/widgets/0/text`.
23        path: String,
24        /// New value.
25        value: Value,
26    },
27    /// Replace an existing value.
28    Replace {
29        /// JSON pointer.
30        path: String,
31        /// New value.
32        value: Value,
33    },
34    /// Remove an object key or array element.
35    Remove {
36        /// JSON pointer.
37        path: String,
38    },
39    /// Append values to an array.
40    Append {
41        /// JSON pointer.
42        path: String,
43        /// Values to append.
44        values: Vec<Value>,
45    },
46    /// Apply several patches in order.
47    Batch {
48        /// The patches.
49        patches: Vec<Patch>,
50    },
51}
52
53impl Patch {
54    /// Apply to a JSON value.
55    ///
56    /// # Errors
57    /// When a path is missing or the parent is not an object/array.
58    pub fn apply(&self, root: &mut Value) -> Result<(), PatchError> {
59        match self {
60            Self::Set { path, value } | Self::Replace { path, value } => set(root, path, value.clone()),
61            Self::Remove { path } => remove(root, path),
62            Self::Append { path, values } => append(root, path, values.clone()),
63            Self::Batch { patches } => {
64                for patch in patches {
65                    patch.apply(root)?;
66                }
67                Ok(())
68            }
69        }
70    }
71}
72
73/// Why a patch could not be applied.
74#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
75#[non_exhaustive]
76/// # Example
77///
78/// ```
79/// use crisol_core::spec::PatchError;
80/// ```
81pub enum PatchError {
82    /// The path does not start with `/`.
83    #[error("invalid JSON pointer `{0}`")]
84    InvalidPointer(String),
85    /// The path does not exist.
86    #[error("missing path `{0}`")]
87    Missing(String),
88    /// The target is not an array.
89    #[error("`{0}` is not an array")]
90    NotArray(String),
91    /// An array index is out of range or not numeric.
92    #[error("bad array index in `{0}`")]
93    BadIndex(String),
94}
95
96fn tokens(path: &str) -> Result<Vec<String>, PatchError> {
97    if path.is_empty() {
98        return Ok(Vec::new());
99    }
100    if !path.starts_with('/') {
101        return Err(PatchError::InvalidPointer(path.to_owned()));
102    }
103    Ok(path
104        .split('/')
105        .skip(1)
106        .map(|token| token.replace("~1", "/").replace("~0", "~"))
107        .collect())
108}
109
110fn set(root: &mut Value, path: &str, value: Value) -> Result<(), PatchError> {
111    let tokens = tokens(path)?;
112    if tokens.is_empty() {
113        *root = value;
114        return Ok(());
115    }
116    let (last, parents) = tokens
117        .split_last()
118        .ok_or_else(|| PatchError::Missing(path.to_owned()))?;
119    let mut current = root;
120    for token in parents {
121        current = child_mut(current, token, path)?;
122    }
123    match current {
124        Value::Object(object) => {
125            object.insert(last.clone(), value);
126            Ok(())
127        }
128        Value::Array(array) => {
129            let index = last
130                .parse::<usize>()
131                .map_err(|_| PatchError::BadIndex(path.to_owned()))?;
132            let slot = array
133                .get_mut(index)
134                .ok_or_else(|| PatchError::Missing(path.to_owned()))?;
135            *slot = value;
136            Ok(())
137        }
138        _ => Err(PatchError::Missing(path.to_owned())),
139    }
140}
141
142fn remove(root: &mut Value, path: &str) -> Result<(), PatchError> {
143    let tokens = tokens(path)?;
144    let (last, parents) = tokens
145        .split_last()
146        .ok_or_else(|| PatchError::Missing(path.to_owned()))?;
147    let mut current = root;
148    for token in parents {
149        current = child_mut(current, token, path)?;
150    }
151    match current {
152        Value::Object(object) => object
153            .remove(last)
154            .map(|_| ())
155            .ok_or_else(|| PatchError::Missing(path.to_owned())),
156        Value::Array(array) => {
157            let index = last
158                .parse::<usize>()
159                .map_err(|_| PatchError::BadIndex(path.to_owned()))?;
160            if index >= array.len() {
161                return Err(PatchError::Missing(path.to_owned()));
162            }
163            array.remove(index);
164            Ok(())
165        }
166        _ => Err(PatchError::Missing(path.to_owned())),
167    }
168}
169
170fn append(root: &mut Value, path: &str, values: Vec<Value>) -> Result<(), PatchError> {
171    let tokens = tokens(path)?;
172    let mut current = root;
173    for token in &tokens {
174        current = child_mut(current, token, path)?;
175    }
176    let Value::Array(array) = current else {
177        return Err(PatchError::NotArray(path.to_owned()));
178    };
179    array.extend(values);
180    Ok(())
181}
182
183fn child_mut<'a>(current: &'a mut Value, token: &str, path: &str) -> Result<&'a mut Value, PatchError> {
184    match current {
185        Value::Object(object) => object
186            .get_mut(token)
187            .ok_or_else(|| PatchError::Missing(path.to_owned())),
188        Value::Array(array) => {
189            let index = token
190                .parse::<usize>()
191                .map_err(|_| PatchError::BadIndex(path.to_owned()))?;
192            array.get_mut(index).ok_or_else(|| PatchError::Missing(path.to_owned()))
193        }
194        _ => Err(PatchError::Missing(path.to_owned())),
195    }
196}
197
198#[cfg(test)]
199mod tests {
200    use super::*;
201    use serde_json::json;
202
203    #[test]
204    fn set_replace_remove_and_append() {
205        let mut value = json!({"widgets": [{"text": "a"}], "items": [1]});
206        Patch::Set {
207            path: "/widgets/0/text".to_owned(),
208            value: json!("b"),
209        }
210        .apply(&mut value)
211        .expect("set");
212        assert_eq!(value["widgets"][0]["text"], "b");
213        Patch::Append {
214            path: "/items".to_owned(),
215            values: vec![json!(2), json!(3)],
216        }
217        .apply(&mut value)
218        .expect("append");
219        assert_eq!(value["items"], json!([1, 2, 3]));
220        Patch::Remove {
221            path: "/items/0".to_owned(),
222        }
223        .apply(&mut value)
224        .expect("remove");
225        assert_eq!(value["items"], json!([2, 3]));
226        Patch::Batch {
227            patches: vec![
228                Patch::Set {
229                    path: "/new".to_owned(),
230                    value: json!(true),
231                },
232                Patch::Replace {
233                    path: "/new".to_owned(),
234                    value: json!(false),
235                },
236            ],
237        }
238        .apply(&mut value)
239        .expect("batch");
240        assert_eq!(value["new"], false);
241    }
242
243    #[test]
244    fn bad_paths_are_errors() {
245        let mut value = json!({"a": 1});
246        assert!(
247            Patch::Set {
248                path: "a".to_owned(),
249                value: json!(2)
250            }
251            .apply(&mut value)
252            .is_err()
253        );
254        assert!(
255            Patch::Append {
256                path: "/a".to_owned(),
257                values: vec![json!(2)]
258            }
259            .apply(&mut value)
260            .is_err()
261        );
262    }
263}