ostrya_core/config/
edit.rs1use std::marker::PhantomData;
4
5use super::{ConfigError, Group, Key, SingleKey, Value, ValueOf, lists, section_header};
6use crate::KeyFile;
7
8pub struct ConfigEdit<'a> {
19 keyfile: &'a mut KeyFile,
20}
21
22impl<'a> ConfigEdit<'a> {
23 pub fn new(keyfile: &'a mut KeyFile) -> ConfigEdit<'a> {
38 ConfigEdit { keyfile }
39 }
40
41 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 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 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 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(§ion_header::<G>(name))
110 }
111
112 pub fn keyfile_mut(&mut self) -> &mut KeyFile {
114 self.keyfile
115 }
116}
117
118pub struct SectionMut<'e, G: Group> {
122 keyfile: &'e mut KeyFile,
123 header: String,
125 group: PhantomData<fn() -> G>,
126}
127
128impl<G: Group> SectionMut<'_, G> {
129 pub fn name(&self) -> &str {
131 &self.header[G::NAME.len() + 2..self.header.len() - 1]
132 }
133
134 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 pub fn remove<K: Key<G>>(&mut self) -> bool {
152 remove_key::<G, K>(self.keyfile, &self.header)
153 }
154}
155
156fn 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
172fn 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 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}