From 2e9e63ed9f29b9d99c9634a859f5cd06374061c2 Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Sun, 31 Jul 2022 10:22:34 +0200 Subject: [PATCH] Create functions to load data files into a single `Vec` --- src/data/load.rs | 44 ++++++++++++++++++++++++++++++++++++++++++++ src/data/mod.rs | 1 + src/main.rs | 4 ++++ 3 files changed, 49 insertions(+) create mode 100644 src/data/load.rs diff --git a/src/data/load.rs b/src/data/load.rs new file mode 100644 index 0000000..234cc7b --- /dev/null +++ b/src/data/load.rs @@ -0,0 +1,44 @@ +use std::path::*; +use glob::{glob, GlobResult}; +use itertools::Itertools; +use crate::data::schema::Card; +use log::*; + + +#[derive(Debug)] +enum LoadingError { + IO(std::io::Error), + Parsing(serde_json::Error), +} + + +/// Load a single data file. +fn load_file(path: PathBuf) -> Result, LoadingError> { + let file = std::fs::File::open(path) + .map_err(LoadingError::IO)?; + let data = serde_json::de::from_reader::>(file) + .map_err(LoadingError::Parsing)?; + Ok(data) +} + + +/// Load a single data file, and handle errors by logging them as warnings. +fn load_file_and_warn(path: PathBuf) -> Vec { + match load_file(path) { + Ok(v) => v, + Err(e) => { + warn!("{:?}", e); + vec![] + } + } +} + + +/// Load all possible data files. +pub fn load_files() -> Vec { + glob("./data/*/en_us/data/*.json") + .unwrap() + .filter_map(GlobResult::ok) + .map(load_file_and_warn) + .concat() +} diff --git a/src/data/mod.rs b/src/data/mod.rs index 1ce7e17..2de4b23 100644 --- a/src/data/mod.rs +++ b/src/data/mod.rs @@ -1 +1,2 @@ pub mod schema; +pub mod load; diff --git a/src/main.rs b/src/main.rs index 86997db..9a4ec7e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -8,6 +8,10 @@ mod data; #[tokio::main] async fn main() { pretty_env_logger::init(); + + let data = data::load::load_files(); + debug!("{:?}", data); + info!("patched-porobot is starting..."); let bot = Bot::from_env().auto_send();