Skip to content

Commit

Permalink
Add checks for empty config file.
Browse files Browse the repository at this point in the history
  • Loading branch information
Sven65 committed Nov 13, 2024
1 parent a46b4de commit aded1bc
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 9 deletions.
29 changes: 25 additions & 4 deletions crates/web-server/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,14 @@ pub struct Config {
pub setup: SetupConfig,
}

pub enum LoadConfigResult {
FileDoesNotExist,
CantReadFile,
FailedDeserialization,
FileEmpty,
Ok,
}

const CONFIG_FILE_PATH: &str = "Config.toml";

impl Config {
Expand Down Expand Up @@ -150,22 +158,35 @@ impl Config {
}
}

pub fn load_from_file(&mut self) {
pub fn load_from_file(&mut self) -> LoadConfigResult {
if let Ok(false) = fs::exists(CONFIG_FILE_PATH) {
panic!("Failed to load config file, as it does not exist.");
eprintln!("Failed to load config file, as it does not exist.");
return LoadConfigResult::FileDoesNotExist;
};

let file_content = match fs::read_to_string(CONFIG_FILE_PATH) {
Ok(content) => content,
Err(e) => panic!("Failed to read config file. {}", e)
Err(e) => {
eprintln!("Failed to read file {}", e);
return LoadConfigResult::CantReadFile
}
};

if file_content == "" {
return LoadConfigResult::FileEmpty
}

let config: Config = match toml::de::from_str(file_content.as_str()) {
Ok(config) => config,
Err(e) => panic!("Failed to deserialize config file: {}", e)
Err(e) => {
eprintln!("Failed to deserialize config file: {}", e);
return LoadConfigResult::FailedDeserialization
}
};

*self = config;

LoadConfigResult::Ok
}

pub fn set(&mut self, new: Config) {
Expand Down
13 changes: 8 additions & 5 deletions crates/web-server/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use axum::{
Extension, Router,
};
use common::GenericMessage;
use config::Config;
use config::{Config, LoadConfigResult};
use db::{
models::{Link, VerificationToken},
DbPool,
Expand Down Expand Up @@ -175,10 +175,13 @@ async fn main() {
env_logger::init();

let mut config = config::Config::new();

if config.file_exists() {
config.load_from_file();
}

let _ = if let true = config.file_exists() {
Some(config.load_from_file())
} else {
None
};


if !config.setup.setup_done {

Expand Down

0 comments on commit aded1bc

Please sign in to comment.