Corrects exporting errors and removes legacy functions

This commit is contained in:
Dandaedre 2024-05-05 02:24:18 +02:00
parent 61c0a344d8
commit b769294c06
3 changed files with 62 additions and 130 deletions

View File

@ -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]

View File

@ -151,6 +151,7 @@ pub(crate) trait WriteRows {
}
impl ClassesArray {
/// Create a new ClassesArray from the tier list
pub fn new(tiers: Vec<Vec<RecordClass>>) -> 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);

View File

@ -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<PathBuf>, 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::<ClassesArray>(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::<ClassesArray>(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<PathBuf> {
.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<T>(f: &T, args: &TableArgs, config: &Config) -> Result<()>
where
T: AsRef<Path> + 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<PathType, RecordType>(filename: &PathType) -> Result<Vec<RecordType>, Error>
where
PathType: AsRef<Path>,
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<PathType, RecordType>(filename: &PathType) -> Result<Vec<RecordType>, Error>
// where
// PathType: AsRef<Path>,
// 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<Vec<RecordClass>>, config: &Config) -> Result<String, Error> {
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.
///