use std::marker::PhantomData;
use super::{ConfigError, Group, Key, Lookup, read_file, read_in_effect, refuse_unknown_keys};
use crate::KeyFile;
pub struct Section<'a, G: Group> {
keyfile: &'a KeyFile,
header: &'a str,
file: Option<&'a str>,
group: PhantomData<fn() -> G>,
}
impl<G: Group> Clone for Section<'_, G> {
fn clone(&self) -> Self {
Section {
keyfile: self.keyfile,
header: self.header,
file: self.file,
group: PhantomData,
}
}
}
impl<G: Group> std::fmt::Debug for Section<'_, G> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Section")
.field("header", &self.header)
.field("file", &self.file)
.finish()
}
}
impl<'a, G: Group> Section<'a, G> {
#[doc(hidden)]
pub fn from_parts(keyfile: &'a KeyFile, header: &'a str, file: Option<&'a str>) -> Self {
Section {
keyfile,
header,
file,
group: PhantomData,
}
}
#[doc(hidden)]
pub fn keyfile(&self) -> &'a KeyFile {
self.keyfile
}
#[doc(hidden)]
pub fn header(&self) -> &'a str {
self.header
}
pub fn name(&self) -> &'a str {
let header: &'a str = self.header;
header
.split_once('"')
.and_then(|(_, rest)| rest.strip_suffix('"'))
.unwrap_or_default()
}
pub fn source(&self) -> RemoteSource<'a> {
match self.file {
None => RemoteSource::Config,
Some(file) => RemoteSource::File(file),
}
}
pub fn get<K: Key<G>>(&self) -> Result<K::Output, ConfigError> {
read_in_effect::<G, K>(self.keyfile, self.header, None)
}
pub fn file_value<K: Key<G>>(&self) -> Result<Option<K::Value>, ConfigError> {
read_file::<G, K>(self.keyfile, self.header)
}
pub fn lookup<K: Key<G>>(&self) -> Result<Option<Lookup<K::Value>>, ConfigError> {
super::lookup::<G, K>(self.keyfile, self.header, None)
}
pub fn refuse_unknown_keys(&self) -> Result<(), ConfigError> {
refuse_unknown_keys::<G>(self.keyfile, self.header)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RemoteSource<'a> {
Config,
File(&'a str),
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::ConfigView;
use crate::config::test_groups::{BASE, test_named};
#[test]
fn the_source_of_a_section_names_its_file() {
let kf = KeyFile::parse(&format!("{BASE}[ex-test n \"a\"]\narch=amd64\n")).unwrap();
let a = ConfigView::new(&kf)
.section::<test_named::Group>("a")
.unwrap();
assert_eq!(a.source(), RemoteSource::Config);
assert_eq!(a.header(), "ex-test n \"a\"");
assert!(std::ptr::eq(a.keyfile(), &kf));
let a = Section::<test_named::Group>::from_parts(&kf, "ex-test n \"a\"", Some("a.conf"));
assert_eq!(a.source(), RemoteSource::File("a.conf"));
assert_eq!(a.name(), "a");
assert_eq!(a.get::<test_named::Arch>().unwrap(), "amd64");
let copy = a.clone();
assert_eq!(copy.source(), RemoteSource::File("a.conf"));
assert_eq!(
format!("{copy:?}"),
"Section { header: \"ex-test n \\\"a\\\"\", file: Some(\"a.conf\") }"
);
}
}