archival 0.14.0

The simplest CMS in existence
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
use crate::{
    fields::{meta::Meta, FieldType, FieldValue, MetaValue, ObjectValues},
    object::Object,
    ObjectDefinition,
};
use liquid::ValueView;
use serde::{Deserialize, Serialize};
use std::{collections::BTreeMap, fmt::Display};
use thiserror::Error;

#[derive(Error, Debug)]
pub enum ValuePathError {
    #[error("Child definition not found for path {0} in {1}")]
    ChildDefNotFound(ValuePath, String),
    #[error("Path {0} was not a children type in {1}")]
    NotChildren(ValuePath, String),
    #[error("Path {0} was not found in {1}")]
    NotFound(ValuePath, String),
    #[error("Child path was missing an index {0}")]
    ChildPathMissingIndex(String),
}

#[derive(Debug, Clone, Serialize, Deserialize, Hash, Eq, PartialEq)]
pub enum ValuePathComponent {
    Key(String),
    Index(usize),
}

impl ValuePathComponent {
    pub fn as_key(&self) -> Option<&String> {
        match self {
            ValuePathComponent::Key(k) => Some(k),
            ValuePathComponent::Index(_) => None,
        }
    }
    pub fn as_index(&self) -> Option<&usize> {
        match self {
            ValuePathComponent::Key(_) => None,
            ValuePathComponent::Index(i) => Some(i),
        }
    }
}

impl From<&String> for ValuePathComponent {
    fn from(value: &String) -> Self {
        ValuePath::key(value)
    }
}
impl From<usize> for ValuePathComponent {
    fn from(value: usize) -> Self {
        ValuePathComponent::Index(value)
    }
}

impl Display for ValuePathComponent {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ValuePathComponent::Index(i) => write!(f, "{}", i),
            ValuePathComponent::Key(k) => write!(f, "{}", k),
        }
    }
}

#[derive(Debug, Default, Clone, Hash, Eq, PartialEq)]
#[cfg_attr(feature = "typescript", derive(typescript_type_def::TypeDef))]
#[cfg_attr(feature = "typescript", serde(transparent))]
pub struct ValuePath(
    #[cfg_attr(feature = "typescript", type_def(type_of = "String"))] Vec<ValuePathComponent>,
);

impl ValuePath {
    pub fn key(name: impl AsRef<str>) -> ValuePathComponent {
        let name = name.as_ref();
        if name.contains(".") {
            panic!("ValuePathComponent Keys may not contain a dot")
        }
        ValuePathComponent::Key(name.to_string())
    }
    pub fn index(index: usize) -> ValuePathComponent {
        ValuePathComponent::Index(index)
    }
}

impl Display for ValuePath {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}",
            self.0
                .iter()
                .map(|p| format!("{}", p))
                .collect::<Vec<String>>()
                .join(".")
        )
    }
}

pub enum FoundValue<'a> {
    Meta(&'a MetaValue),
    String(&'a str),
}

impl Display for FoundValue<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::String(s) => write!(f, "{}", s),
            Self::Meta(mv) => write!(f, "{}", mv.render()),
        }
    }
}

impl FromIterator<ValuePathComponent> for ValuePath {
    fn from_iter<T: IntoIterator<Item = ValuePathComponent>>(iter: T) -> Self {
        Self(iter.into_iter().collect())
    }
}

pub struct ValuePathIterator {
    inner: std::vec::IntoIter<ValuePathComponent>,
}

impl Iterator for ValuePathIterator {
    type Item = ValuePathComponent;

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next()
    }
}
impl IntoIterator for ValuePath {
    type Item = ValuePathComponent;
    type IntoIter = ValuePathIterator;
    fn into_iter(self) -> Self::IntoIter {
        ValuePathIterator {
            inner: self.0.into_iter(),
        }
    }
}

impl ValuePath {
    pub fn empty() -> Self {
        Self(vec![])
    }
    pub fn from_string(string: &str) -> Self {
        let mut vpv: Vec<ValuePathComponent> = vec![];
        if !string.is_empty() {
            for part in string.split('.') {
                match part.parse::<usize>() {
                    Ok(index) => vpv.push(ValuePathComponent::Index(index)),
                    Err(_) => vpv.push(ValuePathComponent::Key(part.to_string())),
                }
            }
        }
        Self(vpv)
    }
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
    pub fn len(&self) -> usize {
        self.0.len()
    }

    pub fn child_name(&self) -> Option<&str> {
        let len = self.len();
        if len < 2 {
            None
        } else {
            let last_components = &self.0.as_slice()[len - 2..];
            if let ValuePathComponent::Key(child_name) = &last_components[0] {
                if matches!(last_components[1], ValuePathComponent::Index(_)) {
                    Some(child_name)
                } else {
                    None
                }
            } else {
                None
            }
        }
    }

    pub fn append(mut self, component: ValuePathComponent) -> Self {
        self.0.push(component);
        self
    }
    pub fn concat(mut self, path: ValuePath) -> Self {
        for p in path.0 {
            self = self.append(p);
        }
        self
    }

    pub fn first(&self) -> Option<&ValuePathComponent> {
        self.0.first()
    }

    pub fn unshift(&mut self) -> Option<ValuePathComponent> {
        if !self.0.is_empty() {
            Some(self.0.remove(0))
        } else {
            None
        }
    }

    pub fn without_first(&self) -> ValuePath {
        ValuePath(self.0[1..].to_vec())
    }
    pub fn without_last(&self) -> ValuePath {
        ValuePath(self.0[..1].to_vec())
    }

    pub fn pop(&mut self) -> Option<ValuePathComponent> {
        self.0.pop()
    }

    pub fn get_in_meta<'a>(&self, meta: &'a Meta) -> Option<&'a MetaValue> {
        let mut i_path = self.0.iter().map(|v| match v {
            ValuePathComponent::Index(i) => ValuePathComponent::Index(*i),
            ValuePathComponent::Key(k) => ValuePathComponent::Key(k.to_owned()),
        });
        let path = if let Some(ValuePathComponent::Key(k)) = i_path.next() {
            k
        } else {
            return None;
        };
        let mut last_val = meta.get_value(&path)?;
        for cmp in i_path {
            match cmp {
                ValuePathComponent::Index(i) => {
                    if let MetaValue::Array(a) = last_val {
                        if let Some(f) = a.get(i) {
                            last_val = f;
                            continue;
                        }
                    }
                    return None;
                }
                ValuePathComponent::Key(k) => match last_val {
                    MetaValue::Map(m) => {
                        if let Some(f) = m.get_value(&k) {
                            last_val = f;
                            continue;
                        }
                    }
                    _ => {
                        return None;
                    }
                },
            }
        }
        Some(last_val)
    }

    pub fn get_value<'a>(&self, field: &'a FieldValue) -> Result<FoundValue<'a>, ValuePathError> {
        let mut i_path = self.0.iter().map(|v| match v {
            ValuePathComponent::Index(i) => ValuePathComponent::Index(*i),
            ValuePathComponent::Key(k) => ValuePathComponent::Key(k.to_owned()),
        });
        let mut last_val = field;
        while let Some(cmp) = &i_path.next() {
            match cmp {
                ValuePathComponent::Index(i) => {
                    if let FieldValue::Objects(o) = field {
                        if let Some(v) = o.get(*i) {
                            if let Some(ValuePathComponent::Key(k)) = i_path.next() {
                                if let Some(fv) = v.get(&k) {
                                    last_val = fv;
                                    continue;
                                }
                            }
                        }
                    }
                    return Err(ValuePathError::NotFound(self.clone(), field.to_string()));
                }
                ValuePathComponent::Key(k) => match last_val {
                    FieldValue::Meta(m) => {
                        let c = cmp.clone();
                        return ValuePath::from_iter(vec![c].into_iter().chain(i_path))
                            .get_in_meta(m)
                            .map(FoundValue::Meta)
                            .ok_or_else(|| {
                                ValuePathError::NotFound(self.clone(), field.to_string())
                            });
                    }
                    FieldValue::File(f) => {
                        return f.get_key(k).map(FoundValue::String).ok_or_else(|| {
                            ValuePathError::NotFound(self.clone(), field.to_string())
                        })
                    }
                    _ => return Err(ValuePathError::NotFound(self.clone(), field.to_string())),
                },
            }
        }
        Err(ValuePathError::NotFound(self.clone(), field.to_string()))
    }

    pub fn get_in_object<'a>(&self, object: &'a Object) -> Option<&'a FieldValue> {
        let mut i_path = self.0.iter().map(|v| match v {
            ValuePathComponent::Index(i) => ValuePathComponent::Index(*i),
            ValuePathComponent::Key(k) => ValuePathComponent::Key(k.to_owned()),
        });
        let mut last_val = None;
        while let Some(cmp) = i_path.next() {
            if last_val.is_none() {
                // At the root, we must have a key string
                if let ValuePathComponent::Key(k) = cmp {
                    last_val = object.values.get(&k);
                    continue;
                }
            } else {
                // more than one level deep. We only allow accessing child
                // values, not children themselves - so this finds a child at
                // the index and then finds a key on it.
                if let Some(FieldValue::Objects(children)) = last_val {
                    if let ValuePathComponent::Index(index) = cmp {
                        if let Some(child) = children.get(index) {
                            if let Some(ValuePathComponent::Key(k)) = i_path.next() {
                                last_val = child.get(&k);
                                continue;
                            }
                        }
                    }
                }
            }
            break;
        }
        last_val
    }

    pub fn get_children<'a>(&self, object: &'a Object) -> Option<&'a Vec<ObjectValues>> {
        let mut i_path = self.0.iter().map(|v| match v {
            ValuePathComponent::Index(i) => ValuePathComponent::Index(*i),
            ValuePathComponent::Key(k) => ValuePathComponent::Key(k.to_owned()),
        });
        let mut last_val = &object.values;
        while let Some(cmp) = i_path.next() {
            if let ValuePathComponent::Key(key) = cmp {
                if let Some(FieldValue::Objects(children)) = last_val.get(&key) {
                    let next = i_path.next();
                    if next.is_none() {
                        // Reached the end of the path, return the
                        // children here.
                        return Some(children);
                    } else if let Some(ValuePathComponent::Index(k)) = next {
                        // Path continues, recurse.
                        if let Some(c) = children.get(k) {
                            last_val = c;
                            continue;
                        }
                    } else {
                        // Path continues but next item is not an index,
                        // so this is not a valid path. Return nothing.
                        return None;
                    }
                }
            }
            break;
        }
        None
    }

    pub fn get_object_values<'a>(&self, object: &'a Object) -> Option<&'a ObjectValues> {
        let mut i_path = self.0.iter().map(|v| match v {
            ValuePathComponent::Index(i) => ValuePathComponent::Index(*i),
            ValuePathComponent::Key(k) => ValuePathComponent::Key(k.to_owned()),
        });
        let mut last_val = &object.values;
        while let Some(cmp) = i_path.next() {
            if let ValuePathComponent::Key(k) = cmp {
                if let Some(FieldValue::Objects(children)) = last_val.get(&k) {
                    if let Some(ValuePathComponent::Index(idx)) = i_path.next() {
                        if let Some(child) = children.get(idx) {
                            last_val = child;
                        }
                    } else {
                        panic!("invalid value path {} for {:?}", self, object);
                    }
                } else {
                    return None;
                }
            } else {
                panic!("invalid value path {} for {:?}", self, object);
            }
        }
        Some(last_val)
    }

    pub fn get_field_definition<'a>(
        &self,
        def: &'a ObjectDefinition,
    ) -> Result<&'a FieldType, ValuePathError> {
        let mut current_def = def;
        for cmp in self.0.iter() {
            match cmp {
                ValuePathComponent::Key(k) => {
                    if let Some(field) = current_def.fields.get(k) {
                        return Ok(field);
                    } else if let Some(child) = current_def.children.get(k) {
                        current_def = child;
                        continue;
                    } else {
                        return Err(ValuePathError::NotFound(
                            self.clone(),
                            format!("{:?}", &def),
                        ));
                    }
                }
                ValuePathComponent::Index(_) => {
                    // Value Paths point to specific children, so when looking
                    // them up in definitions, we just skip over indexes.
                    continue;
                }
            }
        }
        Err(ValuePathError::NotFound(
            self.clone(),
            format!("{:?}", &def),
        ))
    }

    pub fn get_definition<'a>(
        &self,
        def: &'a ObjectDefinition,
    ) -> Result<&'a ObjectDefinition, ValuePathError> {
        let mut last_val = def;
        for cmp in self.0.iter() {
            match cmp {
                ValuePathComponent::Key(k) => {
                    if let Some(child_def) = last_val.children.get(k) {
                        last_val = child_def;
                        continue;
                    }
                }
                ValuePathComponent::Index(_) => {
                    // Skip indexes in definitions
                    continue;
                }
            }
            return Err(ValuePathError::ChildDefNotFound(
                self.clone(),
                format!("{:?}", def),
            ));
        }
        Ok(last_val)
    }

    pub fn add_child(
        &self,
        object: &mut Object,
        index: Option<usize>,
        modify: impl FnOnce(&mut BTreeMap<String, FieldValue>) -> Result<(), ValuePathError>,
    ) -> Result<usize, ValuePathError> {
        let mut new_child = BTreeMap::new();
        modify(&mut new_child)?;
        self.modify_children(object, |children| {
            if let Some(index) = index {
                children.insert(index, new_child);
                index
            } else {
                children.push(new_child);
                children.len() - 1
            }
        })
    }

    pub fn remove_child(&mut self, object: &mut Object) -> Result<(), ValuePathError> {
        if let Some(component) = self.pop() {
            match component {
                ValuePathComponent::Index(index) => self.modify_children(object, |children| {
                    children.remove(index);
                }),
                ValuePathComponent::Key(_) => Err(ValuePathError::ChildPathMissingIndex(
                    self.clone().append(component).to_string(),
                )),
            }
        } else {
            Err(ValuePathError::ChildPathMissingIndex(self.to_string()))
        }
    }
    pub fn modify_children<R>(
        &self,
        object: &mut Object,
        modify: impl FnOnce(&mut Vec<ObjectValues>) -> R,
    ) -> Result<R, ValuePathError> {
        let mut i_path = self.0.iter().map(|v| match v {
            ValuePathComponent::Index(i) => ValuePathComponent::Index(*i),
            ValuePathComponent::Key(k) => ValuePathComponent::Key(k.to_owned()),
        });
        let mut last_val = None;
        while let Some(cmp) = i_path.next() {
            if last_val.is_none() {
                // At the root, we must have a key string
                if let ValuePathComponent::Key(k) = cmp {
                    last_val = object.values.get_mut(&k);
                    continue;
                }
            } else {
                // more than one level deep. We only can recurse if there is an
                // objects value type.
                if let Some(FieldValue::Objects(children)) = last_val {
                    if let ValuePathComponent::Index(index) = cmp {
                        if let Some(child) = children.get_mut(index) {
                            if let Some(ValuePathComponent::Key(k)) = i_path.next() {
                                if child.contains_key(&k) {
                                    last_val = child.get_mut(&k);
                                    continue;
                                }
                            }
                        }
                    }
                }
            }
            return Err(ValuePathError::NotChildren(
                self.clone(),
                format!("{:?}", object),
            ));
        }
        if let Some(FieldValue::Objects(children)) = last_val {
            Ok(modify(children))
        } else {
            Err(ValuePathError::NotChildren(
                self.clone(),
                format!("{:?}", object),
            ))
        }
    }

    pub fn set_in_tree(
        &self,
        child: &mut BTreeMap<String, FieldValue>,
        value: Option<FieldValue>,
    ) -> Result<(), ValuePathError> {
        let mut path = self.0.clone();
        if let ValuePathComponent::Key(key) = path.remove(0) {
            if self.0.len() == 1 {
                // On the last node, either remove or set the value
                if let Some(value) = value {
                    child.insert(key, value);
                } else {
                    child.remove(&key);
                }
                return Ok(());
            } else if let Some(FieldValue::Objects(children)) = child.get_mut(&key) {
                if let ValuePathComponent::Index(idx) = path.remove(0) {
                    if let Some(child) = children.get_mut(idx) {
                        return ValuePath::from(path).set_in_tree(child, value);
                    }
                }
            }
        }
        Err(ValuePathError::NotFound(
            self.clone(),
            format!("{:?}", child),
        ))
    }

    pub fn set_in_object(
        &self,
        object: &mut Object,
        value: Option<FieldValue>,
    ) -> Result<(), ValuePathError> {
        let mut i_path = self.0.iter().map(|v| match v {
            ValuePathComponent::Index(i) => ValuePathComponent::Index(*i),
            ValuePathComponent::Key(k) => ValuePathComponent::Key(k.to_owned()),
        });
        let mut last_val = None;
        while let Some(cmp) = i_path.next() {
            if last_val.is_none() {
                // At the root, we must have a key string
                if let ValuePathComponent::Key(k) = cmp {
                    if i_path.len() > 0 {
                        last_val = object.values.get_mut(&k);
                        continue;
                    } else {
                        match value {
                            Some(value) => object.values.insert(k, value),
                            None => object.values.remove(&k),
                        };
                        break;
                    }
                }
            } else {
                // more than one level deep. We only allow accessing child
                // values, not children themselves - so this finds a child at
                // the index and then finds a key on it.
                if let Some(FieldValue::Objects(children)) = last_val {
                    if let ValuePathComponent::Index(index) = cmp {
                        while children.len() <= index {
                            // No child yet - since we're setting, insert one
                            // here.
                            children.push(ObjectValues::new());
                        }
                        let child = children.get_mut(index).unwrap();
                        ValuePath::from(i_path.collect::<Vec<ValuePathComponent>>())
                            .set_in_tree(child, value)?;
                    }
                }
            }
            break;
        }
        Ok(())
    }
}

impl From<&str> for ValuePath {
    fn from(value: &str) -> Self {
        Self::from_string(value)
    }
}
impl From<&String> for ValuePath {
    fn from(value: &String) -> Self {
        Self::from_string(value)
    }
}

impl From<Vec<ValuePathComponent>> for ValuePath {
    fn from(value: Vec<ValuePathComponent>) -> Self {
        Self(value)
    }
}

impl serde::Serialize for ValuePath {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(self.to_string().as_str())
    }
}
impl<'de> Deserialize<'de> for ValuePath {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s: String = Deserialize::deserialize(deserializer)?;
        Ok(Self::from_string(&s))
    }
}

#[cfg(test)]
pub mod tests {

    use super::*;
    use std::error::Error;

    fn object() -> Object {
        Object {
            filename: "test_filename".to_string(),
            object_name: "test_object_name".to_string(),
            order: None,
            path: "".to_string(),
            values: ObjectValues::from([
                ("title".to_string(), FieldValue::String("title".to_string())),
                ("children".to_string(), tree().remove("children").unwrap()),
            ]),
        }
    }

    fn tree() -> BTreeMap<String, FieldValue> {
        let mut tree = BTreeMap::new();
        tree.insert("foo".to_string(), FieldValue::String("bar".to_string()));
        tree.insert(
            "children".to_string(),
            FieldValue::Objects(vec![
                ObjectValues::from([(
                    "name".to_string(),
                    FieldValue::String("NAME ONE!".to_string()),
                )]),
                ObjectValues::from([(
                    "name".to_string(),
                    FieldValue::String("NAME TWO!".to_string()),
                )]),
            ]),
        );
        tree
    }

    #[test]
    fn get_object_values() -> Result<(), Box<dyn Error>> {
        let object = object();
        let child_vp = ValuePath::from_string("children.1");

        let children = child_vp.get_object_values(&object);
        println!("{:?}", children);
        assert!(children.is_some());

        Ok(())
    }

    #[test]
    fn set_in_tree_with_new_value() {
        let mut tree = tree();

        let vp = ValuePath::from_string("children.1.name");
        let new_val = FieldValue::String("NEW NAME".to_string());
        vp.set_in_tree(&mut tree, Some(new_val.clone())).unwrap();

        let children = tree.get("children").unwrap();
        assert!(matches!(children, FieldValue::Objects(_)));
        if let FieldValue::Objects(o) = children {
            let val = o[1].get("name");
            assert_eq!(val.unwrap(), &new_val);
        }
    }

    #[test]
    fn set_in_tree_with_none() {
        let mut tree = tree();

        let vp = ValuePath::from_string("children.1.name");
        vp.set_in_tree(&mut tree, None).unwrap();
        let children = tree.get("children").unwrap();
        assert!(matches!(children, FieldValue::Objects(_)));
        if let FieldValue::Objects(o) = children {
            assert!(!o[1].contains_key("name"));
        }
    }

    #[test]
    fn add_child() {
        let mut obj = object();

        let new_val = FieldValue::String("NEW NAME".to_string());
        let vp = ValuePath::from_string("children");
        let children = obj.values.get("children").unwrap();
        assert!(matches!(children, FieldValue::Objects(_)));
        let prev_len = if let FieldValue::Objects(o) = children {
            o.len()
        } else {
            panic!("not objects");
        };
        vp.add_child(&mut obj, None, |existing| {
            ValuePath::from_string("name").set_in_tree(existing, Some(new_val.clone()))
        })
        .unwrap();

        let children = obj.values.get("children").unwrap();
        assert!(matches!(children, FieldValue::Objects(_)));
        if let FieldValue::Objects(o) = children {
            assert_eq!(o.len(), prev_len + 1);
            let val = o.last().unwrap().get("name");
            assert_eq!(val.unwrap(), &new_val);
        }
    }

    #[derive(Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
    struct VPHolder {
        value_path: ValuePath,
    }

    #[test]
    fn serialize_deserialize() {
        let value_path = ValuePath::from_string("children.1.name.0.field");
        let holder = VPHolder { value_path };
        let json_string = serde_json::to_string(&holder).expect("serialization failed.");
        assert_eq!(json_string, r#"{"value_path":"children.1.name.0.field"}"#);
        let deserialized: VPHolder =
            serde_json::from_str(&json_string).expect("deserialization failed.");
        assert_eq!(holder, deserialized);
    }
}