Merge pull request 'enum_dispatch' (#2) from enum_dispatch into main
Reviewed-on: Dandaedre/ravenous-tools#2
This commit is contained in:
commit
dc84016969
|
|
@ -7,10 +7,17 @@ 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"] }
|
||||
enum_dispatch = "0.3.13"
|
||||
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"
|
||||
|
||||
[profile.dev]
|
||||
debug = 0
|
||||
|
|
|
|||
|
|
@ -0,0 +1,72 @@
|
|||
[classes]
|
||||
header = '\subsubsection{Tier {}}'
|
||||
|
||||
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'''
|
||||
|
||||
end = ''' \hline
|
||||
\end{tabularx}
|
||||
}'''
|
||||
|
||||
[craft]
|
||||
header_food = '''{\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
|
||||
Ingrédient&Partie&Rareté&Satiété&Effet (Plat)&Effets (Accompagnement)&Difficulté&Toxicité \\
|
||||
\hline'''
|
||||
header_alchemy = '''{\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
|
||||
Ingrédient & Partie & Rareté & Effet (Principal) & Effets (Catalysé) & Difficulté & Toxicité
|
||||
\hline'''
|
||||
header_forge = '''{\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
|
||||
Ingrédient & Rareté & Densité & Effet Armes (Principal) & Effet Armures (Principal) & Effets Armes (Catalysé) & Effet Armures (C) & Difficulté & Préparation
|
||||
\hline'''
|
||||
header_mtrap ='''{\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
|
||||
Élément & Prix & Effet & Difficulté & Activation & Solidité
|
||||
\hline'''
|
||||
header_weapons = '''{\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
|
||||
Nom & Rareté & Dégâts & + & R.Max & Armor.B & Prot & Int. & Deux M & Une M & Esq. & Parr. & Vitesse & Discrétion & Catégorie & Modes & Spécial
|
||||
\hline'''
|
||||
header_armors ='''{\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
|
||||
Nom & Rareté & Dégâts & + & R.Max & Armor.B & Prot & Int. & Deux M & Une M & Esq. & Parr. & Vitesse & Discrétion & Spécial
|
||||
\hline'''
|
||||
header_gadgets ='''{\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
|
||||
Nom & Effet & Prix
|
||||
\hline'''
|
||||
header_potions = '''{\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
|
||||
Nom & Type & Prix & Toxicité & Effet
|
||||
\hline'''
|
||||
header_traps = '''{\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
|
||||
Nom & Type & Prix & Toxicité & Effet
|
||||
\hline'''
|
||||
end = ''' \hline
|
||||
\end{tabularx}
|
||||
}'''
|
||||
53
src/main.rs
53
src/main.rs
|
|
@ -1,23 +1,66 @@
|
|||
//! The `ravenous-tool` command-line tool.
|
||||
//!
|
||||
//! This program is meant as a helper for the ravenous project.
|
||||
//!
|
||||
|
||||
// #![allow(dead_code)]
|
||||
#![warn(missing_docs)]
|
||||
#![warn(clippy::missing_docs_in_private_items)]
|
||||
mod table_structs;
|
||||
mod table_types;
|
||||
mod tablegen;
|
||||
use crate::table_structs::TableArgs;
|
||||
use std::fs;
|
||||
|
||||
use anyhow::Result;
|
||||
use clap::{Parser, Subcommand};
|
||||
use tablegen::{table_gen, TableArgs};
|
||||
use serde::Deserialize;
|
||||
use table_structs::Craft;
|
||||
use tablegen::table_gen;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(version, about)]
|
||||
#[command(propagate_version = true)]
|
||||
struct Arguments {
|
||||
/// The list of commands to run
|
||||
struct Args {
|
||||
/// The subcommand to run.
|
||||
#[command(subcommand)]
|
||||
command: Commands,
|
||||
}
|
||||
|
||||
#[derive(Subcommand, Debug)]
|
||||
/// Enum representing the available commands.
|
||||
enum Commands {
|
||||
/// Generate a table from input data using the provided arguments.
|
||||
Tablegen(TableArgs),
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let args = Arguments::parse();
|
||||
#[derive(Deserialize)]
|
||||
/// The config struct, holding all runtime information
|
||||
struct Config {
|
||||
/// Config specific for the classes table generation
|
||||
classes: Classes,
|
||||
/// Config for all the tables
|
||||
craft: Craft,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
/// The classes config
|
||||
struct Classes {
|
||||
/// The header string formatter
|
||||
header: String,
|
||||
/// The row string formatter
|
||||
row: String,
|
||||
/// The table end string formatter
|
||||
end: String,
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let args = Args::parse();
|
||||
let config = &fs::read_to_string("helper_config.toml")
|
||||
.unwrap_or(include_str!("../helper_config.toml").to_string());
|
||||
let config: Config = toml::from_str(config).expect("Coudln't read the config file");
|
||||
match args.command {
|
||||
Commands::Tablegen(args) => table_gen(&args),
|
||||
Commands::Tablegen(args) => table_gen(&args, &config),
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,121 @@
|
|||
//! Holds all the data structures away from the main routine
|
||||
use clap::Args;
|
||||
use phf::phf_map;
|
||||
use regex::Regex;
|
||||
use serde::Deserialize;
|
||||
use std::fmt::Debug;
|
||||
|
||||
use regex_static::once_cell::sync::Lazy;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
/// The Craft configs
|
||||
pub(crate) struct Craft {
|
||||
/// The food header string formatter
|
||||
pub(crate) header_food: String,
|
||||
/// The alchemy header string formatter
|
||||
pub(crate) header_alchemy: String,
|
||||
/// The forge header string formatter
|
||||
pub(crate) header_forge: String,
|
||||
/// The mtrap header string formatter
|
||||
pub(crate) header_mtrap: String,
|
||||
/// The weapons header string formatter
|
||||
pub(crate) header_weapons: String,
|
||||
/// The armors header string formatter
|
||||
pub(crate) header_armors: String,
|
||||
/// The gadgets header string formatter
|
||||
pub(crate) header_gadgets: String,
|
||||
/// The potions header string formatter
|
||||
pub(crate) header_potions: String,
|
||||
/// The traps header string formatter
|
||||
pub(crate) header_traps: String,
|
||||
/// The table end string formatter
|
||||
pub(crate) end: String,
|
||||
}
|
||||
|
||||
/// Configuration options for processing TSV 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 files followed by a list of files
|
||||
pub kind: TableGenerationTarge,
|
||||
/// A vector of strings representing the names of TSV files to process.
|
||||
pub filenames: Vec<String>,
|
||||
}
|
||||
|
||||
/// An enumeration representing different target types.
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum TableGenerationTarge {
|
||||
/// 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, TableGenerationTarge> = phf_map! {
|
||||
"classes" => TableGenerationTarge::Classes,
|
||||
"craft" => TableGenerationTarge::Craft,
|
||||
"files" => TableGenerationTarge::Files,
|
||||
};
|
||||
|
||||
/// All the type of tsv that can be processed by the program
|
||||
// #[enum_dispatch]
|
||||
#[derive(Clone)]
|
||||
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"★+");
|
||||
|
||||
impl From<&str> for TableGenerationTarge {
|
||||
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()
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,410 @@
|
|||
//! Holds all the table base structure
|
||||
use crate::{table_structs::TableTargets, tablegen::make_latex_string, Config};
|
||||
use anyhow::Result;
|
||||
// use csv::StringRecord;
|
||||
use dynfmt::{Format, SimpleCurlyFormat};
|
||||
use serde::Deserialize;
|
||||
use std::{
|
||||
fmt::{self, Debug},
|
||||
io::{BufWriter, Write},
|
||||
};
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "PascalCase")]
|
||||
/// A single row in a martial class tsv file
|
||||
pub(crate) 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,
|
||||
}
|
||||
|
||||
impl WriteRow for RecordClass {
|
||||
fn write_header(
|
||||
&self,
|
||||
_buffer: &mut BufWriter<Vec<u8>>,
|
||||
_config: &Config,
|
||||
_format: &str,
|
||||
) -> Result<()> {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
fn write_row(
|
||||
&self,
|
||||
buffer: &mut BufWriter<Vec<u8>>,
|
||||
_config: &Config,
|
||||
_format: &str,
|
||||
) -> Result<()> {
|
||||
Ok(writeln!(
|
||||
buffer,
|
||||
" {}&{}&{}&{}{}&{} \\\\",
|
||||
self.technique,
|
||||
self.niveau,
|
||||
self.technique_type,
|
||||
self.cout_blood,
|
||||
self.cout_jauge,
|
||||
self.effet
|
||||
)?)
|
||||
}
|
||||
|
||||
fn write_footer(
|
||||
&self,
|
||||
_buffer: &mut BufWriter<Vec<u8>>,
|
||||
_config: &Config,
|
||||
_format: &str,
|
||||
) -> Result<()> {
|
||||
unimplemented!()
|
||||
}
|
||||
}
|
||||
/// 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
|
||||
pub tiers: Vec<Vec<RecordClass>>,
|
||||
}
|
||||
|
||||
/// Trait needed to be writable as a LaTex table
|
||||
pub(crate) trait WriteTable {
|
||||
/// Takes a config and writes to a string the representation of the Array
|
||||
fn write_table(&self, config: &Config) -> Result<String>;
|
||||
}
|
||||
/// Trait needed to be writable as a LaTex table
|
||||
pub(crate) trait WriteRow {
|
||||
/// Write the header of the LaTex table
|
||||
fn write_header(
|
||||
&self,
|
||||
buffer: &mut BufWriter<Vec<u8>>,
|
||||
config: &Config,
|
||||
format: &str,
|
||||
) -> Result<()>;
|
||||
/// Write the row of the LaTex table
|
||||
fn write_row(
|
||||
&self,
|
||||
buffer: &mut BufWriter<Vec<u8>>,
|
||||
config: &Config,
|
||||
format: &str,
|
||||
) -> Result<()>;
|
||||
/// Write the row of the LaTex table
|
||||
fn write_footer(
|
||||
&self,
|
||||
buffer: &mut BufWriter<Vec<u8>>,
|
||||
config: &Config,
|
||||
format: &str,
|
||||
) -> Result<()>;
|
||||
}
|
||||
|
||||
impl WriteTable for ClassesArray {
|
||||
fn write_table(&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");
|
||||
writeln!(buffer, "{}", formatted_header)?;
|
||||
writeln!(buffer, "{}", config.classes.row)?;
|
||||
for elem in tier {
|
||||
elem.write_row(&mut buffer, config, NO_STRING)?
|
||||
}
|
||||
writeln!(buffer, "{}", config.classes.end)?;
|
||||
}
|
||||
Ok(String::from_utf8(buffer.into_inner()?)?)
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents the whole Craft Array, with a vec for every tier
|
||||
pub(crate) struct GenericArray<RecordType>
|
||||
where
|
||||
RecordType: WriteRow,
|
||||
{
|
||||
/// Every tier held as a vec of vec of rows
|
||||
pub row: Vec<RecordType>,
|
||||
/// Inner craft type, since the array is genric
|
||||
pub craft_type: TableTargets,
|
||||
}
|
||||
|
||||
impl<RecordType> WriteTable for GenericArray<RecordType>
|
||||
where
|
||||
RecordType: WriteRow,
|
||||
{
|
||||
fn write_table(&self, config: &Config) -> Result<String> {
|
||||
let mut buffer = BufWriter::new(Vec::new());
|
||||
let header = match self.craft_type {
|
||||
TableTargets::Classes => unimplemented!(),
|
||||
TableTargets::Food => &config.craft.header_food,
|
||||
TableTargets::Alchemy => &config.craft.header_alchemy,
|
||||
TableTargets::Forge => &config.craft.header_forge,
|
||||
TableTargets::MPieges => &config.craft.header_mtrap,
|
||||
TableTargets::Weapons => &config.craft.header_weapons,
|
||||
TableTargets::Armors => &config.craft.header_armors,
|
||||
TableTargets::Gadgets => &config.craft.header_gadgets,
|
||||
TableTargets::Potions => &config.craft.header_potions,
|
||||
TableTargets::Traps => &config.craft.header_traps,
|
||||
};
|
||||
self.row[0].write_header(&mut buffer, config, header)?;
|
||||
for row in self.row.iter().skip(2) {
|
||||
row.write_row(&mut buffer, config, NO_STRING)?;
|
||||
}
|
||||
self.row[0].write_footer(&mut buffer, config, NO_STRING)?;
|
||||
Ok(String::from_utf8(buffer.into_inner()?)?)
|
||||
}
|
||||
}
|
||||
|
||||
/// Empty string
|
||||
const NO_STRING: &String = &String::new();
|
||||
|
||||
/// 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(crate) 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))
|
||||
}
|
||||
}
|
||||
|
||||
// /// Represents the whole Craft Array, with a vec for every tier
|
||||
// pub(crate) struct CraftArray<RecordType>
|
||||
// where
|
||||
// RecordType: WriteRow,
|
||||
// {
|
||||
// /// Every tier held as a vec of vec of rows
|
||||
// pub row: Vec<RecordType>,
|
||||
// }
|
||||
|
||||
// impl<RecordType> WriteTable for CraftArray<RecordType>
|
||||
// where
|
||||
// RecordType: WriteRow,
|
||||
// {
|
||||
// fn write_table(&self, config: &Config) -> Result<String> {
|
||||
// let mut buffer = BufWriter::new(Vec::new());
|
||||
// self.row[0].write_header(&mut buffer, config, NO_STRING)?;
|
||||
// for row in self.row.iter() {
|
||||
// row.write_row(&mut buffer, config, NO_STRING)?;
|
||||
// }
|
||||
// self.row[0].write_footer(&mut buffer, config, NO_STRING)?;
|
||||
// Ok(String::from_utf8(buffer.into_inner()?)?)
|
||||
// }
|
||||
// }
|
||||
|
||||
// #[derive(Debug, Deserialize)]
|
||||
// #[serde(rename_all = "PascalCase")]
|
||||
// /// A single row in a martial class tsv file
|
||||
// pub(crate) struct RecordFood {
|
||||
// /// The name of the ingredient used in this recipe.
|
||||
// pub ingredient: String,
|
||||
|
||||
// /// The part of the body this food is from.
|
||||
// pub part: String,
|
||||
|
||||
// /// The rarity level of this food, represented as a clean string.
|
||||
// pub rarity: CleanString,
|
||||
|
||||
// /// How much this this food item will fill you.
|
||||
// pub filling: CleanString,
|
||||
|
||||
// /// The main effect that this food has on the player's character (e.g. "healing", "buffing", etc.).
|
||||
// pub effect_main: CleanString,
|
||||
|
||||
// /// Any secondary effects that this food may have on the player's character.
|
||||
// pub effect_secondary: CleanString,
|
||||
|
||||
// /// A measure of how difficult it is to prepare this food item.
|
||||
// pub difficulty: CleanString,
|
||||
|
||||
// /// The toxicity level of this food.
|
||||
// pub toxicity: CleanString,
|
||||
// }
|
||||
|
||||
// impl WriteRow for RecordFood {
|
||||
// fn write_header(
|
||||
// &self,
|
||||
// buffer: &mut BufWriter<Vec<u8>>,
|
||||
// _: &Config,
|
||||
// format: &str,
|
||||
// ) -> Result<()> {
|
||||
// writeln!(buffer, "{}", format).context("Writing header")
|
||||
// }
|
||||
// fn write_row(
|
||||
// &self,
|
||||
// buffer: &mut BufWriter<Vec<u8>>,
|
||||
// _config: &Config,
|
||||
// _format: &str,
|
||||
// ) -> Result<()> {
|
||||
// writeln!(
|
||||
// buffer,
|
||||
// " {}&{}&{}{}&{}&{}&{}&{} \\\\",
|
||||
// self.ingredient,
|
||||
// self.part,
|
||||
// self.rarity,
|
||||
// self.filling,
|
||||
// self.effect_main,
|
||||
// self.effect_secondary,
|
||||
// self.difficulty,
|
||||
// self.toxicity,
|
||||
// )
|
||||
// .context("Writing row")
|
||||
// }
|
||||
|
||||
// fn write_footer(
|
||||
// &self,
|
||||
// buffer: &mut BufWriter<Vec<u8>>,
|
||||
// config: &Config,
|
||||
// _format: &str,
|
||||
// ) -> Result<()> {
|
||||
// writeln!(buffer, "{}", config.craft.end).context("Writing footer")
|
||||
// }
|
||||
// }
|
||||
|
||||
// #[derive(Debug, Deserialize)]
|
||||
// #[serde(rename_all = "PascalCase")]
|
||||
// /// A record of alchemy data.
|
||||
// pub(crate) struct RecordAlchemy {
|
||||
// /// The ingredients name.
|
||||
// pub ingredient: String,
|
||||
|
||||
// /// The part this ingredient came from
|
||||
// pub part: String,
|
||||
|
||||
// /// The rarity level of this alchemy
|
||||
// pub rarity: CleanString,
|
||||
|
||||
// /// A brief description of the main effect of this alchemy.
|
||||
// pub effect_main: CleanString,
|
||||
|
||||
// /// A brief description of any secondary effects of this alchemy.
|
||||
// pub effect_secondary: CleanString,
|
||||
|
||||
// /// The difficulty level required to perform this alchemy
|
||||
// pub difficulty: CleanString,
|
||||
|
||||
// /// The toxicity of this ingredient.
|
||||
// pub toxicity: CleanString,
|
||||
// }
|
||||
|
||||
// impl WriteRow for RecordAlchemy {
|
||||
// fn write_header(
|
||||
// &self,
|
||||
// buffer: &mut BufWriter<Vec<u8>>,
|
||||
// config: &Config,
|
||||
// _format: &str,
|
||||
// ) -> Result<()> {
|
||||
// writeln!(buffer, "{}", config.craft.header_alchemy).context("Writing header")
|
||||
// }
|
||||
// fn write_row(
|
||||
// &self,
|
||||
// buffer: &mut BufWriter<Vec<u8>>,
|
||||
// _config: &Config,
|
||||
// _format: &str,
|
||||
// ) -> Result<()> {
|
||||
// writeln!(
|
||||
// buffer,
|
||||
// " {}&{}&{}{}&{}&{}&{} \\\\",
|
||||
// self.ingredient,
|
||||
// self.part,
|
||||
// self.rarity,
|
||||
// self.effect_main,
|
||||
// self.effect_secondary,
|
||||
// self.difficulty,
|
||||
// self.toxicity,
|
||||
// )
|
||||
// .context("Writing row")
|
||||
// }
|
||||
|
||||
// fn write_footer(
|
||||
// &self,
|
||||
// buffer: &mut BufWriter<Vec<u8>>,
|
||||
// config: &Config,
|
||||
// _format: &str,
|
||||
// ) -> Result<()> {
|
||||
// writeln!(buffer, "{}", config.craft.end).context("Writing footer")
|
||||
// }
|
||||
// }
|
||||
|
||||
// #[derive(Debug, Deserialize)]
|
||||
// #[serde(rename_all = "PascalCase")]
|
||||
// /// A record of alchemy data.
|
||||
// pub(crate) struct RecordForge {
|
||||
// /// The ingredient used in this forging recipe.
|
||||
// pub ingredient: String,
|
||||
|
||||
// /// The rarity level of this forged item.
|
||||
// pub rarity: CleanString,
|
||||
|
||||
// /// The density or weight class of the forged item.
|
||||
// pub density: CleanString,
|
||||
|
||||
// /// Main effect on weapons when using this ingredient.
|
||||
// pub effect_weapon_main: CleanString,
|
||||
|
||||
// /// Main effect on armor when using this ingredient.
|
||||
// pub effect_armor_main: CleanString,
|
||||
|
||||
// /// Secondary effects on weapons when using this ingredient.
|
||||
// pub effect_weapon_secondary: CleanString,
|
||||
|
||||
// /// Secondary effects on armor when using this ingredient.
|
||||
// pub effect_armor_secondary: CleanString,
|
||||
|
||||
// /// The difficulty level
|
||||
// pub difficulty: CleanString,
|
||||
|
||||
// /// The difficulty processing this ingredient.
|
||||
// pub preparation: CleanString,
|
||||
// }
|
||||
|
||||
// impl WriteRow for RecordForge {
|
||||
// fn write_header(
|
||||
// &self,
|
||||
// buffer: &mut BufWriter<Vec<u8>>,
|
||||
// config: &Config,
|
||||
// _format: &str,
|
||||
// ) -> Result<()> {
|
||||
// writeln!(buffer, "{}", config.craft.header_forge).context("Writing header")
|
||||
// }
|
||||
// fn write_row(
|
||||
// &self,
|
||||
// buffer: &mut BufWriter<Vec<u8>>,
|
||||
// _config: &Config,
|
||||
// _format: &str,
|
||||
// ) -> Result<()> {
|
||||
// writeln!(
|
||||
// buffer,
|
||||
// " {}&{}&{}&{}&{}{}&{}&{}&{} \\\\",
|
||||
// self.ingredient,
|
||||
// self.rarity,
|
||||
// self.density,
|
||||
// self.effect_weapon_main,
|
||||
// self.effect_armor_main,
|
||||
// self.effect_weapon_secondary,
|
||||
// self.effect_armor_secondary,
|
||||
// self.difficulty,
|
||||
// self.preparation,
|
||||
// )
|
||||
// .context("Writing row")
|
||||
// }
|
||||
|
||||
// fn write_footer(
|
||||
// &self,
|
||||
// buffer: &mut BufWriter<Vec<u8>>,
|
||||
// config: &Config,
|
||||
// _format: &str,
|
||||
// ) -> Result<()> {
|
||||
// writeln!(buffer, "{}", config.craft.end).context("Writing footer")
|
||||
// }
|
||||
// }
|
||||
328
src/tablegen.rs
328
src/tablegen.rs
|
|
@ -1,85 +1,165 @@
|
|||
//! The csv table generation
|
||||
use clap::Args;
|
||||
use serde::Deserialize;
|
||||
use std::io::{Error, Write};
|
||||
use std::{cell::RefCell, fmt, fs::File, io::BufWriter};
|
||||
//! The tsv table generation
|
||||
use anyhow::{Context, Result};
|
||||
use csv::StringRecord;
|
||||
use glob::glob;
|
||||
use regex::Captures;
|
||||
use std::{
|
||||
cell::RefCell,
|
||||
fs::File,
|
||||
io::{Error, Write},
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
#[derive(Debug, Args)]
|
||||
pub struct TableArgs {
|
||||
#[arg(short)]
|
||||
export: bool,
|
||||
// #[arg(short)]
|
||||
filenames: Vec<String>,
|
||||
}
|
||||
use crate::table_types::{ClassesArray, GenericArray, RecordClass, WriteRow, WriteTable};
|
||||
use crate::{
|
||||
table_structs::{TableArgs, TableGenerationTarge, TableTargets, RE, STR_TO_TARGET_FULL},
|
||||
Config,
|
||||
};
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "PascalCase")]
|
||||
struct Record {
|
||||
technique: String,
|
||||
niveau: String,
|
||||
technique_type: String,
|
||||
cout_blood: CleanString,
|
||||
cout_jauge: CleanString,
|
||||
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) -> Result<()> {
|
||||
let list_files = match args.kind {
|
||||
TableGenerationTarge::Classes => {
|
||||
println!("Processing files in the Tables/ subdirectory");
|
||||
&mut list_dir("Tables/???-*.tsv")
|
||||
}
|
||||
TableGenerationTarge::Craft => {
|
||||
println!("Processing files in the Craft/ subdirectory");
|
||||
&mut list_dir("Craft/???-*.tsv")
|
||||
}
|
||||
// Add the use of glob to save the poor windows users
|
||||
TableGenerationTarge::Files => {
|
||||
println!("Processing the files given as argument");
|
||||
&mut args.filenames.iter().map(PathBuf::from).collect()
|
||||
}
|
||||
};
|
||||
|
||||
pub fn table_gen(args: &TableArgs) {
|
||||
if args.filenames.is_empty() {
|
||||
if list_files.is_empty() {
|
||||
println!("No files to process ... skipping");
|
||||
}
|
||||
for f in &args.filenames {
|
||||
if let Err(e) = convert_file(f, args) {
|
||||
println!("Error while processing {}: {}", f, e)
|
||||
}
|
||||
match args.kind {
|
||||
TableGenerationTarge::Classes => process_files(list_files, args, config),
|
||||
TableGenerationTarge::Craft => process_files(list_files, args, config),
|
||||
// For now every file is considered as a class file
|
||||
TableGenerationTarge::Files => process_files(list_files, args, config),
|
||||
}
|
||||
}
|
||||
pub fn convert_file(f: &String, args: &TableArgs) -> Result<(), Error> {
|
||||
let csv = read_csv(f)?;
|
||||
let converted = records_to_string(csv)?;
|
||||
|
||||
/// 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")?[..3];
|
||||
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 path = f.replace(".tsv", ".tex");
|
||||
println!("[Info] Writing to {}", path);
|
||||
let name = &f
|
||||
.file_name()
|
||||
.context("Extracting old name")?
|
||||
.to_str()
|
||||
.context("Generating new name")?[4..];
|
||||
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!("###### [FILE:{:?}] ######", f);
|
||||
println!("{}", converted);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[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(&replace_all(&self.0))
|
||||
}
|
||||
}
|
||||
|
||||
fn replace_all(arg: &str) -> String {
|
||||
use regex::{Captures, Regex};
|
||||
|
||||
let re = Regex::new(r"★+").unwrap();
|
||||
|
||||
/// Replace all instances of unrepresentable utf8 or non escaped characters with latex ones
|
||||
pub fn make_latex_string(arg: &str) -> String {
|
||||
let temp = arg
|
||||
.replace('🩸', "\\blood")
|
||||
.replace('⚡', "\\gauge")
|
||||
.replace('☽', "\\tranchant")
|
||||
.replace('◅', "\\percant")
|
||||
.replace('⧆', "\\contondant")
|
||||
.replace('Ø', "\\o{}")
|
||||
.replace('⌭', "\\torque")
|
||||
.replace('☆', "\\star")
|
||||
.replace('🗘', "\\reload")
|
||||
.replace('½', "\\sfrac{1}{2}")
|
||||
.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()
|
||||
}
|
||||
|
||||
fn read_csv(filename: &String) -> Result<Vec<Vec<Record>>, Error> {
|
||||
/// 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)
|
||||
|
|
@ -90,13 +170,13 @@ fn read_csv(filename: &String) -> Result<Vec<Vec<Record>>, Error> {
|
|||
.comment(Some(b'#'))
|
||||
.from_reader(file);
|
||||
|
||||
let mut levels = Vec::with_capacity(4);
|
||||
let current_tier = RefCell::new(Vec::with_capacity(4));
|
||||
let mut levels = Vec::with_capacity(8);
|
||||
let current_tier = RefCell::new(Vec::with_capacity(6));
|
||||
for result in rdr.deserialize() {
|
||||
let result: Record = result?;
|
||||
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(6));
|
||||
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
|
||||
|
|
@ -104,43 +184,103 @@ fn read_csv(filename: &String) -> Result<Vec<Vec<Record>>, Error> {
|
|||
current_tier.borrow_mut().push(result);
|
||||
}
|
||||
}
|
||||
// println!("{:#?}", levels);
|
||||
Ok(levels)
|
||||
Ok(ClassesArray { tiers: levels })
|
||||
}
|
||||
|
||||
fn records_to_string(csv: Vec<Vec<Record>>) -> Result<String, Error> {
|
||||
// FUREUR SANGUINAIRE & 1 & Actif, (Guivre) & 6\blood & Sacrifiez 3 points de vie dans toutes les localités, vous gagnez l'altération Rage, vos attaques infligent une réussite supplémentaire tant que vous êtes enragé.\\
|
||||
// FUREUR SANGUINAIRE & 2 & Actif, Exclusif, (Guivre) & 5\blood 1\gauge & Sacrifiez 4 points de vie a la place, vous gagnez 2 dégâts supplémentaires sur chaque attaque tant que vous êtes enragé. Lorsque vous perdez l'altération d'état enragé, regagnez 1\gauge.\\
|
||||
// EXSANGUINATION PROGRESSIVE & 1 & Actif, (Béhémoth) & 3\blood\vfill 1\gauge & Votre prochaine attaque marque la cible en son point d'impact, toutes les attaques ciblant cette marque ignorent jusqu'à 4 points d'armure ce tour-ci.\\
|
||||
// EXSANGUINATION PROGRESSIVE & 1 & Actif, (Béhémoth) & 4\blood\vfill 1\gauge & Ces attaques infligent aussi un saignement de 1 dégât sur 4 tours (chaque attaque viens ajouter un point au saignement total).\\
|
||||
let mut buffer = BufWriter::new(Vec::new());
|
||||
for (lvl, tier) in csv.iter().skip(1).enumerate() {
|
||||
write!(buffer, "\\subsubsection{{Tier {}}}", lvl + 1)?;
|
||||
let open = r#"{\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"#;
|
||||
write!(buffer, "{}", open)?;
|
||||
for elem in tier {
|
||||
write!(
|
||||
buffer,
|
||||
" {}&{}&{}&{}{}&{} \\\\",
|
||||
elem.technique,
|
||||
elem.niveau,
|
||||
elem.technique_type,
|
||||
elem.cout_blood,
|
||||
elem.cout_jauge,
|
||||
elem.effet
|
||||
)?;
|
||||
}
|
||||
/// 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(),
|
||||
};
|
||||
Ok(Box::new(craft_array))
|
||||
}
|
||||
|
||||
impl WriteRow for StringRecord {
|
||||
fn write_header(
|
||||
&self,
|
||||
buffer: &mut std::io::BufWriter<Vec<u8>>,
|
||||
_config: &Config,
|
||||
format: &str,
|
||||
) -> Result<()> {
|
||||
writeln!(buffer, "{}", format).context("Writing header")
|
||||
}
|
||||
|
||||
fn write_row(
|
||||
&self,
|
||||
buffer: &mut std::io::BufWriter<Vec<u8>>,
|
||||
_config: &Config,
|
||||
_format: &str,
|
||||
) -> Result<()> {
|
||||
let mut itr = self.into_iter();
|
||||
write!(
|
||||
buffer,
|
||||
r" \hline
|
||||
\end{{tabularx}}
|
||||
}}
|
||||
"
|
||||
" {}",
|
||||
itr.next().context("Writing firt element of row")?
|
||||
)?;
|
||||
for e in itr {
|
||||
write!(buffer, " & {}", make_latex_string(e)).context("Writing row")?
|
||||
}
|
||||
writeln!(buffer).context("Writing row")
|
||||
}
|
||||
|
||||
fn write_footer(
|
||||
&self,
|
||||
buffer: &mut std::io::BufWriter<Vec<u8>>,
|
||||
config: &Config,
|
||||
_format: &str,
|
||||
) -> Result<()> {
|
||||
writeln!(buffer, "{}", config.craft.end).context("Writing footer")
|
||||
}
|
||||
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.
|
||||
pub(crate) 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))
|
||||
// }
|
||||
|
|
|
|||
Loading…
Reference in New Issue