use anyhow::Result;
use core::fmt;
use etcetera::{choose_app_strategy, AppStrategy, AppStrategyArgs};
use std::fs;
use std::path::PathBuf;
use serde::{Deserialize, Serialize};
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct TcaSection {
pub default_theme: Option<String>,
pub default_dark_theme: Option<String>,
pub default_light_theme: Option<String>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
pub struct TcaConfig {
#[serde(default)]
pub tca: TcaSection,
}
impl TcaConfig {
pub fn path() -> Result<PathBuf> {
let strategy = choose_app_strategy(AppStrategyArgs {
top_level_domain: "org".into(),
author: "TCA".into(),
app_name: "tca".into(),
})?;
Ok(strategy.config_dir().join("tca.toml"))
}
pub fn load() -> Self {
let Ok(path) = TcaConfig::path() else {
return Self::default();
};
let Ok(content) = fs::read_to_string(path) else {
return Self::default();
};
toml::from_str::<TcaConfig>(&content).unwrap_or_default()
}
pub fn store(&self) -> Result<()> {
let path = TcaConfig::path()?;
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
let content = toml::to_string(self)?;
fs::write(&path, content)?;
Ok(())
}
}
impl fmt::Display for TcaConfig {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"default: {:?}\ndefault_dark: {:?}\ndefault_light: {:?}",
self.tca.default_theme.as_deref().unwrap_or("None"),
self.tca.default_dark_theme.as_deref().unwrap_or("None"),
self.tca.default_light_theme.as_deref().unwrap_or("None"),
)
}
}