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)) +// }