49 lines
1.4 KiB
Rust
49 lines
1.4 KiB
Rust
|
use std::{env, path::PathBuf};
|
||
|
|
||
|
use anyhow::{bail, Context, Result};
|
||
|
use directories::ProjectDirs;
|
||
|
use dotenv::from_path;
|
||
|
|
||
|
const CONFIG_FILE_NAME: &str = ".env";
|
||
|
|
||
|
pub fn get_config_dirs() -> Vec<PathBuf> {
|
||
|
let mut config_dirs = vec![
|
||
|
PathBuf::from(""), // Current directory
|
||
|
];
|
||
|
if let Ok(manifest_dir) = env::var("CARGO_MANIFEST_DIR") {
|
||
|
config_dirs.push(PathBuf::from(manifest_dir));
|
||
|
}
|
||
|
if let Some(proj_dirs) = ProjectDirs::from("org", "P4pillon", "Krys4lide") {
|
||
|
config_dirs.push(proj_dirs.config_dir().to_path_buf());
|
||
|
}
|
||
|
config_dirs
|
||
|
}
|
||
|
|
||
|
pub fn get_config_files() -> Result<Vec<PathBuf>> {
|
||
|
let config_dirs = get_config_dirs();
|
||
|
let mut config_files = Vec::new();
|
||
|
for config_dir in config_dirs.iter() {
|
||
|
let config_file = config_dir.join(CONFIG_FILE_NAME);
|
||
|
if config_file.exists() {
|
||
|
config_files.push(config_file);
|
||
|
}
|
||
|
}
|
||
|
if config_files.is_empty() {
|
||
|
bail!(
|
||
|
"No config file {CONFIG_FILE_NAME} found in the following directories: {config_dirs:#?}"
|
||
|
);
|
||
|
}
|
||
|
Ok(config_files)
|
||
|
}
|
||
|
|
||
|
pub fn load_config() -> Result<()> {
|
||
|
let config_files = get_config_files()?;
|
||
|
// Load the first config file found
|
||
|
// TODO: add a verbose log to list all config files found
|
||
|
println!(
|
||
|
"DEBUG: Config files found (1st loaded): {:#?}",
|
||
|
config_files
|
||
|
);
|
||
|
from_path(config_files[0].as_path()).context("Failed to load config file")
|
||
|
}
|