mod config;
mod history;
mod tui;
mod update;
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>,
#[arg(long, global = true, conflicts_with = "query")]
filter: Option<String>,
#[arg(long, global = true)]
query: Option<String>,
#[arg(long, global = true)]
matcher: Option<MatcherMode>,
#[arg(long, global = true)]
sort: Option<SortOrder>,
#[arg(long, global = true)]
config: Option<PathBuf>,
#[arg(long, global = true)]
read0: bool,
#[arg(long, global = true)]
print0: bool,
#[arg(long, global = true)]
multi: bool,
#[arg(long, global = true)]
limit: Option<usize>,
#[arg(long, global = true)]
no_preview: bool,
}
#[derive(Subcommand)]
enum Command {
Files { root: Option<PathBuf> },
Grep { root: Option<PathBuf> },
SelfUpdate {
#[arg(long, short = 'y')]
yes: bool,
#[arg(long)]
check: bool,
},
Serve {
#[arg(long)]
stdio: bool,
},
}
type HistoryReceiver = oneshot::Receiver<Result<Arc<HistoryMap>>>;
pub(crate) trait Search {
fn subscribe(&self) -> watch::Receiver<Arc<Snapshot>>;
fn set_query(&self, query: String) -> u64;
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(args: Args) -> Result<u8> {
if let Some(Command::SelfUpdate { yes, check }) = args.command {
update::run(yes, check).await?;
return Ok(0);
}
let config = config::load(args.config.as_deref())?;
let background =
if args.filter.is_none() && !matches!(args.command, Some(Command::Serve { .. })) {
update::spawn(&config.update)
} else {
None
};
let code = run_command(args, config).await?;
if let Some(background) = background {
update::finish(background).await;
}
Ok(code)
}
async fn run_command(mut args: Args, config: config::Config) -> Result<u8> {
let root = match args.command.take() {
Some(Command::SelfUpdate { .. }) => {
unreachable!("handled before loading the configuration")
}
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 {
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 {
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)
}
async fn grep(args: Args, config: config::Config, root: Option<PathBuf>) -> Result<u8> {
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 {
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)
}
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)))
}
}
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);
}
}