better error return in config
This commit is contained in:
parent
8de3a762ab
commit
0eaddf064e
@ -9,38 +9,52 @@ use crate::PROGRAM_NAME;
|
||||
|
||||
#[derive(Deserialize, Serialize, Debug)]
|
||||
pub struct Config {
|
||||
pub cloudflare_zone_id: Box<str>,
|
||||
pub cloudflare_api_key: Box<str>,
|
||||
pub zone_id: Box<str>,
|
||||
pub api_key: Box<str>,
|
||||
pub domains: Vec<Box<str>>,
|
||||
}
|
||||
|
||||
pub async fn get_config_path() -> Option<PathBuf> {
|
||||
pub async fn get_config_path() -> Result<PathBuf, Vec<PathBuf>> {
|
||||
let mut tried_paths = Vec::with_capacity(2);
|
||||
|
||||
match env::current_dir() {
|
||||
Ok(current_dir) => {
|
||||
let cwd_config = current_dir.join(format!("{}.toml", PROGRAM_NAME));
|
||||
if let Ok(meta) = fs::metadata(&cwd_config).await {
|
||||
if meta.is_file() {
|
||||
return Some(cwd_config);
|
||||
}
|
||||
|
||||
let is_valid_path = fs::metadata(&cwd_config)
|
||||
.await
|
||||
.map_or_else(|_| false, |meta| meta.is_file());
|
||||
|
||||
if is_valid_path {
|
||||
return Ok(cwd_config);
|
||||
} else {
|
||||
tried_paths.push(cwd_config);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
warn!("Failed to get current directory {:?}", &e);
|
||||
warn!("Failed to get current working directory: {:?}", e);
|
||||
}
|
||||
}
|
||||
|
||||
match dirs::config_dir() {
|
||||
Some(config_dir) => {
|
||||
let config_file = config_dir.join(PROGRAM_NAME).join("config.toml");
|
||||
if let Ok(meta) = fs::metadata(&config_file).await {
|
||||
if meta.is_file() {
|
||||
return Some(config_file);
|
||||
}
|
||||
|
||||
let is_valid_path = fs::metadata(&config_file)
|
||||
.await
|
||||
.map_or_else(|_| false, |meta| meta.is_file());
|
||||
if is_valid_path {
|
||||
return Ok(config_file);
|
||||
} else {
|
||||
tried_paths.push(config_file);
|
||||
}
|
||||
}
|
||||
None => {}
|
||||
None => {
|
||||
warn!("No configuration directory found.");
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
Err(tried_paths)
|
||||
}
|
||||
|
||||
pub async fn read_config(path: &PathBuf) -> anyhow::Result<Config> {
|
||||
|
16
src/main.rs
16
src/main.rs
@ -26,9 +26,19 @@ const fn nl_mgrp(group: u32) -> u32 {
|
||||
async fn main() {
|
||||
env_logger::init();
|
||||
let config_path = match get_config_path().await {
|
||||
Some(cp) => cp,
|
||||
None => {
|
||||
error!("Failed to find any config file");
|
||||
Ok(cp) => cp,
|
||||
Err(tried_paths) => {
|
||||
let extra: String = if !tried_paths.is_empty() {
|
||||
let joined = tried_paths
|
||||
.iter()
|
||||
.filter_map(|path| path.to_str())
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
format!(", tried the paths: '{}'", &joined)
|
||||
} else {
|
||||
String::with_capacity(0)
|
||||
};
|
||||
error!("Failed to find any config file{}", &extra);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
Loading…
x
Reference in New Issue
Block a user