use serde::Deserialize;
use std::error::Error;
use std::fs::File;
use std::io::BufReader;
use std::path::Path;
#[derive(Deserialize, Debug)]
pub struct Asciimoji {
names: Vec<String>,
moji: String,
}
impl Asciimoji {
pub fn to_lowercase(mut self) -> Asciimoji{
self.names = self.names.into_iter().map(|name| name.to_lowercase()).collect();
self
}
pub fn names(& self) -> &Vec<String> {
&self.names
}
pub fn moji(& self) -> &String {
&self.moji
}
}
pub fn read_asciimojis_from_file<P: AsRef<Path>>(path: P) -> Result<Vec<Asciimoji>, Box<dyn Error>> {
let yaml = serde_yaml::from_reader(BufReader::new(File::open(path)?))?;
Ok(yaml)
}
pub fn search_name<'a>(asciimojis: &'a Vec<Asciimoji>, name: &String) -> Vec<&'a String> {
asciimojis
.into_iter()
.filter(|ascimoji| ascimoji.names.contains(name))
.map(|ascimoji| &ascimoji.moji)
.collect()
}
pub mod downloader {
use std::error::Error;
use curl::easy::Easy;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
const YAML_URL: &str = "https://gitlab.com/jjocram/asciimoji/-/raw/master/asciimojis.yml";
pub fn download_yaml_file_from_repository(yaml_path: &str) -> Result<(), Box<dyn Error>> {
if Path::new(yaml_path).exists(){
return Ok(());
}
let mut yaml_file = File::create(yaml_path).unwrap();
let mut easy = Easy::new();
easy.url(YAML_URL)?;
easy.write_function(move |data| {
yaml_file.write_all(data).unwrap();
Ok(data.len())
})?;
easy.perform().unwrap();
Ok(())
}
}