From 199e2169dca04fc1de6a5d99411f637355c5fd79 Mon Sep 17 00:00:00 2001 From: EliasSchriefer Date: Sat, 23 Oct 2021 17:59:17 +0200 Subject: [PATCH] Move config init completely into config module --- src/config.rs | 29 ++++++++++++++++++++++++----- src/main.rs | 21 ++++----------------- 2 files changed, 28 insertions(+), 22 deletions(-) diff --git a/src/config.rs b/src/config.rs index 6be34ad..ae43197 100644 --- a/src/config.rs +++ b/src/config.rs @@ -2,6 +2,10 @@ use serde::{ Deserialize, Serialize, }; +use structopt::{ + StructOpt, + clap::ArgMatches, +}; use std::{ net::IpAddr, path::PathBuf, @@ -21,21 +25,36 @@ pub struct Config { } impl Config { - pub async fn get(options: &Options) -> std::io::Result { - if options.no_config { - Ok(Config::default()) + pub async fn get_with_options(clap_matches: ArgMatches<'_>) -> std::io::Result<(Self, Options)> { + let options = Options::from_clap(&clap_matches); + let mut config = if options.no_config { + Config::default() } else { let mut config_file = File::open(&options.config).await?; let mut config_string = String::new(); config_file.read_to_string(&mut config_string).await?; - + toml::from_str(&config_string) .map_err(|err| std::io::Error::new( std::io::ErrorKind::InvalidData, err ) - ) + )? + }; + + if clap_matches.occurrences_of("database-path") > 0 { + config.database_path = options.database_path.clone(); } + + if clap_matches.occurrences_of("ip-address") > 0 { + config.ip_address = options.ip_address; + } + + if clap_matches.occurrences_of("port") > 0 { + config.port = options.port; + } + + Ok((config, options)) } } diff --git a/src/main.rs b/src/main.rs index 5401765..e14da41 100644 --- a/src/main.rs +++ b/src/main.rs @@ -31,28 +31,15 @@ const DEFAULT_PORT_STR: &'static str = "80"; #[tokio::main] async fn main() -> Result<(), Box> { - let clap_matches = Options::clap().get_matches(); - let options = Options::from_clap(&clap_matches); + let (config, options) = Config::get_with_options( + Options::clap().get_matches() + ).await?; if options.generate_config { - println!("{}", toml::to_string_pretty(&Config::default())?); + println!("{}", toml::to_string_pretty(&config)?); return Ok(()); } - let mut config = Config::get(&options).await?; - - if clap_matches.occurrences_of("database-path") > 0 { - config.database_path = options.database_path.clone(); - } - - if clap_matches.occurrences_of("ip-address") > 0 { - config.ip_address = options.ip_address; - } - - if clap_matches.occurrences_of("port") > 0 { - config.port = options.port; - } - dbg!(&config); #[cfg(feature = "sqlite")]