Adds polimorphism and half exports

Also adds a very convenient todo
This commit is contained in:
Dandaedre 2024-05-04 23:13:26 +02:00
parent d1a615a7ed
commit 61c0a344d8
3 changed files with 208 additions and 81 deletions

View File

@ -7,12 +7,14 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
anyhow = "1.0.82"
clap = { version = "4.5.4", features = ["derive"] }
csv = "1.3.0"
dynfmt = { version = "0.1.5", features = ["curly"] }
glob = "0.3.1"
phf = { version = "0.11.2", features = ["macros"] }
regex = "1.10.4"
regex_static = "0.1.1"
serde = { version = "1.0.198", features = ["derive"] }
toml = "0.8.12"

View File

@ -1,12 +1,17 @@
//! Holds all the data structures away from the main routine
use crate::{tablegen::make_latex_string, Config};
use anyhow::Result;
use clap::Args;
use dynfmt::{Format, SimpleCurlyFormat};
use phf::phf_map;
use regex::Regex;
use serde::Deserialize;
use std::fmt;
use std::fmt::Debug;
use std::{
fmt::{self, Debug, Display},
io::{BufWriter, Write},
};
use crate::tablegen::make_latex_string;
use regex_static::once_cell::sync::Lazy;
/// Configuration options for processing CSV files and generating LaTeX tables.
#[derive(Debug, Args)]
@ -40,6 +45,53 @@ static STR_TO_TARGET: phf::Map<&'static str, TargetType> = phf_map! {
"files" => TargetType::Files,
};
/// All the type of tsv that can be processed by the program
pub enum TableTargets {
/// A class tsv
Classes,
/// Foods tsv
Food,
/// Alchemy tsv
Alchemy,
/// Forge tsv
Forge,
/// MPieges tsv
MPieges,
/// Weapons tsv
Weapons,
/// Armors tsv
Armors,
/// Gadgets tsv
Gadgets,
/// Potions tsv
Potions,
/// Traps tsv
Traps,
}
/// A mapping of string names to target types.
pub(crate) static STR_TO_TARGET_FULL: phf::Map<&'static str, TableTargets> = phf_map! {
"cls" => TableTargets::Classes,
"fud" => TableTargets::Food,
"alc" => TableTargets::Alchemy,
"frg" => TableTargets::Forge,
"mpi" => TableTargets::MPieges,
"wpn" => TableTargets::Weapons,
"arm" => TableTargets::Armors,
"gdg" => TableTargets::Gadgets,
"pot" => TableTargets::Potions,
"trp" => TableTargets::Traps,
};
/// The regex for finding and replacing all stars with a custom DD
pub(crate) static RE: Lazy<Regex> = regex_static::lazy_regex!(r"★+");
// /// Type of tables that the program can handle
// pub enum TableType {
// CraftTable,
// CharacterTable,
// }
impl From<&str> for TargetType {
fn from(value: &str) -> Self {
if let Some(target) = STR_TO_TARGET.get(value).cloned() {
@ -71,6 +123,65 @@ pub struct RecordClass {
pub effet: CleanString,
}
impl Display for RecordClass {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
" {}&{}&{}&{}{}&{} \\\\",
self.technique,
self.niveau,
self.technique_type,
self.cout_blood,
self.cout_jauge,
self.effet
)
}
}
/// Represents the whole Classes Array, with a vec for every tier
pub(crate) struct ClassesArray {
/// Every tier held as a vec of vec of rows
tiers: Vec<Vec<RecordClass>>,
}
/// Trait needed to be writable as a LaTex table
pub(crate) trait WriteRows {
/// Takes a config and writes to a string the representation of the Array
fn write_rows(&self, config: &Config) -> Result<String>;
}
impl ClassesArray {
pub fn new(tiers: Vec<Vec<RecordClass>>) -> Self {
Self { tiers }
}
}
impl WriteRows for ClassesArray {
fn write_rows(&self, config: &Config) -> Result<String> {
let mut buffer = BufWriter::new(Vec::new());
for (lvl, tier) in self.tiers.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())
}
}
/// 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,16 +1,24 @@
//! The csv table generation
use anyhow::{Context, Result};
use dynfmt::{Format, SimpleCurlyFormat};
use glob::glob;
use std::fmt::Debug;
use std::fmt::Display;
use std::io::{Error, Write};
use std::path::{Path, PathBuf};
use std::{cell::RefCell, fs::File, io::BufWriter};
use regex::Captures;
use std::{
cell::RefCell,
fmt::Debug,
fs::File,
io::{BufWriter, Error, Write},
ops::ControlFlow,
path::{Path, PathBuf},
};
use crate::table_structs::RecordClass;
use crate::table_structs::TableArgs;
use crate::table_structs::TargetType;
use crate::Config;
use crate::{
table_structs::{
ClassesArray, RecordClass, TableArgs, TableTargets, TargetType, WriteRows, RE,
STR_TO_TARGET_FULL,
},
Config,
};
/// Generate the tables for the specified files
///
@ -27,27 +35,72 @@ pub fn table_gen(args: &TableArgs, config: &Config) {
println!("No files to process ... skipping");
}
match args.kind {
TargetType::Classes => process_files(list_files, args, config, convert_class_csv),
TargetType::Craft => todo!(), //process_files(list_files, args, config, convert_craft_csv::<_, _>),
TargetType::Classes => process_files(list_files, args, config).unwrap(),
TargetType::Craft => process_files(list_files, args, config).unwrap(),
// For now every file is considered as a class file
TargetType::Files => process_files(list_files, args, config, convert_class_csv),
}
TargetType::Files => process_files(list_files, args, config).unwrap(),
};
}
/// Process any type of file, one by one and call the right converter function
fn process_files<
T: for<'a, 'b, 'c> Fn(&'a PathBuf, &'b TableArgs, &'c Config) -> Result<(), Error>,
>(
list_files: &mut Vec<PathBuf>,
args: &TableArgs,
config: &Config,
converter: T,
) {
fn process_files(list_files: &mut Vec<PathBuf>, args: &TableArgs, config: &Config) -> Result<()> {
for f in list_files {
if let Err(e) = converter(f, args, config) {
println!("Error while processing {:?}: {}", f, e)
if let ControlFlow::Break(_) = TODO(f, args, config) {
continue;
}
}
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),
}
ControlFlow::Continue(())
}
#[inline]
/// Extract the type of target of the given file
fn extract_type(f: &Path) -> Result<&TableTargets> {
let key = &f
.file_name()
.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())
}
/// List all files matching a pattern in the given directory
@ -64,39 +117,12 @@ fn list_dir(pattern: &str) -> Vec<PathBuf> {
/// 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_class_csv<T>(f: &T, args: &TableArgs, config: &Config) -> Result<(), Error>
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_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(())
}
/// 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<PathType, RowType>(
f: &PathType,
args: &TableArgs,
config: &Config,
) -> Result<(), Error>
where
PathType: AsRef<Path> + Debug,
RowType: Display,
{
let csv = read_csv_craft(f)?;
let converted = csv_classes_to_string(csv, config)?;
let converted = csv_to_string(csv, config)?;
if args.export {
let path = format!("{:?}", f).replace(".tsv", ".tex");
println!("[Info] Writing to {}", path);
@ -114,14 +140,15 @@ where
/// 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_csv<T>(f: &T, args: &TableArgs, config: &Config) -> Result<(), Error>
pub fn export_csv<RowType>(f: &Path, csv: RowType, args: &TableArgs, config: &Config) -> Result<()>
where
T: AsRef<Path> + Debug,
// PathType: AsRef<Path> + Debug,
RowType: WriteRows,
{
let csv = read_csv_craft(f)?;
let converted = csv_classes_to_string(csv, config)?;
let converted = csv_to_string(csv, config)?;
if args.export {
let path = format!("{:?}", f).replace(".tsv", ".tex");
// let path = f.with_extension(".tex");
println!("[Info] Writing to {}", path);
let mut file = File::create(path)?;
file.write_all(converted.as_bytes())?;
@ -134,15 +161,11 @@ where
/// Replace all instances of unrepresentable utf8 or non escaped characters with latex ones
pub fn make_latex_string(arg: &str) -> String {
use regex::{Captures, Regex};
let re = Regex::new(r"★+").unwrap();
let temp = arg
.replace('🩸', "\\blood")
.replace('⚡', "\\gauge")
.replace('&', "\\&");
let res = re.replace_all(&temp, |caps: &Captures| {
let res = RE.replace_all(&temp, |caps: &Captures| {
format!("\\dd{{{}}}", caps[0].chars().count())
});
res.to_string()
@ -152,7 +175,7 @@ pub fn make_latex_string(arg: &str) -> String {
///
/// 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_classes<T>(filename: &T) -> Result<Vec<Vec<RecordClass>>, Error>
fn read_csv_classes<T>(filename: &T) -> Result<ClassesArray, Error>
where
T: AsRef<Path>,
{
@ -181,14 +204,14 @@ where
}
}
// println!("{:#?}", levels);
Ok(levels)
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_craft<PathType, RecordType>(filename: &PathType) -> Result<Vec<RecordType>, Error>
fn read_csv<PathType, RecordType>(filename: &PathType) -> Result<Vec<RecordType>, Error>
where
PathType: AsRef<Path>,
RecordType: for<'a> serde::Deserialize<'a>,
@ -203,7 +226,7 @@ where
.comment(Some(b'#'))
.from_reader(file);
let mut levels = Vec::with_capacity(8);
let mut levels = Vec::with_capacity(30);
for result in rdr.deserialize() {
let result: RecordType = result?;
levels.push(result);
@ -245,18 +268,9 @@ fn csv_classes_to_string(csv: Vec<Vec<RecordClass>>, config: &Config) -> Result<
///
/// 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.
pub(crate) fn csv_craft_to_string<RowType>(
csv: Vec<RowType>,
config: &Config,
) -> Result<String, Error>
pub(crate) fn csv_to_string<RowType>(csv: RowType, config: &Config) -> Result<String>
where
RowType: Display,
RowType: WriteRows,
{
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())
csv.write_rows(config)
}