Move get_config into config module

This commit is contained in:
Elias Schriefer 2021-07-12 10:59:13 +02:00
parent e32c0e2a70
commit aa021a9754
2 changed files with 26 additions and 23 deletions

View File

@ -3,6 +3,11 @@ use serde::{
Serialize, Serialize,
}; };
use std::path::PathBuf; use std::path::PathBuf;
use tokio::{
fs::File,
io::AsyncReadExt,
};
use crate::cli::Options;
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
#[serde(default, rename_all = "kebab-case")] #[serde(default, rename_all = "kebab-case")]
@ -10,6 +15,25 @@ pub struct Config {
pub database_path: PathBuf, pub database_path: PathBuf,
} }
impl Config {
pub async fn get(options: &Options) -> std::io::Result<Self> {
if options.no_config {
Ok(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
)
)
}
}
}
impl Default for Config { impl Default for Config {
fn default() -> Self { fn default() -> Self {
Config { Config {

View File

@ -3,11 +3,7 @@ use std::{
boxed::Box, boxed::Box,
error::Error, error::Error,
}; };
use tokio::{ use tokio::sync::RwLock;
sync::RwLock,
fs::File,
io::AsyncReadExt,
};
use crate::{ use crate::{
cli::Options, cli::Options,
config::Config, config::Config,
@ -30,7 +26,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
return Ok(()); return Ok(());
} }
let mut config = get_config(&options).await?; let mut config = Config::get(&options).await?;
if clap_matches.is_present("database-path") { if clap_matches.is_present("database-path") {
config.database_path = options.database_path; config.database_path = options.database_path;
@ -46,21 +42,4 @@ async fn main() -> Result<(), Box<dyn Error>> {
sqlite::load_template(sqlite_connection.get_mut()).await?; sqlite::load_template(sqlite_connection.get_mut()).await?;
Ok(()) Ok(())
}
async fn get_config(options: &Options) -> std::io::Result<Config> {
if options.no_config {
Ok(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
)
)
}
} }