feat(cli): fetch from free dictionary
This commit is contained in:
+52
-1
@@ -1,13 +1,64 @@
|
|||||||
use clap::Parser;
|
use clap::Parser;
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
#[derive(Parser, Debug)]
|
#[derive(Parser, Debug)]
|
||||||
#[command(version, about, long_about = None)]
|
#[command(version, about, long_about = None)]
|
||||||
struct Args {
|
struct Args {
|
||||||
word: String,
|
word: String,
|
||||||
|
#[arg(short, long, default_value = "en")]
|
||||||
|
language: String,
|
||||||
|
#[arg(short, long, action = clap::ArgAction::SetTrue)]
|
||||||
|
examples: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
struct DictionarySearchResult {
|
||||||
|
word: String,
|
||||||
|
entries: Vec<DictionaryEntry>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
struct DictionaryEntry {
|
||||||
|
part_of_speech: String,
|
||||||
|
senses: Vec<DictionarySense>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
struct DictionarySense {
|
||||||
|
definition: String,
|
||||||
|
examples: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn define(word: &str, language: &str) -> Result<DictionarySearchResult, reqwest::Error> {
|
||||||
|
let url = format!(
|
||||||
|
"https://freedictionaryapi.com/api/v1/entries/{}/{}",
|
||||||
|
language, word
|
||||||
|
);
|
||||||
|
reqwest::get(url).await?.json().await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() {
|
async fn main() {
|
||||||
let args = Args::parse();
|
let args = Args::parse();
|
||||||
println!("{:?}", args);
|
let result = define(&args.word, &args.language).await;
|
||||||
|
if result.is_err() {
|
||||||
|
panic!("Error: {}", result.err().unwrap());
|
||||||
|
}
|
||||||
|
|
||||||
|
let result = result.unwrap();
|
||||||
|
|
||||||
|
for entry in result.entries {
|
||||||
|
println!("{} ({})", result.word, entry.part_of_speech);
|
||||||
|
for sense in entry.senses {
|
||||||
|
println!("- {}", sense.definition);
|
||||||
|
if args.examples {
|
||||||
|
for example in sense.examples {
|
||||||
|
println!(" ex: {}", example);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user