WIP on generalisation

This commit is contained in:
Dandaedre 2024-05-04 17:02:30 +02:00
parent 0f97616dfd
commit 1e56dc9e5e
2 changed files with 116 additions and 5 deletions

View File

@ -12,3 +12,19 @@ end = '''
\end{tabularx}
}
'''
[alchimie]
[armes]
[armures]
[forge]
[fud]
[gadgets]
[mpieges]
[potions]

View File

@ -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<PathBuf>, 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<PathBuf>, 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<PathBuf>,
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<PathBuf> {
@ -104,6 +132,7 @@ fn list_dir(pattern: &str) -> Vec<PathBuf> {
.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<T>(f: &T, args: &TableArgs, config: &Config) -> Result<(), Error>
where
T: AsRef<Path> + 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<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(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<Vec<RecordClass>>, 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<RowType>(csv: Vec<RowType>, config: &Config) -> Result<String, Error>
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())
}