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, filename: P,
defaults: HashMap<&'a str, HashMap<&'a str, ConfigValue>>, defaults: HashMap<&'a str, HashMap<&'a str, ConfigValue>>,
default_section: Option<&'a str>, default_section: Option<&'a str>,
) -> Self { ) -> Result<Self, Error> {
// TODO: read ini file. let filename: PathBuf = filename.into();
let mut ini = Ini::new();
ini.load(filename.clone())
.map_err(|_| Error::UnableToOpenConfigFile(filename.clone()))?;
Config { Ok(Config {
filename: filename.into(), filename,
defaults, defaults,
default_section: default_section.unwrap_or("default"), default_section: default_section.unwrap_or("default"),
ini: Ini::new(), ini: Ini::new(),
} })
} }
/// Sets a key/value pair in memory and updates the config file. /// 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::error::Error as StdError;
use std::fmt; use std::fmt;
use std::io; use std::io;
use std::path::PathBuf;
#[derive(Debug)] #[derive(Debug)]
pub(crate) enum Error { pub(crate) enum Error {
@ -25,6 +26,7 @@ pub(crate) enum Error {
UnableToCreateConfigDir, UnableToCreateConfigDir,
InvalidConfigValueType(ConfigValue), InvalidConfigValueType(ConfigValue),
InvalidValueType(String), InvalidValueType(String),
UnableToOpenConfigFile(PathBuf),
} }
impl fmt::Display for Error { impl fmt::Display for Error {
@ -34,6 +36,9 @@ impl fmt::Display for Error {
Error::UnableToCreateConfigDir => write!(f, "Unable to create config dir"), Error::UnableToCreateConfigDir => write!(f, "Unable to create config dir"),
Error::InvalidConfigValueType(err) => write!(f, "Invalid ConfigValue type: {}", err), Error::InvalidConfigValueType(err) => write!(f, "Invalid ConfigValue type: {}", err),
Error::InvalidValueType(err) => write!(f, "Invalid value type: {}", err), Error::InvalidValueType(err) => write!(f, "Invalid value type: {}", err),
Error::UnableToOpenConfigFile(err) => {
write!(f, "Unable to open config file: {}", err.display())
}
} }
} }
} }