Adds coverage, docs and starts the mess of generation

This commit is contained in:
Dandaedre 2024-03-25 23:35:29 +01:00
parent d49e3d5378
commit f62e5d7cc1
7 changed files with 959 additions and 6 deletions

View File

@ -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

View File

@ -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: ,

View File

@ -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<T>(&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

View File

@ -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<GlobalConfig>,
}
@ -62,6 +63,7 @@ impl SheetModel {
Ok(())
}
/// Create a Model from a path (shortcut for creating and loading)
pub fn from_file<P>(path: P) -> Result<Self, LoadError>
where
P: AsRef<Path>,
@ -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 => (),
}
}
}

View File

@ -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);
}

221
src/skills_structures.rs Normal file
View File

@ -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<String, String>;
/// The global list of skills
pub struct SkillList {
/// The list of all section in this skilllist
list: Vec<Section>,
/// The name of the list (unused)
data: DataCell,
}
/// A section, marked by @
struct Section {
/// The list of subsection depending on this section
list: Vec<SubSection>,
/// 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<Skill>,
/// 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<SubSkill>,
/// 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<String, String>,
}
/// 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<String, String>,
}
/// 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<String, ErrorSkills>;
/// Render the element header
fn header(&self, model: &str) -> Result<String, ErrorSkills>;
/// Render the element content
fn content(&self, model: &str) -> Result<String, ErrorSkills>;
/// Render the element footer
fn footer(&self, model: &str) -> Result<String, ErrorSkills>;
/// 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<String, ErrorSkills> {
Err(ErrorSkills::NonCallableMethod)
}
fn header(&self, model: &str) -> Result<String, ErrorSkills> {
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<String, ErrorSkills> {
match strfmt(model, &self.get_vars()) {
Ok(r) => Ok(r),
Err(e) => Err(ErrorSkills::FormatError(e)),
}
}
fn footer(&self, _model: &str) -> Result<String, ErrorSkills> {
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);
}
}

671
tarpaulin-report.html Normal file

File diff suppressed because one or more lines are too long