Skip to main content

ostrya_core/config/
edit.rs

1//! The typed writes of the document of `config`.
2
3use std::marker::PhantomData;
4
5use super::{ConfigError, Group, Key, SingleKey, Value, ValueOf, lists, section_header};
6use crate::KeyFile;
7
8/// An edit of the document of `config`.
9///
10/// The edit changes the document in memory. It does no file I/O. Each write
11/// stores the text of [`Value::format`], and the other keys and groups keep
12/// their order and their text. A write takes each key of a single group,
13/// also a key that is not [`Settable`](super::Settable).
14///
15/// [`ConfigEdit::new`] gives an edit of a key file. In the `ostrya` crate,
16/// `UpdateGuard::edit_config` gives an edit of the document of `config`,
17/// and writes the edited document.
18pub struct ConfigEdit<'a> {
19    keyfile: &'a mut KeyFile,
20}
21
22impl<'a> ConfigEdit<'a> {
23    /// Returns an edit of `keyfile`.
24    ///
25    /// # Examples
26    ///
27    /// ```
28    /// use ostrya_core::KeyFile;
29    /// use ostrya_core::config::{ConfigEdit, ConfigError, ConfigView, repo};
30    ///
31    /// let mut kf = KeyFile::parse("[core]\nrepo_version=1\nmode=bare\n")?;
32    /// ConfigEdit::new(&mut kf).set::<repo::Fsync>(false)?;
33    /// assert_eq!(kf.get_value("core", "fsync"), Some("false"));
34    /// assert!(!ConfigView::new(&kf).get::<repo::Fsync>()?);
35    /// # Ok::<(), ConfigError>(())
36    /// ```
37    pub fn new(keyfile: &'a mut KeyFile) -> ConfigEdit<'a> {
38        ConfigEdit { keyfile }
39    }
40
41    /// Sets the key `K` of a single group to `value`.
42    ///
43    /// If the key is present, the new value replaces the old value at the
44    /// same position. If the key is absent, the call adds it at the end of
45    /// its group. If the group is absent, the call adds it at the end of the
46    /// document.
47    ///
48    /// # Errors
49    ///
50    /// [`ConfigError::Core`] if the text of the value cannot be in a key
51    /// file, for example a text with a line break. The document then does not
52    /// change.
53    pub fn set<K>(&mut self, value: ValueOf<K>) -> Result<(), ConfigError>
54    where
55        K: SingleKey + Key<<K as SingleKey>::Group>,
56    {
57        const { assert!(!<K as SingleKey>::Group::NAMED, "a key of a named group") };
58        set_key::<K::Group, K>(self.keyfile, <K as SingleKey>::Group::NAME, value)
59    }
60
61    /// Removes the key `K` of a single group, and returns `true` if the key
62    /// was present.
63    ///
64    /// The group stays, also when it loses its last key.
65    pub fn remove<K>(&mut self) -> bool
66    where
67        K: SingleKey + Key<<K as SingleKey>::Group>,
68    {
69        const { assert!(!<K as SingleKey>::Group::NAMED, "a key of a named group") };
70        remove_key::<K::Group, K>(self.keyfile, <K as SingleKey>::Group::NAME)
71    }
72
73    /// Returns the edit of the section `name` of the named group `G`.
74    ///
75    /// The call does not add the section. The first
76    /// [`set`](SectionMut::set) adds it at the end of the document.
77    ///
78    /// # Errors
79    ///
80    /// [`ConfigError::InvalidInput`] if `name` is empty, or holds `[`, `]`,
81    /// `"`, or a line break. A key file cannot hold such a group header, and
82    /// a read of a section does not take such a name.
83    pub fn section_mut<G: Group>(&mut self, name: &str) -> Result<SectionMut<'_, G>, ConfigError> {
84        const { assert!(G::NAMED, "a single group has no section") };
85        if name.is_empty() {
86            return Err(ConfigError::InvalidInput(format!(
87                "the section name of a [{} \"NAME\"] group is empty",
88                G::NAME
89            )));
90        }
91        if name.contains(['[', ']', '"', '\n', '\r']) {
92            return Err(ConfigError::InvalidInput(format!(
93                "the section name {name:?} of a [{} \"NAME\"] group holds '[', ']', '\"', or a \
94                 line break",
95                G::NAME
96            )));
97        }
98        Ok(SectionMut {
99            keyfile: self.keyfile,
100            header: section_header::<G>(name),
101            group: PhantomData,
102        })
103    }
104
105    /// Removes the section `name` of the named group `G` with its keys, and
106    /// returns `true` if the section was present.
107    pub fn remove_section<G: Group>(&mut self, name: &str) -> bool {
108        const { assert!(G::NAMED, "a single group has no section") };
109        self.keyfile.remove_group(&section_header::<G>(name))
110    }
111
112    /// Returns the document, for an edit that the typed writes do not cover.
113    pub fn keyfile_mut(&mut self) -> &mut KeyFile {
114        self.keyfile
115    }
116}
117
118/// The edit of one section of the named group `G`.
119///
120/// [`ConfigEdit::section_mut`] gives it.
121pub struct SectionMut<'e, G: Group> {
122    keyfile: &'e mut KeyFile,
123    /// The group header, `NAME "SECTION"`.
124    header: String,
125    group: PhantomData<fn() -> G>,
126}
127
128impl<G: Group> SectionMut<'_, G> {
129    /// Returns the name of the section.
130    pub fn name(&self) -> &str {
131        &self.header[G::NAME.len() + 2..self.header.len() - 1]
132    }
133
134    /// Sets the key `K` of the section to `value`.
135    ///
136    /// If the section is absent, the call adds it at the end of the
137    /// document. The key takes its position as
138    /// [`ConfigEdit::set`] states.
139    ///
140    /// # Errors
141    ///
142    /// [`ConfigError::Core`] if the text of the value cannot be in a key
143    /// file, for example a text with a line break. The document then does not
144    /// change.
145    pub fn set<K: Key<G>>(&mut self, value: K::Value) -> Result<(), ConfigError> {
146        set_key::<G, K>(self.keyfile, &self.header, value)
147    }
148
149    /// Removes the key `K` of the section, and returns `true` if the key was
150    /// present.
151    pub fn remove<K: Key<G>>(&mut self) -> bool {
152        remove_key::<G, K>(self.keyfile, &self.header)
153    }
154}
155
156/// Sets the key `K` in the group `header` of `keyfile` to `value`.
157fn set_key<G: Group, K: Key<G>>(
158    keyfile: &mut KeyFile,
159    header: &str,
160    value: K::Value,
161) -> Result<(), ConfigError> {
162    const {
163        assert!(
164            lists(G::KEYS, K::NAME),
165            "the key is not in the key list of its group"
166        )
167    };
168    keyfile.set_value(header, K::NAME, &value.format())?;
169    Ok(())
170}
171
172/// Removes the key `K` from the group `header` of `keyfile`.
173fn remove_key<G: Group, K: Key<G>>(keyfile: &mut KeyFile, header: &str) -> bool {
174    const {
175        assert!(
176            lists(G::KEYS, K::NAME),
177            "the key is not in the key list of its group"
178        )
179    };
180    keyfile.remove_key(header, K::NAME)
181}
182
183#[cfg(test)]
184mod tests {
185    use super::*;
186    use crate::config::GroupRef;
187    use crate::config::test_groups::{BASE, test_named};
188
189    #[test]
190    fn config_edit_writes_sections() {
191        let mut kf = KeyFile::parse(BASE).unwrap();
192        let mut edit = ConfigEdit::new(&mut kf);
193        let mut section = edit.section_mut::<test_named::Group>("n").unwrap();
194        assert_eq!(section.name(), "n");
195        section.set::<test_named::Arch>("amd64".to_owned()).unwrap();
196        section
197            .set::<test_named::Next>(GroupRef::new("m").unwrap())
198            .unwrap();
199        assert!(section.remove::<test_named::Next>());
200        assert!(!section.remove::<test_named::Next>());
201        assert!(edit.section_mut::<test_named::Group>("unused").is_ok());
202        for bad in ["", "a]b", "a[b", "a\"b", "a\nb"] {
203            assert!(
204                matches!(
205                    edit.section_mut::<test_named::Group>(bad),
206                    Err(ConfigError::InvalidInput(_))
207                ),
208                "{bad:?}"
209            );
210        }
211        assert_eq!(
212            kf.to_string(),
213            "[core]\nrepo_version=1\nmode=bare\n\n[ex-test n \"n\"]\narch=amd64\n"
214        );
215        let mut edit = ConfigEdit::new(&mut kf);
216        assert!(edit.remove_section::<test_named::Group>("n"));
217        assert!(!edit.remove_section::<test_named::Group>("n"));
218        assert_eq!(kf.to_string(), BASE);
219    }
220
221    #[test]
222    fn config_edit_escapes_a_value_and_refuses_a_quote_in_a_section_name() {
223        let mut kf = KeyFile::parse(BASE).unwrap();
224        let before = kf.clone();
225        let mut edit = ConfigEdit::new(&mut kf);
226        let mut section = edit.section_mut::<test_named::Group>("n").unwrap();
227        // `format` of a `String` escapes a line break, so a value with one
228        // is written.
229        section.set::<test_named::Arch>("a\nb".to_owned()).unwrap();
230        assert_eq!(kf.get_value("ex-test n \"n\"", "arch"), Some("a\\nb"));
231        let mut kf = before.clone();
232        let mut edit = ConfigEdit::new(&mut kf);
233        let err = edit.section_mut::<test_named::Group>("x\"y").err().unwrap();
234        assert_eq!(
235            err.to_string(),
236            "invalid input: the section name \"x\\\"y\" of a [ex-test n \"NAME\"] group holds \
237             '[', ']', '\"', or a line break"
238        );
239        assert_eq!(kf.to_string(), before.to_string());
240    }
241}