Skip to main content

yaml_subset/yaml/
document.rs

1use super::insert::Additive;
2use super::{HashData, HashElement, Yaml};
3use super::{Pretty, YamlInsert};
4use crate::YamlPath;
5use std::fmt::Write;
6
7#[derive(Debug, Clone, PartialEq)]
8pub enum DocumentData {
9    Comment(String),
10    Yaml(Yaml),
11}
12
13impl YamlInsert for DocumentData {
14    fn edit_hash_structure<F>(&mut self, path: &YamlPath, f: &F) -> usize
15    where
16        F: Fn(&mut Vec<HashData>, String, Option<usize>) -> usize,
17    {
18        match self {
19            DocumentData::Yaml(y) => y.edit_hash_structure(path, f),
20            _ => 0,
21        }
22    }
23    fn for_hash<F, R, A: Additive>(&mut self, path: &YamlPath, f: &F, r: &R) -> A
24    where
25        F: Fn(&mut HashElement) -> A,
26        R: Fn(&mut Yaml) -> A,
27    {
28        match self {
29            DocumentData::Yaml(y) => y.for_hash(path, f, r),
30            _ => A::zero(),
31        }
32    }
33}
34
35impl Pretty for DocumentData {
36    fn pretty_with_options(self, in_inline: bool, _child_of_array: bool) -> Self {
37        match self {
38            DocumentData::Comment(c) => DocumentData::Comment(c),
39            DocumentData::Yaml(c) => DocumentData::Yaml(c.pretty_with_options(in_inline, false)),
40        }
41    }
42}
43
44#[derive(Debug, Clone, PartialEq)]
45pub struct Document {
46    pub leading_comments: Vec<String>,
47    pub items: Vec<DocumentData>,
48}
49
50impl YamlInsert for Document {
51    fn edit_hash_structure<F>(&mut self, path: &YamlPath, f: &F) -> usize
52    where
53        F: Fn(&mut Vec<HashData>, String, Option<usize>) -> usize,
54    {
55        let mut count = 0;
56        for item in self.items.iter_mut() {
57            count += item.edit_hash_structure(path, f);
58        }
59        count
60    }
61    fn for_hash<F, R, A: Additive>(&mut self, path: &YamlPath, f: &F, r: &R) -> A
62    where
63        F: Fn(&mut HashElement) -> A,
64        R: Fn(&mut Yaml) -> A,
65    {
66        let mut count = A::zero();
67        for item in self.items.iter_mut() {
68            count = count + item.for_hash(path, f, r);
69        }
70        count
71    }
72}
73
74impl Document {
75    pub fn format(&self) -> Result<String, std::fmt::Error> {
76        let mut s = String::new();
77        for comment in self.leading_comments.iter() {
78            writeln!(&mut s, "#{}", comment)?;
79        }
80
81        write!(s, "---")?;
82        for item in self.items.iter() {
83            match item {
84                DocumentData::Comment(c) => write!(&mut s, "\n#{}", c),
85                DocumentData::Yaml(y) => y.format(&mut s, 0, None),
86            }?;
87        }
88        Ok(s)
89    }
90}
91
92impl Pretty for Document {
93    fn pretty_with_options(self, _in_inline: bool, _child_of_array: bool) -> Self {
94        Self {
95            leading_comments: self.leading_comments,
96            items: self.items.pretty_with_options(false, false),
97        }
98    }
99}