1mod errors;
30mod macros;
31
32use json_patch::patch;
33#[doc(no_inline)]
36pub use json_patch::{
37 AddOperation,
38 CopyOperation,
39 MoveOperation,
40 Patch,
41 PatchOperation,
42 RemoveOperation,
43 ReplaceOperation,
44 TestOperation,
45};
46#[doc(no_inline)]
47pub use jsonptr::index::Index;
48pub use jsonptr::resolve::ResolveError;
49pub use jsonptr::{
50 Pointer,
51 PointerBuf,
52 Token,
53};
54use serde_json::{
55 Value,
56 json,
57};
58
59pub use crate::errors::PatchError;
60
61pub mod prelude {
62 pub use super::{
63 AddOperation,
64 CopyOperation,
65 MoveOperation,
66 Patch,
67 PatchError,
68 PatchOperation,
69 Pointer,
70 PointerBuf,
71 RemoveOperation,
72 ReplaceOperation,
73 ResolveError,
74 TestOperation,
75 Token,
76 add_operation,
77 copy_operation,
78 escape,
79 format_ptr,
80 matches,
81 move_operation,
82 patch_ext,
83 remove_operation,
84 replace_operation,
85 test_operation,
86 };
87}
88
89#[derive(Debug, Clone, Copy)]
91enum PatchMode {
92 Error,
93 Create,
94 Skip,
95}
96
97pub fn add_operation(path: PointerBuf, value: Value) -> PatchOperation {
98 PatchOperation::Add(AddOperation { path, value })
99}
100
101pub fn copy_operation(from: PointerBuf, path: PointerBuf) -> PatchOperation {
102 PatchOperation::Copy(CopyOperation { from, path })
103}
104
105pub fn move_operation(from: PointerBuf, path: PointerBuf) -> PatchOperation {
106 PatchOperation::Move(MoveOperation { from, path })
107}
108
109pub fn remove_operation(path: PointerBuf) -> PatchOperation {
110 PatchOperation::Remove(RemoveOperation { path })
111}
112
113pub fn replace_operation(path: PointerBuf, value: Value) -> PatchOperation {
114 PatchOperation::Replace(ReplaceOperation { path, value })
115}
116
117pub fn test_operation(path: PointerBuf, value: Value) -> PatchOperation {
118 PatchOperation::Test(TestOperation { path, value })
119}
120
121pub fn escape(input: &str) -> String {
122 Token::new(input).encoded().into()
123}
124
125pub fn matches<'a>(path: &Pointer, value: &'a Value) -> Vec<(PointerBuf, &'a Value)> {
126 let Some(idx) = path.as_str().find("/*") else {
127 if let Ok(v) = path.resolve(value) {
130 return vec![(path.to_buf(), v)];
131 } else {
132 return vec![];
133 }
134 };
135
136 let (head, cons) = path.split_at(idx).unwrap();
138 let mut res = vec![];
139
140 let Ok(head_val) = head.resolve(value) else {
142 return vec![];
143 };
144 let Some(next_array_val) = head_val.as_array() else {
145 return vec![];
146 };
147
148 for (i, v) in next_array_val.iter().enumerate() {
149 let idx_str = format!("/{i}");
151 let idx_path = PointerBuf::parse(&idx_str).unwrap();
152
153 if let Some((_, c)) = cons.split_front() {
157 let subpaths = matches(c, v);
158 res.extend(subpaths.iter().map(|(p, v)| (head.concat(&idx_path.concat(p)), *v)));
159 } else {
160 unreachable!("cons can't be root");
161 }
162 }
163 res
164}
165
166pub fn patch_ext(obj: &mut Value, p: PatchOperation) -> Result<(), PatchError> {
167 match p {
168 PatchOperation::Add(op) => add_or_replace(obj, &op.path, &op.value, false)?,
169 PatchOperation::Remove(op) => remove(obj, &op.path)?,
170 PatchOperation::Replace(op) => add_or_replace(obj, &op.path, &op.value, true)?,
171 x => patch(obj, &[x])?,
172 }
173 Ok(())
174}
175
176fn add_or_replace(obj: &mut Value, path: &Pointer, value: &Value, replace: bool) -> Result<(), PatchError> {
177 let Some((subpath, tail)) = path.split_back() else {
178 return Ok(());
179 };
180
181 let mode = if replace { PatchMode::Error } else { PatchMode::Create };
184 for v in patch_ext_helper(subpath, obj, mode)? {
185 match v {
186 Value::Object(map) => {
187 let key = tail.decoded().into();
188 if replace && !map.contains_key(&key) {
189 return Err(PatchError::TargetDoesNotExist(path.to_string()));
190 }
191 map.insert(key, value.clone());
192 },
193 Value::Array(vec) => match tail.to_index()? {
194 Index::Num(idx) => {
195 vec.get(idx).ok_or(PatchError::OutOfBounds(idx))?;
196 if replace {
197 vec[idx] = value.clone();
198 } else {
199 vec.insert(idx, value.clone());
200 }
201 },
202 Index::Next => {
203 vec.push(value.clone());
204 },
205 },
206 _ => {
207 return Err(PatchError::UnexpectedType(path.to_string()));
208 },
209 }
210 }
211
212 Ok(())
213}
214
215fn remove(obj: &mut Value, path: &Pointer) -> Result<(), PatchError> {
216 let Some((subpath, key)) = path.split_back() else {
217 *obj = Value::Null;
218 return Ok(());
219 };
220
221 for v in patch_ext_helper(subpath, obj, PatchMode::Skip)? {
222 match v {
223 Value::Object(map) => {
224 map.remove(key.decoded().as_ref());
225 },
226 Value::Array(vec) => {
227 if key.decoded() == "*" {
228 vec.clear();
229 } else if let Index::Num(idx) = key.to_index()? {
230 vec.get(idx).ok_or(PatchError::OutOfBounds(idx))?;
231 vec.remove(idx);
232 } else {
233 return Err(PatchError::UnexpectedType(key.to_string()));
234 }
235 },
236 _ => {
237 return Err(PatchError::UnexpectedType(path.to_string()));
238 },
239 }
240 }
241
242 Ok(())
243}
244
245fn patch_ext_helper<'a>(
248 path: &Pointer,
249 value: &'a mut Value,
250 mode: PatchMode,
251) -> Result<Vec<&'a mut Value>, PatchError> {
252 let Some(idx) = path.as_str().find("/*") else {
253 if path.resolve(value).is_err() {
254 match mode {
255 PatchMode::Error => return Err(PatchError::TargetDoesNotExist(path.as_str().into())),
256 PatchMode::Create => {
257 path.assign(value, json!({}))?;
258 },
259 PatchMode::Skip => return Ok(vec![]),
260 }
261 }
262 return Ok(vec![path.resolve_mut(value)?]);
263 };
264
265 let (head, cons) = path.split_at(idx).unwrap();
267 let mut res = vec![];
268
269 if head.resolve(value).is_err() {
273 match mode {
274 PatchMode::Error => return Err(PatchError::TargetDoesNotExist(path.as_str().into())),
275 PatchMode::Create => {
276 path.assign(value, json!([]))?;
277 },
278 PatchMode::Skip => return Ok(vec![]),
279 }
280 }
281
282 let next_array_val =
284 head.resolve_mut(value)?.as_array_mut().ok_or(PatchError::UnexpectedType(head.as_str().into()))?;
285
286 for v in next_array_val {
288 if let Some((_, c)) = cons.split_front() {
292 res.extend(patch_ext_helper(c, v, mode)?);
293 } else {
294 unreachable!("cons can't be root");
295 }
296 }
297 Ok(res)
298}
299
300#[cfg(test)]
301mod tests {
302 use assertables::*;
303 use rstest::*;
304
305 use super::*;
306 use crate as json_patch_ext; #[fixture]
309 fn data() -> Value {
310 json!({
311 "foo": [
312 {"baz": {"buzz": 0}},
313 {"baz": {"quzz": 1}},
314 {"baz": {"fixx": 2}},
315 ],
316 })
317 }
318
319 #[rstest]
320 fn test_matches_1(data: Value) {
321 let path = format_ptr!("/foo");
322 let m: Vec<_> = matches(&path, &data).iter().map(|(p, _)| p.clone()).collect();
323 assert_eq!(m, vec![format_ptr!("/foo")]);
324 }
325
326 #[rstest]
327 fn test_matches_2(data: Value) {
328 let path = format_ptr!("/foo/*/baz");
329 let m: Vec<_> = matches(&path, &data).iter().map(|(p, _)| p.clone()).collect();
330 assert_eq!(m, vec![format_ptr!("/foo/0/baz"), format_ptr!("/foo/1/baz"), format_ptr!("/foo/2/baz")]);
331 }
332
333 #[rstest]
334 fn test_matches_3(data: Value) {
335 let path = format_ptr!("/foo/*");
336 let m: Vec<_> = matches(&path, &data).iter().map(|(p, _)| p.clone()).collect();
337 assert_eq!(m, vec![format_ptr!("/foo/0"), format_ptr!("/foo/1"), format_ptr!("/foo/2")]);
338 }
339
340 #[rstest]
341 #[case(format_ptr!("/foo/*/baz/fixx"))]
342 #[case(format_ptr!("/foo/2/baz/fixx"))]
343 fn test_matches_4(#[case] path: PointerBuf, data: Value) {
344 let m: Vec<_> = matches(&path, &data).iter().map(|(p, _)| p.clone()).collect();
345 assert_eq!(m, vec![format_ptr!("/foo/2/baz/fixx")]);
346 }
347
348 #[rstest]
349 fn test_matches_root() {
350 let path = format_ptr!("/*");
351 let data = json!(["foo", "bar"]);
352 let m: Vec<_> = matches(&path, &data).iter().map(|(p, _)| p.clone()).collect();
353 assert_eq!(m, vec![format_ptr!("/0"), format_ptr!("/1")]);
354 }
355
356 #[rstest]
357 #[case(format_ptr!("/*"))]
358 #[case(format_ptr!("/food"))]
359 #[case(format_ptr!("/foo/3/baz"))]
360 #[case(format_ptr!("/foo/bar/baz"))]
361 #[case(format_ptr!("/foo/0/baz/fixx"))]
362 fn test_no_match(#[case] path: PointerBuf, data: Value) {
363 let m = matches(&path, &data);
364 assert_is_empty!(m);
365 }
366
367 #[rstest]
368 fn test_patch_ext_add(mut data: Value) {
369 let path = format_ptr!("/foo/*/baz/buzz");
370 let res = patch_ext(&mut data, add_operation(path, json!(42)));
371 assert_ok!(res);
372 assert_eq!(
373 data,
374 json!({
375 "foo": [
376 {"baz": {"buzz": 42 }},
377 {"baz": {"quzz": 1, "buzz": 42}},
378 {"baz": {"fixx": 2, "buzz": 42}},
379 ],
380 })
381 );
382 }
383
384 #[rstest]
385 fn test_patch_ext_add_vec1(mut data: Value) {
386 let path = format_ptr!("/foo/1");
387 let res = patch_ext(&mut data, add_operation(path, json!(42)));
388 assert_ok!(res);
389 assert_eq!(
390 data,
391 json!({
392 "foo": [
393 {"baz": {"buzz": 0}},
394 42,
395 {"baz": {"quzz": 1}},
396 {"baz": {"fixx": 2}},
397 ],
398 })
399 );
400 }
401
402 #[rstest]
403 fn test_patch_ext_add_vec2(mut data: Value) {
404 let path = format_ptr!("/foo/-");
405 let res = patch_ext(&mut data, add_operation(path, json!(42)));
406 assert_ok!(res);
407 assert_eq!(
408 data,
409 json!({
410 "foo": [
411 {"baz": {"buzz": 0}},
412 {"baz": {"quzz": 1}},
413 {"baz": {"fixx": 2}},
414 42,
415 ],
416 })
417 );
418 }
419
420 #[rstest]
421 fn test_patch_ext_add_vec_err(mut data: Value) {
422 let path = format_ptr!("/foo/a");
423 let res = patch_ext(&mut data, add_operation(path, json!(42)));
424 assert_err!(res);
425 }
426
427 #[rstest]
428 fn test_patch_ext_add_escaped() {
429 let path = format_ptr!("/foo/bar/{}", escape("testing.sh/baz"));
430 let mut data = json!({});
431 let res = patch_ext(&mut data, add_operation(path, json!(42)));
432 assert_ok!(res);
433 assert_eq!(data, json!({"foo": {"bar": {"testing.sh/baz": 42}}}));
434 }
435
436 #[rstest]
437 fn test_patch_ext_replace(mut data: Value) {
438 let path = format_ptr!("/foo/*/baz");
439 let res = patch_ext(&mut data, replace_operation(path, json!(42)));
440 assert_ok!(res);
441 assert_eq!(
442 data,
443 json!({
444 "foo": [
445 {"baz": 42},
446 {"baz": 42},
447 {"baz": 42},
448 ],
449 })
450 );
451 }
452
453 #[rstest]
454 fn test_patch_ext_replace_vec1(mut data: Value) {
455 let path = format_ptr!("/foo/1");
456 let res = patch_ext(&mut data, replace_operation(path, json!(42)));
457 assert_ok!(res);
458 assert_eq!(
459 data,
460 json!({
461 "foo": [
462 {"baz": {"buzz": 0}},
463 42,
464 {"baz": {"fixx": 2}},
465 ],
466 })
467 );
468 }
469
470 #[rstest]
471 fn test_patch_ext_replace_vec2(mut data: Value) {
472 let path = format_ptr!("/foo/-");
473 let res = patch_ext(&mut data, replace_operation(path, json!(42)));
474 assert_ok!(res);
475 assert_eq!(
476 data,
477 json!({
478 "foo": [
479 {"baz": {"buzz": 0}},
480 {"baz": {"quzz": 1}},
481 {"baz": {"fixx": 2}},
482 42,
483 ],
484 })
485 );
486 }
487
488 #[rstest]
489 fn test_patch_ext_replace_err(mut data: Value) {
490 let path = format_ptr!("/foo/*/baz/buzz");
491 let res = patch_ext(&mut data, replace_operation(path, json!(42)));
492 assert_err!(res);
493 }
494
495 #[rstest]
496 fn test_patch_ext_remove_root(mut data: Value) {
497 let path = format_ptr!("");
498 let res = patch_ext(&mut data, remove_operation(path));
499 assert_ok!(res);
500 assert_eq!(data, json!(null));
501 }
502
503 #[rstest]
504 fn test_patch_ext_remove(mut data: Value) {
505 let path = format_ptr!("/foo/*/baz/quzz");
506 let res = patch_ext(&mut data, remove_operation(path));
507 assert_ok!(res);
508 assert_eq!(
509 data,
510 json!({
511 "foo": [
512 {"baz": {"buzz": 0}},
513 {"baz": {}},
514 {"baz": {"fixx": 2}},
515 ],
516 })
517 );
518 }
519
520 #[rstest]
521 fn test_patch_ext_remove_wildcard(mut data: Value) {
522 let path = format_ptr!("/foo/*");
523 let res = patch_ext(&mut data, remove_operation(path));
524 assert_ok!(res);
525 assert_eq!(data, json!({"foo": []}));
526 }
527
528 #[rstest]
529 fn test_patch_ext_remove_nested_wildcards() {
530 let mut data = json!([[
531 [{"bar": "baz"}, {"qwerty": "yuiop"}],
532 [{"fuzz": "quzz"}],
533 [{"asdf": "hjkl"}],
534 ]]);
535 let path = format_ptr!("/*/*/*");
536 let res = patch_ext(&mut data, remove_operation(path));
537 assert_ok!(res);
538 assert_eq!(data, json!([[[], [], []]]));
539 }
540
541 #[rstest]
542 fn test_patch_ext_remove_vec(mut data: Value) {
543 let path = format_ptr!("/foo/1");
544 let res = patch_ext(&mut data, remove_operation(path));
545 assert_ok!(res);
546 assert_eq!(
547 data,
548 json!({
549 "foo": [
550 {"baz": {"buzz": 0}},
551 {"baz": {"fixx": 2}},
552 ],
553 })
554 );
555 }
556
557 #[rstest]
558 fn test_patch_ext_remove_vec_err(mut data: Value) {
559 let path = format_ptr!("/foo/-");
560 let res = patch_ext(&mut data, remove_operation(path));
561 assert_err!(res);
562 }
563}