From b769294c06ec69fec1e7124fea437fd5e5a70e5c Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 5 May 2024 02:24:18 +0200 Subject: [PATCH] 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. ///