kiri-cli 0.1.2

Terminal and Neovim worker for the progressive kiri fuzzy finder
use anyhow::{Context, Result, ensure};
use kiri_core::{CaseSensitivity, FilesOptions, MatcherMode, SessionOptions, SortOrder};
use serde::Deserialize;
use std::{
    collections::HashMap,
    path::{Path, PathBuf},
};
use teravars::{ConfigSource, Engine, discover_config_files, load_merged_sources, system_context};

const DEFAULT_CONFIG: &str = include_str!("../defaults.toml");

#[derive(Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Config {
    matcher: MatcherOptions,
    sorter: SorterOptions,
    pub max_results: usize,
    pub files: FilesOptions,
    pub history: HistoryConfig,
    #[serde(default)]
    pickers: HashMap<String, PickerOptions>,
}

#[derive(Clone, Deserialize)]
#[serde(deny_unknown_fields)]
struct MatcherOptions {
    mode: MatcherMode,
    case_sensitive: CaseSensitivity,
}

#[derive(Clone, Deserialize)]
#[serde(deny_unknown_fields)]
struct SorterOptions {
    order: SortOrder,
    empty_query_order: SortOrder,
    history_weight: f64,
}

#[derive(Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HistoryConfig {
    pub enabled: bool,
    pub path: Option<PathBuf>,
    pub half_life_days: f64,
    pub max_entries: usize,
}

impl HistoryConfig {
    pub(crate) fn database_path(&self) -> Result<PathBuf> {
        match &self.path {
            Some(path) => expand_home(path),
            None => dirs::data_local_dir()
                .map(|dir| dir.join("kiri").join("history.sqlite3"))
                .context("cannot locate the local data directory; set history.path"),
        }
    }
}

#[derive(Clone, Deserialize)]
#[serde(deny_unknown_fields)]
struct PickerOptions {
    matcher: Option<MatcherOverride>,
    sorter: Option<SorterOverride>,
    max_results: Option<usize>,
}

#[derive(Clone, Deserialize)]
#[serde(deny_unknown_fields)]
struct MatcherOverride {
    mode: Option<MatcherMode>,
    case_sensitive: Option<CaseSensitivity>,
}

#[derive(Clone, Deserialize)]
#[serde(deny_unknown_fields)]
struct SorterOverride {
    order: Option<SortOrder>,
    empty_query_order: Option<SortOrder>,
    history_weight: Option<f64>,
}

impl Config {
    pub fn session_options(
        &self,
        picker: &str,
        query: String,
        limit: Option<usize>,
    ) -> SessionOptions {
        let overrides = self.pickers.get(picker);
        let matcher = overrides.and_then(|p| p.matcher.as_ref());
        let sorter = overrides.and_then(|p| p.sorter.as_ref());
        SessionOptions {
            query,
            matcher: matcher.and_then(|m| m.mode).unwrap_or(self.matcher.mode),
            case_sensitive: matcher
                .and_then(|m| m.case_sensitive)
                .unwrap_or(self.matcher.case_sensitive),
            sort: sorter
                .and_then(|s| s.order.clone())
                .unwrap_or_else(|| self.sorter.order.clone()),
            empty_query_sort: sorter
                .and_then(|s| s.empty_query_order.clone())
                .unwrap_or_else(|| self.sorter.empty_query_order.clone()),
            history_weight: sorter
                .and_then(|s| s.history_weight)
                .unwrap_or(self.sorter.history_weight),
            limit: Some(
                limit
                    .or(overrides.and_then(|p| p.max_results))
                    .unwrap_or(self.max_results),
            ),
        }
    }

    fn validate(&self) -> Result<()> {
        validate_search_options(self.max_results, self.sorter.history_weight)?;
        for (name, picker) in &self.pickers {
            validate_search_options(
                picker.max_results.unwrap_or(self.max_results),
                picker
                    .sorter
                    .as_ref()
                    .and_then(|s| s.history_weight)
                    .unwrap_or(self.sorter.history_weight),
            )
            .with_context(|| format!("invalid options for picker {name:?}"))?;
        }
        let half_life = self.history.half_life_days * 86_400_000.0;
        ensure!(
            half_life.is_finite() && half_life > 0.0,
            "history.half_life_days must be finite and positive"
        );
        ensure!(
            self.history.max_entries > 0 && i64::try_from(self.history.max_entries).is_ok(),
            "history.max_entries must be a positive SQLite integer"
        );
        ensure!(
            self.history
                .path
                .as_ref()
                .is_none_or(|p| !p.as_os_str().is_empty()),
            "history.path must not be empty"
        );
        Ok(())
    }
}

fn validate_search_options(max_results: usize, history_weight: f64) -> Result<()> {
    ensure!(max_results > 0, "max_results must be positive");
    ensure!(
        (0.0..=1.0).contains(&history_weight),
        "history_weight must be between 0 and 1"
    );
    Ok(())
}

fn expand_home(path: &Path) -> Result<PathBuf> {
    if let Ok(rest) = path.strip_prefix("~") {
        return Ok(dirs::home_dir()
            .context("cannot expand ~: home directory is unknown")?
            .join(rest));
    }
    Ok(path.to_path_buf())
}

fn config_directory() -> Result<Option<PathBuf>> {
    // Allow a shared Unix-style configuration on Windows as well.
    if let Some(home) = dirs::home_dir() {
        let path = home.join(".config").join("kiri");
        if path
            .try_exists()
            .with_context(|| format!("cannot inspect {}", path.display()))?
        {
            return Ok(Some(path));
        }
    }
    Ok(dirs::config_dir().map(|dir| dir.join("kiri")))
}

fn discover() -> Result<Vec<PathBuf>> {
    let Some(dir) = config_directory()? else {
        return Ok(Vec::new());
    };
    if !dir
        .try_exists()
        .with_context(|| format!("cannot inspect {}", dir.display()))?
    {
        return Ok(Vec::new());
    }
    discover_config_files(&dir)
        .with_context(|| format!("cannot discover configuration in {}", dir.display()))
}

pub fn load(path: Option<&Path>) -> Result<Config> {
    let files = match path {
        Some(path) => vec![expand_home(path)?],
        None => discover()?,
    };
    let sources = std::iter::once(ConfigSource::string("<kiri defaults>", DEFAULT_CONFIG))
        .chain(files.iter().map(|path| ConfigSource::path(path.as_path())));
    let mut merged = load_merged_sources(sources, &mut Engine::new(), &system_context())
        .context("cannot load kiri configuration")?;
    merged.config.remove("vars");
    let config: Config = merged.config.try_into().with_context(|| {
        let names = files
            .iter()
            .map(|path| path.display().to_string())
            .collect::<Vec<_>>()
            .join(", ");
        format!(
            "invalid kiri configuration (embedded defaults{}{})",
            if names.is_empty() { "" } else { ", " },
            names
        )
    })?;
    config.validate().context("invalid kiri configuration")?;
    Ok(config)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;

    #[test]
    fn includes_render_and_merge_into_picker_overrides() -> Result<()> {
        let dir = tempfile::tempdir()?;
        fs::write(
            dir.path().join("common.toml"),
            r#"
[vars]
ordering = "size"

[files]
hidden = true

[pickers.files]
max_results = 7

[pickers.files.sorter]
history_weight = 0.5
"#,
        )?;
        let path = dir.path().join("config.toml");
        fs::write(
            &path,
            r#"
include = ["common.toml"]
max_results = 31

[sorter]
order = "{{ vars.ordering }}"

[pickers.files]
max_results = 9

[pickers.files.sorter]
empty_query_order = "modified"
"#,
        )?;
        let config = load(Some(&path))?;
        assert!(config.files.hidden);
        assert!(config.files.respect_ignore);
        let files = config.session_options("files", "abc".into(), None);
        assert!(files.sort.needs_metadata());
        assert!(files.empty_query_sort.needs_metadata());
        assert_eq!(files.history_weight, 0.5);
        assert_eq!(files.limit, Some(9));
        let other = config.session_options("other", String::new(), None);
        assert_eq!(other.limit, Some(31));
        assert!(!other.empty_query_sort.needs_metadata());
        assert_eq!(
            config
                .session_options("files", String::new(), Some(4))
                .limit,
            Some(4)
        );
        Ok(())
    }

    #[test]
    fn explicit_missing_and_invalid_files_are_errors() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let path = dir.path().join("config.toml");
        assert!(load(Some(&path)).is_err());
        fs::write(&path, "[pickers.files]\nmax_results = 0\n")?;
        let error = load(Some(&path)).err().expect("invalid picker limit");
        let description = format!("{error:#}");
        assert!(description.contains("files") && description.contains("max_results"));
        Ok(())
    }
}