From 18cc6cd48e946ba99d2a9156bc71a924ae082977 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Fri, 3 May 2024 15:06:30 +0200 Subject: [PATCH 01/13] Adds Documentation --- src/main.rs | 11 +++++++++++ src/tablegen.rs | 45 +++++++++++++++++++++++++++++++++++++-------- 2 files changed, 48 insertions(+), 8 deletions(-) diff --git a/src/main.rs b/src/main.rs index 2378a37..f3e5b67 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,10 @@ +//! The `ravenous-tool` command-line tool. +//! +//! This program is meant as a helper for the ravenous project. +//! + +#![warn(missing_docs)] +#![warn(clippy::missing_docs_in_private_items)] mod tablegen; use clap::{Parser, Subcommand}; use tablegen::{table_gen, TableArgs}; @@ -5,13 +12,17 @@ use tablegen::{table_gen, TableArgs}; #[derive(Parser, Debug)] #[command(version, about)] #[command(propagate_version = true)] +/// The list of commands to run struct Arguments { + /// The subcommand to run. #[command(subcommand)] command: Commands, } #[derive(Subcommand, Debug)] +/// Enum representing the available commands. enum Commands { + /// Generate a table from input data using the provided arguments. Tablegen(TableArgs), } diff --git a/src/tablegen.rs b/src/tablegen.rs index 274246c..b5a381b 100644 --- a/src/tablegen.rs +++ b/src/tablegen.rs @@ -2,24 +2,38 @@ use clap::Args; use serde::Deserialize; use std::io::{Error, Write}; +use std::path::Path; use std::{cell::RefCell, fmt, fs::File, io::BufWriter}; +/// Configuration options for processing CSV files and generating LaTeX tables. #[derive(Debug, Args)] pub struct TableArgs { + /// A boolean indicating whether to generate LaTeX code and write it to an output file + /// (if true) or just print the generated code to stdout #[arg(short)] export: bool, - // #[arg(short)] + + // #[arg(shorl, long)] + // type: + /// A vector of strings representing the names of CSV files to process. filenames: Vec, } #[derive(Debug, Deserialize)] #[serde(rename_all = "PascalCase")] +/// A single row in a martial class csv file struct Record { + /// The name of a technique. technique: String, + /// The level or rank of a technique niveau: String, + /// The type of technique, such as Actif or Exclusif. technique_type: String, + /// The blood cost for this technique. cout_blood: CleanString, + /// The gauge cost for this technique. cout_jauge: CleanString, + /// A brief description of the effect or outcome of using this technique. effet: CleanString, } @@ -33,6 +47,11 @@ pub fn table_gen(args: &TableArgs) { } } } +/// Converts a CSV file to LaTeX code. +/// +/// This function reads in a CSV file, processes its contents according to the provided configuration, +/// and writes out the resulting LaTeX code as a string. If an error occurs during processing or writing, +/// it will be returned as part of the result. pub fn convert_file(f: &String, args: &TableArgs) -> Result<(), Error> { let csv = read_csv(f)?; let converted = records_to_string(csv)?; @@ -48,6 +67,7 @@ pub fn convert_file(f: &String, args: &TableArgs) -> Result<(), Error> { Ok(()) } +/// This type is used to represent strings in LaTeX tables, where certain characters need to be escaped or replaced with special commands. #[derive(Deserialize)] struct CleanString(String); @@ -57,14 +77,16 @@ impl fmt::Debug for CleanString { ::fmt(&self.0, f) } } + impl fmt::Display for CleanString { #[inline] fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - f.write_str(&replace_all(&self.0)) + f.write_str(&make_latex_string(&self.0)) } } -fn replace_all(arg: &str) -> String { +/// Replace all instances of unrepresentable utf8 or non escaped characters with latex ones +fn make_latex_string(arg: &str) -> String { use regex::{Captures, Regex}; let re = Regex::new(r"★+").unwrap(); @@ -79,7 +101,14 @@ fn replace_all(arg: &str) -> String { res.to_string() } -fn read_csv(filename: &String) -> Result>, Error> { +/// Reads a CSV file into a table. +/// +/// This function reads in a comma-separated values (CSV) 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_csv(filename: &T) -> Result>, Error> +where + T: AsRef, +{ let file = File::open(filename)?; let mut rdr = csv::ReaderBuilder::new() .has_headers(false) @@ -108,11 +137,11 @@ fn read_csv(filename: &String) -> Result>, Error> { Ok(levels) } +/// 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. fn records_to_string(csv: Vec>) -> Result { - // FUREUR SANGUINAIRE & 1 & Actif, (Guivre) & 6\blood & Sacrifiez 3 points de vie dans toutes les localités, vous gagnez l'altération Rage, vos attaques infligent une réussite supplémentaire tant que vous êtes enragé.\\ - // FUREUR SANGUINAIRE & 2 & Actif, Exclusif, (Guivre) & 5\blood 1\gauge & Sacrifiez 4 points de vie a la place, vous gagnez 2 dégâts supplémentaires sur chaque attaque tant que vous êtes enragé. Lorsque vous perdez l'altération d'état enragé, regagnez 1\gauge.\\ - // EXSANGUINATION PROGRESSIVE & 1 & Actif, (Béhémoth) & 3\blood\vfill 1\gauge & Votre prochaine attaque marque la cible en son point d'impact, toutes les attaques ciblant cette marque ignorent jusqu'à 4 points d'armure ce tour-ci.\\ - // EXSANGUINATION PROGRESSIVE & 1 & Actif, (Béhémoth) & 4\blood\vfill 1\gauge & Ces attaques infligent aussi un saignement de 1 dégât sur 4 tours (chaque attaque viens ajouter un point au saignement total).\\ let mut buffer = BufWriter::new(Vec::new()); for (lvl, tier) in csv.iter().skip(1).enumerate() { write!(buffer, "\\subsubsection{{Tier {}}}", lvl + 1)?; -- 2.45.1 From c4a6c5095193567295fbe43a02795a8fa7a46155 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Fri, 3 May 2024 15:37:27 +0200 Subject: [PATCH 02/13] Adds doc --- Cargo.toml | 1 + src/tablegen.rs | 36 ++++++++++++++++++++++++++++++++++-- 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 53eef8f..9622919 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,6 +9,7 @@ edition = "2021" [dependencies] clap = { version = "4.5.4", features = ["derive"] } csv = "1.3.0" +phf = { version = "0.11.2", features = ["macros"] } regex = "1.10.4" serde = { version = "1.0.198", features = ["derive"] } diff --git a/src/tablegen.rs b/src/tablegen.rs index b5a381b..746a709 100644 --- a/src/tablegen.rs +++ b/src/tablegen.rs @@ -1,5 +1,6 @@ //! The csv table generation use clap::Args; +use phf::phf_map; use serde::Deserialize; use std::io::{Error, Write}; use std::path::Path; @@ -13,12 +14,43 @@ pub struct TableArgs { #[arg(short)] export: bool, - // #[arg(shorl, long)] - // type: + /// The kind of tables to operate on: classes, craft or a specific file + kind: TargetType, /// A vector of strings representing the names of CSV files to process. filenames: Vec, } +/// An enumeration representing different target types. +#[derive(Debug, Clone)] +enum TargetType { + /// Processes all classes + Classes, + /// Processes all the craft tables + Craft, + /// Processes only the given files + Files, +} + +/// A mapping of string representations to target types. +static STR_TO_TARGET: phf::Map<&'static str, TargetType> = phf_map! { + "classes" => TargetType::Classes, + "craft" => TargetType::Craft, + "files" => TargetType::Files, +}; + +impl From<&str> for TargetType { + fn from(value: &str) -> Self { + if let Some(target) = STR_TO_TARGET.get(value).cloned() { + target + } else { + panic!( + "Only the following target can be used: {:?}", + STR_TO_TARGET.keys() + ) + } + } +} + #[derive(Debug, Deserialize)] #[serde(rename_all = "PascalCase")] /// A single row in a martial class csv file -- 2.45.1 From 6c60a76b8860b26a2af8ee46da9872658ef6de5c Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Fri, 3 May 2024 17:21:56 +0200 Subject: [PATCH 03/13] Adds config and doc --- Cargo.toml | 2 ++ helper_config.toml | 14 ++++++++++++++ src/main.rs | 30 +++++++++++++++++++++++++++--- src/tablegen.rs | 40 ++++++++++++++++++---------------------- 4 files changed, 61 insertions(+), 25 deletions(-) create mode 100644 helper_config.toml diff --git a/Cargo.toml b/Cargo.toml index 9622919..a0d9cde 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,9 +9,11 @@ edition = "2021" [dependencies] clap = { version = "4.5.4", features = ["derive"] } csv = "1.3.0" +dynfmt = { version = "0.1.5", features = ["curly"] } phf = { version = "0.11.2", features = ["macros"] } regex = "1.10.4" serde = { version = "1.0.198", features = ["derive"] } +toml = "0.8.12" [profile.dev] debug = 0 diff --git a/helper_config.toml b/helper_config.toml new file mode 100644 index 0000000..7611c79 --- /dev/null +++ b/helper_config.toml @@ -0,0 +1,14 @@ +[classes] +header = '\subsubsection{Tier {}}' +row = ''' + let open = r#"{\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 + Technique & Niv & Type & Coût & Effet\\\hline"#; +''' +end = ''' + r" \hline +\end{tabularx} +} +''' diff --git a/src/main.rs b/src/main.rs index f3e5b67..1b7a45e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,14 +6,17 @@ #![warn(missing_docs)] #![warn(clippy::missing_docs_in_private_items)] mod tablegen; +use std::fs; + use clap::{Parser, Subcommand}; +use serde::Deserialize; use tablegen::{table_gen, TableArgs}; #[derive(Parser, Debug)] #[command(version, about)] #[command(propagate_version = true)] /// The list of commands to run -struct Arguments { +struct Args { /// The subcommand to run. #[command(subcommand)] command: Commands, @@ -26,9 +29,30 @@ enum Commands { Tablegen(TableArgs), } +#[derive(Deserialize)] +/// The config struct, holding all runtime information +struct Config { + /// Config specific for the classes table generation + classes: Classes, +} + +#[derive(Deserialize)] +/// The classes config +struct Classes { + /// The header string formatter + header: String, + /// The row string formatter + row: String, + /// The table end string formatter + end: String, +} + fn main() { - let args = Arguments::parse(); + let args = Args::parse(); + let config = &fs::read_to_string("helper_config.toml") + .unwrap_or(include_str!("../helper_config.toml").to_string()); + let config: Config = toml::from_str(config).expect("Coudln't read the config file"); match args.command { - Commands::Tablegen(args) => table_gen(&args), + Commands::Tablegen(args) => table_gen(&args, &config), } } diff --git a/src/tablegen.rs b/src/tablegen.rs index 746a709..a45a542 100644 --- a/src/tablegen.rs +++ b/src/tablegen.rs @@ -1,11 +1,14 @@ //! The csv table generation use clap::Args; +use dynfmt::{Format, SimpleCurlyFormat}; use phf::phf_map; use serde::Deserialize; use std::io::{Error, Write}; use std::path::Path; use std::{cell::RefCell, fmt, fs::File, io::BufWriter}; +use crate::Config; + /// Configuration options for processing CSV files and generating LaTeX tables. #[derive(Debug, Args)] pub struct TableArgs { @@ -69,12 +72,12 @@ struct Record { effet: CleanString, } -pub fn table_gen(args: &TableArgs) { +pub fn table_gen(args: &TableArgs, config: &Config) { if args.filenames.is_empty() { println!("No files to process ... skipping"); } for f in &args.filenames { - if let Err(e) = convert_file(f, args) { + if let Err(e) = convert_file(f, args, config) { println!("Error while processing {}: {}", f, e) } } @@ -84,9 +87,9 @@ pub fn table_gen(args: &TableArgs) { /// This function reads in a CSV file, processes its contents according to the provided configuration, /// and writes out the resulting LaTeX code as a string. If an error occurs during processing or writing, /// it will be returned as part of the result. -pub fn convert_file(f: &String, args: &TableArgs) -> Result<(), Error> { +pub fn convert_file(f: &String, args: &TableArgs, config: &Config) -> Result<(), Error> { let csv = read_csv(f)?; - let converted = records_to_string(csv)?; + let converted = records_to_string(csv, config)?; if args.export { let path = f.replace(".tsv", ".tex"); println!("[Info] Writing to {}", path); @@ -151,13 +154,13 @@ where .comment(Some(b'#')) .from_reader(file); - let mut levels = Vec::with_capacity(4); - let current_tier = RefCell::new(Vec::with_capacity(4)); + let mut levels = Vec::with_capacity(8); + let current_tier = RefCell::new(Vec::with_capacity(6)); for result in rdr.deserialize() { let result: Record = result?; if result.technique.starts_with("Tier ") { // Getto way of knowing we have a new tier - let old_tier = current_tier.replace(Vec::with_capacity(6)); + let old_tier = current_tier.replace(Vec::with_capacity(8)); levels.push(old_tier); } else if (result.technique == "Technique") | result.technique.is_empty() { // Skip this entry @@ -173,16 +176,15 @@ where /// /// 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. -fn records_to_string(csv: Vec>) -> Result { +fn records_to_string(csv: Vec>, config: &Config) -> Result { let mut buffer = BufWriter::new(Vec::new()); for (lvl, tier) in csv.iter().skip(1).enumerate() { - write!(buffer, "\\subsubsection{{Tier {}}}", lvl + 1)?; - let open = r#"{\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 - Technique & Niv & Type & Coût & Effet\\\hline"#; - write!(buffer, "{}", open)?; + // rt_write!(buffer, config.classes.header, lvl + 1)?; + let formatted_header = SimpleCurlyFormat + .format(&config.classes.header, [lvl + 1]) + .expect("Formatting failed"); + write!(buffer, "{}", formatted_header)?; + write!(buffer, "{}", config.classes.row)?; for elem in tier { write!( buffer, @@ -195,13 +197,7 @@ fn records_to_string(csv: Vec>) -> Result { elem.effet )?; } - write!( - buffer, - r" \hline -\end{{tabularx}} -}} -" - )?; + write!(buffer, "{}", config.classes.end)?; } Ok(String::from_utf8(buffer.into_inner()?).unwrap()) } -- 2.45.1 From 0f97616dfddc98ec752ee3c462f498aafee6d93d Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Fri, 3 May 2024 22:19:24 +0200 Subject: [PATCH 04/13] Works on tables --- Cargo.toml | 1 + src/tablegen.rs | 53 ++++++++++++++++++++++++++++++++++++------------- 2 files changed, 40 insertions(+), 14 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index a0d9cde..3dd0dd7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,6 +10,7 @@ edition = "2021" clap = { version = "4.5.4", features = ["derive"] } csv = "1.3.0" dynfmt = { version = "0.1.5", features = ["curly"] } +glob = "0.3.1" phf = { version = "0.11.2", features = ["macros"] } regex = "1.10.4" serde = { version = "1.0.198", features = ["derive"] } diff --git a/src/tablegen.rs b/src/tablegen.rs index a45a542..8856463 100644 --- a/src/tablegen.rs +++ b/src/tablegen.rs @@ -1,10 +1,12 @@ //! The csv table generation use clap::Args; use dynfmt::{Format, SimpleCurlyFormat}; +use glob::glob; use phf::phf_map; use serde::Deserialize; +use std::fmt::Debug; use std::io::{Error, Write}; -use std::path::Path; +use std::path::{Path, PathBuf}; use std::{cell::RefCell, fmt, fs::File, io::BufWriter}; use crate::Config; @@ -57,7 +59,7 @@ impl From<&str> for TargetType { #[derive(Debug, Deserialize)] #[serde(rename_all = "PascalCase")] /// A single row in a martial class csv file -struct Record { +struct RecordClass { /// The name of a technique. technique: String, /// The level or rank of a technique @@ -73,30 +75,53 @@ struct Record { } pub fn table_gen(args: &TableArgs, config: &Config) { - if args.filenames.is_empty() { + let list_files = match args.kind { + TargetType::Classes => &mut list_dir("Tables/*.csv"), + TargetType::Craft => &mut list_dir("Craft/*.csv"), + TargetType::Files => &mut args.filenames.iter().map(PathBuf::from).collect(), + }; + + if list_files.is_empty() { println!("No files to process ... skipping"); } - for f in &args.filenames { - if let Err(e) = convert_file(f, args, config) { - println!("Error while processing {}: {}", f, e) + // match args.kind { + // TargetType::Classes => todo!(), + // TargetType::Craft => todo!(), + // TargetType::Files => todo!(), + // } + for f in list_files { + if let Err(e) = convert_class_csv(f, args, config) { + println!("Error while processing {:?}: {}", f, e) } } } + +/// List all files matching a pattern in the given directory +#[inline] +fn list_dir(pattern: &str) -> Vec { + glob(pattern) + .expect("Failed to read glob pattern") + .flatten() + .collect() +} /// Converts a CSV file to LaTeX code. /// /// This function reads in a CSV file, processes its contents according to the provided configuration, /// and writes out the resulting LaTeX code as a string. If an error occurs during processing or writing, /// it will be returned as part of the result. -pub fn convert_file(f: &String, args: &TableArgs, config: &Config) -> Result<(), Error> { - let csv = read_csv(f)?; - let converted = records_to_string(csv, config)?; +pub fn convert_class_csv(f: &T, args: &TableArgs, config: &Config) -> Result<(), Error> +where + T: AsRef + Debug, +{ + let csv = read_csv_classes(f)?; + let converted = csv_classes_to_string(csv, config)?; if args.export { - let path = f.replace(".tsv", ".tex"); + let path = format!("{:?}", f).replace(".tsv", ".tex"); println!("[Info] Writing to {}", path); let mut file = File::create(path)?; file.write_all(converted.as_bytes())?; } else { - println!("###### [FILE:{}] ######", f); + println!("###### [FILE:{:?}] ######", f); println!("{}", converted); } Ok(()) @@ -140,7 +165,7 @@ fn make_latex_string(arg: &str) -> String { /// /// This function reads in a comma-separated values (CSV) 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_csv(filename: &T) -> Result>, Error> +fn read_csv_classes(filename: &T) -> Result>, Error> where T: AsRef, { @@ -157,7 +182,7 @@ where let mut levels = Vec::with_capacity(8); let current_tier = RefCell::new(Vec::with_capacity(6)); for result in rdr.deserialize() { - let result: Record = result?; + let result: RecordClass = result?; if result.technique.starts_with("Tier ") { // Getto way of knowing we have a new tier let old_tier = current_tier.replace(Vec::with_capacity(8)); @@ -176,7 +201,7 @@ where /// /// 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. -fn records_to_string(csv: Vec>, config: &Config) -> Result { +fn csv_classes_to_string(csv: Vec>, config: &Config) -> Result { let mut buffer = BufWriter::new(Vec::new()); for (lvl, tier) in csv.iter().skip(1).enumerate() { // rt_write!(buffer, config.classes.header, lvl + 1)?; -- 2.45.1 From 1e56dc9e5e7cf4be92e610451da1592c1bec7317 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sat, 4 May 2024 17:02:30 +0200 Subject: [PATCH 05/13] WIP on generalisation --- helper_config.toml | 16 +++++++ src/tablegen.rs | 105 ++++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 116 insertions(+), 5 deletions(-) diff --git a/helper_config.toml b/helper_config.toml index 7611c79..06e8286 100644 --- a/helper_config.toml +++ b/helper_config.toml @@ -12,3 +12,19 @@ end = ''' \end{tabularx} } ''' +[alchimie] + +[armes] + +[armures] + +[forge] + +[fud] + +[gadgets] + +[mpieges] + + +[potions] diff --git a/src/tablegen.rs b/src/tablegen.rs index 8856463..dde9d96 100644 --- a/src/tablegen.rs +++ b/src/tablegen.rs @@ -5,6 +5,7 @@ use glob::glob; use phf::phf_map; use serde::Deserialize; use std::fmt::Debug; +use std::fmt::Display; use std::io::{Error, Write}; use std::path::{Path, PathBuf}; use std::{cell::RefCell, fmt, fs::File, io::BufWriter}; @@ -84,11 +85,16 @@ pub fn table_gen(args: &TableArgs, config: &Config) { if list_files.is_empty() { println!("No files to process ... skipping"); } - // match args.kind { - // TargetType::Classes => todo!(), - // TargetType::Craft => todo!(), - // TargetType::Files => todo!(), - // } + match args.kind { + TargetType::Classes => process_class_files(list_files, args, config), + TargetType::Craft => process_craft_files(list_files, args, config), + // For now every file is considered as a class file + TargetType::Files => process_class_files(list_files, args, config), + } +} + +/// Loop over all class files and process them one by one +fn process_class_files(list_files: &mut Vec, args: &TableArgs, config: &Config) { for f in list_files { if let Err(e) = convert_class_csv(f, args, config) { println!("Error while processing {:?}: {}", f, e) @@ -96,6 +102,28 @@ pub fn table_gen(args: &TableArgs, config: &Config) { } } +/// Process all craft files +fn process_craft_files(list_files: &mut Vec, args: &TableArgs, config: &Config) { + for f in list_files { + if let Err(e) = convert_craft_csv(f, args, config) { + println!("Error while processing {:?}: {}", f, e) + } + } +} + +/// Process any type of file, one by one and call the right converter function +fn process_files( + list_files: &mut Vec, + args: &TableArgs, + config: &Config, + converter: &mut dyn FnMut(&mut PathBuf, &TableArgs, &Config) -> Result<(), Error>, +) { + for f in list_files { + if let Err(e) = converter(f, args, config) { + println!("Error while processing {:?}: {}", f, e) + } + } +} /// List all files matching a pattern in the given directory #[inline] fn list_dir(pattern: &str) -> Vec { @@ -104,6 +132,7 @@ fn list_dir(pattern: &str) -> Vec { .flatten() .collect() } + /// Converts a CSV file to LaTeX code. /// /// This function reads in a CSV file, processes its contents according to the provided configuration, @@ -126,6 +155,28 @@ where } Ok(()) } +/// Converts a CSV file to LaTeX code. +/// +/// This function reads in a CSV file, processes its contents according to the provided configuration, +/// and writes out the resulting LaTeX code as a string. If an error occurs during processing or writing, +/// it will be returned as part of the result. +pub fn convert_craft_csv(f: &T, args: &TableArgs, config: &Config) -> Result<(), Error> +where + T: AsRef + Debug, +{ + let csv = read_csv_craft(f)?; + let converted = csv_classes_to_string(csv, config)?; + if args.export { + let path = format!("{:?}", f).replace(".tsv", ".tex"); + println!("[Info] Writing to {}", path); + let mut file = File::create(path)?; + file.write_all(converted.as_bytes())?; + } else { + println!("###### [FILE:{:?}] ######", f); + println!("{}", converted); + } + Ok(()) +} /// This type is used to represent strings in LaTeX tables, where certain characters need to be escaped or replaced with special commands. #[derive(Deserialize)] @@ -197,6 +248,33 @@ where Ok(levels) } +/// Reads a CSV file into a table. +/// +/// This function reads in a comma-separated values (CSV) 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_csv_craft(filename: &PathType) -> Result, Error> +where + PathType: AsRef, + RecordType: for<'a> serde::Deserialize<'a>, +{ + let file = File::open(filename)?; + let mut rdr = csv::ReaderBuilder::new() + .has_headers(false) + .delimiter(b'\t') + .double_quote(false) + .escape(Some(b'\\')) + .flexible(true) + .comment(Some(b'#')) + .from_reader(file); + + let mut levels = Vec::with_capacity(8); + for result in rdr.deserialize() { + let result: RecordType = result?; + levels.push(result); + } + Ok(levels) +} + /// Converts a table of data into a string representation. /// /// This function takes in a Table object and returns its contents as a formatted string, @@ -226,3 +304,20 @@ fn csv_classes_to_string(csv: Vec>, config: &Config) -> Result< } Ok(String::from_utf8(buffer.into_inner()?).unwrap()) } + +/// 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. +fn csv_craft_to_string(csv: Vec, config: &Config) -> Result +where + RowType: Display, +{ + let mut buffer = BufWriter::new(Vec::new()); + write!(buffer, "{}", config.classes.row)?; + for elem in csv { + write!(buffer, " {}", elem)?; + } + write!(buffer, "{}", config.classes.end)?; + Ok(String::from_utf8(buffer.into_inner()?).unwrap()) +} -- 2.45.1 From d1a615a7ed43cce0362d9393de64a71447e9515c Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sat, 4 May 2024 17:53:33 +0200 Subject: [PATCH 06/13] Refactors into two files --- src/main.rs | 4 +- src/table_structs.rs | 90 ++++++++++++++++++++++++ src/tablegen.rs | 161 ++++++++++++++----------------------------- 3 files changed, 143 insertions(+), 112 deletions(-) create mode 100644 src/table_structs.rs diff --git a/src/main.rs b/src/main.rs index 1b7a45e..8aa2b08 100644 --- a/src/main.rs +++ b/src/main.rs @@ -5,12 +5,14 @@ #![warn(missing_docs)] #![warn(clippy::missing_docs_in_private_items)] +mod table_structs; mod tablegen; +use crate::table_structs::TableArgs; use std::fs; use clap::{Parser, Subcommand}; use serde::Deserialize; -use tablegen::{table_gen, TableArgs}; +use tablegen::table_gen; #[derive(Parser, Debug)] #[command(version, about)] diff --git a/src/table_structs.rs b/src/table_structs.rs new file mode 100644 index 0000000..5a0758e --- /dev/null +++ b/src/table_structs.rs @@ -0,0 +1,90 @@ +//! Holds all the data structures away from the main routine + +use clap::Args; +use phf::phf_map; +use serde::Deserialize; +use std::fmt; +use std::fmt::Debug; + +use crate::tablegen::make_latex_string; + +/// Configuration options for processing CSV files and generating LaTeX tables. +#[derive(Debug, Args)] +pub(crate) struct TableArgs { + /// A boolean indicating whether to generate LaTeX code and write it to an output file + /// (if true) or just print the generated code to stdout + #[arg(short)] + pub export: bool, + + /// The kind of tables to operate on: classes, craft or a specific file + pub kind: TargetType, + /// A vector of strings representing the names of CSV files to process. + pub filenames: Vec, +} + +/// An enumeration representing different target types. +#[derive(Debug, Clone)] +pub enum TargetType { + /// Processes all classes + Classes, + /// Processes all the craft tables + Craft, + /// Processes only the given files + Files, +} + +/// A mapping of string representations to target types. +static STR_TO_TARGET: phf::Map<&'static str, TargetType> = phf_map! { + "classes" => TargetType::Classes, + "craft" => TargetType::Craft, + "files" => TargetType::Files, +}; + +impl From<&str> for TargetType { + fn from(value: &str) -> Self { + if let Some(target) = STR_TO_TARGET.get(value).cloned() { + target + } else { + panic!( + "Only the following target can be used: {:?}", + STR_TO_TARGET.keys() + ) + } + } +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "PascalCase")] +/// A single row in a martial class csv file +pub struct RecordClass { + /// The name of a technique. + pub technique: String, + /// The level or rank of a technique + pub niveau: String, + /// The type of technique, such as Actif or Exclusif. + pub technique_type: String, + /// The blood cost for this technique. + pub cout_blood: CleanString, + /// The gauge cost for this technique. + pub cout_jauge: CleanString, + /// A brief description of the effect or outcome of using this technique. + pub effet: CleanString, +} + +/// 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); + +impl fmt::Debug for CleanString { + #[inline] + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + ::fmt(&self.0, f) + } +} + +impl fmt::Display for CleanString { + #[inline] + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.write_str(&make_latex_string(&self.0)) + } +} diff --git a/src/tablegen.rs b/src/tablegen.rs index dde9d96..8b2820e 100644 --- a/src/tablegen.rs +++ b/src/tablegen.rs @@ -1,84 +1,25 @@ //! The csv table generation -use clap::Args; use dynfmt::{Format, SimpleCurlyFormat}; use glob::glob; -use phf::phf_map; -use serde::Deserialize; use std::fmt::Debug; use std::fmt::Display; use std::io::{Error, Write}; use std::path::{Path, PathBuf}; -use std::{cell::RefCell, fmt, fs::File, io::BufWriter}; +use std::{cell::RefCell, fs::File, io::BufWriter}; +use crate::table_structs::RecordClass; +use crate::table_structs::TableArgs; +use crate::table_structs::TargetType; use crate::Config; -/// Configuration options for processing CSV files and generating LaTeX tables. -#[derive(Debug, Args)] -pub struct TableArgs { - /// A boolean indicating whether to generate LaTeX code and write it to an output file - /// (if true) or just print the generated code to stdout - #[arg(short)] - export: bool, - - /// The kind of tables to operate on: classes, craft or a specific file - kind: TargetType, - /// A vector of strings representing the names of CSV files to process. - filenames: Vec, -} - -/// An enumeration representing different target types. -#[derive(Debug, Clone)] -enum TargetType { - /// Processes all classes - Classes, - /// Processes all the craft tables - Craft, - /// Processes only the given files - Files, -} - -/// A mapping of string representations to target types. -static STR_TO_TARGET: phf::Map<&'static str, TargetType> = phf_map! { - "classes" => TargetType::Classes, - "craft" => TargetType::Craft, - "files" => TargetType::Files, -}; - -impl From<&str> for TargetType { - fn from(value: &str) -> Self { - if let Some(target) = STR_TO_TARGET.get(value).cloned() { - target - } else { - panic!( - "Only the following target can be used: {:?}", - STR_TO_TARGET.keys() - ) - } - } -} - -#[derive(Debug, Deserialize)] -#[serde(rename_all = "PascalCase")] -/// A single row in a martial class csv file -struct RecordClass { - /// The name of a technique. - technique: String, - /// The level or rank of a technique - niveau: String, - /// The type of technique, such as Actif or Exclusif. - technique_type: String, - /// The blood cost for this technique. - cout_blood: CleanString, - /// The gauge cost for this technique. - cout_jauge: CleanString, - /// A brief description of the effect or outcome of using this technique. - effet: CleanString, -} - +/// Generate the tables for the specified files +/// +/// In charge of the dispatch and the whole conversion pub fn table_gen(args: &TableArgs, config: &Config) { let list_files = match args.kind { TargetType::Classes => &mut list_dir("Tables/*.csv"), TargetType::Craft => &mut list_dir("Craft/*.csv"), + // Add the use of glob to save the poor windows users TargetType::Files => &mut args.filenames.iter().map(PathBuf::from).collect(), }; @@ -86,37 +27,21 @@ pub fn table_gen(args: &TableArgs, config: &Config) { println!("No files to process ... skipping"); } match args.kind { - TargetType::Classes => process_class_files(list_files, args, config), - TargetType::Craft => process_craft_files(list_files, args, config), + TargetType::Classes => process_files(list_files, args, config, convert_class_csv), + TargetType::Craft => todo!(), //process_files(list_files, args, config, convert_craft_csv::<_, _>), // For now every file is considered as a class file - TargetType::Files => process_class_files(list_files, args, config), - } -} - -/// Loop over all class files and process them one by one -fn process_class_files(list_files: &mut Vec, args: &TableArgs, config: &Config) { - for f in list_files { - if let Err(e) = convert_class_csv(f, args, config) { - println!("Error while processing {:?}: {}", f, e) - } - } -} - -/// Process all craft files -fn process_craft_files(list_files: &mut Vec, args: &TableArgs, config: &Config) { - for f in list_files { - if let Err(e) = convert_craft_csv(f, args, config) { - println!("Error while processing {:?}: {}", f, e) - } + TargetType::Files => process_files(list_files, args, config, convert_class_csv), } } /// Process any type of file, one by one and call the right converter function -fn process_files( +fn process_files< + T: for<'a, 'b, 'c> Fn(&'a PathBuf, &'b TableArgs, &'c Config) -> Result<(), Error>, +>( list_files: &mut Vec, args: &TableArgs, config: &Config, - converter: &mut dyn FnMut(&mut PathBuf, &TableArgs, &Config) -> Result<(), Error>, + converter: T, ) { for f in list_files { if let Err(e) = converter(f, args, config) { @@ -124,6 +49,7 @@ fn process_files( } } } + /// List all files matching a pattern in the given directory #[inline] fn list_dir(pattern: &str) -> Vec { @@ -160,7 +86,35 @@ where /// This function reads in a CSV file, processes its contents according to the provided configuration, /// and writes out the resulting LaTeX code as a string. If an error occurs during processing or writing, /// it will be returned as part of the result. -pub fn convert_craft_csv(f: &T, args: &TableArgs, config: &Config) -> Result<(), Error> +pub fn convert_craft_csv( + f: &PathType, + args: &TableArgs, + config: &Config, +) -> Result<(), Error> +where + PathType: AsRef + Debug, + RowType: Display, +{ + let csv = read_csv_craft(f)?; + let converted = csv_classes_to_string(csv, config)?; + if args.export { + let path = format!("{:?}", f).replace(".tsv", ".tex"); + println!("[Info] Writing to {}", path); + let mut file = File::create(path)?; + file.write_all(converted.as_bytes())?; + } else { + println!("###### [FILE:{:?}] ######", f); + println!("{}", converted); + } + Ok(()) +} + +/// Converts a CSV file to LaTeX code. +/// +/// This function reads in a CSV file, processes its contents according to the provided configuration, +/// and writes out the resulting LaTeX code as a string. If an error occurs during processing or writing, +/// it will be returned as part of the result. +pub fn convert_csv(f: &T, args: &TableArgs, config: &Config) -> Result<(), Error> where T: AsRef + Debug, { @@ -178,26 +132,8 @@ where Ok(()) } -/// This type is used to represent strings in LaTeX tables, where certain characters need to be escaped or replaced with special commands. -#[derive(Deserialize)] -struct CleanString(String); - -impl fmt::Debug for CleanString { - #[inline] - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - ::fmt(&self.0, f) - } -} - -impl fmt::Display for CleanString { - #[inline] - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - f.write_str(&make_latex_string(&self.0)) - } -} - /// Replace all instances of unrepresentable utf8 or non escaped characters with latex ones -fn make_latex_string(arg: &str) -> String { +pub fn make_latex_string(arg: &str) -> String { use regex::{Captures, Regex}; let re = Regex::new(r"★+").unwrap(); @@ -309,7 +245,10 @@ fn csv_classes_to_string(csv: Vec>, config: &Config) -> Result< /// /// 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. -fn csv_craft_to_string(csv: Vec, config: &Config) -> Result +pub(crate) fn csv_craft_to_string( + csv: Vec, + config: &Config, +) -> Result where RowType: Display, { -- 2.45.1 From 61c0a344d8c2cb33eab649f6694b756e57ddd360 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sat, 4 May 2024 23:13:26 +0200 Subject: [PATCH 07/13] Adds polimorphism and half exports Also adds a very convenient todo --- Cargo.toml | 2 + src/table_structs.rs | 119 ++++++++++++++++++++++++++++-- src/tablegen.rs | 168 +++++++++++++++++++++++-------------------- 3 files changed, 208 insertions(+), 81 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 3dd0dd7..89e0829 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,12 +7,14 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +anyhow = "1.0.82" clap = { version = "4.5.4", features = ["derive"] } csv = "1.3.0" dynfmt = { version = "0.1.5", features = ["curly"] } glob = "0.3.1" phf = { version = "0.11.2", features = ["macros"] } regex = "1.10.4" +regex_static = "0.1.1" serde = { version = "1.0.198", features = ["derive"] } toml = "0.8.12" diff --git a/src/table_structs.rs b/src/table_structs.rs index 5a0758e..a21b15a 100644 --- a/src/table_structs.rs +++ b/src/table_structs.rs @@ -1,12 +1,17 @@ //! Holds all the data structures away from the main routine - +use crate::{tablegen::make_latex_string, Config}; +use anyhow::Result; use clap::Args; +use dynfmt::{Format, SimpleCurlyFormat}; use phf::phf_map; +use regex::Regex; use serde::Deserialize; -use std::fmt; -use std::fmt::Debug; +use std::{ + fmt::{self, Debug, Display}, + io::{BufWriter, Write}, +}; -use crate::tablegen::make_latex_string; +use regex_static::once_cell::sync::Lazy; /// Configuration options for processing CSV files and generating LaTeX tables. #[derive(Debug, Args)] @@ -40,6 +45,53 @@ static STR_TO_TARGET: phf::Map<&'static str, TargetType> = phf_map! { "files" => TargetType::Files, }; +/// All the type of tsv that can be processed by the program +pub enum TableTargets { + /// A class tsv + Classes, + /// Foods tsv + Food, + /// Alchemy tsv + Alchemy, + /// Forge tsv + Forge, + /// MPieges tsv + MPieges, + /// Weapons tsv + Weapons, + /// Armors tsv + Armors, + /// Gadgets tsv + Gadgets, + /// Potions tsv + Potions, + /// Traps tsv + Traps, +} + +/// A mapping of string names to target types. +pub(crate) static STR_TO_TARGET_FULL: phf::Map<&'static str, TableTargets> = phf_map! { + "cls" => TableTargets::Classes, + "fud" => TableTargets::Food, + "alc" => TableTargets::Alchemy, + "frg" => TableTargets::Forge, + "mpi" => TableTargets::MPieges, + "wpn" => TableTargets::Weapons, + "arm" => TableTargets::Armors, + "gdg" => TableTargets::Gadgets, + "pot" => TableTargets::Potions, + "trp" => TableTargets::Traps, +}; + +/// The regex for finding and replacing all stars with a custom DD +pub(crate) static RE: Lazy = 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() { @@ -71,6 +123,65 @@ pub struct RecordClass { pub effet: CleanString, } +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 + ) + } +} + +/// 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 + tiers: Vec>, +} + +/// Trait needed to be writable as a LaTex table +pub(crate) trait WriteRows { + /// Takes a config and writes to a string the representation of the Array + fn write_rows(&self, config: &Config) -> Result; +} + +impl ClassesArray { + pub fn new(tiers: Vec>) -> Self { + Self { tiers } + } +} +impl WriteRows for ClassesArray { + fn write_rows(&self, config: &Config) -> Result { + 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)?; + let formatted_header = SimpleCurlyFormat + .format(&config.classes.header, [lvl + 1]) + .expect("Formatting failed"); + write!(buffer, "{}", formatted_header)?; + write!(buffer, "{}", config.classes.row)?; + for elem in tier { + write!( + buffer, + " {}&{}&{}&{}{}&{} \\\\", + elem.technique, + elem.niveau, + elem.technique_type, + elem.cout_blood, + elem.cout_jauge, + elem.effet + )?; + } + write!(buffer, "{}", config.classes.end)?; + } + 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); diff --git a/src/tablegen.rs b/src/tablegen.rs index 8b2820e..acb3917 100644 --- a/src/tablegen.rs +++ b/src/tablegen.rs @@ -1,16 +1,24 @@ //! The csv table generation +use anyhow::{Context, Result}; use dynfmt::{Format, SimpleCurlyFormat}; use glob::glob; -use std::fmt::Debug; -use std::fmt::Display; -use std::io::{Error, Write}; -use std::path::{Path, PathBuf}; -use std::{cell::RefCell, fs::File, io::BufWriter}; +use regex::Captures; +use std::{ + cell::RefCell, + fmt::Debug, + fs::File, + io::{BufWriter, Error, Write}, + ops::ControlFlow, + path::{Path, PathBuf}, +}; -use crate::table_structs::RecordClass; -use crate::table_structs::TableArgs; -use crate::table_structs::TargetType; -use crate::Config; +use crate::{ + table_structs::{ + ClassesArray, RecordClass, TableArgs, TableTargets, TargetType, WriteRows, RE, + STR_TO_TARGET_FULL, + }, + Config, +}; /// Generate the tables for the specified files /// @@ -27,27 +35,72 @@ pub fn table_gen(args: &TableArgs, config: &Config) { println!("No files to process ... skipping"); } match args.kind { - TargetType::Classes => process_files(list_files, args, config, convert_class_csv), - TargetType::Craft => todo!(), //process_files(list_files, args, config, convert_craft_csv::<_, _>), + TargetType::Classes => process_files(list_files, args, config).unwrap(), + TargetType::Craft => process_files(list_files, args, config).unwrap(), // For now every file is considered as a class file - TargetType::Files => process_files(list_files, args, config, convert_class_csv), - } + TargetType::Files => process_files(list_files, args, config).unwrap(), + }; } /// Process any type of file, one by one and call the right converter function -fn process_files< - T: for<'a, 'b, 'c> Fn(&'a PathBuf, &'b TableArgs, &'c Config) -> Result<(), Error>, ->( - list_files: &mut Vec, - args: &TableArgs, - config: &Config, - converter: T, -) { +fn process_files(list_files: &mut Vec, args: &TableArgs, config: &Config) -> Result<()> { for f in list_files { - if let Err(e) = converter(f, args, config) { - println!("Error while processing {:?}: {}", f, e) + if let ControlFlow::Break(_) = TODO(f, args, config) { + continue; } } + Ok(()) +} + +fn TODO(f: &mut PathBuf, args: &TableArgs, config: &Config) -> ControlFlow<()> { + match extract_type(f) { + Ok(tt) => { + let csv = match match tt { + TableTargets::Classes => read_csv_classes(f), + _ => todo!(), + } { + Ok(c) => c, + Err(_) => { + println!("An error occured while reading {:?}...skipping", f); + return ControlFlow::Break(()); + } + }; + + if let Err(e) = match tt { + TableTargets::Classes => export_csv::(f, csv, args, config), + TableTargets::Food => todo!(), + TableTargets::Alchemy => todo!(), + TableTargets::Forge => todo!(), + TableTargets::MPieges => todo!(), + TableTargets::Weapons => todo!(), + TableTargets::Armors => todo!(), + TableTargets::Gadgets => todo!(), + TableTargets::Potions => todo!(), + TableTargets::Traps => todo!(), + } { + println!( + "An error occured while processing {:?}...skipping\n{}", + f, e + ) + } + } + Err(e) => println!("Error extracting file type {:?} ... skipping\n{}", f, e), + } + ControlFlow::Continue(()) +} + +#[inline] +/// Extract the type of target of the given file +fn extract_type(f: &Path) -> Result<&TableTargets> { + let key = &f + .file_name() + .context("The filename of can't be extracted...skipping")? + .to_str() + .context("Can't convert filename to string")?[..3]; + Ok(STR_TO_TARGET_FULL + .get(key) + .with_context(|| format!("Can't find key {} in file", key)) + .unwrap()) } /// List all files matching a pattern in the given directory @@ -64,39 +117,12 @@ fn list_dir(pattern: &str) -> Vec { /// This function reads in a CSV file, processes its contents according to the provided configuration, /// and writes out the resulting LaTeX code as a string. If an error occurs during processing or writing, /// it will be returned as part of the result. -pub fn convert_class_csv(f: &T, args: &TableArgs, config: &Config) -> Result<(), Error> +pub fn export_class_csv(f: &T, args: &TableArgs, config: &Config) -> Result<()> where T: AsRef + Debug, { let csv = read_csv_classes(f)?; - let converted = csv_classes_to_string(csv, config)?; - if args.export { - let path = format!("{:?}", f).replace(".tsv", ".tex"); - println!("[Info] Writing to {}", path); - let mut file = File::create(path)?; - file.write_all(converted.as_bytes())?; - } else { - println!("###### [FILE:{:?}] ######", f); - println!("{}", converted); - } - Ok(()) -} -/// Converts a CSV file to LaTeX code. -/// -/// This function reads in a CSV file, processes its contents according to the provided configuration, -/// and writes out the resulting LaTeX code as a string. If an error occurs during processing or writing, -/// it will be returned as part of the result. -pub fn convert_craft_csv( - f: &PathType, - args: &TableArgs, - config: &Config, -) -> Result<(), Error> -where - PathType: AsRef + Debug, - RowType: Display, -{ - let csv = read_csv_craft(f)?; - let converted = csv_classes_to_string(csv, config)?; + let converted = csv_to_string(csv, config)?; if args.export { let path = format!("{:?}", f).replace(".tsv", ".tex"); println!("[Info] Writing to {}", path); @@ -114,14 +140,15 @@ where /// This function reads in a CSV file, processes its contents according to the provided configuration, /// and writes out the resulting LaTeX code as a string. If an error occurs during processing or writing, /// it will be returned as part of the result. -pub fn convert_csv(f: &T, args: &TableArgs, config: &Config) -> Result<(), Error> +pub fn export_csv(f: &Path, csv: RowType, args: &TableArgs, config: &Config) -> Result<()> where - T: AsRef + Debug, + // PathType: AsRef + Debug, + RowType: WriteRows, { - let csv = read_csv_craft(f)?; - let converted = csv_classes_to_string(csv, config)?; + let converted = csv_to_string(csv, config)?; if args.export { let path = format!("{:?}", f).replace(".tsv", ".tex"); + // let path = f.with_extension(".tex"); println!("[Info] Writing to {}", path); let mut file = File::create(path)?; file.write_all(converted.as_bytes())?; @@ -134,15 +161,11 @@ where /// Replace all instances of unrepresentable utf8 or non escaped characters with latex ones pub fn make_latex_string(arg: &str) -> String { - use regex::{Captures, Regex}; - - let re = Regex::new(r"★+").unwrap(); - let temp = arg .replace('🩸', "\\blood") .replace('⚡', "\\gauge") .replace('&', "\\&"); - let res = re.replace_all(&temp, |caps: &Captures| { + let res = RE.replace_all(&temp, |caps: &Captures| { format!("\\dd{{{}}}", caps[0].chars().count()) }); res.to_string() @@ -152,7 +175,7 @@ pub fn make_latex_string(arg: &str) -> String { /// /// This function reads in a comma-separated values (CSV) 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_csv_classes(filename: &T) -> Result>, Error> +fn read_csv_classes(filename: &T) -> Result where T: AsRef, { @@ -181,14 +204,14 @@ where } } // println!("{:#?}", levels); - Ok(levels) + Ok(ClassesArray::new(levels)) } /// Reads a CSV file into a table. /// /// This function reads in a comma-separated values (CSV) 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_csv_craft(filename: &PathType) -> Result, Error> +fn read_csv(filename: &PathType) -> Result, Error> where PathType: AsRef, RecordType: for<'a> serde::Deserialize<'a>, @@ -203,7 +226,7 @@ where .comment(Some(b'#')) .from_reader(file); - let mut levels = Vec::with_capacity(8); + let mut levels = Vec::with_capacity(30); for result in rdr.deserialize() { let result: RecordType = result?; levels.push(result); @@ -245,18 +268,9 @@ fn csv_classes_to_string(csv: Vec>, config: &Config) -> Result< /// /// 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 csv_craft_to_string( - csv: Vec, - config: &Config, -) -> Result +pub(crate) fn csv_to_string(csv: RowType, config: &Config) -> Result where - RowType: Display, + RowType: WriteRows, { - let mut buffer = BufWriter::new(Vec::new()); - write!(buffer, "{}", config.classes.row)?; - for elem in csv { - write!(buffer, " {}", elem)?; - } - write!(buffer, "{}", config.classes.end)?; - Ok(String::from_utf8(buffer.into_inner()?).unwrap()) + csv.write_rows(config) } -- 2.45.1 From b769294c06ec69fec1e7124fea437fd5e5a70e5c Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 5 May 2024 02:24:18 +0200 Subject: [PATCH 08/13] Corrects exporting errors and removes legacy functions --- helper_config.toml | 15 ++-- src/table_structs.rs | 10 +-- src/tablegen.rs | 167 +++++++++++++------------------------------ 3 files changed, 62 insertions(+), 130 deletions(-) diff --git a/helper_config.toml b/helper_config.toml index 06e8286..f612ad0 100644 --- a/helper_config.toml +++ b/helper_config.toml @@ -1,15 +1,14 @@ [classes] header = '\subsubsection{Tier {}}' -row = ''' - let open = r#"{\footnotesize - \rowcolors{2}{gray!25}{white} +row = '''{\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 - Technique & Niv & Type & Coût & Effet\\\hline"#; + \hline\rowcolor{gray!50}\hline + Technique & Niv & Type & Coût & Effet\\ + \hline" ''' -end = ''' - r" \hline -\end{tabularx} +end = ''' \hline + \end{tabularx} } ''' [alchimie] diff --git a/src/table_structs.rs b/src/table_structs.rs index a21b15a..9b4b10a 100644 --- a/src/table_structs.rs +++ b/src/table_structs.rs @@ -151,6 +151,7 @@ pub(crate) trait WriteRows { } impl ClassesArray { + /// Create a new ClassesArray from the tier list pub fn new(tiers: Vec>) -> Self { Self { tiers } } @@ -163,10 +164,10 @@ impl WriteRows for ClassesArray { let formatted_header = SimpleCurlyFormat .format(&config.classes.header, [lvl + 1]) .expect("Formatting failed"); - write!(buffer, "{}", formatted_header)?; - write!(buffer, "{}", config.classes.row)?; + writeln!(buffer, "{}", formatted_header)?; + writeln!(buffer, "{}", config.classes.row)?; for elem in tier { - write!( + writeln!( buffer, " {}&{}&{}&{}{}&{} \\\\", elem.technique, @@ -177,11 +178,12 @@ impl WriteRows for ClassesArray { elem.effet )?; } - write!(buffer, "{}", config.classes.end)?; + writeln!(buffer, "{}", config.classes.end)?; } 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); diff --git a/src/tablegen.rs b/src/tablegen.rs index acb3917..a7c3ccc 100644 --- a/src/tablegen.rs +++ b/src/tablegen.rs @@ -1,14 +1,11 @@ //! The csv table generation use anyhow::{Context, Result}; -use dynfmt::{Format, SimpleCurlyFormat}; use glob::glob; use regex::Captures; use std::{ cell::RefCell, - fmt::Debug, fs::File, - io::{BufWriter, Error, Write}, - ops::ControlFlow, + io::{Error, Write}, path::{Path, PathBuf}, }; @@ -45,48 +42,35 @@ pub fn table_gen(args: &TableArgs, config: &Config) { /// Process any type of file, one by one and call the right converter function fn process_files(list_files: &mut Vec, args: &TableArgs, config: &Config) -> Result<()> { for f in list_files { - if let ControlFlow::Break(_) = TODO(f, args, config) { - continue; + if let Err(e) = process_one_file(f, args, config) { + println!("An error occured while processing the file {:?}\n{}", f, e) } } Ok(()) } -fn TODO(f: &mut PathBuf, args: &TableArgs, config: &Config) -> ControlFlow<()> { - match extract_type(f) { - Ok(tt) => { - let csv = match match tt { - TableTargets::Classes => read_csv_classes(f), - _ => todo!(), - } { - Ok(c) => c, - Err(_) => { - println!("An error occured while reading {:?}...skipping", f); - return ControlFlow::Break(()); - } - }; - - if let Err(e) = match tt { - TableTargets::Classes => export_csv::(f, csv, args, config), - TableTargets::Food => todo!(), - TableTargets::Alchemy => todo!(), - TableTargets::Forge => todo!(), - TableTargets::MPieges => todo!(), - TableTargets::Weapons => todo!(), - TableTargets::Armors => todo!(), - TableTargets::Gadgets => todo!(), - TableTargets::Potions => todo!(), - TableTargets::Traps => todo!(), - } { - println!( - "An error occured while processing {:?}...skipping\n{}", - f, e - ) - } - } - Err(e) => println!("Error extracting file type {:?} ... skipping\n{}", f, e), +/// 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 csv = match tt { + TableTargets::Classes => read_csv_classes(f), + _ => todo!(), } - ControlFlow::Continue(()) + .context("Error reading file")?; + + match tt { + TableTargets::Classes => export_csv::(f, csv, args, config), + TableTargets::Food => todo!(), + TableTargets::Alchemy => todo!(), + TableTargets::Forge => todo!(), + TableTargets::MPieges => todo!(), + TableTargets::Weapons => todo!(), + TableTargets::Armors => todo!(), + TableTargets::Gadgets => todo!(), + TableTargets::Potions => todo!(), + TableTargets::Traps => todo!(), + } + .context("Error exporting the csv") } #[inline] @@ -112,29 +96,6 @@ fn list_dir(pattern: &str) -> Vec { .collect() } -/// Converts a CSV file to LaTeX code. -/// -/// This function reads in a CSV file, processes its contents according to the provided configuration, -/// and writes out the resulting LaTeX code as a string. If an error occurs during processing or writing, -/// it will be returned as part of the result. -pub fn export_class_csv(f: &T, args: &TableArgs, config: &Config) -> Result<()> -where - T: AsRef + Debug, -{ - let csv = read_csv_classes(f)?; - let converted = csv_to_string(csv, config)?; - if args.export { - let path = format!("{:?}", f).replace(".tsv", ".tex"); - println!("[Info] Writing to {}", path); - let mut file = File::create(path)?; - file.write_all(converted.as_bytes())?; - } else { - println!("###### [FILE:{:?}] ######", f); - println!("{}", converted); - } - Ok(()) -} - /// Converts a CSV file to LaTeX code. /// /// This function reads in a CSV file, processes its contents according to the provided configuration, @@ -207,62 +168,32 @@ where Ok(ClassesArray::new(levels)) } -/// Reads a CSV file into a table. -/// -/// This function reads in a comma-separated values (CSV) 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_csv(filename: &PathType) -> Result, Error> -where - PathType: AsRef, - RecordType: for<'a> serde::Deserialize<'a>, -{ - let file = File::open(filename)?; - let mut rdr = csv::ReaderBuilder::new() - .has_headers(false) - .delimiter(b'\t') - .double_quote(false) - .escape(Some(b'\\')) - .flexible(true) - .comment(Some(b'#')) - .from_reader(file); +// /// Reads a CSV file into a table. +// /// +// /// This function reads in a comma-separated values (CSV) 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_csv(filename: &PathType) -> Result, Error> +// where +// PathType: AsRef, +// RecordType: for<'a> serde::Deserialize<'a>, +// { +// let file = File::open(filename)?; +// let mut rdr = csv::ReaderBuilder::new() +// .has_headers(false) +// .delimiter(b'\t') +// .double_quote(false) +// .escape(Some(b'\\')) +// .flexible(true) +// .comment(Some(b'#')) +// .from_reader(file); - let mut levels = Vec::with_capacity(30); - for result in rdr.deserialize() { - let result: RecordType = result?; - levels.push(result); - } - Ok(levels) -} - -/// 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. -fn csv_classes_to_string(csv: Vec>, config: &Config) -> Result { - let mut buffer = BufWriter::new(Vec::new()); - for (lvl, tier) in csv.iter().skip(1).enumerate() { - // rt_write!(buffer, config.classes.header, lvl + 1)?; - let formatted_header = SimpleCurlyFormat - .format(&config.classes.header, [lvl + 1]) - .expect("Formatting failed"); - write!(buffer, "{}", formatted_header)?; - write!(buffer, "{}", config.classes.row)?; - for elem in tier { - write!( - buffer, - " {}&{}&{}&{}{}&{} \\\\", - elem.technique, - elem.niveau, - elem.technique_type, - elem.cout_blood, - elem.cout_jauge, - elem.effet - )?; - } - write!(buffer, "{}", config.classes.end)?; - } - Ok(String::from_utf8(buffer.into_inner()?).unwrap()) -} +// let mut levels = Vec::with_capacity(30); +// for result in rdr.deserialize() { +// let result: RecordType = result?; +// levels.push(result); +// } +// Ok(levels) +// } /// Converts a table of data into a string representation. /// -- 2.45.1 From 658c6e1e7b440999a42bd37c9fba2a43df096c03 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 5 May 2024 03:17:10 +0200 Subject: [PATCH 09/13] Stalled at the creation of generic types --- helper_config.toml | 9 ++-- src/table_structs.rs | 16 +++---- src/tablegen.rs | 101 +++++++++++++++++++++---------------------- 3 files changed, 61 insertions(+), 65 deletions(-) diff --git a/helper_config.toml b/helper_config.toml index f612ad0..83f2d7c 100644 --- a/helper_config.toml +++ b/helper_config.toml @@ -1,16 +1,17 @@ [classes] header = '\subsubsection{Tier {}}' + row = '''{\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 Technique & Niv & Type & Coût & Effet\\ - \hline" -''' + \hline''' + end = ''' \hline \end{tabularx} -} -''' +}''' + [alchimie] [armes] diff --git a/src/table_structs.rs b/src/table_structs.rs index 9b4b10a..483f009 100644 --- a/src/table_structs.rs +++ b/src/table_structs.rs @@ -13,7 +13,7 @@ use std::{ use regex_static::once_cell::sync::Lazy; -/// Configuration options for processing CSV files and generating LaTeX tables. +/// Configuration options for processing TSV files and generating LaTeX tables. #[derive(Debug, Args)] pub(crate) struct TableArgs { /// A boolean indicating whether to generate LaTeX code and write it to an output file @@ -23,7 +23,7 @@ pub(crate) struct TableArgs { /// The kind of tables to operate on: classes, craft or a specific file pub kind: TargetType, - /// A vector of strings representing the names of CSV files to process. + /// A vector of strings representing the names of TSV files to process. pub filenames: Vec, } @@ -107,7 +107,7 @@ impl From<&str> for TargetType { #[derive(Debug, Deserialize)] #[serde(rename_all = "PascalCase")] -/// A single row in a martial class csv file +/// A single row in a martial class tsv file pub struct RecordClass { /// The name of a technique. pub technique: String, @@ -141,7 +141,7 @@ impl Display for RecordClass { /// 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 - tiers: Vec>, + pub tiers: Vec>, } /// Trait needed to be writable as a LaTex table @@ -150,12 +150,8 @@ pub(crate) trait WriteRows { fn write_rows(&self, config: &Config) -> Result; } -impl ClassesArray { - /// Create a new ClassesArray from the tier list - pub fn new(tiers: Vec>) -> Self { - Self { tiers } - } -} +// impl ClassesArray { +// } impl WriteRows for ClassesArray { fn write_rows(&self, config: &Config) -> Result { let mut buffer = BufWriter::new(Vec::new()); diff --git a/src/tablegen.rs b/src/tablegen.rs index a7c3ccc..ffacc88 100644 --- a/src/tablegen.rs +++ b/src/tablegen.rs @@ -1,4 +1,4 @@ -//! The csv table generation +//! The tsv table generation use anyhow::{Context, Result}; use glob::glob; use regex::Captures; @@ -52,14 +52,13 @@ fn process_files(list_files: &mut Vec, 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 csv = match tt { - TableTargets::Classes => read_csv_classes(f), - _ => todo!(), - } - .context("Error reading file")?; + let tsv: Box = match tt { + TableTargets::Classes => Box::new(read_tsv_classes(f)?), + _ => Box::new(read_tsv::(f)?), + }; match tt { - TableTargets::Classes => export_csv::(f, csv, args, config), + TableTargets::Classes => export_tsv(f, tsv, args, config), TableTargets::Food => todo!(), TableTargets::Alchemy => todo!(), TableTargets::Forge => todo!(), @@ -69,8 +68,9 @@ fn process_one_file(f: &mut PathBuf, args: &TableArgs, config: &Config) -> Resul TableTargets::Gadgets => todo!(), TableTargets::Potions => todo!(), TableTargets::Traps => todo!(), + // TableTargets::Classes => todo!(), } - .context("Error exporting the csv") + .context("Error exporting the tsv") } #[inline] @@ -96,17 +96,18 @@ fn list_dir(pattern: &str) -> Vec { .collect() } -/// Converts a CSV file to LaTeX code. +/// Converts a TSV file to LaTeX code. /// -/// This function reads in a CSV file, processes its contents according to the provided configuration, +/// This function reads in a TSV file, processes its contents according to the provided configuration, /// and writes out the resulting LaTeX code as a string. If an error occurs during processing or writing, /// it will be returned as part of the result. -pub fn export_csv(f: &Path, csv: RowType, args: &TableArgs, config: &Config) -> Result<()> -where - // PathType: AsRef + Debug, - RowType: WriteRows, -{ - let converted = csv_to_string(csv, config)?; +pub fn export_tsv( + f: &Path, + tsv: Box, + args: &TableArgs, + config: &Config, +) -> Result<()> { + let converted = tsv_to_string(tsv, config)?; if args.export { let path = format!("{:?}", f).replace(".tsv", ".tex"); // let path = f.with_extension(".tex"); @@ -132,11 +133,11 @@ pub fn make_latex_string(arg: &str) -> String { res.to_string() } -/// Reads a CSV file into a table. +/// Reads a TSV file into a table. /// -/// This function reads in a comma-separated values (CSV) file and returns it as a Table object, +/// 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_csv_classes(filename: &T) -> Result +fn read_tsv_classes(filename: &T) -> Result where T: AsRef, { @@ -164,44 +165,42 @@ where current_tier.borrow_mut().push(result); } } - // println!("{:#?}", levels); - Ok(ClassesArray::new(levels)) + Ok(ClassesArray { tiers: levels }) } -// /// Reads a CSV file into a table. -// /// -// /// This function reads in a comma-separated values (CSV) 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_csv(filename: &PathType) -> Result, Error> -// where -// PathType: AsRef, -// RecordType: for<'a> serde::Deserialize<'a>, -// { -// let file = File::open(filename)?; -// let mut rdr = csv::ReaderBuilder::new() -// .has_headers(false) -// .delimiter(b'\t') -// .double_quote(false) -// .escape(Some(b'\\')) -// .flexible(true) -// .comment(Some(b'#')) -// .from_reader(file); +/// Reads a TSV file into a table. +/// +/// 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(filename: &Path) -> Result +where + RecordType: for<'a> serde::Deserialize<'a>, + RecordHolder: WriteRows, +{ + let file = File::open(filename)?; + let mut rdr = csv::ReaderBuilder::new() + .has_headers(false) + .delimiter(b'\t') + .double_quote(false) + .escape(Some(b'\\')) + .flexible(true) + .comment(Some(b'#')) + .from_reader(file); -// let mut levels = Vec::with_capacity(30); -// for result in rdr.deserialize() { -// let result: RecordType = result?; -// levels.push(result); -// } -// Ok(levels) -// } + let mut levels = Vec::with_capacity(30); + for result in rdr.deserialize() { + let result: RecordType = result?; + levels.push(result); + } + + // Ok(RecordHolder{}) + todo!() +} /// 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 csv_to_string(csv: RowType, config: &Config) -> Result -where - RowType: WriteRows, -{ - csv.write_rows(config) +pub(crate) fn tsv_to_string(tsv: Box, config: &Config) -> Result { + tsv.write_rows(config) } -- 2.45.1 From cd64e4423ba44b0bab52d1d7a2bebc9a05d74b96 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 5 May 2024 05:26:09 +0200 Subject: [PATCH 10/13] Working dispatch, needs to stop beying dynamic --- Cargo.toml | 1 + helper_config.toml | 34 +++++----- src/main.rs | 30 ++++++++- src/table_structs.rs | 154 +++++++++++++++++++++++++++++++++++-------- src/tablegen.rs | 26 ++++---- 5 files changed, 186 insertions(+), 59 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 89e0829..b2a9780 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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" diff --git a/helper_config.toml b/helper_config.toml index 83f2d7c..18e965a 100644 --- a/helper_config.toml +++ b/helper_config.toml @@ -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} +}''' diff --git a/src/main.rs b/src/main.rs index 8aa2b08..8c8e4c0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -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") diff --git a/src/table_structs.rs b/src/table_structs.rs index 483f009..daa4c6d 100644 --- a/src/table_structs.rs +++ b/src/table_structs.rs @@ -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_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>, _configg: &Config) -> Result<()> { + unimplemented!() + } + + fn write_row(&self, buffer: &mut BufWriter>, _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>, _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; + fn write_table(&self, config: &Config) -> Result; } - -// impl ClassesArray { +/// Trait needed to be writable as a LaTex table +pub(crate) trait WriteRow { + fn write_header(&self, buffer: &mut BufWriter>, config: &Config) -> Result<()>; + fn write_row(&self, buffer: &mut BufWriter>, config: &Config) -> Result<()>; + fn write_footer(&self, buffer: &mut BufWriter>, 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; // } -impl WriteRows for ClassesArray { - fn write_rows(&self, config: &Config) -> Result { + +impl WriteTable for ClassesArray { + fn write_table(&self, config: &Config) -> Result { 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>, 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>, _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>, 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 +where + RecordType: WriteRow, +{ + /// Every tier held as a vec of vec of rows + pub row: Vec, +} + +impl WriteTable for CraftArray +where + RecordType: WriteRow, +{ + fn write_table(&self, config: &Config) -> Result { + 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); diff --git a/src/tablegen.rs b/src/tablegen.rs index ffacc88..e4bf2e1 100644 --- a/src/tablegen.rs +++ b/src/tablegen.rs @@ -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, 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 = match tt { + let tsv: Box = match tt { TableTargets::Classes => Box::new(read_tsv_classes(f)?), - _ => Box::new(read_tsv::(f)?), + _ => read_tsv::(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 { /// it will be returned as part of the result. pub fn export_tsv( f: &Path, - tsv: Box, + tsv: Box, 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(filename: &Path) -> Result +fn read_tsv(filename: &Path, target_type: &TableTargets) -> Result> 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, config: &Config) -> Result { - tsv.write_rows(config) +pub(crate) fn tsv_to_string(tsv: Box, config: &Config) -> Result { + tsv.write_table(config) } -- 2.45.1 From 333d5e6981008ac2ce02165f203f4aaeff359767 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 5 May 2024 18:41:31 +0200 Subject: [PATCH 11/13] Implements basic traits and serialization --- helper_config.toml | 58 ++++++-- src/main.rs | 5 +- src/table_structs.rs | 203 +------------------------- src/table_types.rs | 335 +++++++++++++++++++++++++++++++++++++++++++ src/tablegen.rs | 38 +++-- 5 files changed, 405 insertions(+), 234 deletions(-) create mode 100644 src/table_types.rs diff --git a/helper_config.toml b/helper_config.toml index 18e965a..993c2e0 100644 --- a/helper_config.toml +++ b/helper_config.toml @@ -17,16 +17,56 @@ 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é \\ +Ingrédient&Partie&Rareté&Satiété&Effet (Plat)&Effets (Accompagnement)&Difficulté&Toxicité \\ + \hline''' +header_alchemy = '''{\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é & Effet (Principal) & Effets (Catalysé) & Difficulté & Toxicité + \hline''' +header_forge = '''{\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 & Rareté & Densité & Effet Armes (Principal) & Effet Armures (Principal) & Effets Armes (Catalysé) & Effet Armures (C) & Difficulté & Préparation + \hline''' +header_mtrap ='''{\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 +Élément & Prix & Effet & Difficulté & Activation & Solidité + \hline''' +header_weapons = '''{\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 +Nom & Rareté & Dégâts & + & R.Max & Armor.B & Prot & Int. & Deux M & Une M & Esq. & Parr. & Vitesse & Discrétion & Catégorie & Modes & Spécial + \hline''' +header_armors ='''{\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 +Nom & Rareté & Dégâts & + & R.Max & Armor.B & Prot & Int. & Deux M & Une M & Esq. & Parr. & Vitesse & Discrétion & Spécial + \hline''' +header_gadgets ='''{\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 +Nom & Effet & Prix + \hline''' +header_potions = '''{\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 +Nom & Type & Prix & Toxicité & Effet + \hline''' +header_traps = '''{\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 +Nom & Type & Prix & Toxicité & Effet \hline''' -header_alchemy = "" -header_forge = "" -header_mtrap = "" -header_weapons = "" -header_armors = "" -header_gadgets = "" -header_potions = "" -header_traps = "" end = ''' \hline \end{tabularx} }''' diff --git a/src/main.rs b/src/main.rs index 8c8e4c0..495a312 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,10 +3,11 @@ //! This program is meant as a helper for the ravenous project. //! -#![allow(dead_code)] +// #![allow(dead_code)] #![warn(missing_docs)] -// #![warn(clippy::missing_docs_in_private_items)] +#![warn(clippy::missing_docs_in_private_items)] mod table_structs; +mod table_types; mod tablegen; use crate::table_structs::TableArgs; use std::fs; diff --git a/src/table_structs.rs b/src/table_structs.rs index daa4c6d..8c172c7 100644 --- a/src/table_structs.rs +++ b/src/table_structs.rs @@ -1,15 +1,8 @@ //! Holds all the data structures away from the main routine -use crate::{tablegen::make_latex_string, Config}; -use anyhow::{Context, Result}; use clap::Args; -use dynfmt::{Format, SimpleCurlyFormat}; use phf::phf_map; use regex::Regex; -use serde::Deserialize; -use std::{ - fmt::{self, Debug, Display}, - io::{BufWriter, Write}, -}; +use std::fmt::Debug; use regex_static::once_cell::sync::Lazy; @@ -99,197 +92,3 @@ impl From<&str> for TargetType { } } } - -#[derive(Debug, Deserialize)] -#[serde(rename_all = "PascalCase")] -/// A single row in a martial class tsv file -pub struct RecordClass { - /// The name of a technique. - pub technique: String, - /// The level or rank of a technique - pub niveau: String, - /// The type of technique, such as Actif or Exclusif. - pub technique_type: String, - /// The blood cost for this technique. - pub cout_blood: CleanString, - /// The gauge cost for this technique. - pub cout_jauge: CleanString, - /// A brief description of the effect or outcome of using this technique. - pub effet: CleanString, -} - -// 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>, _configg: &Config) -> Result<()> { - unimplemented!() - } - - fn write_row(&self, buffer: &mut BufWriter>, _config: &Config) -> Result<()> { - Ok(write!( - buffer, - " {}&{}&{}&{}{}&{} \\\\", - self.technique, - self.niveau, - self.technique_type, - self.cout_blood, - self.cout_jauge, - self.effet - )?) - } - - fn write_footer(&self, _buffer: &mut BufWriter>, _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 - pub tiers: Vec>, -} - -/// Trait needed to be writable as a LaTex table -pub(crate) trait WriteTable { - /// Takes a config and writes to a string the representation of the Array - fn write_table(&self, config: &Config) -> Result; -} -/// Trait needed to be writable as a LaTex table -pub(crate) trait WriteRow { - fn write_header(&self, buffer: &mut BufWriter>, config: &Config) -> Result<()>; - fn write_row(&self, buffer: &mut BufWriter>, config: &Config) -> Result<()>; - fn write_footer(&self, buffer: &mut BufWriter>, 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; -// } - -impl WriteTable for ClassesArray { - fn write_table(&self, config: &Config) -> Result { - 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)?; - let formatted_header = SimpleCurlyFormat - .format(&config.classes.header, [lvl + 1]) - .expect("Formatting failed"); - writeln!(buffer, "{}", formatted_header)?; - writeln!(buffer, "{}", config.classes.row)?; - for elem in tier { - elem.write_row(&mut buffer, config)? - } - writeln!(buffer, "{}", config.classes.end)?; - } - Ok(String::from_utf8(buffer.into_inner()?).unwrap()) - } -} - -#[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>, 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>, _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>, 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 -where - RecordType: WriteRow, -{ - /// Every tier held as a vec of vec of rows - pub row: Vec, -} - -impl WriteTable for CraftArray -where - RecordType: WriteRow, -{ - fn write_table(&self, config: &Config) -> Result { - 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); - -impl fmt::Debug for CleanString { - #[inline] - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - ::fmt(&self.0, f) - } -} - -impl fmt::Display for CleanString { - #[inline] - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - f.write_str(&make_latex_string(&self.0)) - } -} diff --git a/src/table_types.rs b/src/table_types.rs new file mode 100644 index 0000000..6a73e0a --- /dev/null +++ b/src/table_types.rs @@ -0,0 +1,335 @@ +//! Holds all the table base structure +use crate::{tablegen::make_latex_string, Config}; +use anyhow::{Context, Result}; +use dynfmt::{Format, SimpleCurlyFormat}; +use serde::Deserialize; +use std::{ + fmt::{self, Debug}, + io::{BufWriter, Write}, +}; + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "PascalCase")] +/// A single row in a martial class tsv file +pub(crate) struct RecordClass { + /// The name of a technique. + pub technique: String, + /// The level or rank of a technique + pub niveau: String, + /// The type of technique, such as Actif or Exclusif. + pub technique_type: String, + /// The blood cost for this technique. + pub cout_blood: CleanString, + /// The gauge cost for this technique. + pub cout_jauge: CleanString, + /// A brief description of the effect or outcome of using this technique. + pub effet: CleanString, +} + +impl WriteRow for RecordClass { + fn write_header(&self, _buffer: &mut BufWriter>, _configg: &Config) -> Result<()> { + unimplemented!() + } + + fn write_row(&self, buffer: &mut BufWriter>, _config: &Config) -> Result<()> { + Ok(write!( + buffer, + " {}&{}&{}&{}{}&{} \\\\", + self.technique, + self.niveau, + self.technique_type, + self.cout_blood, + self.cout_jauge, + self.effet + )?) + } + + fn write_footer(&self, _buffer: &mut BufWriter>, _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 + pub tiers: Vec>, +} + +/// Trait needed to be writable as a LaTex table +pub(crate) trait WriteTable { + /// Takes a config and writes to a string the representation of the Array + fn write_table(&self, config: &Config) -> Result; +} +/// Trait needed to be writable as a LaTex table +pub(crate) trait WriteRow { + /// Write the header of the LaTex table + fn write_header(&self, buffer: &mut BufWriter>, config: &Config) -> Result<()>; + /// Write the row of the LaTex table + fn write_row(&self, buffer: &mut BufWriter>, config: &Config) -> Result<()>; + /// Write the row of the LaTex table + fn write_footer(&self, buffer: &mut BufWriter>, config: &Config) -> Result<()>; +} + +impl WriteTable for ClassesArray { + fn write_table(&self, config: &Config) -> Result { + 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)?; + let formatted_header = SimpleCurlyFormat + .format(&config.classes.header, [lvl + 1]) + .expect("Formatting failed"); + writeln!(buffer, "{}", formatted_header)?; + writeln!(buffer, "{}", config.classes.row)?; + for elem in tier { + elem.write_row(&mut buffer, config)? + } + writeln!(buffer, "{}", config.classes.end)?; + } + Ok(String::from_utf8(buffer.into_inner()?).unwrap()) + } +} + +/// Represents the whole Craft Array, with a vec for every tier +pub(crate) struct CraftArray +where + RecordType: WriteRow, +{ + /// Every tier held as a vec of vec of rows + pub row: Vec, +} + +impl WriteTable for CraftArray +where + RecordType: WriteRow, +{ + fn write_table(&self, config: &Config) -> Result { + 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(crate) struct CleanString(String); + +impl fmt::Debug for CleanString { + #[inline] + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + ::fmt(&self.0, f) + } +} + +impl fmt::Display for CleanString { + #[inline] + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.write_str(&make_latex_string(&self.0)) + } +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "PascalCase")] +/// A single row in a martial class tsv file +pub(crate) struct RecordFood { + /// The name of the ingredient used in this recipe. + pub ingredient: String, + + /// The part of the body this food is from. + pub part: String, + + /// The rarity level of this food, represented as a clean string. + pub rarity: CleanString, + + /// How much this this food item will fill you. + pub filling: CleanString, + + /// The main effect that this food has on the player's character (e.g. "healing", "buffing", etc.). + pub effect_main: CleanString, + + /// Any secondary effects that this food may have on the player's character. + pub effect_secondary: CleanString, + + /// A measure of how difficult it is to prepare this food item. + pub difficulty: CleanString, + + /// The toxicity level of this food. + pub toxicity: CleanString, +} + +impl WriteRow for RecordFood { + fn write_header(&self, buffer: &mut BufWriter>, 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>, _config: &Config) -> Result<()> { + writeln!( + 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>, config: &Config) -> Result<()> { + writeln!(buffer, "{}", config.craft.end).context("Writing footer") + } +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "PascalCase")] +/// A record of alchemy data. +pub(crate) struct RecordAlchemy { + /// The ingredients name. + pub ingredient: String, + + /// The part this ingredient came from + pub part: String, + + /// The rarity level of this alchemy + pub rarity: CleanString, + + /// A brief description of the main effect of this alchemy. + pub effect_main: CleanString, + + /// A brief description of any secondary effects of this alchemy. + pub effect_secondary: CleanString, + + /// The difficulty level required to perform this alchemy + pub difficulty: CleanString, + + /// The toxicity of this ingredient. + pub toxicity: CleanString, +} + +impl WriteRow for RecordAlchemy { + fn write_header(&self, buffer: &mut BufWriter>, config: &Config) -> Result<()> { + writeln!(buffer, "{}", config.craft.header_alchemy).context("Writing header") + } + fn write_row(&self, buffer: &mut BufWriter>, _config: &Config) -> Result<()> { + writeln!( + buffer, + " {}&{}&{}{}&{}&{}&{} \\\\", + self.ingredient, + self.part, + self.rarity, + self.effect_main, + self.effect_secondary, + self.difficulty, + self.toxicity, + ) + .context("Writing row") + } + + fn write_footer(&self, buffer: &mut BufWriter>, config: &Config) -> Result<()> { + writeln!(buffer, "{}", config.craft.end).context("Writing footer") + } +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "PascalCase")] +/// A record of alchemy data. +pub(crate) struct RecordForge { + /// The ingredient used in this forging recipe. + pub ingredient: String, + + /// The rarity level of this forged item. + pub rarity: CleanString, + + /// The density or weight class of the forged item. + pub density: CleanString, + + /// Main effect on weapons when using this ingredient. + pub effect_weapon_main: CleanString, + + /// Main effect on armor when using this ingredient. + pub effect_armor_main: CleanString, + + /// Secondary effects on weapons when using this ingredient. + pub effect_weapon_secondary: CleanString, + + /// Secondary effects on armor when using this ingredient. + pub effect_armor_secondary: CleanString, + + /// The difficulty level + pub difficulty: CleanString, + + /// The difficulty processing this ingredient. + pub preparation: CleanString, +} + +impl WriteRow for RecordForge { + fn write_header(&self, buffer: &mut BufWriter>, config: &Config) -> Result<()> { + writeln!(buffer, "{}", config.craft.header_forge).context("Writing header") + } + fn write_row(&self, buffer: &mut BufWriter>, _config: &Config) -> Result<()> { + writeln!( + buffer, + " {}&{}&{}&{}&{}{}&{}&{}&{} \\\\", + self.ingredient, + self.rarity, + self.density, + self.effect_weapon_main, + self.effect_armor_main, + self.effect_weapon_secondary, + self.effect_armor_secondary, + self.difficulty, + self.preparation, + ) + .context("Writing row") + } + + fn write_footer(&self, buffer: &mut BufWriter>, config: &Config) -> Result<()> { + writeln!(buffer, "{}", config.craft.end).context("Writing footer") + } +} + +// #[derive(Debug, Deserialize)] +// #[serde(rename_all = "PascalCase")] +// pub(crate) struct Weapons { +// name: String, +// rarity: CleanString, +// damage: String, +// damage_add: String, +// rmax: String, +// armorbreak: String, +// protection: String, +// integrity: String, +// twohanded: String, +// onehanded: String, +// dodge: String, +// } + +// impl WriteRow for Weapons { +// fn write_header(&self, buffer: &mut BufWriter>, config: &Config) -> Result<()> { +// writeln!(buffer, "{}", config.craft.header_alchemy).context("Writing header") +// } +// fn write_row(&self, buffer: &mut BufWriter>, _config: &Config) -> Result<()> { +// writeln!( +// buffer, +// " {}&{}&{}{}&{}&{}&{} \\\\", +// self.ingredient, +// self.part, +// self.rarity, +// self.effect_main, +// self.effect_secondary, +// self.difficulty, +// self.toxicity, +// ) +// .context("Writing row") +// } + +// fn write_footer(&self, buffer: &mut BufWriter>, config: &Config) -> Result<()> { +// writeln!(buffer, "{}", config.craft.end).context("Writing footer") +// } +// } diff --git a/src/tablegen.rs b/src/tablegen.rs index e4bf2e1..543911a 100644 --- a/src/tablegen.rs +++ b/src/tablegen.rs @@ -9,11 +9,12 @@ use std::{ path::{Path, PathBuf}, }; +use crate::table_types::{ + ClassesArray, CraftArray, RecordAlchemy, RecordClass, RecordFood, RecordForge, WriteRow, + WriteTable, +}; use crate::{ - table_structs::{ - ClassesArray, CraftArray, RecordClass, RecordFood, TableArgs, TableTargets, TargetType, - WriteRow, WriteTable, RE, STR_TO_TARGET_FULL, - }, + table_structs::{TableArgs, TableTargets, TargetType, RE, STR_TO_TARGET_FULL}, Config, }; @@ -54,23 +55,18 @@ fn process_one_file(f: &mut PathBuf, args: &TableArgs, config: &Config) -> Resul let tt = extract_type(f).context("Error extracting file type ... skipping")?; let tsv: Box = match tt { TableTargets::Classes => Box::new(read_tsv_classes(f)?), - _ => read_tsv::(f, tt)?, - }; - - match tt { - TableTargets::Classes => export_tsv(f, tsv, args, config), - TableTargets::Food => export_tsv(f, tsv, args, config), - TableTargets::Alchemy => todo!(), - TableTargets::Forge => todo!(), + TableTargets::Food => read_tsv::(f)?, + TableTargets::Alchemy => read_tsv::(f)?, + TableTargets::Forge => read_tsv::(f)?, TableTargets::MPieges => todo!(), TableTargets::Weapons => todo!(), TableTargets::Armors => todo!(), TableTargets::Gadgets => todo!(), TableTargets::Potions => todo!(), TableTargets::Traps => todo!(), - // TableTargets::Classes => todo!(), - } - .context("Error exporting the tsv") + }; + + export_tsv(f, tsv, args, config).context("Error exporting the tsv") } #[inline] @@ -126,6 +122,7 @@ pub fn make_latex_string(arg: &str) -> String { let temp = arg .replace('🩸', "\\blood") .replace('⚡', "\\gauge") + .replace('☆', "\\star") .replace('&', "\\&"); let res = RE.replace_all(&temp, |caps: &Captures| { format!("\\dd{{{}}}", caps[0].chars().count()) @@ -135,7 +132,7 @@ pub fn make_latex_string(arg: &str) -> String { /// Reads a TSV file into a table. /// -/// This function reads in a comma-separated values (TSV) file and returns it as a Table object, +/// This function reads in a tab-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_classes(filename: &T) -> Result where @@ -170,12 +167,11 @@ where /// Reads a TSV file into a table. /// -/// 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(filename: &Path, target_type: &TableTargets) -> Result> +/// Reads a tab-separated values (TSV) file and deserializes its contents into a table. +fn read_tsv(filename: &Path) -> Result> where + // TODO: Remove the static and do not return a Box RecordType: for<'a> serde::Deserialize<'a> + WriteRow + 'static, - // RecordHolder: WriteRows, { let file = File::open(filename)?; let mut rdr = csv::ReaderBuilder::new() @@ -188,7 +184,7 @@ where .from_reader(file); let mut levels = Vec::with_capacity(30); - for result in rdr.deserialize() { + for result in rdr.deserialize().skip(2) { let result: RecordType = result?; levels.push(result); } -- 2.45.1 From cc5af1907c590892822b12b4b0d0fa57d6ade6da Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 5 May 2024 20:25:10 +0200 Subject: [PATCH 12/13] Adds true generics and sorts some of the mess --- src/table_structs.rs | 1 + src/table_types.rs | 200 +++++++++++++++++++++++++++++-------------- src/tablegen.rs | 81 ++++++++++++++++-- 3 files changed, 214 insertions(+), 68 deletions(-) diff --git a/src/table_structs.rs b/src/table_structs.rs index 8c172c7..73986e3 100644 --- a/src/table_structs.rs +++ b/src/table_structs.rs @@ -40,6 +40,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] +#[derive(Clone)] pub enum TableTargets { /// A class tsv Classes, diff --git a/src/table_types.rs b/src/table_types.rs index 6a73e0a..7457a0f 100644 --- a/src/table_types.rs +++ b/src/table_types.rs @@ -1,6 +1,7 @@ //! Holds all the table base structure -use crate::{tablegen::make_latex_string, Config}; +use crate::{table_structs::TableTargets, tablegen::make_latex_string, Config}; use anyhow::{Context, Result}; +// use csv::StringRecord; use dynfmt::{Format, SimpleCurlyFormat}; use serde::Deserialize; use std::{ @@ -27,11 +28,21 @@ pub(crate) struct RecordClass { } impl WriteRow for RecordClass { - fn write_header(&self, _buffer: &mut BufWriter>, _configg: &Config) -> Result<()> { + fn write_header( + &self, + _buffer: &mut BufWriter>, + _config: &Config, + _format: &str, + ) -> Result<()> { unimplemented!() } - fn write_row(&self, buffer: &mut BufWriter>, _config: &Config) -> Result<()> { + fn write_row( + &self, + buffer: &mut BufWriter>, + _config: &Config, + _format: &str, + ) -> Result<()> { Ok(write!( buffer, " {}&{}&{}&{}{}&{} \\\\", @@ -44,7 +55,12 @@ impl WriteRow for RecordClass { )?) } - fn write_footer(&self, _buffer: &mut BufWriter>, _configg: &Config) -> Result<()> { + fn write_footer( + &self, + _buffer: &mut BufWriter>, + _config: &Config, + _format: &str, + ) -> Result<()> { unimplemented!() } } @@ -62,11 +78,26 @@ pub(crate) trait WriteTable { /// Trait needed to be writable as a LaTex table pub(crate) trait WriteRow { /// Write the header of the LaTex table - fn write_header(&self, buffer: &mut BufWriter>, config: &Config) -> Result<()>; + fn write_header( + &self, + buffer: &mut BufWriter>, + config: &Config, + format: &str, + ) -> Result<()>; /// Write the row of the LaTex table - fn write_row(&self, buffer: &mut BufWriter>, config: &Config) -> Result<()>; + fn write_row( + &self, + buffer: &mut BufWriter>, + config: &Config, + format: &str, + ) -> Result<()>; /// Write the row of the LaTex table - fn write_footer(&self, buffer: &mut BufWriter>, config: &Config) -> Result<()>; + fn write_footer( + &self, + buffer: &mut BufWriter>, + config: &Config, + format: &str, + ) -> Result<()>; } impl WriteTable for ClassesArray { @@ -80,7 +111,7 @@ impl WriteTable for ClassesArray { writeln!(buffer, "{}", formatted_header)?; writeln!(buffer, "{}", config.classes.row)?; for elem in tier { - elem.write_row(&mut buffer, config)? + elem.write_row(&mut buffer, config, NO_STRING)? } writeln!(buffer, "{}", config.classes.end)?; } @@ -103,14 +134,54 @@ where { fn write_table(&self, config: &Config) -> Result { let mut buffer = BufWriter::new(Vec::new()); - self.row[0].write_header(&mut buffer, config)?; + self.row[0].write_header(&mut buffer, config, NO_STRING)?; for row in self.row.iter() { - row.write_row(&mut buffer, config)?; + row.write_row(&mut buffer, config, NO_STRING)?; } - self.row[0].write_footer(&mut buffer, config)?; + self.row[0].write_footer(&mut buffer, config, NO_STRING)?; Ok(String::from_utf8(buffer.into_inner()?).unwrap()) } } +/// Represents the whole Craft Array, with a vec for every tier +pub(crate) struct GenericArray +where + RecordType: WriteRow, +{ + /// Every tier held as a vec of vec of rows + pub row: Vec, + /// Inner craft type, since the array is genric + pub craft_type: TableTargets, +} + +impl WriteTable for GenericArray +where + RecordType: WriteRow, +{ + fn write_table(&self, config: &Config) -> Result { + let mut buffer = BufWriter::new(Vec::new()); + let header = match self.craft_type { + TableTargets::Classes => unimplemented!(), + TableTargets::Food => &config.craft.header_food, + TableTargets::Alchemy => &config.craft.header_alchemy, + TableTargets::Forge => &config.craft.header_forge, + TableTargets::MPieges => &config.craft.header_mtrap, + TableTargets::Weapons => &config.craft.header_weapons, + TableTargets::Armors => &config.craft.header_armors, + TableTargets::Gadgets => &config.craft.header_gadgets, + TableTargets::Potions => &config.craft.header_potions, + TableTargets::Traps => &config.craft.header_traps, + }; + self.row[0].write_header(&mut buffer, config, header)?; + for row in self.row.iter().skip(2) { + row.write_row(&mut buffer, config, NO_STRING)?; + } + self.row[0].write_footer(&mut buffer, config, NO_STRING)?; + Ok(String::from_utf8(buffer.into_inner()?).unwrap()) + } +} + +/// Empty string +const NO_STRING: &String = &String::new(); /// This type is used to represent strings in LaTeX tables, where certain characters need to be escaped or replaced with special commands. #[derive(Deserialize)] @@ -160,12 +231,20 @@ pub(crate) struct RecordFood { } impl WriteRow for RecordFood { - fn write_header(&self, buffer: &mut BufWriter>, config: &Config) -> Result<()> { - writeln!(buffer, "{}", config.craft.header_food).context("Writing header") - - // Ok(String::from_utf8(buffer.into_inner()?).unwrap()) + fn write_header( + &self, + buffer: &mut BufWriter>, + _: &Config, + format: &str, + ) -> Result<()> { + writeln!(buffer, "{}", format).context("Writing header") } - fn write_row(&self, buffer: &mut BufWriter>, _config: &Config) -> Result<()> { + fn write_row( + &self, + buffer: &mut BufWriter>, + _config: &Config, + _format: &str, + ) -> Result<()> { writeln!( buffer, " {}&{}&{}{}&{}&{}&{}&{} \\\\", @@ -181,7 +260,12 @@ impl WriteRow for RecordFood { .context("Writing row") } - fn write_footer(&self, buffer: &mut BufWriter>, config: &Config) -> Result<()> { + fn write_footer( + &self, + buffer: &mut BufWriter>, + config: &Config, + _format: &str, + ) -> Result<()> { writeln!(buffer, "{}", config.craft.end).context("Writing footer") } } @@ -213,10 +297,20 @@ pub(crate) struct RecordAlchemy { } impl WriteRow for RecordAlchemy { - fn write_header(&self, buffer: &mut BufWriter>, config: &Config) -> Result<()> { + fn write_header( + &self, + buffer: &mut BufWriter>, + config: &Config, + _format: &str, + ) -> Result<()> { writeln!(buffer, "{}", config.craft.header_alchemy).context("Writing header") } - fn write_row(&self, buffer: &mut BufWriter>, _config: &Config) -> Result<()> { + fn write_row( + &self, + buffer: &mut BufWriter>, + _config: &Config, + _format: &str, + ) -> Result<()> { writeln!( buffer, " {}&{}&{}{}&{}&{}&{} \\\\", @@ -231,7 +325,12 @@ impl WriteRow for RecordAlchemy { .context("Writing row") } - fn write_footer(&self, buffer: &mut BufWriter>, config: &Config) -> Result<()> { + fn write_footer( + &self, + buffer: &mut BufWriter>, + config: &Config, + _format: &str, + ) -> Result<()> { writeln!(buffer, "{}", config.craft.end).context("Writing footer") } } @@ -269,10 +368,20 @@ pub(crate) struct RecordForge { } impl WriteRow for RecordForge { - fn write_header(&self, buffer: &mut BufWriter>, config: &Config) -> Result<()> { + fn write_header( + &self, + buffer: &mut BufWriter>, + config: &Config, + _format: &str, + ) -> Result<()> { writeln!(buffer, "{}", config.craft.header_forge).context("Writing header") } - fn write_row(&self, buffer: &mut BufWriter>, _config: &Config) -> Result<()> { + fn write_row( + &self, + buffer: &mut BufWriter>, + _config: &Config, + _format: &str, + ) -> Result<()> { writeln!( buffer, " {}&{}&{}&{}&{}{}&{}&{}&{} \\\\", @@ -289,47 +398,12 @@ impl WriteRow for RecordForge { .context("Writing row") } - fn write_footer(&self, buffer: &mut BufWriter>, config: &Config) -> Result<()> { + fn write_footer( + &self, + buffer: &mut BufWriter>, + config: &Config, + _format: &str, + ) -> Result<()> { writeln!(buffer, "{}", config.craft.end).context("Writing footer") } } - -// #[derive(Debug, Deserialize)] -// #[serde(rename_all = "PascalCase")] -// pub(crate) struct Weapons { -// name: String, -// rarity: CleanString, -// damage: String, -// damage_add: String, -// rmax: String, -// armorbreak: String, -// protection: String, -// integrity: String, -// twohanded: String, -// onehanded: String, -// dodge: String, -// } - -// impl WriteRow for Weapons { -// fn write_header(&self, buffer: &mut BufWriter>, config: &Config) -> Result<()> { -// writeln!(buffer, "{}", config.craft.header_alchemy).context("Writing header") -// } -// fn write_row(&self, buffer: &mut BufWriter>, _config: &Config) -> Result<()> { -// writeln!( -// buffer, -// " {}&{}&{}{}&{}&{}&{} \\\\", -// self.ingredient, -// self.part, -// self.rarity, -// self.effect_main, -// self.effect_secondary, -// self.difficulty, -// self.toxicity, -// ) -// .context("Writing row") -// } - -// fn write_footer(&self, buffer: &mut BufWriter>, config: &Config) -> Result<()> { -// writeln!(buffer, "{}", config.craft.end).context("Writing footer") -// } -// } diff --git a/src/tablegen.rs b/src/tablegen.rs index 543911a..f6c1c63 100644 --- a/src/tablegen.rs +++ b/src/tablegen.rs @@ -1,5 +1,6 @@ //! The tsv table generation use anyhow::{Context, Result}; +use csv::StringRecord; use glob::glob; use regex::Captures; use std::{ @@ -10,8 +11,8 @@ use std::{ }; use crate::table_types::{ - ClassesArray, CraftArray, RecordAlchemy, RecordClass, RecordFood, RecordForge, WriteRow, - WriteTable, + ClassesArray, CraftArray, GenericArray, RecordAlchemy, RecordClass, RecordFood, RecordForge, + WriteRow, WriteTable, }; use crate::{ table_structs::{TableArgs, TableTargets, TargetType, RE, STR_TO_TARGET_FULL}, @@ -58,9 +59,9 @@ fn process_one_file(f: &mut PathBuf, args: &TableArgs, config: &Config) -> Resul TableTargets::Food => read_tsv::(f)?, TableTargets::Alchemy => read_tsv::(f)?, TableTargets::Forge => read_tsv::(f)?, - TableTargets::MPieges => todo!(), - TableTargets::Weapons => todo!(), - TableTargets::Armors => todo!(), + TableTargets::MPieges => read_generic_tsv(f, tt)?, + TableTargets::Weapons => read_generic_tsv(f, tt)?, + TableTargets::Armors => read_generic_tsv(f, tt)?, TableTargets::Gadgets => todo!(), TableTargets::Potions => todo!(), TableTargets::Traps => todo!(), @@ -122,7 +123,14 @@ pub fn make_latex_string(arg: &str) -> String { let temp = arg .replace('🩸', "\\blood") .replace('⚡', "\\gauge") + .replace('☽', "\\tranchant") + .replace('◅', "\\percant") + .replace('⧆', "\\contondant") + .replace('Ø', "\\o{}") + .replace('⌭', "\\torque") .replace('☆', "\\star") + .replace('🗘', "\\reload") + .replace('½', "\\sfrac{1}{2}") .replace('&', "\\&"); let res = RE.replace_all(&temp, |caps: &Captures| { format!("\\dd{{{}}}", caps[0].chars().count()) @@ -193,6 +201,69 @@ where Ok(Box::new(craft_array)) } +/// Reads a TSV file into a table. +/// +/// Reads a tab-separated values (TSV) file and deserializes its contents into a table. +fn read_generic_tsv(filename: &Path, craft_type: &TableTargets) -> Result> { + let file = File::open(filename)?; + let rdr = csv::ReaderBuilder::new() + .has_headers(false) + .delimiter(b'\t') + .double_quote(false) + .escape(Some(b'\\')) + .flexible(true) + .comment(Some(b'#')) + .from_reader(file); + + let res = rdr + .into_records() + .map(|r| r.context("reading row").unwrap()) + .collect(); + + let craft_array = GenericArray { + row: res, + craft_type: craft_type.clone(), + }; + Ok(Box::new(craft_array)) +} + +impl WriteRow for StringRecord { + fn write_header( + &self, + buffer: &mut std::io::BufWriter>, + _config: &Config, + format: &str, + ) -> Result<()> { + writeln!(buffer, "{}", format).context("Writing header") + } + + fn write_row( + &self, + buffer: &mut std::io::BufWriter>, + _config: &Config, + _format: &str, + ) -> Result<()> { + let mut itr = self.into_iter(); + write!( + buffer, + " {}", + itr.next().context("Writing firt element of row").unwrap() + )?; + for e in itr { + write!(buffer, " & {}", make_latex_string(e)).context("Writing row")? + } + writeln!(buffer).context("Writing row") + } + + fn write_footer( + &self, + buffer: &mut std::io::BufWriter>, + config: &Config, + _format: &str, + ) -> Result<()> { + writeln!(buffer, "{}", config.craft.end).context("Writing footer") + } +} /// Converts a table of data into a string representation. /// /// This function takes in a Table object and returns its contents as a formatted string, -- 2.45.1 From 6186d9ab18aa292d8bddcc22b38e062bb1833278 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Mon, 6 May 2024 03:08:16 +0200 Subject: [PATCH 13/13] Adds full implementation of the tablegen --- src/main.rs | 29 +-- src/table_structs.rs | 42 ++++- src/table_types.rs | 409 ++++++++++++++++++++++--------------------- src/tablegen.rs | 133 +++++++------- 4 files changed, 315 insertions(+), 298 deletions(-) diff --git a/src/main.rs b/src/main.rs index 495a312..d5af324 100644 --- a/src/main.rs +++ b/src/main.rs @@ -12,8 +12,10 @@ mod tablegen; use crate::table_structs::TableArgs; use std::fs; +use anyhow::Result; use clap::{Parser, Subcommand}; use serde::Deserialize; +use table_structs::Craft; use tablegen::table_gen; #[derive(Parser, Debug)] @@ -53,32 +55,7 @@ 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() { +fn main() -> Result<()> { let args = Args::parse(); let config = &fs::read_to_string("helper_config.toml") .unwrap_or(include_str!("../helper_config.toml").to_string()); diff --git a/src/table_structs.rs b/src/table_structs.rs index 73986e3..e03a86a 100644 --- a/src/table_structs.rs +++ b/src/table_structs.rs @@ -2,10 +2,36 @@ use clap::Args; use phf::phf_map; use regex::Regex; +use serde::Deserialize; use std::fmt::Debug; use regex_static::once_cell::sync::Lazy; +#[derive(Deserialize)] +/// The Craft configs +pub(crate) struct Craft { + /// The food header string formatter + pub(crate) header_food: String, + /// The alchemy header string formatter + pub(crate) header_alchemy: String, + /// The forge header string formatter + pub(crate) header_forge: String, + /// The mtrap header string formatter + pub(crate) header_mtrap: String, + /// The weapons header string formatter + pub(crate) header_weapons: String, + /// The armors header string formatter + pub(crate) header_armors: String, + /// The gadgets header string formatter + pub(crate) header_gadgets: String, + /// The potions header string formatter + pub(crate) header_potions: String, + /// The traps header string formatter + pub(crate) header_traps: String, + /// The table end string formatter + pub(crate) end: String, +} + /// Configuration options for processing TSV files and generating LaTeX tables. #[derive(Debug, Args)] pub(crate) struct TableArgs { @@ -14,15 +40,15 @@ pub(crate) struct TableArgs { #[arg(short)] pub export: bool, - /// The kind of tables to operate on: classes, craft or a specific file - pub kind: TargetType, + /// The kind of tables to operate on: classes, craft or files followed by a list of files + pub kind: TableGenerationTarge, /// A vector of strings representing the names of TSV files to process. pub filenames: Vec, } /// An enumeration representing different target types. #[derive(Debug, Clone)] -pub enum TargetType { +pub enum TableGenerationTarge { /// Processes all classes Classes, /// Processes all the craft tables @@ -32,10 +58,10 @@ pub enum TargetType { } /// A mapping of string representations to target types. -static STR_TO_TARGET: phf::Map<&'static str, TargetType> = phf_map! { - "classes" => TargetType::Classes, - "craft" => TargetType::Craft, - "files" => TargetType::Files, +static STR_TO_TARGET: phf::Map<&'static str, TableGenerationTarge> = phf_map! { + "classes" => TableGenerationTarge::Classes, + "craft" => TableGenerationTarge::Craft, + "files" => TableGenerationTarge::Files, }; /// All the type of tsv that can be processed by the program @@ -81,7 +107,7 @@ 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_static::lazy_regex!(r"★+"); -impl From<&str> for TargetType { +impl From<&str> for TableGenerationTarge { fn from(value: &str) -> Self { if let Some(target) = STR_TO_TARGET.get(value).cloned() { target diff --git a/src/table_types.rs b/src/table_types.rs index 7457a0f..07c0acd 100644 --- a/src/table_types.rs +++ b/src/table_types.rs @@ -1,6 +1,6 @@ //! Holds all the table base structure use crate::{table_structs::TableTargets, tablegen::make_latex_string, Config}; -use anyhow::{Context, Result}; +use anyhow::Result; // use csv::StringRecord; use dynfmt::{Format, SimpleCurlyFormat}; use serde::Deserialize; @@ -43,7 +43,7 @@ impl WriteRow for RecordClass { _config: &Config, _format: &str, ) -> Result<()> { - Ok(write!( + Ok(writeln!( buffer, " {}&{}&{}&{}{}&{} \\\\", self.technique, @@ -115,33 +115,10 @@ impl WriteTable for ClassesArray { } writeln!(buffer, "{}", config.classes.end)?; } - Ok(String::from_utf8(buffer.into_inner()?).unwrap()) + Ok(String::from_utf8(buffer.into_inner()?)?) } } -/// Represents the whole Craft Array, with a vec for every tier -pub(crate) struct CraftArray -where - RecordType: WriteRow, -{ - /// Every tier held as a vec of vec of rows - pub row: Vec, -} - -impl WriteTable for CraftArray -where - RecordType: WriteRow, -{ - fn write_table(&self, config: &Config) -> Result { - let mut buffer = BufWriter::new(Vec::new()); - self.row[0].write_header(&mut buffer, config, NO_STRING)?; - for row in self.row.iter() { - row.write_row(&mut buffer, config, NO_STRING)?; - } - self.row[0].write_footer(&mut buffer, config, NO_STRING)?; - Ok(String::from_utf8(buffer.into_inner()?).unwrap()) - } -} /// Represents the whole Craft Array, with a vec for every tier pub(crate) struct GenericArray where @@ -176,7 +153,7 @@ where row.write_row(&mut buffer, config, NO_STRING)?; } self.row[0].write_footer(&mut buffer, config, NO_STRING)?; - Ok(String::from_utf8(buffer.into_inner()?).unwrap()) + Ok(String::from_utf8(buffer.into_inner()?)?) } } @@ -201,209 +178,233 @@ impl fmt::Display for CleanString { } } -#[derive(Debug, Deserialize)] -#[serde(rename_all = "PascalCase")] -/// A single row in a martial class tsv file -pub(crate) struct RecordFood { - /// The name of the ingredient used in this recipe. - pub ingredient: String, +// /// Represents the whole Craft Array, with a vec for every tier +// pub(crate) struct CraftArray +// where +// RecordType: WriteRow, +// { +// /// Every tier held as a vec of vec of rows +// pub row: Vec, +// } - /// The part of the body this food is from. - pub part: String, +// impl WriteTable for CraftArray +// where +// RecordType: WriteRow, +// { +// fn write_table(&self, config: &Config) -> Result { +// let mut buffer = BufWriter::new(Vec::new()); +// self.row[0].write_header(&mut buffer, config, NO_STRING)?; +// for row in self.row.iter() { +// row.write_row(&mut buffer, config, NO_STRING)?; +// } +// self.row[0].write_footer(&mut buffer, config, NO_STRING)?; +// Ok(String::from_utf8(buffer.into_inner()?)?) +// } +// } - /// The rarity level of this food, represented as a clean string. - pub rarity: CleanString, +// #[derive(Debug, Deserialize)] +// #[serde(rename_all = "PascalCase")] +// /// A single row in a martial class tsv file +// pub(crate) struct RecordFood { +// /// The name of the ingredient used in this recipe. +// pub ingredient: String, - /// How much this this food item will fill you. - pub filling: CleanString, +// /// The part of the body this food is from. +// pub part: String, - /// The main effect that this food has on the player's character (e.g. "healing", "buffing", etc.). - pub effect_main: CleanString, +// /// The rarity level of this food, represented as a clean string. +// pub rarity: CleanString, - /// Any secondary effects that this food may have on the player's character. - pub effect_secondary: CleanString, +// /// How much this this food item will fill you. +// pub filling: CleanString, - /// A measure of how difficult it is to prepare this food item. - pub difficulty: CleanString, +// /// The main effect that this food has on the player's character (e.g. "healing", "buffing", etc.). +// pub effect_main: CleanString, - /// The toxicity level of this food. - pub toxicity: CleanString, -} +// /// Any secondary effects that this food may have on the player's character. +// pub effect_secondary: CleanString, -impl WriteRow for RecordFood { - fn write_header( - &self, - buffer: &mut BufWriter>, - _: &Config, - format: &str, - ) -> Result<()> { - writeln!(buffer, "{}", format).context("Writing header") - } - fn write_row( - &self, - buffer: &mut BufWriter>, - _config: &Config, - _format: &str, - ) -> Result<()> { - writeln!( - buffer, - " {}&{}&{}{}&{}&{}&{}&{} \\\\", - self.ingredient, - self.part, - self.rarity, - self.filling, - self.effect_main, - self.effect_secondary, - self.difficulty, - self.toxicity, - ) - .context("Writing row") - } +// /// A measure of how difficult it is to prepare this food item. +// pub difficulty: CleanString, - fn write_footer( - &self, - buffer: &mut BufWriter>, - config: &Config, - _format: &str, - ) -> Result<()> { - writeln!(buffer, "{}", config.craft.end).context("Writing footer") - } -} +// /// The toxicity level of this food. +// pub toxicity: CleanString, +// } -#[derive(Debug, Deserialize)] -#[serde(rename_all = "PascalCase")] -/// A record of alchemy data. -pub(crate) struct RecordAlchemy { - /// The ingredients name. - pub ingredient: String, +// impl WriteRow for RecordFood { +// fn write_header( +// &self, +// buffer: &mut BufWriter>, +// _: &Config, +// format: &str, +// ) -> Result<()> { +// writeln!(buffer, "{}", format).context("Writing header") +// } +// fn write_row( +// &self, +// buffer: &mut BufWriter>, +// _config: &Config, +// _format: &str, +// ) -> Result<()> { +// writeln!( +// buffer, +// " {}&{}&{}{}&{}&{}&{}&{} \\\\", +// self.ingredient, +// self.part, +// self.rarity, +// self.filling, +// self.effect_main, +// self.effect_secondary, +// self.difficulty, +// self.toxicity, +// ) +// .context("Writing row") +// } - /// The part this ingredient came from - pub part: String, +// fn write_footer( +// &self, +// buffer: &mut BufWriter>, +// config: &Config, +// _format: &str, +// ) -> Result<()> { +// writeln!(buffer, "{}", config.craft.end).context("Writing footer") +// } +// } - /// The rarity level of this alchemy - pub rarity: CleanString, +// #[derive(Debug, Deserialize)] +// #[serde(rename_all = "PascalCase")] +// /// A record of alchemy data. +// pub(crate) struct RecordAlchemy { +// /// The ingredients name. +// pub ingredient: String, - /// A brief description of the main effect of this alchemy. - pub effect_main: CleanString, +// /// The part this ingredient came from +// pub part: String, - /// A brief description of any secondary effects of this alchemy. - pub effect_secondary: CleanString, +// /// The rarity level of this alchemy +// pub rarity: CleanString, - /// The difficulty level required to perform this alchemy - pub difficulty: CleanString, +// /// A brief description of the main effect of this alchemy. +// pub effect_main: CleanString, - /// The toxicity of this ingredient. - pub toxicity: CleanString, -} +// /// A brief description of any secondary effects of this alchemy. +// pub effect_secondary: CleanString, -impl WriteRow for RecordAlchemy { - fn write_header( - &self, - buffer: &mut BufWriter>, - config: &Config, - _format: &str, - ) -> Result<()> { - writeln!(buffer, "{}", config.craft.header_alchemy).context("Writing header") - } - fn write_row( - &self, - buffer: &mut BufWriter>, - _config: &Config, - _format: &str, - ) -> Result<()> { - writeln!( - buffer, - " {}&{}&{}{}&{}&{}&{} \\\\", - self.ingredient, - self.part, - self.rarity, - self.effect_main, - self.effect_secondary, - self.difficulty, - self.toxicity, - ) - .context("Writing row") - } +// /// The difficulty level required to perform this alchemy +// pub difficulty: CleanString, - fn write_footer( - &self, - buffer: &mut BufWriter>, - config: &Config, - _format: &str, - ) -> Result<()> { - writeln!(buffer, "{}", config.craft.end).context("Writing footer") - } -} +// /// The toxicity of this ingredient. +// pub toxicity: CleanString, +// } -#[derive(Debug, Deserialize)] -#[serde(rename_all = "PascalCase")] -/// A record of alchemy data. -pub(crate) struct RecordForge { - /// The ingredient used in this forging recipe. - pub ingredient: String, +// impl WriteRow for RecordAlchemy { +// fn write_header( +// &self, +// buffer: &mut BufWriter>, +// config: &Config, +// _format: &str, +// ) -> Result<()> { +// writeln!(buffer, "{}", config.craft.header_alchemy).context("Writing header") +// } +// fn write_row( +// &self, +// buffer: &mut BufWriter>, +// _config: &Config, +// _format: &str, +// ) -> Result<()> { +// writeln!( +// buffer, +// " {}&{}&{}{}&{}&{}&{} \\\\", +// self.ingredient, +// self.part, +// self.rarity, +// self.effect_main, +// self.effect_secondary, +// self.difficulty, +// self.toxicity, +// ) +// .context("Writing row") +// } - /// The rarity level of this forged item. - pub rarity: CleanString, +// fn write_footer( +// &self, +// buffer: &mut BufWriter>, +// config: &Config, +// _format: &str, +// ) -> Result<()> { +// writeln!(buffer, "{}", config.craft.end).context("Writing footer") +// } +// } - /// The density or weight class of the forged item. - pub density: CleanString, +// #[derive(Debug, Deserialize)] +// #[serde(rename_all = "PascalCase")] +// /// A record of alchemy data. +// pub(crate) struct RecordForge { +// /// The ingredient used in this forging recipe. +// pub ingredient: String, - /// Main effect on weapons when using this ingredient. - pub effect_weapon_main: CleanString, +// /// The rarity level of this forged item. +// pub rarity: CleanString, - /// Main effect on armor when using this ingredient. - pub effect_armor_main: CleanString, +// /// The density or weight class of the forged item. +// pub density: CleanString, - /// Secondary effects on weapons when using this ingredient. - pub effect_weapon_secondary: CleanString, +// /// Main effect on weapons when using this ingredient. +// pub effect_weapon_main: CleanString, - /// Secondary effects on armor when using this ingredient. - pub effect_armor_secondary: CleanString, +// /// Main effect on armor when using this ingredient. +// pub effect_armor_main: CleanString, - /// The difficulty level - pub difficulty: CleanString, +// /// Secondary effects on weapons when using this ingredient. +// pub effect_weapon_secondary: CleanString, - /// The difficulty processing this ingredient. - pub preparation: CleanString, -} +// /// Secondary effects on armor when using this ingredient. +// pub effect_armor_secondary: CleanString, -impl WriteRow for RecordForge { - fn write_header( - &self, - buffer: &mut BufWriter>, - config: &Config, - _format: &str, - ) -> Result<()> { - writeln!(buffer, "{}", config.craft.header_forge).context("Writing header") - } - fn write_row( - &self, - buffer: &mut BufWriter>, - _config: &Config, - _format: &str, - ) -> Result<()> { - writeln!( - buffer, - " {}&{}&{}&{}&{}{}&{}&{}&{} \\\\", - self.ingredient, - self.rarity, - self.density, - self.effect_weapon_main, - self.effect_armor_main, - self.effect_weapon_secondary, - self.effect_armor_secondary, - self.difficulty, - self.preparation, - ) - .context("Writing row") - } +// /// The difficulty level +// pub difficulty: CleanString, - fn write_footer( - &self, - buffer: &mut BufWriter>, - config: &Config, - _format: &str, - ) -> Result<()> { - writeln!(buffer, "{}", config.craft.end).context("Writing footer") - } -} +// /// The difficulty processing this ingredient. +// pub preparation: CleanString, +// } + +// impl WriteRow for RecordForge { +// fn write_header( +// &self, +// buffer: &mut BufWriter>, +// config: &Config, +// _format: &str, +// ) -> Result<()> { +// writeln!(buffer, "{}", config.craft.header_forge).context("Writing header") +// } +// fn write_row( +// &self, +// buffer: &mut BufWriter>, +// _config: &Config, +// _format: &str, +// ) -> Result<()> { +// writeln!( +// buffer, +// " {}&{}&{}&{}&{}{}&{}&{}&{} \\\\", +// self.ingredient, +// self.rarity, +// self.density, +// self.effect_weapon_main, +// self.effect_armor_main, +// self.effect_weapon_secondary, +// self.effect_armor_secondary, +// self.difficulty, +// self.preparation, +// ) +// .context("Writing row") +// } + +// fn write_footer( +// &self, +// buffer: &mut BufWriter>, +// config: &Config, +// _format: &str, +// ) -> Result<()> { +// writeln!(buffer, "{}", config.craft.end).context("Writing footer") +// } +// } diff --git a/src/tablegen.rs b/src/tablegen.rs index f6c1c63..ad3f38c 100644 --- a/src/tablegen.rs +++ b/src/tablegen.rs @@ -10,35 +10,41 @@ use std::{ path::{Path, PathBuf}, }; -use crate::table_types::{ - ClassesArray, CraftArray, GenericArray, RecordAlchemy, RecordClass, RecordFood, RecordForge, - WriteRow, WriteTable, -}; +use crate::table_types::{ClassesArray, GenericArray, RecordClass, WriteRow, WriteTable}; use crate::{ - table_structs::{TableArgs, TableTargets, TargetType, RE, STR_TO_TARGET_FULL}, + table_structs::{TableArgs, TableGenerationTarge, TableTargets, RE, STR_TO_TARGET_FULL}, Config, }; /// Generate the tables for the specified files /// /// In charge of the dispatch and the whole conversion -pub fn table_gen(args: &TableArgs, config: &Config) { +pub fn table_gen(args: &TableArgs, config: &Config) -> Result<()> { let list_files = match args.kind { - TargetType::Classes => &mut list_dir("Tables/*.csv"), - TargetType::Craft => &mut list_dir("Craft/*.csv"), + TableGenerationTarge::Classes => { + println!("Processing files in the Tables/ subdirectory"); + &mut list_dir("Tables/???-*.tsv") + } + TableGenerationTarge::Craft => { + println!("Processing files in the Craft/ subdirectory"); + &mut list_dir("Craft/???-*.tsv") + } // Add the use of glob to save the poor windows users - TargetType::Files => &mut args.filenames.iter().map(PathBuf::from).collect(), + TableGenerationTarge::Files => { + println!("Processing the files given as argument"); + &mut args.filenames.iter().map(PathBuf::from).collect() + } }; if list_files.is_empty() { println!("No files to process ... skipping"); } match args.kind { - TargetType::Classes => process_files(list_files, args, config).unwrap(), - TargetType::Craft => process_files(list_files, args, config).unwrap(), + TableGenerationTarge::Classes => process_files(list_files, args, config), + TableGenerationTarge::Craft => process_files(list_files, args, config), // For now every file is considered as a class file - TargetType::Files => process_files(list_files, args, config).unwrap(), - }; + TableGenerationTarge::Files => process_files(list_files, args, config), + } } /// Process any type of file, one by one and call the right converter function @@ -53,21 +59,16 @@ fn process_files(list_files: &mut Vec, 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 tt = extract_type(f)?; let tsv: Box = match tt { TableTargets::Classes => Box::new(read_tsv_classes(f)?), - TableTargets::Food => read_tsv::(f)?, - TableTargets::Alchemy => read_tsv::(f)?, - TableTargets::Forge => read_tsv::(f)?, - TableTargets::MPieges => read_generic_tsv(f, tt)?, - TableTargets::Weapons => read_generic_tsv(f, tt)?, - TableTargets::Armors => read_generic_tsv(f, tt)?, - TableTargets::Gadgets => todo!(), - TableTargets::Potions => todo!(), - TableTargets::Traps => todo!(), + // TableTargets::Food => read_tsv::(f)?, + // TableTargets::Alchemy => read_tsv::(f)?, + // TableTargets::Forge => read_tsv::(f)?, + _ => read_generic_tsv(f, tt)?, }; - export_tsv(f, tsv, args, config).context("Error exporting the tsv") + export_tsv(f, tsv, args, config) } #[inline] @@ -78,15 +79,24 @@ fn extract_type(f: &Path) -> Result<&TableTargets> { .context("The filename of can't be extracted...skipping")? .to_str() .context("Can't convert filename to string")?[..3]; - Ok(STR_TO_TARGET_FULL - .get(key) - .with_context(|| format!("Can't find key {} in file", key)) - .unwrap()) + STR_TO_TARGET_FULL.get(key).with_context(|| { + format!( + "Could not find the type of file given based on the prefix of your file ({})\n\ + Are you sure {:?} contains a viable identifying prefix ?\n\ + The list of available prefixes is: [{:?}]", + key, + f, + STR_TO_TARGET_FULL.keys() + ) + }) } /// List all files matching a pattern in the given directory #[inline] fn list_dir(pattern: &str) -> Vec { + // println!("{}", pattern); + // println!("{:?}", glob(pattern)); + glob(pattern) .expect("Failed to read glob pattern") .flatten() @@ -106,9 +116,13 @@ pub fn export_tsv( ) -> Result<()> { let converted = tsv_to_string(tsv, config)?; if args.export { - let path = format!("{:?}", f).replace(".tsv", ".tex"); - // let path = f.with_extension(".tex"); - println!("[Info] Writing to {}", path); + let name = &f + .file_name() + .context("Extracting old name")? + .to_str() + .context("Generating new name")?[4..]; + let path = f.with_file_name(name).with_extension("tex"); + println!("[Info] Writing to {:?}", path); let mut file = File::create(path)?; file.write_all(converted.as_bytes())?; } else { @@ -173,34 +187,6 @@ where Ok(ClassesArray { tiers: levels }) } -/// Reads a TSV file into a table. -/// -/// Reads a tab-separated values (TSV) file and deserializes its contents into a table. -fn read_tsv(filename: &Path) -> Result> -where - // TODO: Remove the static and do not return a Box - RecordType: for<'a> serde::Deserialize<'a> + WriteRow + 'static, -{ - let file = File::open(filename)?; - let mut rdr = csv::ReaderBuilder::new() - .has_headers(false) - .delimiter(b'\t') - .double_quote(false) - .escape(Some(b'\\')) - .flexible(true) - .comment(Some(b'#')) - .from_reader(file); - - let mut levels = Vec::with_capacity(30); - for result in rdr.deserialize().skip(2) { - let result: RecordType = result?; - levels.push(result); - } - - let craft_array = CraftArray { row: levels }; - Ok(Box::new(craft_array)) -} - /// Reads a TSV file into a table. /// /// Reads a tab-separated values (TSV) file and deserializes its contents into a table. @@ -247,7 +233,7 @@ impl WriteRow for StringRecord { write!( buffer, " {}", - itr.next().context("Writing firt element of row").unwrap() + itr.next().context("Writing firt element of row")? )?; for e in itr { write!(buffer, " & {}", make_latex_string(e)).context("Writing row")? @@ -271,3 +257,30 @@ impl WriteRow for StringRecord { pub(crate) fn tsv_to_string(tsv: Box, config: &Config) -> Result { tsv.write_table(config) } +// /// Reads a TSV file into a table. +// /// +// /// Reads a tab-separated values (TSV) file and deserializes its contents into a table. +// fn read_tsv(filename: &Path) -> Result> +// where +// // TODO: Remove the static and do not return a Box +// RecordType: for<'a> serde::Deserialize<'a> + WriteRow + 'static, +// { +// let file = File::open(filename)?; +// let mut rdr = csv::ReaderBuilder::new() +// .has_headers(false) +// .delimiter(b'\t') +// .double_quote(false) +// .escape(Some(b'\\')) +// .flexible(true) +// .comment(Some(b'#')) +// .from_reader(file); + +// let mut levels = Vec::with_capacity(30); +// for result in rdr.deserialize().skip(2) { +// let result: RecordType = result?; +// levels.push(result); +// } + +// let craft_array = CraftArray { row: levels }; +// Ok(Box::new(craft_array)) +// } -- 2.45.1