From 2afda17d4b13e828b31a0a15fb44a1837e2a80cf Mon Sep 17 00:00:00 2001 From: Joscha Date: Sun, 30 Apr 2023 22:51:28 +0200 Subject: [PATCH] Improve config loading error handling --- Cargo.lock | 1 + cove-config/Cargo.toml | 1 + cove-config/src/lib.rs | 26 ++++++++++++++++---------- cove/src/main.rs | 2 +- 4 files changed, 19 insertions(+), 11 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ab7cc05..234a1cd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -284,6 +284,7 @@ dependencies = [ "cove-input", "cove-macro", "serde", + "thiserror", "toml", ] diff --git a/cove-config/Cargo.toml b/cove-config/Cargo.toml index 252e228..a5bb70b 100644 --- a/cove-config/Cargo.toml +++ b/cove-config/Cargo.toml @@ -8,5 +8,6 @@ cove-input = { path = "../cove-input" } cove-macro = { path = "../cove-macro" } serde = { workspace = true } +thiserror = { workspace = true } toml = "0.7.3" diff --git a/cove-config/src/lib.rs b/cove-config/src/lib.rs index 6d00391..d2a773a 100644 --- a/cove-config/src/lib.rs +++ b/cove-config/src/lib.rs @@ -13,8 +13,9 @@ pub mod doc; mod euph; mod keys; -use std::fs; +use std::io::ErrorKind; use std::path::{Path, PathBuf}; +use std::{fs, io}; use doc::Document; use serde::Deserialize; @@ -22,6 +23,14 @@ use serde::Deserialize; pub use crate::euph::*; pub use crate::keys::*; +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("failed to read config file")] + Io(#[from] io::Error), + #[error("failed to parse config file")] + Toml(#[from] toml::de::Error), +} + #[derive(Debug, Default, Deserialize, Document)] pub struct Config { /// The directory that cove stores its data in when not running in ephemeral @@ -90,15 +99,12 @@ pub struct Config { } impl Config { - pub fn load(path: &Path) -> Self { - let Ok(content) = fs::read_to_string(path) else { return Self::default(); }; - match toml::from_str(&content) { - Ok(config) => config, - Err(err) => { - eprintln!("Error loading config file: {err}"); - Self::default() - } - } + pub fn load(path: &Path) -> Result { + Ok(match fs::read_to_string(path) { + Ok(content) => toml::from_str(&content)?, + Err(err) if err.kind() == ErrorKind::NotFound => Self::default(), + Err(err) => Err(err)?, + }) } pub fn euph_room(&self, name: &str) -> EuphRoom { diff --git a/cove/src/main.rs b/cove/src/main.rs index eb71d85..e9dc920 100644 --- a/cove/src/main.rs +++ b/cove/src/main.rs @@ -146,7 +146,7 @@ async fn main() -> anyhow::Result<()> { eprintln!("Config file: {}", config_path.to_string_lossy()); // Load config - let mut config = Config::load(&config_path); + let mut config = Config::load(&config_path)?; update_config_with_args(&mut config, &args); let config = Box::leak(Box::new(config));