use std::marker::PhantomData;
use ostrya_core::KeyFile;
use super::section::section_header;
use super::typed::{ValueOf, lists};
use super::value::Value;
use super::{Group, Key, SingleKey};
use crate::error::{Error, Result};
pub struct ConfigEdit<'a> {
keyfile: &'a mut KeyFile,
}
impl<'a> ConfigEdit<'a> {
pub(crate) fn new(keyfile: &'a mut KeyFile) -> ConfigEdit<'a> {
ConfigEdit { keyfile }
}
pub fn set<K>(&mut self, value: ValueOf<K>) -> Result<()>
where
K: SingleKey + Key<<K as SingleKey>::Group>,
{
const { assert!(!<K as SingleKey>::Group::NAMED, "a key of a named group") };
set_key::<K::Group, K>(self.keyfile, <K as SingleKey>::Group::NAME, value)
}
pub fn remove<K>(&mut self) -> bool
where
K: SingleKey + Key<<K as SingleKey>::Group>,
{
const { assert!(!<K as SingleKey>::Group::NAMED, "a key of a named group") };
remove_key::<K::Group, K>(self.keyfile, <K as SingleKey>::Group::NAME)
}
pub fn section_mut<G: Group>(&mut self, name: &str) -> Result<SectionMut<'_, G>> {
const { assert!(G::NAMED, "a single group has no section") };
if name.is_empty() {
return Err(Error::InvalidInput(format!(
"the section name of a [{} \"NAME\"] group is empty",
G::NAME
)));
}
if name.contains(['[', ']', '"', '\n', '\r']) {
return Err(Error::InvalidInput(format!(
"the section name {name:?} of a [{} \"NAME\"] group holds '[', ']', '\"', or a \
line break",
G::NAME
)));
}
Ok(SectionMut {
keyfile: self.keyfile,
header: section_header::<G>(name),
group: PhantomData,
})
}
pub fn remove_section<G: Group>(&mut self, name: &str) -> bool {
const { assert!(G::NAMED, "a single group has no section") };
self.keyfile.remove_group(§ion_header::<G>(name))
}
pub fn keyfile_mut(&mut self) -> &mut KeyFile {
self.keyfile
}
}
pub struct SectionMut<'e, G: Group> {
keyfile: &'e mut KeyFile,
header: String,
group: PhantomData<fn() -> G>,
}
impl<G: Group> SectionMut<'_, G> {
pub fn name(&self) -> &str {
&self.header[G::NAME.len() + 2..self.header.len() - 1]
}
pub fn set<K: Key<G>>(&mut self, value: K::Value) -> Result<()> {
set_key::<G, K>(self.keyfile, &self.header, value)
}
pub fn remove<K: Key<G>>(&mut self) -> bool {
remove_key::<G, K>(self.keyfile, &self.header)
}
}
fn set_key<G: Group, K: Key<G>>(
keyfile: &mut KeyFile,
header: &str,
value: K::Value,
) -> Result<()> {
const {
assert!(
lists(G::KEYS, K::NAME),
"the key is not in the key list of its group"
)
};
keyfile.set_value(header, K::NAME, &value.format())?;
Ok(())
}
fn remove_key<G: Group, K: Key<G>>(keyfile: &mut KeyFile, header: &str) -> bool {
const {
assert!(
lists(G::KEYS, K::NAME),
"the key is not in the key list of its group"
)
};
keyfile.remove_key(header, K::NAME)
}