add interactive mode

This commit is contained in:
jojii 2021-03-16 14:45:58 +01:00
parent 25bd627643
commit 22c7a785c9
No known key found for this signature in database
GPG key ID: 87B75C673974601F

View file

@ -1,4 +1,6 @@
use argparse::{ArgumentParser, List, Print, Store}; use std::io::{stdin, stdout, Write};
use argparse::{ArgumentParser, List, Print, Store, StoreTrue};
use colored::*; use colored::*;
use serde_json::Value; use serde_json::Value;
@ -13,6 +15,7 @@ struct Options {
limit: usize, limit: usize,
query: String, query: String,
kanji: bool, // Sadly not (yet) supported by jisho.org's API kanji: bool, // Sadly not (yet) supported by jisho.org's API
interactive: bool,
} }
impl Default for Options { impl Default for Options {
@ -21,6 +24,7 @@ impl Default for Options {
limit: 4, limit: 4,
query: String::default(), query: String::default(),
kanji: false, kanji: false,
interactive: false,
} }
} }
} }
@ -28,8 +32,22 @@ impl Default for Options {
fn main() -> Result<(), ureq::Error> { fn main() -> Result<(), ureq::Error> {
let options = parse_args(); let options = parse_args();
let mut query = {
if options.interactive {
print!("=> ");
stdout().flush().unwrap();
let mut o = String::new();
stdin().read_line(&mut o).expect("Can't read from stdin");
o
} else {
options.query.clone()
}
};
loop {
// Do API request // Do API request
let body: Value = ureq::get(&format!(JISHO_URL!(), options.query)) let body: Value = ureq::get(&format!(JISHO_URL!(), query))
.call()? .call()?
.into_json()?; .into_json()?;
@ -45,17 +63,33 @@ fn main() -> Result<(), ureq::Error> {
body.unwrap() body.unwrap()
}); });
if options.interactive {
println!();
}
// Iterate over meanings and print them // Iterate over meanings and print them
for (i, entry) in body.iter().enumerate() { for (i, entry) in body.iter().enumerate() {
if i >= options.limit { if i >= options.limit {
break; break;
} }
if print_item(&options.query, entry).is_some() && i + 2 <= options.limit { if print_item(&query, entry).is_some() && i + 2 <= options.limit {
println!(); println!();
} }
} }
if !options.interactive {
break;
}
print!("\n=> ");
stdout().flush().unwrap();
query.clear();
stdin()
.read_line(&mut query)
.expect("Can't read from stdin");
}
Ok(()) Ok(())
} }
@ -228,6 +262,12 @@ fn parse_args() -> Options {
ap.refer(&mut query_vec) ap.refer(&mut query_vec)
.add_argument("Query", List, "The query to search for"); .add_argument("Query", List, "The query to search for");
ap.refer(&mut options.interactive).add_option(
&["-i", "--interactive"],
StoreTrue,
"Don't exit after running a query",
);
/* Uncomment when supported by jisho.org /* Uncomment when supported by jisho.org
ap.refer(&mut options.kanji).add_option( ap.refer(&mut options.kanji).add_option(
&["--kanji", "-k"], &["--kanji", "-k"],