Move config init completely into config module

This commit is contained in:
Elias Schriefer 2021-10-23 17:59:17 +02:00
parent cc2a453c97
commit 199e2169dc
2 changed files with 28 additions and 22 deletions

View File

@ -2,6 +2,10 @@ use serde::{
Deserialize, Deserialize,
Serialize, Serialize,
}; };
use structopt::{
StructOpt,
clap::ArgMatches,
};
use std::{ use std::{
net::IpAddr, net::IpAddr,
path::PathBuf, path::PathBuf,
@ -21,21 +25,36 @@ pub struct Config {
} }
impl Config { impl Config {
pub async fn get(options: &Options) -> std::io::Result<Self> { pub async fn get_with_options(clap_matches: ArgMatches<'_>) -> std::io::Result<(Self, Options)> {
if options.no_config { let options = Options::from_clap(&clap_matches);
Ok(Config::default()) let mut config = if options.no_config {
Config::default()
} else { } else {
let mut config_file = File::open(&options.config).await?; let mut config_file = File::open(&options.config).await?;
let mut config_string = String::new(); let mut config_string = String::new();
config_file.read_to_string(&mut config_string).await?; config_file.read_to_string(&mut config_string).await?;
toml::from_str(&config_string) toml::from_str(&config_string)
.map_err(|err| std::io::Error::new( .map_err(|err| std::io::Error::new(
std::io::ErrorKind::InvalidData, std::io::ErrorKind::InvalidData,
err 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))
} }
} }

View File

@ -31,28 +31,15 @@ const DEFAULT_PORT_STR: &'static str = "80";
#[tokio::main] #[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> { async fn main() -> Result<(), Box<dyn Error>> {
let clap_matches = Options::clap().get_matches(); let (config, options) = Config::get_with_options(
let options = Options::from_clap(&clap_matches); Options::clap().get_matches()
).await?;
if options.generate_config { if options.generate_config {
println!("{}", toml::to_string_pretty(&Config::default())?); println!("{}", toml::to_string_pretty(&config)?);
return Ok(()); 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); dbg!(&config);
#[cfg(feature = "sqlite")] #[cfg(feature = "sqlite")]