From 26ee2ff0199e7e8db1d64e315dfb052fd6aee44c Mon Sep 17 00:00:00 2001 From: Joscha Date: Mon, 7 Aug 2023 15:00:13 +0200 Subject: [PATCH] Process config before using it --- src/config.rs | 53 ++++++++++++++++++++++++++++------------- src/server/recurring.rs | 2 +- src/server/web.rs | 4 ++-- 3 files changed, 40 insertions(+), 19 deletions(-) diff --git a/src/config.rs b/src/config.rs index 5060035..d950ade 100644 --- a/src/config.rs +++ b/src/config.rs @@ -54,24 +54,14 @@ impl Default for Web { } } -impl Web { - pub fn base(&self) -> String { - self.base - .strip_suffix('/') - .unwrap_or(&self.base) - .to_string() - } -} - #[derive(Debug, Default, Deserialize)] -pub struct Config { - pub repo: Repo, - pub web: Web, +struct ConfigFile { + repo: Repo, + web: Web, } -impl Config { - pub fn load(path: &Path) -> somehow::Result { - info!(path = %path.display(), "Loading config"); +impl ConfigFile { + fn load(path: &Path) -> somehow::Result { let config = match fs::read_to_string(path) { Ok(str) => toml::from_str(&str)?, Err(e) if e.kind() == ErrorKind::NotFound => { @@ -81,7 +71,38 @@ impl Config { Err(e) => Err(e)?, }; - debug!("Loaded config:\n{config:#?}"); Ok(config) } + + fn web_base(&self) -> String { + self.web + .base + .strip_prefix('/') + .unwrap_or(&self.web.base) + .strip_suffix('/') + .unwrap_or(&self.web.base) + .to_string() + } +} + +pub struct Config { + pub repo_name: String, + pub repo_update_delay: Duration, + pub web_base: String, +} + +impl Config { + pub fn load(path: &Path) -> somehow::Result { + info!(path = %path.display(), "Loading config"); + let config_file = ConfigFile::load(path)?; + debug!("Loaded config file:\n{config_file:#?}"); + + let web_base = config_file.web_base(); + + Ok(Self { + repo_name: config_file.repo.name, + repo_update_delay: config_file.repo.update_delay, + web_base, + }) + } } diff --git a/src/server/recurring.rs b/src/server/recurring.rs index 5209499..32db6b7 100644 --- a/src/server/recurring.rs +++ b/src/server/recurring.rs @@ -31,6 +31,6 @@ async fn recurring_task(state: &Server) { pub async fn run(state: Server) { loop { recurring_task(&state).await; - tokio::time::sleep(state.config.repo.update_delay).await; + tokio::time::sleep(state.config.repo_update_delay).await; } } diff --git a/src/server/web.rs b/src/server/web.rs index 2f5d5b2..40f1dab 100644 --- a/src/server/web.rs +++ b/src/server/web.rs @@ -32,8 +32,8 @@ impl Base { Tab::Queue => "queue", }; Self { - root: config.web.base(), - repo_name: config.repo.name.clone(), + root: config.web_base.clone(), + repo_name: config.repo_name.clone(), current: current.to_string(), } }