From f62e5d7cc1d01066faa5bcc98ddb61a0208b834c Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Mon, 25 Mar 2024 23:35:29 +0100 Subject: [PATCH] Adds coverage, docs and starts the mess of generation --- Cargo.toml | 10 + src/data_structure.rs | 28 +- src/generator.rs | 9 +- src/loader.rs | 17 +- src/main.rs | 9 +- src/skills_structures.rs | 221 +++++++++++++ tarpaulin-report.html | 671 +++++++++++++++++++++++++++++++++++++++ 7 files changed, 959 insertions(+), 6 deletions(-) create mode 100644 src/skills_structures.rs create mode 100644 tarpaulin-report.html diff --git a/Cargo.toml b/Cargo.toml index a881529..43b4028 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,6 +10,7 @@ edition = "2021" criterion = "0.5.1" divan = "0.1.14" serde = { version = "1.0.197", features = ["derive"] } +strfmt = "0.2.4" toml = { version = "0.8.12", features = ["preserve_order"] } [profile.dev] @@ -21,6 +22,15 @@ lto = true codegen-units = 1 panic = "abort" +[profile.testing] +inherits = "dev" +opt-level = 0 +debug = 0 +strip = false +lto = false +codegen-units = 256 +incremental = true + [[bench]] name = "test_ascii_div" harness = false diff --git a/src/data_structure.rs b/src/data_structure.rs index 10bcb77..d8ce156 100644 --- a/src/data_structure.rs +++ b/src/data_structure.rs @@ -4,9 +4,9 @@ //! use serde::Deserialize; -use toml::Table; #[derive(Deserialize, Debug)] +/// The GlobalConfiguration, loads and holds all information needed to generate a character pub struct GlobalConfig { /// The config section, includes all important links to external skills/data config: Config, @@ -40,6 +40,32 @@ pub struct Data { css_footer: String, } +/// Repeating skill data + +/// Skill generation data +pub struct SkillGenerator { + /// Content of a skill, to be formatted + skill_content: String, + /// Content of a subskill, to be formatted + subskill_content: String, + /// Filler of a subskill, added before each skill, to be formatted + subskill_filler: String, + + /// Content of a section + section_content: String, + /// Header of a section + section_header: String, + /// Footer of a section + section_footer: String, + + /// Content of a sub_section + sub_section_content: String, + /// Header of a sub_section + sub_section_header: String, + /// Footer of a sub_section + sub_section_footer: String, +} + // #[derive(Deserialize, Debug)] // pub struct SkillsData { // sections: , diff --git a/src/generator.rs b/src/generator.rs index e5986da..27106c1 100644 --- a/src/generator.rs +++ b/src/generator.rs @@ -6,8 +6,6 @@ //! Data -> CS_Raw -> CS_Empty -> CS_Ready //! -> CH_Raw -> CH_Ready -^ -use std::path::Path; - use crate::{ data_structure::Data, loader::{LoadError, SheetModel}, @@ -15,22 +13,27 @@ use crate::{ /// A raw CharacterSheet, with everything ready to generate all fields pub trait CsRaw { + /// Build a CharacterSheet from the given data fn from_data(data: &Data) -> Self; + /// Transform the character sheet into an empty character sheet fn build(&self) -> impl CsEmpty; } /// A build CharacterSheet, ready to be filled with the skills loaded pub trait CsEmpty { + /// Fill all fields in the character sheet fn fill(&self, skills: &impl ChRaw) -> impl ChReady; } /// A finished CharacterSheet, ready to be exported pub trait CsReady { + /// Export the character sheet into the given path fn export(&self, path: T) -> Result<(), LoadError>; } /// A raw SkillList, loaded from file, ready to generate all skills pub trait ChRaw { + /// Create a Raw Character with a SheetModel, ready to be exported fn from_data(data: &SheetModel) -> impl ChReady; } @@ -39,7 +42,7 @@ pub trait ChReady {} /// Can generate a character sheet pub trait Generator { - fn new() {} + // fn new() {} } /// Strip the skill name from any non AZaz character diff --git a/src/loader.rs b/src/loader.rs index 47beb40..55db238 100644 --- a/src/loader.rs +++ b/src/loader.rs @@ -2,7 +2,7 @@ //! //! The `loader` module provides functionality for loading a specific model file and handling IO operations and errors. -use std::{borrow::Borrow, fs, io, path::Path}; +use std::{fs, io, path::Path}; use crate::data_structure::GlobalConfig; @@ -18,6 +18,7 @@ pub enum LoadError { /// Represents a model once loaded #[derive(Debug)] pub struct SheetModel { + /// The Config associated with a Model config: Option, } @@ -62,6 +63,7 @@ impl SheetModel { Ok(()) } + /// Create a Model from a path (shortcut for creating and loading) pub fn from_file

(path: P) -> Result where P: AsRef, @@ -96,4 +98,17 @@ mod tests { let mut modl = SheetModel::new(); assert!(modl.load_model(Path::new("wrong_file")).is_err()) } + + #[test] + fn test_from_file() { + let modl = SheetModel::from_file(Path::new("data/cyberpunk.toml")); + assert!(modl.is_ok()); + assert!(modl.unwrap().config.is_some()); + let modl = SheetModel::from_file(Path::new("wrong_file")); + assert!(modl.is_err()); + match modl.err().unwrap() { + crate::loader::LoadError::Io(_e) => (), + crate::loader::LoadError::InvalidFormat => (), + } + } } diff --git a/src/main.rs b/src/main.rs index ea7646a..8d9d38c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,11 +1,18 @@ +//! rust20_d10 is a character sheet generator for tabletop role-playing games (TTRPGs) for the roll20 website. +//! This project is written in Rust, aiming for efficiency, reliability, and speed. + +#![allow(dead_code)] +#![warn(missing_docs)] +#![warn(clippy::missing_docs_in_private_items)] use loader::SheetModel; mod data_structure; mod export; mod generator; mod loader; +mod skills_structures; fn main() { - let mut modl = SheetModel::from_file("data/cyberpunk.toml"); + let modl = SheetModel::from_file("data/cyberpunk.toml"); println!("{:?}", modl); } diff --git a/src/skills_structures.rs b/src/skills_structures.rs new file mode 100644 index 0000000..d0e0767 --- /dev/null +++ b/src/skills_structures.rs @@ -0,0 +1,221 @@ +//! # Skills Module +//! +//! The `skills` module provides data structures and methods for managing skills. +//! +//! Includes all Section/Subsection/Skill/Sub-skill and a skill-list parser +use std::{collections::HashMap, str::FromStr}; +use strfmt::strfmt; + +/// Type sugarcoat of a replacement hashmap +type HashReplace = HashMap; + +/// The global list of skills +pub struct SkillList { + /// The list of all section in this skilllist + list: Vec

, + /// The name of the list (unused) + data: DataCell, +} + +/// A section, marked by @ +struct Section { + /// The list of subsection depending on this section + list: Vec, + /// The name of the cell + data: DataCell, + // /// The identifier number of the cell + // id: usize, + // /// The global identifier of the cell + // global_id: usize, + // /// The various fields needed to transform a skill Section html + // vars: HashReplace, +} + +/// A subsection, marked by + +struct SubSection { + /// The list of skills depending of this SubSection + list: Vec, + /// The name of the cell + data: DataCell, + // /// The identifier number of the cell + // id: usize, + // /// The global identifier of the cell + // global_id: usize, + // /// The various fields needed to transform a subsection into html + // vars: HashReplace, +} + +/// A skill, marked by = +struct Skill { + /// The list of subskills depending of this skill + list: Vec, + /// The name of the cell + data: DataCell, + // /// The identifier number of the cell + // id: usize, + // /// The global identifier of the cell + // global_id: usize, + // /// The various fields needed to transform a skill into html + // vars: HashMap, +} + +/// A subskill, marked by - +struct SubSkill { + /// The name of the cell + data: DataCell, + // /// The various fields needed to transform a subskill into html + // vars: HashMap, +} + +/// The data of a cell +struct DataCell { + /// The name, untouched, as a string + name: String, + /// The name, stripped of any non AZaz + stripped_name: String, + /// The identifier number of the cell + id: usize, + /// The global identifier of the cell + global_id: usize, +} + +/// A Data point, holds the name and stripped name of element +impl DataCell { + /// Create a datacell from the given raw string + pub fn new(raw_name: &str, id: usize, global_id: usize) -> Self { + let name = String::from_str(raw_name).unwrap(); + let stripped_name = name.replace(|c: char| !c.is_ascii_alphabetic(), ""); + DataCell { + name, + stripped_name, + id, + global_id, + } + } + + /// Create a hashmap with all the data in the DataCell + pub fn to_hashmap(&self) -> HashReplace { + let mut h = HashReplace::new(); + h.insert("name".to_string(), self.name.to_string()); + h.insert("pname".to_string(), self.stripped_name.to_string()); + h.insert("id".to_string(), self.id.to_string()); + h.insert("global_id".to_string(), self.global_id.to_string()); + if self.id == 1 { + h.insert("selected".to_string(), "true".to_owned()); + } else { + h.insert("selected".to_string(), "false".to_owned()); + } + h + } +} + +/// A CharacterSheet ready to be rendered +trait Renderable { + /// Create a new renderable + fn new(name: &str, id: usize, global_id: usize, size_hint: usize) -> Self; + /// Get the vars hashmap + fn get_vars(&self) -> HashReplace; + /// Render the element and all sub elements + fn render(&self, model: &str) -> Result; + /// Render the element header + fn header(&self, model: &str) -> Result; + /// Render the element content + fn content(&self, model: &str) -> Result; + /// Render the element footer + fn footer(&self, model: &str) -> Result; + /// Get the underlying name of the skill + fn get_name(&self) -> &str; + /// Get the underlying short name + fn get_stripped_name(&self) -> &str; + /// Get the id (compared to elements of the same level) + fn get_id(&self) -> usize; + /// Get the global id (compared to every element) + fn get_global_id(&self) -> usize; +} + +impl Renderable for Section { + fn get_id(&self) -> usize { + self.data.id + } + fn get_global_id(&self) -> usize { + self.data.global_id + } + fn get_name(&self) -> &str { + &self.data.name + } + fn get_stripped_name(&self) -> &str { + &self.data.stripped_name + } + fn get_vars(&self) -> HashReplace { + self.data.to_hashmap() + } + + /// A section cannot be rendered as a whole + fn render(&self, _model: &str) -> Result { + Err(ErrorSkills::NonCallableMethod) + } + + fn header(&self, model: &str) -> Result { + let mut vars = HashMap::new(); + vars.insert("number".to_string(), "0"); + vars.insert("name".to_string(), self.get_name()); + + match self.get_id() { + 0 => vars.insert("checked".to_string(), "checked=\"checked\""), + _ => vars.insert("checked".to_string(), ""), + }; + match strfmt(model, &vars) { + Ok(res) => Ok(res), + Err(e) => Err(ErrorSkills::FormatError(e)), + } + } + + fn content(&self, model: &str) -> Result { + match strfmt(model, &self.get_vars()) { + Ok(r) => Ok(r), + Err(e) => Err(ErrorSkills::FormatError(e)), + } + } + + fn footer(&self, _model: &str) -> Result { + Err(ErrorSkills::NonCallableMethod) + } + + fn new(name: &str, id: usize, global_id: usize, size_hint: usize) -> Self { + Self { + list: Vec::with_capacity(size_hint), + data: DataCell::new(name, id, global_id), + } + } +} + +/// All errors regarding the skill handling +pub enum ErrorSkills { + /// The formatting failed + FormatError(strfmt::FmtError), + /// This method can't be called in this implementation, lighter than a panic + NonCallableMethod, +} + +#[cfg(test)] +mod tests { + use super::{DataCell, Renderable, Section}; + + static S1: &str = + "This is a test sentence with some non-ASCII characters like café and résumé."; + static S2: &str = "ThisisatestsentencewithsomenonASCIIcharacterslikecafandrsum"; + static T1: &str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris in velit purus. Cras commodo, libero vel tempus facilisis, erat metus eleifend nulla, at dignissim nibh erat vel magna. Maecenas in augue eget tortor rhoncus venenatis. Fusce non odio vitae velit dictum ultricies eget a mauris. Nullam sodales nisi in enim pulvinar, ut eleifend ex feugiat. Integer tincidunt, metus et consectetur ultricies, magna dolor fringilla lorem, non ultricies ligula est quis justo. Quisque non diam at magna efficitur fermentum."; + static T2: &str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris in velit purus. Cras commodo, libero vel tempus facilisis, erat metus eleifend nulla, at dignissim nibh erat vel magna. Maecenas in augue eget tortor rhoncus venenatis. Fusce non odio vitae velit dictum ultricies eget a mauris. Nullam sodales nisi in enim pulvinar, ut eleifend ex feugiat. Integer tincidunt, metus et consectetur ultricies, magna dolor fringilla lorem, non ultricies ligula est quis justo. Quisque non diam at magna efficitur fermentum."; + static U: &str = "Thïs ïs å råñdôm têšt wïth 1234 sÿmbøls ãñd chårãctêrs lïkê ¡@#$%^&*()_+={}[]:;'\"<>,.?/èéêëēęëēæœöôóøōõúüùûūų"; + static V: &str = "Testing special characters like ©, ®, ™, and emojis like 😊, 💻."; + #[test] + fn test_datacell() { + let ds = DataCell::new(S1, 1, 1); + assert_eq!(ds.name, S1); + assert_eq!(ds.stripped_name, S2); + } + #[test] + fn test_section() { + let _s1 = Section::new(T1, 0, 1, 30); + } +} diff --git a/tarpaulin-report.html b/tarpaulin-report.html new file mode 100644 index 0000000..71582eb --- /dev/null +++ b/tarpaulin-report.html @@ -0,0 +1,671 @@ + + + + + + + +
+ + + + + + \ No newline at end of file