From 0ace78a01e59545953ef5be6ca6bcaa4a125a70b Mon Sep 17 00:00:00 2001 From: WriterV2 Date: Sun, 4 Sep 2022 18:12:55 +0200 Subject: Add error context + comments --- src/main.rs | 5 +++-- src/works/mod.rs | 22 +++++++++++++++++++--- src/works/stories.rs | 5 +++++ 3 files changed, 27 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/main.rs b/src/main.rs index 77f4fef..942b621 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,14 +6,15 @@ use crate::works::Works; mod works; fn main() -> Result<()> { + // new tera instance let tera = Tera::new("templates/**/*.html")?; + // render index.html file let context = Context::new(); - let output = tera.render("index.html", &context)?; - std::fs::write("docs/index.html", output)?; + // render stories.html file let stories = works::stories::Stories::new_from_file(std::fs::File::open( std::path::PathBuf::from("stories.json"), )?); diff --git a/src/works/mod.rs b/src/works/mod.rs index 8941542..8de16d7 100644 --- a/src/works/mod.rs +++ b/src/works/mod.rs @@ -1,19 +1,28 @@ -use anyhow::Result; +use anyhow::{Context, Result}; use serde::{Deserialize, Serialize}; pub mod stories; +// functionality for a group of work, e.g. stories or games 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 { - Ok(serde_json::from_reader(std::io::BufReader::new(file))?) + Ok(serde_json::from_reader(std::io::BufReader::new(&file)) + // add error context + .with_context(|| format!("Failed to create works from {:?}", &file))?) } + // crate tera context from the group of work + // tera context can be accessed in HTML tera templating fn create_tera_context(&self) -> Result { let mut context = tera::Context::new(); context.insert("works", &self); Ok(context) } + // render corresponding overview HTML template + // with its tera context fn render_overview_page( &self, tera_instance: &tera::Tera, @@ -25,6 +34,13 @@ pub trait Works: for<'a> Deserialize<'a> + Serialize { format!("{}.html", filename_without_extension).as_str(), &self.create_tera_context()?, )?, - )?) + ) + // add error context + .with_context(|| { + format!( + "Failed to render overview page for {:?}", + filename_without_extension + ) + })?) } } diff --git a/src/works/stories.rs b/src/works/stories.rs index 73d89ad..e6f5427 100644 --- a/src/works/stories.rs +++ b/src/works/stories.rs @@ -1,5 +1,8 @@ use serde::{Deserialize, Serialize}; +// stories and their information +// derive from JSON +// process to context for HTML #[derive(Debug, Deserialize, Serialize)] pub struct Stories(pub Vec); @@ -13,8 +16,10 @@ pub struct Story { pub language: Language, } +// see src/works/mod.rs for information of Works trait impl super::Works for Stories {} +// language of story content #[derive(Deserialize, Serialize, Debug)] pub enum Language { German, -- cgit v1.2.3