use super::{
ConfigError, Group, Key, Lookup, OutputOf, Section, SingleKey, ValueOf, is_section_name,
lookup, read_file, read_in_effect, refuse_unknown_keys, section_header, section_name,
};
use crate::KeyFile;
#[derive(Debug, Clone, Copy)]
pub struct ConfigView<'a> {
keyfile: &'a KeyFile,
}
impl<'a> ConfigView<'a> {
pub fn new(keyfile: &'a KeyFile) -> ConfigView<'a> {
ConfigView { keyfile }
}
pub fn get<K>(&self) -> Result<OutputOf<K>, ConfigError>
where
K: SingleKey + Key<<K as SingleKey>::Group>,
{
const { assert!(!<K as SingleKey>::Group::NAMED, "a key of a named group") };
read_in_effect::<K::Group, K>(self.keyfile, <K as SingleKey>::Group::NAME, None)
}
pub fn file_value<K>(&self) -> Result<Option<ValueOf<K>>, ConfigError>
where
K: SingleKey + Key<<K as SingleKey>::Group>,
{
const { assert!(!<K as SingleKey>::Group::NAMED, "a key of a named group") };
read_file::<K::Group, K>(self.keyfile, <K as SingleKey>::Group::NAME)
}
pub fn lookup<K>(&self) -> Result<Option<Lookup<ValueOf<K>>>, ConfigError>
where
K: SingleKey + Key<<K as SingleKey>::Group>,
{
const { assert!(!<K as SingleKey>::Group::NAMED, "a key of a named group") };
lookup::<K::Group, K>(self.keyfile, <K as SingleKey>::Group::NAME, None)
}
pub fn section<G: Group>(&self, name: &str) -> Option<Section<'a, G>> {
const { assert!(G::NAMED, "a single group has no section") };
if !is_section_name(name) {
return None;
}
let keyfile: &'a KeyFile = self.keyfile;
let header = keyfile.group_name(§ion_header::<G>(name))?;
Some(Section::from_parts(keyfile, header, None))
}
pub fn sections<G: Group>(&self) -> impl Iterator<Item = Section<'a, G>> + use<'a, G> {
const { assert!(G::NAMED, "a single group has no section") };
let keyfile: &'a KeyFile = self.keyfile;
keyfile.groups().filter_map(move |header| {
section_name::<G>(header)?;
Some(Section::from_parts(keyfile, header, None))
})
}
pub fn refuse_unknown_keys<G: Group>(&self) -> Result<(), ConfigError> {
if !G::CLOSED {
return Ok(());
}
if !G::NAMED {
return refuse_unknown_keys::<G>(self.keyfile, G::NAME);
}
self.keyfile
.groups()
.filter(|header| section_name::<G>(header).is_some())
.try_for_each(|header| refuse_unknown_keys::<G>(self.keyfile, header))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::test_groups::{BASE, test_named, test_single};
use crate::config::{GroupRef, repo};
#[test]
fn a_view_reads_single_keys_with_their_source() {
let kf = KeyFile::parse(&format!("{BASE}fsync=false\n[ex-test]\njobs=8\n")).unwrap();
let view = ConfigView::new(&kf);
assert!(!view.get::<repo::Fsync>().unwrap());
assert_eq!(view.file_value::<repo::Fsync>().unwrap(), Some(false));
assert_eq!(
view.lookup::<repo::Fsync>().unwrap(),
Some(Lookup::File(false))
);
assert!(view.get::<repo::Locking>().unwrap());
assert_eq!(view.file_value::<repo::Locking>().unwrap(), None);
assert_eq!(
view.lookup::<repo::Locking>().unwrap(),
Some(Lookup::Default(true))
);
assert_eq!(view.get::<repo::CollectionId>().unwrap(), None);
assert_eq!(view.lookup::<repo::CollectionId>().unwrap(), None);
assert_eq!(view.get::<test_single::Jobs>().unwrap(), 8);
assert_eq!(view.get::<test_single::Name>().unwrap(), None);
}
#[test]
fn a_view_gives_the_sections_of_a_named_group_in_the_order_of_the_file() {
let kf = KeyFile::parse(&format!(
"{BASE}[ex-test n \"b\"]\narch=arm64\nnext=a\n\
[remote \"o\"]\nurl=http://o/\n\
[ex-test n \"a\"]\narch=amd64\ntags=x;y;\n\
[ex-test n \"\"]\narch=amd64\n\
[ex-test n \"x\" \"y\"]\narch=amd64\n\
[ex-test n \"c\"]\ntags=z\n\
[ex-test nx \"d\"]\narch=amd64\n"
))
.unwrap();
let view = ConfigView::new(&kf);
let names: Vec<_> = view
.sections::<test_named::Group>()
.map(|s| s.name())
.collect();
assert_eq!(names, ["b", "a", "c"]);
assert!(view.section::<test_named::Group>("absent").is_none());
assert!(view.section::<test_named::Group>("").is_none());
assert!(view.section::<test_named::Group>("x\" \"y").is_none());
let b = view.section::<test_named::Group>("b").unwrap();
assert_eq!(b.name(), "b");
assert_eq!(b.get::<test_named::Arch>().unwrap(), "arm64");
assert_eq!(b.get::<test_named::Tags>().unwrap(), Vec::<String>::new());
assert_eq!(
b.lookup::<test_named::Tags>().unwrap(),
Some(Lookup::Default(Vec::new()))
);
assert_eq!(b.file_value::<test_named::Tags>().unwrap(), None);
assert_eq!(
b.get::<test_named::Next>().unwrap(),
Some(GroupRef::new("a").unwrap())
);
let a = view.section::<test_named::Group>("a").unwrap();
assert_eq!(a.get::<test_named::Tags>().unwrap(), ["x", "y"]);
assert_eq!(
a.lookup::<test_named::Tags>().unwrap(),
Some(Lookup::File(vec!["x".to_owned(), "y".to_owned()]))
);
let c = view.section::<test_named::Group>("c").unwrap();
let err = c.get::<test_named::Arch>().unwrap_err();
assert!(matches!(err, ConfigError::InvalidFormat(_)));
assert_eq!(
err.to_string(),
"invalid format: [ex-test n \"c\"] has no arch"
);
assert_eq!(c.lookup::<test_named::Arch>().unwrap(), None);
}
#[test]
fn a_view_read_names_the_group_header_in_an_error() {
let kf = KeyFile::parse(&format!(
"{BASE}[ex-test]\njobs=-1\n[ex-test n \"a\"]\narch=amd64\nnext=\n\
[ex-test n \"b\"]\narch=\\q\n"
))
.unwrap();
let view = ConfigView::new(&kf);
assert_eq!(
view.get::<test_single::Jobs>().unwrap_err().to_string(),
"invalid format: [ex-test] jobs -1 is out of the range 0-4294967295"
);
let a = view.section::<test_named::Group>("a").unwrap();
assert_eq!(
a.get::<test_named::Next>().unwrap_err().to_string(),
"invalid format: [ex-test n \"a\"] next is empty"
);
let b = view.section::<test_named::Group>("b").unwrap();
assert_eq!(
b.get::<test_named::Arch>().unwrap_err().to_string(),
r"keyfile: invalid escape '\q'"
);
crate::config_group! {
pub group flags = named "ex-flags" {
On: Option<bool> = "on";
}
}
let kf = KeyFile::parse(&format!("{BASE}[ex-flags \"s\"]\non=x\n")).unwrap();
let err = ConfigView::new(&kf)
.section::<flags::Group>("s")
.unwrap()
.get::<flags::On>()
.unwrap_err();
assert!(matches!(err, ConfigError::Core(_)));
assert_eq!(
err.to_string(),
"keyfile: value 'x' for ex-flags \"s\".on is not a boolean"
);
}
#[test]
fn a_view_refuses_an_unknown_key_of_a_closed_group() {
let kf = KeyFile::parse(&format!(
"{BASE}zzz=1\n[ex-test]\njobs=1\n\
[ex-test n \"a\"]\narch=amd64\n[ex-test n \"\"]\nyyy=1\n"
))
.unwrap();
let view = ConfigView::new(&kf);
view.refuse_unknown_keys::<test_single::Group>().unwrap();
view.refuse_unknown_keys::<test_named::Group>().unwrap();
view.refuse_unknown_keys::<repo::Group>().unwrap();
let kf = KeyFile::parse(&format!(
"{BASE}[ex-test]\njobs=1\nzzz=1\n\
[ex-test n \"a\"]\narch=amd64\n[ex-test n \"b\"]\nyyy=1\nxxx=1\n"
))
.unwrap();
let view = ConfigView::new(&kf);
let err = view
.refuse_unknown_keys::<test_single::Group>()
.unwrap_err();
assert!(matches!(err, ConfigError::InvalidFormat(_)));
assert_eq!(
err.to_string(),
"invalid format: [ex-test] holds the unknown key 'zzz'"
);
assert_eq!(
view.refuse_unknown_keys::<test_named::Group>()
.unwrap_err()
.to_string(),
"invalid format: [ex-test n \"b\"] holds the unknown key 'yyy'"
);
let a = view.section::<test_named::Group>("a").unwrap();
a.refuse_unknown_keys().unwrap();
let b = view.section::<test_named::Group>("b").unwrap();
assert_eq!(
b.refuse_unknown_keys().unwrap_err().to_string(),
"invalid format: [ex-test n \"b\"] holds the unknown key 'yyy'"
);
}
}