ravenous-tools/tablegen/src/tablegen.rs

292 lines
11 KiB
Rust

// Workspace: tablegen
// File: tablegen/src/tablegen.rs
//! The tsv table generation module contains functionalities to read, convert and export TSV files.
//!
//! This module provides functionality for reading a tab-separated values (TSV) file into a table structure,
//! converting the table data into LaTeX code, and exporting the resulting code as a string or writing it to a file.
//!
//! # Usage
//!
//! The `table_gen` function is the main entry point of this module. It takes in configuration arguments and a
//! config object, then processes the specified files according to their type (classes, craft, etc.). If an error occurs during processing,
//! it will be reported via a Result. For more information on each function's usage, see the respective sections below.
//!
//! # Functions
//!
//! - [`table_gen`]: Generates the tables for the specified files.
//! - [`process_files`]: Processes any type of file, one by one and calls the right converter function.
//! - [`export_tsv`]: Converts a TSV file to LaTeX code.
//! - [`make_latex_string`]: Replaces all instances of unrepresentable utf8 or non escaped characters with latex ones.
//! - [`read_tsv_classes`]: Reads a TSV file into a table for classes.
//! - [`read_generic_tsv`]: Reads a TSV file into a table for generic types.
//! - [`tsv_to_string`]: Converts a table of data into a string representation.
//!
//! # Submodules
//!
//! This module consists of several submodules:
//! - `table_structs`: Defines the structure and behavior of tables.
//! - `table_types`: Contains types related to TSV files and LaTeX code generation.
use anyhow::{Context, Result};
use config::tablegen::{TableArgs, TableGenerationTarget};
use glob::glob;
use regex::Captures;
use std::{
cell::RefCell,
fs::File,
io::{Error, Write},
path::{Path, PathBuf},
};
use crate::{
Config,
table_structs::{RE_MATHS, RE_PLUS_STARS, RE_STARS, STR_TO_TARGET_FULL, TableTargets},
table_types::{ClassesArray, GenericArray, RecordClass, WriteTable},
};
/// Generate the tables for the specified files
///
/// In charge of the dispatch and the whole conversion
pub fn table_gen(args: &TableArgs, config: &Config) -> Result<()> {
let list_files = match args.kind {
TableGenerationTarget::Classes => {
println!("Processing files in the Tables/ subdirectory");
&mut list_dir("Tables/??? - *.tsv")
}
TableGenerationTarget::Craft => {
println!("Processing files in the Craft/ subdirectory");
&mut list_dir("Craft/??? - *.tsv")
}
// Add the use of glob to save the poor windows users
TableGenerationTarget::Files => {
println!("Processing the files given as argument");
&mut args.filenames.iter().map(PathBuf::from).collect()
}
TableGenerationTarget::All => &mut {
println!("Processing files in the Tables and Craft subdirectory");
let mut targets = list_dir("Tables/??? - *.tsv");
targets.append(&mut list_dir("Craft/??? - *.tsv"));
targets
},
};
if list_files.is_empty() {
println!("No files to process ... skipping");
}
// match args.kind {
// TableGenerationTarget::Classes => process_files(list_files, args, config),
// TableGenerationTarget::Craft => process_files(list_files, args, config),
// // For now every file is considered as a class file
// TableGenerationTarget::Files => process_files(list_files, args, config),
// TableGenerationTarget::All =>process_files(list_files, args, config),
// }
process_files(list_files, args, 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 Err(e) = process_one_file(f, args, config) {
println!("An error occured while processing the file {:?}\n{}", f, e)
}
}
Ok(())
}
/// Process one file
fn process_one_file(f: &mut PathBuf, args: &TableArgs, config: &Config) -> Result<()> {
let tt = extract_type(f)?;
let tsv: Box<dyn WriteTable> = match tt {
TableTargets::Classes => Box::new(read_tsv_classes(f)?),
// TableTargets::Food => read_tsv::<RecordFood>(f)?,
// TableTargets::Alchemy => read_tsv::<RecordAlchemy>(f)?,
// TableTargets::Forge => read_tsv::<RecordForge>(f)?,
_ => read_generic_tsv(f, tt)?,
};
export_tsv(f, tsv, args, config)
}
#[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")?[7..10];
STR_TO_TARGET_FULL.get(key).with_context(|| {
format!(
"Could not find the type of file given based on the prefix of your file ({})\n\
Are you sure {:?} contains a viable identifying prefix ?\n\
The list of available prefixes is: [{:?}]",
key,
f,
STR_TO_TARGET_FULL.keys()
)
})
}
/// List all files matching a pattern in the given directory
#[inline]
fn list_dir(pattern: &str) -> Vec<PathBuf> {
// println!("{}", pattern);
// println!("{:?}", glob(pattern));
glob(pattern)
.expect("Failed to read glob pattern")
.flatten()
.collect()
}
/// Converts a TSV file to LaTeX code.
///
/// This function reads in a TSV 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_tsv(
f: &Path,
tsv: Box<dyn WriteTable>,
args: &TableArgs,
config: &Config,
) -> Result<()> {
let converted = tsv_to_string(tsv, config)?;
if args.export {
let name = &f
.file_name()
.context("Extracting old name")?
.to_str()
.context("Generating new name")?[12..];
let name = format!("gen-{}", name);
let path = f.with_file_name(name).with_extension("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(())
}
/// Replace all instances of unrepresentable utf8 or non escaped characters with latex ones
pub(super) fn make_latex_string(arg: &str) -> String {
let res = arg
.replace('🩸', "\\blood{}")
.replace('⚡', "\\gauge{}")
.replace('☽', "\\slash{}")
.replace('◅', "\\pierce{}")
.replace('⧆', "\\blunt{}")
.replace('Ø', "\\o{}")
.replace('⌭', "\\torque{}")
.replace('☆', "\\ddzero{}")
.replace('🗘', "\\reload{}")
.replace('½', "\\sfrac{1}{2}")
.replace("0.5", "\\sfrac{1}{2}")
.replace('&', "\\&");
let res = RE_PLUS_STARS.replace_all(&res, |caps: &Captures| {
format!("\\ddmod{{{}}}{{{}}}", &caps[1], caps[2].chars().count())
});
let res = RE_STARS.replace_all(&res, |caps: &Captures| {
format!("\\ddlvl{{{}}}", caps[0].chars().count())
});
let res = RE_MATHS.replace_all(&res, |caps: &Captures| format!("${}$", &caps[0]));
res.to_string()
}
/// Reads a TSV file into a table.
///
/// This function reads in a tab-separated values (TSV) 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_tsv_classes<T>(filename: &T) -> Result<ClassesArray, Error>
where
T: AsRef<Path>,
{
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);
let current_tier = RefCell::new(Vec::with_capacity(6));
for result in rdr.deserialize() {
let result: RecordClass = result?;
if result.technique.starts_with("Tier ") {
// Getto way of knowing we have a new tier
let old_tier = current_tier.replace(Vec::with_capacity(8));
levels.push(old_tier);
} else if (result.technique == "Technique") | result.technique.is_empty() {
// Skip this entry
} else {
current_tier.borrow_mut().push(result);
}
}
Ok(ClassesArray { tiers: levels })
}
/// Reads a TSV file into a table.
///
/// Reads a tab-separated values (TSV) file and deserializes its contents into a table.
fn read_generic_tsv(filename: &Path, craft_type: &TableTargets) -> Result<Box<dyn WriteTable>> {
let file = File::open(filename)?;
let 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 res = rdr
.into_records()
.map(|r| r.context("reading row").unwrap())
.collect();
let craft_array = GenericArray {
row: res,
craft_type: craft_type.clone(),
};
let generic_array = Box::new(craft_array);
Ok(generic_array)
}
/// 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.
pub(super) fn tsv_to_string(tsv: Box<dyn WriteTable>, config: &Config) -> Result<String> {
tsv.write_table(config)
}
// /// Reads a TSV file into a table.
// ///
// /// Reads a tab-separated values (TSV) file and deserializes its contents into a table.
// fn read_tsv<RecordType>(filename: &Path) -> Result<Box<dyn WriteTable>>
// where
// // TODO: Remove the static and do not return a Box
// RecordType: for<'a> serde::Deserialize<'a> + WriteRow + 'static,
// {
// 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().skip(2) {
// let result: RecordType = result?;
// levels.push(result);
// }
// let craft_array = CraftArray { row: levels };
// Ok(Box::new(craft_array))
// }