kiri-cli 0.2.0

Terminal and Neovim worker for the progressive kiri fuzzy finder
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
mod config;
mod history;
mod tui;
mod worker;

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

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

#[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>,
    /// Never show the preview pane (Ctrl-O toggles it otherwise).
    #[arg(long, global = true)]
    no_preview: bool,
}

#[derive(Subcommand)]
enum Command {
    /// Find files under a directory (default: current directory).
    Files { root: Option<PathBuf> },
    /// Search file contents live under a directory (default: current directory).
    ///
    /// Prints `path:line:column:text` for each selected hit.
    Grep { 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>>>;

/// A query-driven stream of snapshots: what the finder and `--filter` need from
/// files/stdin sessions and from live grep alike.
pub(crate) trait Search {
    fn subscribe(&self) -> watch::Receiver<Arc<Snapshot>>;
    fn set_query(&self, query: String) -> u64;
    /// Sources without history ignore it.
    fn set_history(&self, _stats: Arc<HistoryMap>) -> u64 {
        0
    }
}

impl Search for Session {
    fn subscribe(&self) -> watch::Receiver<Arc<Snapshot>> {
        Session::subscribe(self)
    }

    fn set_query(&self, query: String) -> u64 {
        Session::set_query(self, query)
    }

    fn set_history(&self, stats: Arc<HistoryMap>) -> u64 {
        Session::set_history(self, stats)
    }
}

impl Search for GrepSession {
    fn subscribe(&self) -> watch::Receiver<Arc<Snapshot>> {
        GrepSession::subscribe(self)
    }

    fn set_query(&self, query: String) -> u64 {
        GrepSession::set_query(self, query)
    }
}

#[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(mut args: Args) -> Result<u8> {
    let config = config::load(args.config.as_deref())?;
    let root = match args.command.take() {
        Some(Command::Serve { stdio }) => {
            anyhow::ensure!(stdio, "serve requires --stdio");
            worker::run(config).await?;
            return Ok(0);
        }
        Some(Command::Grep { root }) => return grep(args, config, root).await,
        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, files && !args.no_preview)?;
    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)
}

/// Live grep: prints `path:line:column:text` records, as `--filter` output or the
/// interactive selection. Hits never touch the selection history.
async fn grep(args: Args, config: config::Config, root: Option<PathBuf>) -> Result<u8> {
    // Hit values are root-joined paths: an absolute root makes them absolute.
    let root = std::path::absolute(root.map_or_else(std::env::current_dir, Ok)?)
        .context("resolving the search root")?;
    let filtering = args.filter.is_some();
    let query = args.filter.or(args.query).unwrap_or_default();
    let mut options = config.grep_options(root.clone(), query, args.limit);
    if filtering {
        // Configuration limits bound interactive rendering, not batch output.
        options.limit = args.limit.unwrap_or(usize::MAX);
    }
    if let Some(matcher) = args.matcher {
        options.matcher = matcher;
    }
    let session = GrepSession::start(options);
    let hits = if filtering {
        let snapshot = filter(&session, None).await?;
        snapshot
            .results
            .iter()
            .map(|item| item.candidate.clone())
            .collect()
    } else {
        match tui::run(&session, None, args.multi, !args.no_preview)? {
            Some(hits) => hits,
            None => return Ok(130),
        }
    };
    drop(session);
    if hits.is_empty() {
        return Ok(1);
    }
    write_values(
        io::stdout().lock(),
        hits.iter().filter_map(|hit| grep_record(&root, hit)),
        args.print0,
    )?;
    Ok(0)
}

/// The path of a files/grep candidate value (the raw bytes of an OS path).
pub(crate) fn value_path(value: &[u8]) -> PathBuf {
    #[cfg(unix)]
    {
        use std::os::unix::ffi::OsStrExt;
        PathBuf::from(OsStr::from_bytes(value))
    }
    #[cfg(not(unix))]
    {
        PathBuf::from(OsStr::new(&*String::from_utf8_lossy(value)))
    }
}

/// `<absolute path>:<line>:<column>:<content>`, where content is the hit text after
/// the `<relative path>:<line>: ` prefix that grep candidates display.
fn grep_record(root: &Path, hit: &Candidate) -> Option<Vec<u8>> {
    let location = hit.location?;
    let path = value_path(&hit.value);
    let relative = path.strip_prefix(root).unwrap_or(&path).to_string_lossy();
    let prefix = relative.len() + format!(":{}: ", location.line).len();
    let content = hit.text.get(prefix..).unwrap_or_default();
    let mut record = hit.value.clone();
    record
        .extend_from_slice(format!(":{}:{}:{content}", location.line, location.column).as_bytes());
    Some(record)
}

async fn filter(search: &impl Search, history: Option<HistoryReceiver>) -> Result<Arc<Snapshot>> {
    let mut snapshots = search.subscribe();
    let history_revision = if let Some(history) = history {
        search.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"]
        );
    }

    #[test]
    fn grep_records_use_absolute_paths_and_keep_the_hit_text_verbatim() {
        let root = PathBuf::from(if cfg!(windows) {
            r"C:\Users\名前\proj"
        } else {
            "/home/名前/proj"
        });
        let relative = Path::new("src").join("日本語: 5: x.rs");
        let path = root.join(&relative);
        let content = "fn 関数() { // 7: ok:";
        let hit = Candidate {
            id: 0,
            text: format!("{}:{}: {content}", relative.to_string_lossy(), 42),
            value: path.as_os_str().as_encoded_bytes().to_vec(),
            size: None,
            modified: None,
            location: Some(kiri_core::Location {
                line: 42,
                column: 4,
            }),
        };
        let mut expected = path.to_string_lossy().into_owned();
        expected.push_str(&format!(":42:4:{content}"));
        assert_eq!(grep_record(&root, &hit).unwrap(), expected.as_bytes());
        let mut output = Vec::new();
        write_values(&mut output, grep_record(&root, &hit), true).unwrap();
        assert_eq!(output, [expected.as_bytes(), b"\0"].concat());
        assert_eq!(value_path(&hit.value), path);
    }
}