use anyhow::{anyhow, Result};
use indexmap::IndexMap;
use log::{debug, warn};
use serde_derive::Deserialize;
use std::{io::Read, path::PathBuf};
const NUM: &str = "%n";
const ICON: &str = "%i";
#[derive(Debug, Deserialize)]
pub struct Config {
pub default_icon: String,
format_str: String,
pub icon_separator: String,
pub icons: IndexMap<String, String>,
}
impl Default for Config {
fn default() -> Self {
warn!("Using default config.");
let content = std::include_str!("../default.toml");
toml::from_str(content).expect("Parsing default works.")
}
}
impl Config {
pub fn load(path: Option<PathBuf>) -> Result<Self> {
let cfg_path: PathBuf = if let Some(p) = path {
p
} else {
let sys_dir = PathBuf::from("/etc/xdg");
dirs::config_dir()
.unwrap_or(sys_dir)
.join(env!("CARGO_PKG_NAME"))
.join("config.toml")
};
debug!("Loading config file '{}'", &cfg_path.to_string_lossy());
let mut f = std::fs::File::open(cfg_path)?;
let mut content = String::new();
f.read_to_string(&mut content)?;
toml::from_str(&content).map_err(|e| anyhow!("Failed to parse config: {}", e))
}
pub fn format(&self, num: String, icon: String) -> String {
self.format_str.replace(NUM, &num).replace(ICON, &icon)
}
}