Working dispatch, needs to stop beying dynamic

This commit is contained in:
Dandaedre 2024-05-05 05:26:09 +02:00
parent 658c6e1e7b
commit cd64e4423b
5 changed files with 186 additions and 59 deletions

View File

@ -11,6 +11,7 @@ anyhow = "1.0.82"
clap = { version = "4.5.4", features = ["derive"] }
csv = "1.3.0"
dynfmt = { version = "0.1.5", features = ["curly"] }
enum_dispatch = "0.3.13"
glob = "0.3.1"
phf = { version = "0.11.2", features = ["macros"] }
regex = "1.10.4"

View File

@ -12,19 +12,21 @@ end = ''' \hline
\end{tabularx}
}'''
[alchimie]
[armes]
[armures]
[forge]
[fud]
[gadgets]
[mpieges]
[potions]
[craft]
header_food = '''{\footnotesize
\rowcolors{2}{gray!25}{white}
\begin{tabularx}{\textwidth}{|p{0.17\linewidth\hyphenpenalty=9000}lp{0.13\linewidth}p{0.042\linewidth}X|}
\hline\rowcolor{gray!50}\hline
Ingrédient&Partie&Rareté&Satiété&Effet&(Plat)&Effets&(Accompagnement)&Difficulté&Toxicité \\
\hline'''
header_alchemy = ""
header_forge = ""
header_mtrap = ""
header_weapons = ""
header_armors = ""
header_gadgets = ""
header_potions = ""
header_traps = ""
end = ''' \hline
\end{tabularx}
}'''

View File

@ -3,8 +3,9 @@
//! This program is meant as a helper for the ravenous project.
//!
#![allow(dead_code)]
#![warn(missing_docs)]
#![warn(clippy::missing_docs_in_private_items)]
// #![warn(clippy::missing_docs_in_private_items)]
mod table_structs;
mod tablegen;
use crate::table_structs::TableArgs;
@ -36,6 +37,8 @@ enum Commands {
struct Config {
/// Config specific for the classes table generation
classes: Classes,
/// Config for all the tables
craft: Craft,
}
#[derive(Deserialize)]
@ -49,6 +52,31 @@ struct Classes {
end: String,
}
#[derive(Deserialize)]
/// The Craft configs
struct Craft {
/// The food header string formatter
header_food: String,
/// The alchemy header string formatter
header_alchemy: String,
/// The forge header string formatter
header_forge: String,
/// The mtrap header string formatter
header_mtrap: String,
/// The weapons header string formatter
header_weapons: String,
/// The armors header string formatter
header_armors: String,
/// The gadgets header string formatter
header_gadgets: String,
/// The potions header string formatter
header_potions: String,
/// The traps header string formatter
header_traps: String,
/// The table end string formatter
end: String,
}
fn main() {
let args = Args::parse();
let config = &fs::read_to_string("helper_config.toml")

View File

@ -1,6 +1,6 @@
//! Holds all the data structures away from the main routine
use crate::{tablegen::make_latex_string, Config};
use anyhow::Result;
use anyhow::{Context, Result};
use clap::Args;
use dynfmt::{Format, SimpleCurlyFormat};
use phf::phf_map;
@ -46,6 +46,7 @@ static STR_TO_TARGET: phf::Map<&'static str, TargetType> = phf_map! {
};
/// All the type of tsv that can be processed by the program
// #[enum_dispatch]
pub enum TableTargets {
/// A class tsv
Classes,
@ -86,12 +87,6 @@ pub(crate) static STR_TO_TARGET_FULL: phf::Map<&'static str, TableTargets> = phf
/// The regex for finding and replacing all stars with a custom DD
pub(crate) static RE: Lazy<Regex> = regex_static::lazy_regex!(r"★+");
// /// Type of tables that the program can handle
// pub enum TableType {
// CraftTable,
// CharacterTable,
// }
impl From<&str> for TargetType {
fn from(value: &str) -> Self {
if let Some(target) = STR_TO_TARGET.get(value).cloned() {
@ -123,10 +118,28 @@ pub struct RecordClass {
pub effet: CleanString,
}
impl Display for RecordClass {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
// impl Display for RecordClass {
// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// write!(
// f,
// " {}&{}&{}&{}{}&{} \\\\",
// self.technique,
// self.niveau,
// self.technique_type,
// self.cout_blood,
// self.cout_jauge,
// self.effet
// )
// }
// }
impl WriteRow for RecordClass {
fn write_header(&self, _buffer: &mut BufWriter<Vec<u8>>, _configg: &Config) -> Result<()> {
unimplemented!()
}
fn write_row(&self, buffer: &mut BufWriter<Vec<u8>>, _config: &Config) -> Result<()> {
Ok(write!(
buffer,
" {}&{}&{}&{}{}&{} \\\\",
self.technique,
self.niveau,
@ -134,10 +147,13 @@ impl Display for RecordClass {
self.cout_blood,
self.cout_jauge,
self.effet
)
)?)
}
fn write_footer(&self, _buffer: &mut BufWriter<Vec<u8>>, _configg: &Config) -> Result<()> {
unimplemented!()
}
}
/// Represents the whole Classes Array, with a vec for every tier
pub(crate) struct ClassesArray {
/// Every tier held as a vec of vec of rows
@ -145,15 +161,23 @@ pub(crate) struct ClassesArray {
}
/// Trait needed to be writable as a LaTex table
pub(crate) trait WriteRows {
pub(crate) trait WriteTable {
/// Takes a config and writes to a string the representation of the Array
fn write_rows(&self, config: &Config) -> Result<String>;
fn write_table(&self, config: &Config) -> Result<String>;
}
// impl ClassesArray {
/// Trait needed to be writable as a LaTex table
pub(crate) trait WriteRow {
fn write_header(&self, buffer: &mut BufWriter<Vec<u8>>, config: &Config) -> Result<()>;
fn write_row(&self, buffer: &mut BufWriter<Vec<u8>>, config: &Config) -> Result<()>;
fn write_footer(&self, buffer: &mut BufWriter<Vec<u8>>, config: &Config) -> Result<()>;
}
// pub(crate) trait WriteRows {
// /// Takes a config and writes to a string the representation of the Array
// fn write_rows(&self, config: &Config) -> Result<String>;
// }
impl WriteRows for ClassesArray {
fn write_rows(&self, config: &Config) -> Result<String> {
impl WriteTable for ClassesArray {
fn write_table(&self, config: &Config) -> Result<String> {
let mut buffer = BufWriter::new(Vec::new());
for (lvl, tier) in self.tiers.iter().skip(1).enumerate() {
// rt_write!(buffer, config.classes.header, lvl + 1)?;
@ -163,16 +187,7 @@ impl WriteRows for ClassesArray {
writeln!(buffer, "{}", formatted_header)?;
writeln!(buffer, "{}", config.classes.row)?;
for elem in tier {
writeln!(
buffer,
" {}&{}&{}&{}{}&{} \\\\",
elem.technique,
elem.niveau,
elem.technique_type,
elem.cout_blood,
elem.cout_jauge,
elem.effet
)?;
elem.write_row(&mut buffer, config)?
}
writeln!(buffer, "{}", config.classes.end)?;
}
@ -180,6 +195,87 @@ impl WriteRows for ClassesArray {
}
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "PascalCase")]
/// A single row in a martial class tsv file
pub struct RecordFood {
pub ingredient: String,
pub part: String,
pub rarity: CleanString,
pub filling: CleanString,
pub effect_main: CleanString,
pub effect_secondary: CleanString,
pub difficulty: CleanString,
pub toxicity: CleanString,
}
impl Display for RecordFood {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
" {}&{}&{}{}&{}&{}&{}&{} \\\\",
self.ingredient,
self.part,
self.rarity,
self.filling,
self.effect_main,
self.effect_secondary,
self.difficulty,
self.toxicity,
)
}
}
impl WriteRow for RecordFood {
fn write_header(&self, buffer: &mut BufWriter<Vec<u8>>, config: &Config) -> Result<()> {
writeln!(buffer, "{}", config.craft.header_food).context("Writing header")
// Ok(String::from_utf8(buffer.into_inner()?).unwrap())
}
fn write_row(&self, buffer: &mut BufWriter<Vec<u8>>, _config: &Config) -> Result<()> {
write!(
buffer,
" {}&{}&{}{}&{}&{}&{}&{} \\\\",
self.ingredient,
self.part,
self.rarity,
self.filling,
self.effect_main,
self.effect_secondary,
self.difficulty,
self.toxicity,
)
.context("Writing row")
}
fn write_footer(&self, buffer: &mut BufWriter<Vec<u8>>, config: &Config) -> Result<()> {
writeln!(buffer, "{}", config.craft.end).context("Writing footer")
}
}
/// Represents the whole Craft Array, with a vec for every tier
pub(crate) struct CraftArray<RecordType>
where
RecordType: WriteRow,
{
/// Every tier held as a vec of vec of rows
pub row: Vec<RecordType>,
}
impl<RecordType> WriteTable for CraftArray<RecordType>
where
RecordType: WriteRow,
{
fn write_table(&self, config: &Config) -> Result<String> {
let mut buffer = BufWriter::new(Vec::new());
self.row[0].write_header(&mut buffer, config)?;
for row in self.row.iter() {
row.write_row(&mut buffer, config)?;
}
self.row[0].write_footer(&mut buffer, config)?;
Ok(String::from_utf8(buffer.into_inner()?).unwrap())
}
}
/// This type is used to represent strings in LaTeX tables, where certain characters need to be escaped or replaced with special commands.
#[derive(Deserialize)]
pub struct CleanString(String);

View File

@ -11,8 +11,8 @@ use std::{
use crate::{
table_structs::{
ClassesArray, RecordClass, TableArgs, TableTargets, TargetType, WriteRows, RE,
STR_TO_TARGET_FULL,
ClassesArray, CraftArray, RecordClass, RecordFood, TableArgs, TableTargets, TargetType,
WriteRow, WriteTable, RE, STR_TO_TARGET_FULL,
},
Config,
};
@ -52,14 +52,14 @@ fn process_files(list_files: &mut Vec<PathBuf>, args: &TableArgs, config: &Confi
/// Process one file
fn process_one_file(f: &mut PathBuf, args: &TableArgs, config: &Config) -> Result<()> {
let tt = extract_type(f).context("Error extracting file type ... skipping")?;
let tsv: Box<dyn WriteRows> = match tt {
let tsv: Box<dyn WriteTable> = match tt {
TableTargets::Classes => Box::new(read_tsv_classes(f)?),
_ => Box::new(read_tsv::<RecordClass, ClassesArray>(f)?),
_ => read_tsv::<RecordFood>(f, tt)?,
};
match tt {
TableTargets::Classes => export_tsv(f, tsv, args, config),
TableTargets::Food => todo!(),
TableTargets::Food => export_tsv(f, tsv, args, config),
TableTargets::Alchemy => todo!(),
TableTargets::Forge => todo!(),
TableTargets::MPieges => todo!(),
@ -103,7 +103,7 @@ fn list_dir(pattern: &str) -> Vec<PathBuf> {
/// it will be returned as part of the result.
pub fn export_tsv(
f: &Path,
tsv: Box<dyn WriteRows>,
tsv: Box<dyn WriteTable>,
args: &TableArgs,
config: &Config,
) -> Result<()> {
@ -172,10 +172,10 @@ where
///
/// This function reads in a comma-separated values (TSV) file and returns it as a Table object,
/// which can be used to generate LaTeX code or perform other operations on the data.
fn read_tsv<RecordType, RecordHolder>(filename: &Path) -> Result<RecordHolder>
fn read_tsv<RecordType>(filename: &Path, target_type: &TableTargets) -> Result<Box<dyn WriteTable>>
where
RecordType: for<'a> serde::Deserialize<'a>,
RecordHolder: WriteRows,
RecordType: for<'a> serde::Deserialize<'a> + WriteRow + 'static,
// RecordHolder: WriteRows,
{
let file = File::open(filename)?;
let mut rdr = csv::ReaderBuilder::new()
@ -193,14 +193,14 @@ where
levels.push(result);
}
// Ok(RecordHolder{})
todo!()
let craft_array = CraftArray { row: levels };
Ok(Box::new(craft_array))
}
/// Converts a table of data into a string representation.
///
/// This function takes in a Table object and returns its contents as a formatted string,
/// which can be used to generate LaTeX code or perform other operations on the data.
pub(crate) fn tsv_to_string(tsv: Box<dyn WriteRows>, config: &Config) -> Result<String> {
tsv.write_rows(config)
pub(crate) fn tsv_to_string(tsv: Box<dyn WriteTable>, config: &Config) -> Result<String> {
tsv.write_table(config)
}