use std::fmt;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use crate::keys::Keymap;
use crate::theme::{Colors, ThemeSetting};
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields, default)]
pub(crate) struct Config {
pub(crate) herdr: HerdrConfig,
pub(crate) ui: UiConfig,
pub(crate) keys: Keymap,
pub(crate) colors: Colors,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, default)]
pub(crate) struct UiConfig {
pub(crate) theme: ThemeSetting,
pub(crate) horizontal_margin: u16,
pub(crate) max_width: u16,
pub(crate) doc_width: u16,
pub(crate) copy_on_select: bool,
}
impl Default for UiConfig {
fn default() -> Self {
Self {
theme: ThemeSetting::default(),
horizontal_margin: 0,
max_width: 0,
doc_width: 0,
copy_on_select: true,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, default)]
pub(crate) struct HerdrConfig {
pub(crate) placement: Placement,
pub(crate) split_direction: SplitDirection,
pub(crate) popup_width: String,
pub(crate) popup_height: String,
}
impl Default for HerdrConfig {
fn default() -> Self {
Self {
placement: Placement::Overlay,
split_direction: SplitDirection::Right,
popup_width: "90%".to_owned(),
popup_height: "85%".to_owned(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub(crate) enum Placement {
#[default]
Overlay,
Split,
Popup,
}
impl Placement {
pub(crate) fn as_str(self) -> &'static str {
match self {
Self::Overlay => "overlay",
Self::Split => "split",
Self::Popup => "popup",
}
}
}
impl fmt::Display for Placement {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl FromStr for Placement {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self> {
match s {
"overlay" => Ok(Self::Overlay),
"split" => Ok(Self::Split),
"popup" => Ok(Self::Popup),
other => anyhow::bail!("unknown placement {other:?}; expected overlay, split or popup"),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub(crate) enum SplitDirection {
#[default]
Right,
Down,
}
impl SplitDirection {
pub(crate) fn as_str(self) -> &'static str {
match self {
Self::Right => "right",
Self::Down => "down",
}
}
}
impl fmt::Display for SplitDirection {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
pub(crate) fn config_path(env: impl Fn(&str) -> Option<String>, home: &Path) -> PathBuf {
if let Some(explicit) = env("PLANNOTATOR_TUI_CONFIG").filter(|s| !s.is_empty()) {
return PathBuf::from(explicit);
}
#[cfg(windows)]
if let Some(appdata) = env("APPDATA").map(PathBuf::from).filter(|p| p.is_absolute()) {
return appdata.join("plannotator-tui").join("config.toml");
}
let xdg = env("XDG_CONFIG_HOME").map(PathBuf::from).filter(|p| p.is_absolute());
xdg.unwrap_or_else(|| home.join(".config")).join("plannotator-tui").join("config.toml")
}
impl Config {
pub(crate) fn parse(text: &str) -> Result<Self> {
toml::from_str(text).map_err(|e| anyhow::anyhow!("{}", e.message().trim()))
}
pub(crate) fn load() -> Result<Self> {
let home = std::env::home_dir().unwrap_or_else(|| PathBuf::from("/"));
let path = config_path(|k| std::env::var(k).ok(), &home);
Self::load_from(&path)
}
pub(crate) fn load_from(path: &Path) -> Result<Self> {
match std::fs::read_to_string(path) {
Ok(text) => Self::parse(&text).with_context(|| format!("in {}", path.display())),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
Err(e) => Err(e).with_context(|| format!("reading {}", path.display())),
}
}
pub(crate) fn to_toml(&self) -> Result<String> {
Ok(toml::to_string(self)?)
}
}
#[cfg(test)]
#[allow(clippy::expect_used, reason = "tests assert by panicking")]
mod tests {
use super::*;
#[test]
fn empty_file_is_the_default_config() {
assert_eq!(Config::parse("").expect("parses"), Config::default());
assert_eq!(Config::default().herdr.placement, Placement::Overlay);
}
#[test]
fn unknown_key_error_names_the_key() {
let err = Config::parse("[herdr]\nplacment = \"popup\"\n").expect_err("rejected");
assert!(err.to_string().contains("placment"), "{err}");
}
#[test]
fn invalid_placement_error_names_the_value() {
let err = Config::parse("[herdr]\nplacement = \"floating\"\n").expect_err("rejected");
assert!(err.to_string().contains("floating"), "{err}");
}
#[test]
fn partial_file_keeps_other_defaults() {
let config = Config::parse("[herdr]\nplacement = \"split\"\n").expect("parses");
assert_eq!(config.herdr.placement, Placement::Split);
assert_eq!(config.herdr.split_direction, SplitDirection::Right);
assert_eq!(config.herdr.popup_width, "90%");
}
#[cfg(windows)]
#[test]
fn config_lives_under_appdata_on_windows() {
let lookup = |k: &str| (k == "APPDATA").then(|| r"C:\Users\u\AppData\Roaming".to_owned());
assert_eq!(
config_path(lookup, Path::new(r"C:\Users\u")),
PathBuf::from(r"C:\Users\u\AppData\Roaming\plannotator-tui\config.toml")
);
}
#[cfg(unix)]
#[test]
fn config_path_precedence() {
let home = Path::new("/home/u");
let lookup = |vars: &'static [(&'static str, &'static str)]| {
move |k: &str| vars.iter().find(|(name, _)| *name == k).map(|(_, v)| (*v).to_owned())
};
assert_eq!(
config_path(
lookup(&[("PLANNOTATOR_TUI_CONFIG", "/etc/p.toml"), ("XDG_CONFIG_HOME", "/x")]),
home
),
PathBuf::from("/etc/p.toml")
);
assert_eq!(
config_path(lookup(&[("XDG_CONFIG_HOME", "/x")]), home),
PathBuf::from("/x/plannotator-tui/config.toml")
);
assert_eq!(
config_path(lookup(&[("XDG_CONFIG_HOME", "rel")]), home),
PathBuf::from("/home/u/.config/plannotator-tui/config.toml")
);
assert_eq!(
config_path(lookup(&[]), home),
PathBuf::from("/home/u/.config/plannotator-tui/config.toml")
);
}
#[test]
fn the_theme_defaults_to_asking_the_terminal() {
assert_eq!(Config::default().ui.theme, ThemeSetting::Auto);
assert_eq!(Config::parse("").expect("parses").ui.theme, ThemeSetting::Auto);
}
#[test]
fn a_configured_theme_is_read_and_leaves_the_rest_alone() {
let config = Config::parse("[ui]\ntheme = \"light\"\n").expect("parses");
assert_eq!(config.ui.theme, ThemeSetting::Light);
assert_eq!(config.herdr.placement, Placement::Overlay);
}
#[test]
fn an_unknown_theme_error_names_the_value() {
let err = Config::parse("[ui]\ntheme = \"solarized\"\n").expect_err("rejected");
assert!(err.to_string().contains("solarized"), "{err}");
}
#[test]
fn widths_default_to_filling_the_terminal_and_roundtrip() {
assert_eq!(Config::default().ui.horizontal_margin, 0);
assert_eq!(Config::default().ui.max_width, 0);
assert_eq!(Config::default().ui.doc_width, 0);
let config =
Config::parse("[ui]\nhorizontal_margin = 2\nmax_width = 168\ndoc_width = 120\n").expect("parses");
assert_eq!((config.ui.horizontal_margin, config.ui.max_width, config.ui.doc_width), (2, 168, 120));
assert_eq!(Config::parse(&config.to_toml().expect("serializes")).expect("parses"), config);
}
#[test]
fn copy_on_select_defaults_on_and_turns_off() {
assert!(Config::default().ui.copy_on_select);
assert!(!Config::parse("[ui]\ncopy_on_select = false\n").expect("parses").ui.copy_on_select);
}
#[test]
fn roundtrips_through_toml() {
let text = Config::default().to_toml().expect("serializes");
assert_eq!(Config::parse(&text).expect("parses"), Config::default());
}
#[test]
fn colors_are_read_by_role_and_roundtrip() {
let config =
Config::parse("[colors]\naccent = \"magenta\"\nlooks-good-bg = \"#a6e3a1\"\nblock = \"236\"\n")
.expect("parses");
assert_eq!(config.colors.accent.map(|c| c.0), Some(ratatui::style::Color::Magenta));
assert_eq!(config.colors.looks_good_bg.map(|c| c.0), Some(ratatui::style::Color::Rgb(166, 227, 161)));
assert_eq!(config.colors.heading, None);
let text = config.to_toml().expect("serializes");
assert_eq!(Config::parse(&text).expect("reparses"), config);
}
#[test]
fn a_color_may_be_a_bare_index() {
let config = Config::parse("[colors]\nheading = 238\n").expect("parses");
assert_eq!(config.colors.heading.map(|c| c.0), Some(ratatui::style::Color::Indexed(238)));
let err = Config::parse("[colors]\nheading = 256\n").expect_err("out of range");
assert!(err.to_string().contains("256"), "{err}");
}
#[test]
fn an_unknown_color_role_error_names_the_role() {
let err = Config::parse("[colors]\nbackground = \"black\"\n").expect_err("rejected");
assert!(err.to_string().contains("background"), "{err}");
}
#[test]
fn an_unreadable_color_error_names_the_value() {
let err = Config::parse("[colors]\nheading = \"chartreuse\"\n").expect_err("rejected");
assert!(err.to_string().contains("chartreuse"), "{err}");
}
}