/src/bin/rga-fzf.rs

https://github.com/phiresky/ripgrep-all · Rust · 64 lines · 55 code · 7 blank · 2 comment · 3 complexity · caebbe136f600dec0284bc1486bcec94 MD5 · raw file

  1. use anyhow::Context;
  2. use rga::adapters::spawning::map_exe_error;
  3. use ripgrep_all as rga;
  4. use std::process::{Command, Stdio};
  5. // TODO: add --rg-params=..., --rg-preview-params=... and --fzf-params=... params
  6. // TODO: remove passthrough_args
  7. fn main() -> anyhow::Result<()> {
  8. env_logger::init();
  9. let mut passthrough_args: Vec<String> = std::env::args().skip(1).collect();
  10. let inx = passthrough_args.iter().position(|e| !e.starts_with("-"));
  11. let initial_query = if let Some(inx) = inx {
  12. passthrough_args.remove(inx)
  13. } else {
  14. "".to_string()
  15. };
  16. let exe = std::env::current_exe().context("Could not get executable location")?;
  17. let preproc_exe = exe.with_file_name("rga");
  18. let preproc_exe = preproc_exe
  19. .to_str()
  20. .context("rga executable is in non-unicode path")?;
  21. let open_exe = exe.with_file_name("rga-fzf-open");
  22. let open_exe = open_exe
  23. .to_str()
  24. .context("rga-fzf-open executable is in non-unicode path")?;
  25. let rg_prefix = format!(
  26. "{} --files-with-matches --rga-cache-max-blob-len=10M",
  27. preproc_exe
  28. );
  29. let child = Command::new("fzf")
  30. .arg(format!(
  31. "--preview={} --pretty --context 5 {{q}} --rga-fzf-path=_{{}}",
  32. preproc_exe
  33. ))
  34. .arg("--preview-window=70%:wrap")
  35. .arg("--phony")
  36. .arg("--query")
  37. .arg(&initial_query)
  38. .arg("--print-query")
  39. .arg(format!("--bind=change:reload: {} {{q}}", rg_prefix))
  40. .arg(format!("--bind=ctrl-m:execute:{} {{q}} {{}}", open_exe))
  41. .env(
  42. "FZF_DEFAULT_COMMAND",
  43. format!("{} '{}'", rg_prefix, &initial_query),
  44. )
  45. .env("RGA_FZF_INSTANCE", format!("{}", std::process::id())) // may be useful to open stuff in the same tab
  46. .stdout(Stdio::piped())
  47. .spawn()
  48. .map_err(|e| map_exe_error(e, "fzf", "Please make sure you have fzf installed."))?;
  49. let output = child.wait_with_output()?;
  50. let mut x = output.stdout.split(|e| e == &b'\n');
  51. let final_query =
  52. std::str::from_utf8(x.next().context("fzf output empty")?).context("fzf query not utf8")?;
  53. let selected_file = std::str::from_utf8(x.next().context("fzf output not two line")?)
  54. .context("fzf ofilename not utf8")?;
  55. println!("query='{}', file='{}'", final_query, selected_file);
  56. Ok(())
  57. }