Improve config loading error handling
This commit is contained in:
parent
101d36cd45
commit
2afda17d4b
4 changed files with 19 additions and 11 deletions
1
Cargo.lock
generated
1
Cargo.lock
generated
|
|
@ -284,6 +284,7 @@ dependencies = [
|
|||
"cove-input",
|
||||
"cove-macro",
|
||||
"serde",
|
||||
"thiserror",
|
||||
"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"
|
||||
|
|
|
|||
|
|
@ -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<Self, Error> {
|
||||
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 {
|
||||
|
|
|
|||
|
|
@ -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));
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue