From 64ef178558398cb7914ff6664e8f2b3f51761de1 Mon Sep 17 00:00:00 2001 From: LordMZTE Date: Mon, 12 Apr 2021 17:04:56 +0200 Subject: [PATCH] add fzf integration --- cli/src/commands/list.rs | 41 +++++++++++++++++++++++++++++++++++++--- cli/src/main.rs | 8 ++++++-- 2 files changed, 44 insertions(+), 5 deletions(-) diff --git a/cli/src/commands/list.rs b/cli/src/commands/list.rs index e27e4c5..024a0fc 100644 --- a/cli/src/commands/list.rs +++ b/cli/src/commands/list.rs @@ -1,5 +1,9 @@ -use anyhow::Result; +use anyhow::{Context, Result}; use reqwest::Client; +use std::{ + io::Write, + process::{Command, Stdio}, +}; use crate::util::IntoTableRow; use jm_client_core::util::{self, api, MemeSorting}; @@ -9,6 +13,7 @@ pub async fn run( cat: Option, user: Option, sorting: Option, + fzf: bool, ) -> Result<()> { // This needs to be done so both users, memes and categories will be requested // at once @@ -42,11 +47,41 @@ pub async fn run( let mut table = crate::util::list_table(); - for m in memes { + for m in memes.iter() { table.add_row(m.into_table_row()); } - println!("{}", table.render()); + let table_str = table.render(); + + if fzf { + let mut child = Command::new("fzf") + .args(&["--delimiter", "\\t", "--with-nth", "2"]) + .stdout(Stdio::piped()) + .stdin(Stdio::piped()) + .spawn() + .context("Failed to spawn FZF")?; + let stdin = child.stdin.as_mut().context("could not get FZF stdin")?; + + for (idx, line) in table_str.lines().enumerate() { + stdin + .write(format!("{}\t{}\n", idx, line).as_bytes()) + .context("Failed to write to FZF")?; + } + + let out = child.wait_with_output()?; + let out_str = String::from_utf8(out.stdout).context("FZF output is invalid UTF-8")?; + let idx = out_str + .split('\t') + .next() + .and_then(|s| s.parse::().ok()) + .context("Failed to parse FZF output")?; + let meme = memes + .get(idx) + .context("Falied to retrieve meme FZF returned")?; + println!("{}", meme.link); + } else { + println!("{}", table_str); + } Ok(()) } diff --git a/cli/src/main.rs b/cli/src/main.rs index a35c19a..e75dcef 100644 --- a/cli/src/main.rs +++ b/cli/src/main.rs @@ -64,7 +64,7 @@ enum Cmd { cat: bool, }, - #[structopt(about = "lists all memes")] + #[structopt(about = "lists all memes", alias = "l")] List { #[structopt(long, short, help = "filter by category")] category: Option, @@ -78,6 +78,9 @@ enum Cmd { help = "how to sort the results. can be id, user, category or link" )] sort: Option, + + #[structopt(long, short, help = "search memes with FZF")] + fzf: bool, }, #[structopt(about = "Lists all users")] @@ -114,7 +117,8 @@ async fn main() -> Result<()> { category, user, sort, - } => commands::list::run(&http, category, user, sort).await?, + fzf, + } => commands::list::run(&http, category, user, sort, fzf).await?, Cmd::Users => commands::users::run(&http).await?, }