Refactors into two files
This commit is contained in:
parent
1e56dc9e5e
commit
d1a615a7ed
|
|
@ -5,12 +5,14 @@
|
|||
|
||||
#![warn(missing_docs)]
|
||||
#![warn(clippy::missing_docs_in_private_items)]
|
||||
mod table_structs;
|
||||
mod tablegen;
|
||||
use crate::table_structs::TableArgs;
|
||||
use std::fs;
|
||||
|
||||
use clap::{Parser, Subcommand};
|
||||
use serde::Deserialize;
|
||||
use tablegen::{table_gen, TableArgs};
|
||||
use tablegen::table_gen;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(version, about)]
|
||||
|
|
|
|||
|
|
@ -0,0 +1,90 @@
|
|||
//! Holds all the data structures away from the main routine
|
||||
|
||||
use clap::Args;
|
||||
use phf::phf_map;
|
||||
use serde::Deserialize;
|
||||
use std::fmt;
|
||||
use std::fmt::Debug;
|
||||
|
||||
use crate::tablegen::make_latex_string;
|
||||
|
||||
/// Configuration options for processing CSV files and generating LaTeX tables.
|
||||
#[derive(Debug, Args)]
|
||||
pub(crate) struct TableArgs {
|
||||
/// A boolean indicating whether to generate LaTeX code and write it to an output file
|
||||
/// (if true) or just print the generated code to stdout
|
||||
#[arg(short)]
|
||||
pub export: bool,
|
||||
|
||||
/// The kind of tables to operate on: classes, craft or a specific file
|
||||
pub kind: TargetType,
|
||||
/// A vector of strings representing the names of CSV files to process.
|
||||
pub filenames: Vec<String>,
|
||||
}
|
||||
|
||||
/// An enumeration representing different target types.
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum TargetType {
|
||||
/// Processes all classes
|
||||
Classes,
|
||||
/// Processes all the craft tables
|
||||
Craft,
|
||||
/// Processes only the given files
|
||||
Files,
|
||||
}
|
||||
|
||||
/// A mapping of string representations to target types.
|
||||
static STR_TO_TARGET: phf::Map<&'static str, TargetType> = phf_map! {
|
||||
"classes" => TargetType::Classes,
|
||||
"craft" => TargetType::Craft,
|
||||
"files" => TargetType::Files,
|
||||
};
|
||||
|
||||
impl From<&str> for TargetType {
|
||||
fn from(value: &str) -> Self {
|
||||
if let Some(target) = STR_TO_TARGET.get(value).cloned() {
|
||||
target
|
||||
} else {
|
||||
panic!(
|
||||
"Only the following target can be used: {:?}",
|
||||
STR_TO_TARGET.keys()
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "PascalCase")]
|
||||
/// A single row in a martial class csv file
|
||||
pub struct RecordClass {
|
||||
/// The name of a technique.
|
||||
pub technique: String,
|
||||
/// The level or rank of a technique
|
||||
pub niveau: String,
|
||||
/// The type of technique, such as Actif or Exclusif.
|
||||
pub technique_type: String,
|
||||
/// The blood cost for this technique.
|
||||
pub cout_blood: CleanString,
|
||||
/// The gauge cost for this technique.
|
||||
pub cout_jauge: CleanString,
|
||||
/// A brief description of the effect or outcome of using this technique.
|
||||
pub effet: CleanString,
|
||||
}
|
||||
|
||||
/// 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);
|
||||
|
||||
impl fmt::Debug for CleanString {
|
||||
#[inline]
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
<String as fmt::Debug>::fmt(&self.0, f)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for CleanString {
|
||||
#[inline]
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
f.write_str(&make_latex_string(&self.0))
|
||||
}
|
||||
}
|
||||
161
src/tablegen.rs
161
src/tablegen.rs
|
|
@ -1,84 +1,25 @@
|
|||
//! The csv table generation
|
||||
use clap::Args;
|
||||
use dynfmt::{Format, SimpleCurlyFormat};
|
||||
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};
|
||||
use std::{cell::RefCell, fs::File, io::BufWriter};
|
||||
|
||||
use crate::table_structs::RecordClass;
|
||||
use crate::table_structs::TableArgs;
|
||||
use crate::table_structs::TargetType;
|
||||
use crate::Config;
|
||||
|
||||
/// Configuration options for processing CSV files and generating LaTeX tables.
|
||||
#[derive(Debug, Args)]
|
||||
pub struct TableArgs {
|
||||
/// A boolean indicating whether to generate LaTeX code and write it to an output file
|
||||
/// (if true) or just print the generated code to stdout
|
||||
#[arg(short)]
|
||||
export: bool,
|
||||
|
||||
/// The kind of tables to operate on: classes, craft or a specific file
|
||||
kind: TargetType,
|
||||
/// A vector of strings representing the names of CSV files to process.
|
||||
filenames: Vec<String>,
|
||||
}
|
||||
|
||||
/// An enumeration representing different target types.
|
||||
#[derive(Debug, Clone)]
|
||||
enum TargetType {
|
||||
/// Processes all classes
|
||||
Classes,
|
||||
/// Processes all the craft tables
|
||||
Craft,
|
||||
/// Processes only the given files
|
||||
Files,
|
||||
}
|
||||
|
||||
/// A mapping of string representations to target types.
|
||||
static STR_TO_TARGET: phf::Map<&'static str, TargetType> = phf_map! {
|
||||
"classes" => TargetType::Classes,
|
||||
"craft" => TargetType::Craft,
|
||||
"files" => TargetType::Files,
|
||||
};
|
||||
|
||||
impl From<&str> for TargetType {
|
||||
fn from(value: &str) -> Self {
|
||||
if let Some(target) = STR_TO_TARGET.get(value).cloned() {
|
||||
target
|
||||
} else {
|
||||
panic!(
|
||||
"Only the following target can be used: {:?}",
|
||||
STR_TO_TARGET.keys()
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "PascalCase")]
|
||||
/// A single row in a martial class csv file
|
||||
struct RecordClass {
|
||||
/// The name of a technique.
|
||||
technique: String,
|
||||
/// The level or rank of a technique
|
||||
niveau: String,
|
||||
/// The type of technique, such as Actif or Exclusif.
|
||||
technique_type: String,
|
||||
/// The blood cost for this technique.
|
||||
cout_blood: CleanString,
|
||||
/// The gauge cost for this technique.
|
||||
cout_jauge: CleanString,
|
||||
/// A brief description of the effect or outcome of using this technique.
|
||||
effet: CleanString,
|
||||
}
|
||||
|
||||
/// Generate the tables for the specified files
|
||||
///
|
||||
/// In charge of the dispatch and the whole conversion
|
||||
pub fn table_gen(args: &TableArgs, config: &Config) {
|
||||
let list_files = match args.kind {
|
||||
TargetType::Classes => &mut list_dir("Tables/*.csv"),
|
||||
TargetType::Craft => &mut list_dir("Craft/*.csv"),
|
||||
// Add the use of glob to save the poor windows users
|
||||
TargetType::Files => &mut args.filenames.iter().map(PathBuf::from).collect(),
|
||||
};
|
||||
|
||||
|
|
@ -86,37 +27,21 @@ pub fn table_gen(args: &TableArgs, config: &Config) {
|
|||
println!("No files to process ... skipping");
|
||||
}
|
||||
match args.kind {
|
||||
TargetType::Classes => process_class_files(list_files, args, config),
|
||||
TargetType::Craft => process_craft_files(list_files, args, config),
|
||||
TargetType::Classes => process_files(list_files, args, config, convert_class_csv),
|
||||
TargetType::Craft => todo!(), //process_files(list_files, args, config, convert_craft_csv::<_, _>),
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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)
|
||||
}
|
||||
TargetType::Files => process_files(list_files, args, config, convert_class_csv),
|
||||
}
|
||||
}
|
||||
|
||||
/// Process any type of file, one by one and call the right converter function
|
||||
fn process_files(
|
||||
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: &mut dyn FnMut(&mut PathBuf, &TableArgs, &Config) -> Result<(), Error>,
|
||||
converter: T,
|
||||
) {
|
||||
for f in list_files {
|
||||
if let Err(e) = converter(f, args, config) {
|
||||
|
|
@ -124,6 +49,7 @@ fn process_files(
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// List all files matching a pattern in the given directory
|
||||
#[inline]
|
||||
fn list_dir(pattern: &str) -> Vec<PathBuf> {
|
||||
|
|
@ -160,7 +86,35 @@ 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_craft_csv<T>(f: &T, args: &TableArgs, config: &Config) -> Result<(), Error>
|
||||
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)?;
|
||||
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_csv<T>(f: &T, args: &TableArgs, config: &Config) -> Result<(), Error>
|
||||
where
|
||||
T: AsRef<Path> + Debug,
|
||||
{
|
||||
|
|
@ -178,26 +132,8 @@ where
|
|||
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)]
|
||||
struct CleanString(String);
|
||||
|
||||
impl fmt::Debug for CleanString {
|
||||
#[inline]
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
<String as fmt::Debug>::fmt(&self.0, f)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for CleanString {
|
||||
#[inline]
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
f.write_str(&make_latex_string(&self.0))
|
||||
}
|
||||
}
|
||||
|
||||
/// Replace all instances of unrepresentable utf8 or non escaped characters with latex ones
|
||||
fn make_latex_string(arg: &str) -> String {
|
||||
pub fn make_latex_string(arg: &str) -> String {
|
||||
use regex::{Captures, Regex};
|
||||
|
||||
let re = Regex::new(r"★+").unwrap();
|
||||
|
|
@ -309,7 +245,10 @@ 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.
|
||||
fn csv_craft_to_string<RowType>(csv: Vec<RowType>, config: &Config) -> Result<String, Error>
|
||||
pub(crate) fn csv_craft_to_string<RowType>(
|
||||
csv: Vec<RowType>,
|
||||
config: &Config,
|
||||
) -> Result<String, Error>
|
||||
where
|
||||
RowType: Display,
|
||||
{
|
||||
|
|
|
|||
Loading…
Reference in New Issue