From 3d1e4859f6a09208966407cefaae5ba6803ddc26 Mon Sep 17 00:00:00 2001 From: WriterV2 Date: Sat, 3 Jun 2023 14:52:30 +0200 Subject: Refactor file operations to method that creates work --- src/works/mod.rs | 14 ++++++++++---- src/works/stories.rs | 11 +++++++++-- 2 files changed, 19 insertions(+), 6 deletions(-) (limited to 'src/works') diff --git a/src/works/mod.rs b/src/works/mod.rs index 0970cb1..a588ae8 100644 --- a/src/works/mod.rs +++ b/src/works/mod.rs @@ -1,3 +1,6 @@ +use std::fs::File; +use std::path::PathBuf; + use anyhow::{Context, Ok, Result}; use serde::{Deserialize, Serialize}; @@ -7,10 +10,13 @@ pub mod stories; pub trait Works: for<'a> Deserialize<'a> + Serialize { // create works from the corresponding JSON file, // e.g. stories from stories.json - fn new_from_file(file: &std::fs::File) -> Result { - let file = serde_json::from_reader(std::io::BufReader::new(file)) - .with_context(|| format!("Failed to create works from {:#?}", &file))?; - Ok(file) + fn new_from_file(workname: &str) -> Result { + let work = serde_json::from_reader(std::io::BufReader::new( + &File::open(PathBuf::from(workname)) + .with_context(|| format!("Failed to open {}.json", workname))?, + )) + .with_context(|| format!("Failed to create works from {}.json", workname))?; + Ok(work) } // crate tera context from the group of work diff --git a/src/works/stories.rs b/src/works/stories.rs index 2623db6..1c96e2a 100644 --- a/src/works/stories.rs +++ b/src/works/stories.rs @@ -1,3 +1,5 @@ +use std::fs::File; +use std::path::PathBuf; use anyhow::{Result, Ok, Context}; use chrono::NaiveDate; use serde::{Deserialize, Serialize}; @@ -44,8 +46,13 @@ impl super::Works for Stories { } // create stories from stories.json and add last modification date - fn new_from_file(file: &std::fs::File) -> Result { - let mut stories: Stories = serde_json::from_reader(std::io::BufReader::new(file)).with_context(|| format!("Failed to read JSON from {:#?}", file))?; + fn new_from_file(workname: &str) -> Result { + let mut stories: Self = serde_json::from_reader(std::io::BufReader::new( + &File::open(PathBuf::from(workname)) + .with_context(|| format!("Failed to open {}.json", workname))?, + )) + .with_context(|| format!("Failed to create works from {}.json", workname))?; + for story in stories.0.iter_mut() { story.get_last_modified().with_context(|| format!("Failed to get last modified date for {}", story.title))?; story.get_pages_num().with_context(|| format!("Failed to get number of pages from {}'s PDF", story.title))?; -- cgit v1.2.3