add fzf integration
continuous-integration/drone/push Build is passing Details

This commit is contained in:
LordMZTE 2021-04-12 17:04:56 +02:00
parent 00ed1609ba
commit 64ef178558
2 changed files with 44 additions and 5 deletions

View File

@ -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<String>,
user: Option<String>,
sorting: Option<MemeSorting>,
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::<usize>().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(())
}

View File

@ -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<String>,
@ -78,6 +78,9 @@ enum Cmd {
help = "how to sort the results. can be id, user, category or link"
)]
sort: Option<MemeSorting>,
#[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?,
}