diff --git a/Cargo.toml b/Cargo.toml index b2a9780..3e58724 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ cargo-features = ["codegen-backend"] [package] name = "ravenous-tools" -version = "0.1.0" +version = "0.1.3" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/helper_config.toml b/helper_config.toml index 993c2e0..852f4ee 100644 --- a/helper_config.toml +++ b/helper_config.toml @@ -9,64 +9,36 @@ row = '''{\footnotesize \hline''' end = ''' \hline - \end{tabularx} + \end{tabularx} }''' [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 = '''{\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é +header_alchemy = ''' 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 +header_armors = ''' Nom & Rareté & Dégâts & + & R.Max & Armor.B & Prot & Int. & Deux M & Une M & Esq. & Parr. & Vitesse & Discrétion & Spécial \\ + \hline''' +header_forge = ''' 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é +header_weapons = ''' Nom & \rotbx{Rareté} & \rotbx{Dégâts} & + & \rotbx{R.Max} & \rotbx{Armr.B} & \rotbx{Protbx} & \rotbx{Int.} & \rotbx{Deux M} & \rotbx{Une M} & \rotbx{Esq.} & \rotbx{Parr.} & \rotbx{Vitesse} & \rotbx{Discr.} & \rotbx{Catégorie} & \rotbx{Modes} & \rotbx{Spécial} \\ \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 +header_food = ''' Ingrédient&Partie&Rareté&Satiété&Effet (Plat)&Effets (Accompagnement)&Difficulté&Toxicité \\ \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 +header_mtrap = ''' Élément & Prix & Effet & Difficulté & Activation & Solidité \\ \hline''' +header_traps = ''' Nom & Type & Prix & Toxicité & Effet \\ + \hline''' +header_gadgets =''' Nom & Effet & Prix\\ + \hline''' +header_potions = ''' Nom & Type & Prix & Toxicité & Effet \\ + \hline''' end = ''' \hline \end{tabularx} }''' +end_long = ''' \hline + \end{longtable} +}''' +end_long_side = ''' \hline + \end{longtable} +} +\end{landscape}''' +end_empty = "" diff --git a/src/main.rs b/src/main.rs index d5af324..06d2a9a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -10,10 +10,13 @@ mod table_structs; mod table_types; mod tablegen; use crate::table_structs::TableArgs; -use std::fs; +use std::{ + fs::{self, OpenOptions}, + io::Write, +}; -use anyhow::Result; -use clap::{Parser, Subcommand}; +use anyhow::{Context, Result}; +use clap::{Args, Parser, Subcommand}; use serde::Deserialize; use table_structs::Craft; use tablegen::table_gen; @@ -22,7 +25,7 @@ use tablegen::table_gen; #[command(version, about)] #[command(propagate_version = true)] /// The list of commands to run -struct Args { +struct ParserCLIArgs { /// The subcommand to run. #[command(subcommand)] command: Commands, @@ -33,6 +36,22 @@ struct Args { enum Commands { /// Generate a table from input data using the provided arguments. Tablegen(TableArgs), + /// Show/Export config + Config(ConfigArgs), +} + +#[derive(Debug, Args)] +struct ConfigArgs { + /// Wether to write the config to file, or just show it + #[arg(short, long, default_value_t = false)] + write: bool, + /// Wether to overwrite the file if it exists + + #[arg(short, long, default_value_t = false)] + force: bool, + + /// The path to overwrite to + path: Option, } #[derive(Deserialize)] @@ -56,11 +75,38 @@ struct Classes { } fn main() -> Result<()> { - let args = Args::parse(); - let config = &fs::read_to_string("helper_config.toml") + let args = ParserCLIArgs::parse(); + let config_str = &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"); + let config: Config = toml::from_str(config_str).expect("Coudln't read the config file"); match args.command { Commands::Tablegen(args) => table_gen(&args, &config), + Commands::Config(args) => write_config(&args, &config, config_str), } } + +/// Write the config either to stdout, or to a file +fn write_config(args: &ConfigArgs, _configg: &Config, config_str: &str) -> Result<()> { + // if + // fs::write("./helper_config.toml", config_str).context("Writing config") + if args.write { + let p = match &args.path { + Some(p) => p, + None => "./helper_config.toml", + }; + let mut file = match &args.force { + true => OpenOptions::new() + .write(true) + .create(true) + .truncate(true) + .open(p), + false => OpenOptions::new().write(true).create_new(true).open(p), + } + .with_context(|| format!("Trying to write to file {}", p))?; + file.write_all(config_str.as_bytes())?; + println!("Config sucessfuly written to {}", p); + } else { + println!("{}", config_str); + } + Ok(()) +} diff --git a/src/table_structs.rs b/src/table_structs.rs index a802822..fedb357 100644 --- a/src/table_structs.rs +++ b/src/table_structs.rs @@ -7,6 +7,8 @@ use std::fmt::Debug; use regex_static::once_cell::sync::Lazy; +// This config is can contain unconstructed code for compatibility purposes +#[allow(dead_code)] #[derive(Deserialize)] /// The Craft configs pub(crate) struct Craft { @@ -30,6 +32,12 @@ pub(crate) struct Craft { pub(crate) header_traps: String, /// The table end string formatter pub(crate) end: String, + /// The long table end string formatter + pub(crate) end_long: String, + /// The long sideways table end string formatter + pub(crate) end_long_side: String, + /// The no_headers table end string formatter + pub(crate) end_empty: String, } /// Configuration options for processing TSV files and generating LaTeX tables. diff --git a/src/table_types.rs b/src/table_types.rs index 07c0acd..8d5aedf 100644 --- a/src/table_types.rs +++ b/src/table_types.rs @@ -1,6 +1,7 @@ //! Holds all the table base structure use crate::{table_structs::TableTargets, tablegen::make_latex_string, Config}; -use anyhow::Result; +use anyhow::{Context, Result}; +use csv::StringRecord; // use csv::StringRecord; use dynfmt::{Format, SimpleCurlyFormat}; use serde::Deserialize; @@ -100,6 +101,12 @@ pub(crate) trait WriteRow { ) -> Result<()>; } +/// This table stores it's row types +pub(crate) trait TypedRow { + /// Get the row type of the table + fn get_type(&self) -> &TableTargets; +} + impl WriteTable for ClassesArray { fn write_table(&self, config: &Config) -> Result { let mut buffer = BufWriter::new(Vec::new()); @@ -148,15 +155,77 @@ where TableTargets::Potions => &config.craft.header_potions, TableTargets::Traps => &config.craft.header_traps, }; + // let ln = self.row.len(); + // if ln < 2 { + // return Err(anyhow!("No entries were found in the tsv")); + // } self.row[0].write_header(&mut buffer, config, header)?; + // for row in 2..=ln - 2 { + // self.row[row].write_row(&mut buffer, config, NO_STRING)?; + // writeln!(buffer, "\\\\")?; + // } + // self.row[ln - 1].write_row(&mut buffer, config, NO_STRING)?; 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)?; + let footer = match self.get_type() { + TableTargets::Classes => unimplemented!("Classes can't be handle by generics"), + TableTargets::Gadgets | TableTargets::Potions => &config.craft.end_long, + _ => &config.craft.end_long_side, + }; + self.row[0].write_footer(&mut buffer, config, footer)?; Ok(String::from_utf8(buffer.into_inner()?)?) } } +impl TypedRow for GenericArray +where + RecordType: WriteRow, +{ + fn get_type(&self) -> &TableTargets { + &self.craft_type + } +} + +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")? + )?; + for e in itr { + write!(buffer, " & {}", make_latex_string(e)).context("Writing row")? + } + // Must switch to manual row writing to avoid empty line if tex + writeln!(buffer, "\\\\").context("Writing row") + } + + fn write_footer( + &self, + buffer: &mut std::io::BufWriter>, + _config: &Config, + format: &str, + ) -> Result<()> { + writeln!(buffer, "{}", format).context("Writing footer") + } +} + /// Empty string const NO_STRING: &String = &String::new(); @@ -177,234 +246,3 @@ impl fmt::Display for CleanString { f.write_str(&make_latex_string(&self.0)) } } - -// /// 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()?)?) -// } -// } - -// #[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, -// 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") -// } - -// 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")] -// /// 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, -// _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") -// } - -// 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")] -// /// 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, -// _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 2703ce2..d5790d1 100644 --- a/src/tablegen.rs +++ b/src/tablegen.rs @@ -1,6 +1,5 @@ //! The tsv table generation use anyhow::{Context, Result}; -use csv::StringRecord; use glob::glob; use regex::Captures; use std::{ @@ -10,7 +9,7 @@ use std::{ path::{Path, PathBuf}, }; -use crate::table_types::{ClassesArray, GenericArray, RecordClass, WriteRow, WriteTable}; +use crate::table_types::{ClassesArray, GenericArray, RecordClass, WriteTable}; use crate::{ table_structs::{TableArgs, TableGenerationTarget, TableTargets, RE, STR_TO_TARGET_FULL}, Config, @@ -145,9 +144,9 @@ pub fn make_latex_string(arg: &str) -> String { let temp = arg .replace('🩸', "\\blood") .replace('⚡', "\\gauge") - .replace('☽', "\\tranchant") - .replace('◅', "\\percant") - .replace('⧆', "\\contondant") + .replace('☽', "\\slash") + .replace('◅', "\\pierce") + .replace('⧆', "\\blunt") .replace('Ø', "\\o{}") .replace('⌭', "\\torque") .replace('☆', "\\ddzero") @@ -218,46 +217,10 @@ fn read_generic_tsv(filename: &Path, craft_type: &TableTargets) -> Result>, - _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")? - )?; - 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,