From f1d1636beeddd56635f248bd0eb2b5841c65f562 Mon Sep 17 00:00:00 2001 From: Lars Wirzenius Date: Sat, 6 Feb 2021 18:03:49 +0200 Subject: feat: make client config fields be optional, have defaults We don't want to require the user to have to specify every possible setting in client configuration files. Having reasonable defaults when possible is a better way. --- src/client.rs | 38 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 36 insertions(+), 2 deletions(-) diff --git a/src/client.rs b/src/client.rs index 7cd6df7..7a4ce21 100644 --- a/src/client.rs +++ b/src/client.rs @@ -17,16 +17,35 @@ use std::fs::File; use std::io::prelude::*; use std::path::{Path, PathBuf}; +const DEFAULT_CHUNK_SIZE: usize = 1024 * 1024; +const DEVNULL: &str = "/dev/null"; + +#[derive(Debug, Serialize, Deserialize, Clone)] +struct TentativeClientConfig { + server_url: String, + verify_tls_cert: Option, + chunk_size: Option, + root: PathBuf, + log: Option, +} + #[derive(Debug, Serialize, Deserialize, Clone)] pub struct ClientConfig { pub server_url: String, pub verify_tls_cert: bool, + pub chunk_size: usize, pub root: PathBuf, - pub log: Option, + pub log: PathBuf, } #[derive(Debug, thiserror::Error)] pub enum ClientConfigError { + #[error("server_url is empty")] + ServerUrlIsEmpty, + + #[error("backup root is unset or empty")] + NoBackupRoot, + #[error("server URL doesn't use https: {0}")] NotHttps(String), @@ -43,15 +62,30 @@ impl ClientConfig { pub fn read_config(filename: &Path) -> ClientConfigResult { trace!("read_config: filename={:?}", filename); let config = std::fs::read_to_string(filename)?; - let config: ClientConfig = serde_yaml::from_str(&config)?; + let tentative: TentativeClientConfig = serde_yaml::from_str(&config)?; + + let config = ClientConfig { + server_url: tentative.server_url, + root: tentative.root, + verify_tls_cert: tentative.verify_tls_cert.or(Some(false)).unwrap(), + chunk_size: tentative.chunk_size.or(Some(DEFAULT_CHUNK_SIZE)).unwrap(), + log: tentative.log.or(Some(PathBuf::from(DEVNULL))).unwrap(), + }; + config.check()?; Ok(config) } fn check(&self) -> Result<(), ClientConfigError> { + if self.server_url.is_empty() { + return Err(ClientConfigError::ServerUrlIsEmpty); + } if !self.server_url.starts_with("https://") { return Err(ClientConfigError::NotHttps(self.server_url.to_string())); } + if self.root.to_string_lossy().is_empty() { + return Err(ClientConfigError::NoBackupRoot); + } Ok(()) } } -- cgit v1.2.1