kiri-cli 0.1.2

Terminal and Neovim worker for the progressive kiri fuzzy finder
mod config;
mod history;
mod tui;
mod worker;

use std::{
    io::{self, BufRead, IsTerminal, Write},
    path::PathBuf,
    process::ExitCode,
    sync::Arc,
};

use anyhow::{Context, Result, anyhow};
use clap::{Parser, Subcommand};
use kiri_core::{
    CandidateInput, HistoryMap, MatcherMode, ProviderEvent, Session, Snapshot, SortOrder,
    spawn_files,
};
use tokio::sync::{mpsc, oneshot};

#[derive(Parser)]
#[command(name = "kiri", version, about = "A progressive fuzzy finder")]
struct Args {
    #[command(subcommand)]
    command: Option<Command>,

    /// Find matches without opening the interactive finder.
    #[arg(long, global = true, conflicts_with = "query")]
    filter: Option<String>,
    /// Initial interactive query.
    #[arg(long, global = true)]
    query: Option<String>,
    /// Matcher: fuzzy, exact, migemo, regex, fuzzy_migemo, exact_migemo.
    #[arg(long, global = true)]
    matcher: Option<MatcherMode>,
    /// Sort order (e.g. score, alphabetical, frecency, modified).
    #[arg(long, global = true)]
    sort: Option<SortOrder>,
    /// Path to a configuration file.
    #[arg(long, global = true)]
    config: Option<PathBuf>,
    /// Read NUL-delimited instead of newline-delimited stdin.
    #[arg(long, global = true)]
    read0: bool,
    /// Write NUL-delimited instead of newline-delimited records.
    #[arg(long, global = true)]
    print0: bool,
    /// Mark multiple candidates with Tab.
    #[arg(long, global = true)]
    multi: bool,
    /// Maximum number of results; filtering is unlimited by default.
    #[arg(long, global = true)]
    limit: Option<usize>,
}

#[derive(Subcommand)]
enum Command {
    /// Find files under a directory (default: current directory).
    Files { root: Option<PathBuf> },
    /// Run the editor protocol worker.
    Serve {
        /// Communicate using stdin and stdout.
        #[arg(long)]
        stdio: bool,
    },
}

type HistoryReceiver = oneshot::Receiver<Result<Arc<HistoryMap>>>;

#[tokio::main]
async fn main() -> ExitCode {
    let args = Args::parse();
    match run(args).await {
        Ok(code) => ExitCode::from(code),
        Err(err) => {
            eprintln!("kiri: {err:#}");
            ExitCode::from(2)
        }
    }
}

async fn run(args: Args) -> Result<u8> {
    let config = config::load(args.config.as_deref())?;
    let root = match args.command {
        Some(Command::Serve { stdio }) => {
            anyhow::ensure!(stdio, "serve requires --stdio");
            worker::run(config).await?;
            return Ok(0);
        }
        Some(Command::Files { root }) => Some(root.map_or_else(std::env::current_dir, Ok)?),
        None if io::stdin().is_terminal() => Some(std::env::current_dir()?),
        None => None,
    };
    let files = root.is_some();
    let filtering = args.filter.is_some();
    let query = args.filter.or(args.query).unwrap_or_default();
    let picker = if files { "files" } else { "stdin" };
    let mut options = config.session_options(picker, query, args.limit);
    if filtering {
        // Configuration limits bound interactive rendering, not batch output.
        options.limit = args.limit;
    }
    if let Some(matcher) = args.matcher {
        options.matcher = matcher;
    }
    if let Some(sort) = args.sort {
        options.empty_query_sort = sort.clone();
        options.sort = sort;
    }
    let mut files_options = config.files.clone();
    files_options.metadata |=
        options.sort.needs_metadata() || options.empty_query_sort.needs_metadata();
    let (session, input) = Session::start(options);
    let history = if files && config.history.enabled {
        let (tx, rx) = oneshot::channel();
        let history_config = config.history.clone();
        tokio::spawn(async move {
            let _ = tx.send(history::load(&history_config).await);
        });
        Some(rx)
    } else {
        None
    };
    if let Some(root) = root {
        spawn_files(root, files_options, input);
    } else {
        // A blocking read can outlive the session, especially with a named pipe.
        // A dedicated thread must not keep Tokio runtime shutdown waiting.
        std::thread::Builder::new()
            .name("kiri-stdin".into())
            .spawn(move || read_stdin(io::stdin().lock(), args.read0, input))
            .context("starting stdin reader")?;
    }
    if filtering {
        let snapshot = filter(&session, history).await?;
        drop(session);
        if snapshot.results.is_empty() {
            return Ok(1);
        }
        write_values(
            io::stdout().lock(),
            snapshot.results.iter().map(|item| &item.candidate.value),
            args.print0,
        )?;
        return Ok(0);
    }
    let values = tui::run(&session, history, args.multi)?;
    drop(session);
    let Some(values) = values else {
        return Ok(130);
    };
    write_values(
        io::stdout().lock(),
        values.iter().map(|item| &item.value),
        args.print0,
    )?;
    if files && config.history.enabled {
        history::record(
            &config.history,
            values.into_iter().map(|item| item.value.clone()).collect(),
        )
        .await?;
    }
    Ok(0)
}

async fn filter(session: &Session, history: Option<HistoryReceiver>) -> Result<Arc<Snapshot>> {
    let mut snapshots = session.subscribe();
    let history_revision = if let Some(history) = history {
        session.set_history(history.await.context("loading history")??)
    } else {
        0
    };
    loop {
        {
            let snapshot = snapshots.borrow_and_update();
            if !snapshot.discovering
                && !snapshot.matching
                && snapshot.history_revision >= history_revision
            {
                if let Some(error) = &snapshot.error {
                    return Err(anyhow!("{error}"));
                }
                return Ok(snapshot.clone());
            }
        }
        snapshots
            .changed()
            .await
            .context("search ended before completion")?;
    }
}

fn read_stdin(mut reader: impl BufRead, read0: bool, input: mpsc::Sender<ProviderEvent>) {
    let delimiter = if read0 { 0 } else { b'\n' };
    while !input.is_closed() {
        let mut value = Vec::new();
        match reader.read_until(delimiter, &mut value) {
            Ok(0) => break,
            Ok(_) => {
                if value.last() == Some(&delimiter) {
                    value.pop();
                    if !read0 && value.last() == Some(&b'\r') {
                        value.pop();
                    }
                }
                let text = String::from_utf8_lossy(&value).into_owned();
                if input
                    .blocking_send(ProviderEvent::Candidate(CandidateInput::new(text, value)))
                    .is_err()
                {
                    break;
                }
            }
            Err(err) => {
                let _ = input.blocking_send(ProviderEvent::Error(format!("reading stdin: {err}")));
                break;
            }
        }
    }
}

fn write_values<V: AsRef<[u8]>>(
    mut writer: impl Write,
    values: impl IntoIterator<Item = V>,
    print0: bool,
) -> io::Result<()> {
    let delimiter = if print0 { b'\0' } else { b'\n' };
    for value in values {
        writer.write_all(value.as_ref())?;
        writer.write_all(&[delimiter])?;
    }
    writer.flush()
}

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

    fn read_records(bytes: &[u8], read0: bool) -> Vec<CandidateInput> {
        let (tx, mut rx) = mpsc::channel(10);
        read_stdin(bytes, read0, tx);
        let mut result = Vec::new();
        while let Ok(event) = rx.try_recv() {
            match event {
                ProviderEvent::Candidate(candidate) => result.push(candidate),
                ProviderEvent::Error(err) => panic!("unexpected error: {err}"),
            }
        }
        result
    }

    #[test]
    fn preserves_binary_values_and_empty_records() {
        let candidates = read_records(b"a\n\xff\0\0b\0", true);
        assert_eq!(
            candidates
                .iter()
                .map(|c| c.value.as_slice())
                .collect::<Vec<_>>(),
            [b"a\n\xff".as_slice(), b"", b"b"]
        );
        assert_eq!(candidates[0].text, "a\n\u{fffd}");
        let mut output = Vec::new();
        let values = candidates.into_iter().map(|c| c.value).collect::<Vec<_>>();
        write_values(&mut output, &values, true).unwrap();
        assert_eq!(output, b"a\n\xff\0\0b\0");
    }

    #[test]
    fn strips_line_endings_but_not_unterminated_carriage_return() {
        let candidates = read_records(b"a\r\n\nlast\r", false);
        assert_eq!(
            candidates
                .iter()
                .map(|c| c.value.as_slice())
                .collect::<Vec<_>>(),
            [b"a".as_slice(), b"", b"last\r"]
        );
    }
}