kiri-cli 0.3.0

Terminal and Neovim worker for the progressive kiri fuzzy finder
//! `kiri self-update` and the throttled background update check, following
//! rvpm's use of kaishin. The check only ever runs after an interactive command
//! so the protocol worker and scripted `--filter` calls never touch the network.

use crate::config::{UpdateConfig, UpdateMode};
use anyhow::Result;
use std::time::Duration;

type Latest = Result<Option<kaishin::LatestRelease>>;

pub(crate) enum AutoUpdate {
    /// Within the throttle window; the cache already knows about a newer release.
    Cached {
        checker: kaishin::Checker,
        latest: kaishin::LatestRelease,
    },
    Checking {
        checker: kaishin::Checker,
        handle: tokio::task::JoinHandle<Latest>,
        cached: Option<kaishin::LatestRelease>,
    },
    Installing {
        handle: tokio::task::JoinHandle<Latest>,
    },
}

fn options() -> kaishin::KaishinOptions {
    kaishin::KaishinOptions::new("yukimemi", "kiri", "kiri", env!("CARGO_PKG_VERSION"))
}

fn disabled_by_env() -> bool {
    std::env::var("KIRI_NO_AUTOUPDATE").is_ok_and(|value| {
        let value = value.trim();
        !(value.is_empty() || value == "0" || value.eq_ignore_ascii_case("false"))
    })
}

/// Start the background check configured by `[update]`, or `None` when it is
/// off, disabled by the environment, or the cache directory is unknown.
pub(crate) fn spawn(config: &UpdateConfig) -> Option<AutoUpdate> {
    if config.mode == UpdateMode::Off || disabled_by_env() {
        return None;
    }
    let interval = config
        .check_interval
        .as_deref()
        .and_then(|value| kaishin::parse_interval(value).ok())
        .unwrap_or_else(kaishin::default_interval);
    let state = dirs::cache_dir()?
        .join("kiri")
        .join("last_update_check.json");
    let checker = kaishin::Checker::new("kiri", options())
        .interval(interval)
        .state_path(state);
    match config.mode {
        UpdateMode::Off => None,
        UpdateMode::Notify => {
            if !checker.should_check() {
                return checker
                    .cached_update()
                    .map(|latest| AutoUpdate::Cached { checker, latest });
            }
            let cached = checker.cached_update();
            let worker = checker.clone();
            let handle = tokio::spawn(async move { worker.check_and_save().await });
            Some(AutoUpdate::Checking {
                checker,
                handle,
                cached,
            })
        }
        UpdateMode::Install => {
            let handle = tokio::spawn(async move { checker.auto_update().await });
            Some(AutoUpdate::Installing { handle })
        }
    }
}

/// Wait briefly for the background work and report on stderr. A slow check is
/// left for the next launch.
pub(crate) async fn finish(update: AutoUpdate) {
    match update {
        AutoUpdate::Cached { checker, latest } => eprintln!("\n{}", checker.format_banner(&latest)),
        AutoUpdate::Checking {
            checker,
            handle,
            cached,
        } => match tokio::time::timeout(Duration::from_secs(1), handle).await {
            Ok(Ok(Ok(Some(latest)))) => eprintln!("\n{}", checker.format_banner(&latest)),
            Ok(Ok(Ok(None))) => {}
            _ => {
                if let Some(latest) = cached {
                    eprintln!("\n{}", checker.format_banner(&latest));
                }
            }
        },
        AutoUpdate::Installing { handle } => {
            if let Ok(Ok(Ok(Some(latest)))) =
                tokio::time::timeout(Duration::from_secs(5), handle).await
            {
                let version = latest.tag_name.trim_start_matches('v');
                eprintln!(
                    "\n\u{2713} kiri {version} installed in the background — restart to apply."
                );
            }
        }
    }
}

/// `kiri self-update [--yes] [--check]`.
pub(crate) async fn run(yes: bool, check_only: bool) -> Result<()> {
    let update = kaishin::UpdateOptions::new()
        .yes(yes)
        .check_only(check_only);
    kaishin::run_self_update(&options(), update).await
}