jensmemesclient/cli/src/commands/list.rs
LordMZTE 64ef178558
All checks were successful
continuous-integration/drone/push Build is passing
add fzf integration
2021-04-12 17:04:56 +02:00

88 lines
2.3 KiB
Rust

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};
pub async fn run(
http: &Client,
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
let (memes, ..) = tokio::try_join!(
api::memes(
http,
cat.as_ref().map(String::from),
user.as_ref().map(String::from)
),
async {
if let Some(c) = cat.as_ref() {
util::assert_category_exists(http, c).await
} else {
Ok(())
}
},
async {
if let Some(u) = user.as_ref() {
util::assert_user_exists(http, u).await
} else {
Ok(())
}
},
)?;
let mut memes = memes.iter().collect::<Vec<_>>();
if let Some(s) = sorting {
s.sort_with(&mut memes);
}
let mut table = crate::util::list_table();
for m in memes.iter() {
table.add_row(m.into_table_row());
}
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(())
}