roezio/config: implement Config.new

Signed-off-by: Maxime “pep” Buquet <pep@bouah.net>
This commit is contained in:
Maxime “pep” Buquet 2022-08-25 11:29:37 +02:00
parent 937d30195b
commit bae5bdae98
Signed by: pep
GPG key ID: DEDA74AEECA9D0F2
2 changed files with 13 additions and 5 deletions

View file

@ -92,15 +92,18 @@ impl<'a> Config<'a> {
filename: P,
defaults: HashMap<&'a str, HashMap<&'a str, ConfigValue>>,
default_section: Option<&'a str>,
) -> Self {
// TODO: read ini file.
) -> Result<Self, Error> {
let filename: PathBuf = filename.into();
let mut ini = Ini::new();
ini.load(filename.clone())
.map_err(|_| Error::UnableToOpenConfigFile(filename.clone()))?;
Config {
filename: filename.into(),
Ok(Config {
filename,
defaults,
default_section: default_section.unwrap_or("default"),
ini: Ini::new(),
}
})
}
/// Sets a key/value pair in memory and updates the config file.

View file

@ -18,6 +18,7 @@ use crate::config::ConfigValue;
use std::error::Error as StdError;
use std::fmt;
use std::io;
use std::path::PathBuf;
#[derive(Debug)]
pub(crate) enum Error {
@ -25,6 +26,7 @@ pub(crate) enum Error {
UnableToCreateConfigDir,
InvalidConfigValueType(ConfigValue),
InvalidValueType(String),
UnableToOpenConfigFile(PathBuf),
}
impl fmt::Display for Error {
@ -34,6 +36,9 @@ impl fmt::Display for Error {
Error::UnableToCreateConfigDir => write!(f, "Unable to create config dir"),
Error::InvalidConfigValueType(err) => write!(f, "Invalid ConfigValue type: {}", err),
Error::InvalidValueType(err) => write!(f, "Invalid value type: {}", err),
Error::UnableToOpenConfigFile(err) => {
write!(f, "Unable to open config file: {}", err.display())
}
}
}
}