use std::path::{Path, PathBuf};
use serde::Deserialize;
#[derive(Debug, Clone, Default, Deserialize, PartialEq)]
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
pub struct Config {
pub theme: Option<String>,
pub light_theme: Option<String>,
pub dark_theme: Option<String>,
pub syntax_theme: Option<String>,
pub width: Option<usize>,
pub margin: Option<usize>,
pub tab_width: Option<usize>,
pub pager: Option<bool>,
pub mouse: Option<bool>,
pub images: Option<bool>,
pub image_protocol: Option<String>,
pub remote_images: Option<bool>,
pub max_image_rows: Option<u16>,
pub center_figures: Option<bool>,
pub links: Option<String>,
pub color: Option<String>,
pub unicode: Option<String>,
pub line_numbers: Option<bool>,
pub heading_rules: Option<bool>,
pub smart_punctuation: Option<bool>,
pub probe: Option<bool>,
}
impl Config {
pub fn load() -> anyhow::Result<Self> {
match Self::path() {
Some(path) if path.exists() => Self::from_file(&path),
_ => Ok(Self::default()),
}
}
pub fn from_file(path: &Path) -> anyhow::Result<Self> {
let text = std::fs::read_to_string(path)
.map_err(|e| anyhow::anyhow!("reading {}: {e}", path.display()))?;
Self::from_toml(&text).map_err(|e| anyhow::anyhow!("in {}: {e}", path.display()))
}
pub fn from_toml(text: &str) -> anyhow::Result<Self> {
Ok(toml::from_str(text)?)
}
pub fn path() -> Option<PathBuf> {
if let Some(explicit) = std::env::var_os("TERMMD_CONFIG") {
return Some(PathBuf::from(explicit));
}
if let Some(xdg) = std::env::var_os("XDG_CONFIG_HOME") {
return Some(PathBuf::from(xdg).join("termmd").join("config.toml"));
}
dirs::config_dir().map(|d| d.join("termmd").join("config.toml"))
}
pub fn theme_dir() -> Option<PathBuf> {
Self::path().and_then(|p| p.parent().map(|d| d.join("themes")))
}
}
pub fn theme_dir_for_lookup() -> Option<PathBuf> {
Config::theme_dir()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty_config_is_all_defaults() {
assert_eq!(Config::from_toml("").unwrap(), Config::default());
}
#[test]
fn parses_kebab_case_keys() {
let c = Config::from_toml(
r#"
theme = "light"
width = 100
line-numbers = true
image-protocol = "kitty"
remote-images = true
"#,
)
.unwrap();
assert_eq!(c.theme.as_deref(), Some("light"));
assert_eq!(c.width, Some(100));
assert_eq!(c.line_numbers, Some(true));
assert_eq!(c.image_protocol.as_deref(), Some("kitty"));
assert_eq!(c.remote_images, Some(true));
}
#[test]
fn rejects_unknown_keys() {
let err = Config::from_toml("thmee = \"dark\"").unwrap_err();
assert!(err.to_string().contains("thmee"), "unhelpful error: {err}");
}
#[test]
fn the_shipped_example_config_is_valid() {
let text = include_str!("../docs/config.example.toml");
Config::from_toml(text).expect("docs/config.example.toml should parse");
}
#[test]
fn rejects_wrong_types() {
assert!(Config::from_toml("width = \"wide\"").is_err());
}
}