40 lines
1.1 KiB
Rust
40 lines
1.1 KiB
Rust
use anyhow::{anyhow, Context, Result};
|
|
use serde::Deserialize;
|
|
use std::fs;
|
|
use std::path::PathBuf;
|
|
use xdg::BaseDirectories;
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
pub struct Config {
|
|
pub working_directory: Option<PathBuf>,
|
|
}
|
|
|
|
impl Config {
|
|
pub fn default() -> Config {
|
|
Config {
|
|
working_directory: None,
|
|
}
|
|
}
|
|
}
|
|
|
|
pub fn load_config(app_name: &str, file_name: &str) -> Result<Config> {
|
|
// Create an XDG base directories instance
|
|
let xdg_dirs =
|
|
BaseDirectories::with_prefix(app_name).context("Failed to initialize XDG directories")?;
|
|
|
|
let config_path = xdg_dirs
|
|
.place_config_file(file_name)
|
|
.context("Failed to determine configuration file path")?;
|
|
|
|
if !config_path.exists() {
|
|
return Err(anyhow!("No configuration file at {:?}", config_path));
|
|
}
|
|
|
|
let contents = fs::read_to_string(&config_path)
|
|
.with_context(|| format!("Failed to read configuration file at {:?}", config_path))?;
|
|
|
|
let config: Config = toml::from_str(&contents)
|
|
.with_context(|| format!("Failed to parse TOML configuration at {:?}", config_path))?;
|
|
Ok(config)
|
|
}
|