refactor Conf to be object oriented

This commit is contained in:
Marc Planard 2023-06-04 12:08:44 +02:00
parent 49830795e6
commit ec15004085
3 changed files with 16 additions and 13 deletions

View File

@ -16,11 +16,14 @@ pub struct Conf {
pub dac_id: Option<u8>, pub dac_id: Option<u8>,
pub dac_url: Option<String>, pub dac_url: Option<String>,
} }
pub fn load_config(path: &str) -> Result<Conf, Box<dyn std::error::Error>> {
impl Conf {
pub fn new(path: &str) -> Result<Conf, Box<dyn std::error::Error>> {
let settings = Config::builder() let settings = Config::builder()
.add_source(config::File::with_name(path)) .add_source(config::File::with_name(path))
.build()?; .build()?;
let conf : Conf = settings.try_deserialize()?; let conf : Conf = settings.try_deserialize()?;
Ok(conf) Ok(conf)
}
} }

View File

@ -18,7 +18,7 @@ use helios_dac::{
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc; use std::sync::Arc;
use redis_ctrl::{RedisCtrl,Order}; use redis_ctrl::{RedisCtrl,Order};
use conf::{load_config,Conf}; use conf::Conf;
use errors::LJError; use errors::LJError;
const CENTER : (u16,u16) = (2000, 2000); const CENTER : (u16,u16) = (2000, 2000);
@ -36,7 +36,7 @@ fn run_all() -> Result<(), Box<dyn std::error::Error>> {
let Some(filename) = std::env::args().nth(1) else { let Some(filename) = std::env::args().nth(1) else {
return Err(Box::new(LJError::ConfigFileMissing)); return Err(Box::new(LJError::ConfigFileMissing));
}; };
let config = load_config(&filename)?; let config = Conf::new(&filename)?;
let mut rs = RedisCtrl::new()?; let mut rs = RedisCtrl::new()?;
let running = Arc::new(AtomicBool::new(true)); let running = Arc::new(AtomicBool::new(true));

View File

@ -1,20 +1,20 @@
use lj_rust::conf::{load_config, DacFamily}; use lj_rust::conf::{Conf, DacFamily};
#[test] #[test]
fn it_loads_a_valid_conf() { fn it_loads_a_valid_conf() {
let result = load_config("tests/settings/valid"); let result = Conf::new("tests/settings/valid");
assert!(result.is_ok()); assert!(result.is_ok());
} }
#[test] #[test]
fn it_fails_invalid_conf() { fn it_fails_invalid_conf() {
let result = load_config("tests/settings/empty"); let result = Conf::new("tests/settings/empty");
assert!(result.is_err()); assert!(result.is_err());
} }
#[test] #[test]
fn it_finds_struct_fields() { fn it_finds_struct_fields() {
let config = match load_config("tests/settings/valid") { let config = match Conf::new("tests/settings/valid") {
Ok(c) => c, Ok(c) => c,
Err(err) => { Err(err) => {
panic!("Unable to load config file: {:?}", err) panic!("Unable to load config file: {:?}", err)