formatter #71

Merged
Dandaedre merged 5 commits from formatter into main 2026-04-23 17:11:01 +02:00
50 changed files with 594 additions and 30 deletions

View File

@ -0,0 +1,12 @@
specs:
- name: base
prefix: r
source_url: "https://github.com/bearcove/tracey"
include:
- "requirements/**/*.md"
impls:
- name: main
include:
- "crates/**/*.rs"
exclude:
- "target/**"

1
.gitignore vendored
View File

@ -23,3 +23,4 @@ Cargo.lock
/target
.cargo/
.tracey/

View File

@ -1,13 +1,10 @@
# cargo-features = ["edition2024"]
[workspace]
members = [ "cli_parser", "config", "graphs", "make",
"ravenous-tools", "stats",
"tablegen", "weaponry",
]
members = ["crates/*"]
resolver = "3"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
# [workspace.package]
# edition = "2024"
# license = "MIT OR Apache-2.0"
[profile.dev]
debug = 0

5
TODO.md Normal file
View File

@ -0,0 +1,5 @@
# TODO
* Remake graphs
* Remake export
* Remake dashboard

View File

@ -4,6 +4,7 @@
use clap::{Args, Parser, Subcommand};
use config::{
formatter::FormatterConfig,
graph::GraphConfig,
make::{
HELP_BLOCK_SELECTION, HELP_BUILD_TARGET_LIST, HELP_VERBOSITY_LEVEL, MakeTargets,
@ -42,6 +43,8 @@ pub enum Commands {
Make(MakeConfig),
/// Make all graphs
Graphs(GraphConfig),
/// Format the file given on input
Format(FormatterConfig),
}
#[derive(Debug, Args)]

View File

@ -0,0 +1,57 @@
//! # `fast_table` Configuration
//!
//! This module defines the command‑line configuration used by the **fast‑tables**
//! tool. The struct `FastTableConfig` is a thin wrapper around the `clap`
//! `Args` derive macro, which automatically turns the struct into a CLI
//! parser. All public fields are exposed to the user via command‑line flags
//! (or environment variables) and are documented below.
//!
use clap::{Args, ValueEnum};
/// Configuration for the `fast‑tables` command.
///
/// This struct is passed directly to `clap::Command::new` when creating the
/// CLI. Each field corresponds to a CLI flag; the attribute annotations
/// control how `clap` renders help text and parses values.
///
#[derive(Args, Debug, Clone)]
pub struct FastTableConfig {
/// Target table type to generate or operate on.
#[arg()]
pub target: TableTargetType,
/// Optional path to the destination directory for the generated tables.
#[arg(short, long)]
pub destination: Option<String>,
/// Optional path to an existing configuration file.
/// If omitted, a new config will be created with default values.
#[arg(short, long)]
pub config: Option<String>,
/// Simple string filter applied to class names.
/// Empty string matches all classes.
#[arg(long)]
pub filter: String,
}
/// Enumerated set of table target types.
///
/// This enum implements `ValueEnum`, which gives it two important traits:
/// * It can be used directly as a `clap` argument type.
/// * It can be parsed from a string (`"classes"`, `"alchemy"`, etc.) in a
/// case‑insensitive manner.
#[derive(ValueEnum, Debug, Clone)]
pub enum TableTargetType {
/// Classes table
Classes,
/// Alchemy table
Alchemy,
/// Brewry table
Brewry,
/// All crafting tables
AllCraft,
/// All tables
All,
}

View File

@ -0,0 +1,17 @@
// Workspace: config
// File: config/src/formatter.rs
//! The inner config for formatter module
use clap::Args;
#[derive(Args, Debug, Clone)]
/// The configuration struct for the Formatter
pub struct FormatterConfig {
/// Export the config
#[arg(short, long)]
pub config: bool,
/// Take the arguments via stdin
#[arg(long)]
pub stdin: bool,
}

View File

@ -70,12 +70,3 @@ impl From<&str> for GraphTargetType {
}
}
}
// #[cfg(test)]
// mod tests {
// use super::*;
// #[test]
// fn it_works() {}
// }
//

View File

@ -7,6 +7,8 @@
#![warn(missing_docs, clippy::missing_docs_in_private_items)]
// Internal Modules
pub mod fast_tables;
pub mod formatter;
pub mod graph;
pub mod make;
pub mod statsolver;

View File

@ -0,0 +1,7 @@
[package]
name = "fast_class"
version = "0.1.0"
edition = "2024"
[dependencies]
facet = "0.42.0"

View File

@ -0,0 +1,135 @@
//! # Class & Tool Utility
//!
//! This module defines the core data structures used for representing classes in the
//! game's balancing engine. Each class is a collection of metrics and a list of
//! skill tiers. The structures are intentionally lightweight and designed to be
//! serialisable with the `Facet` derive macro (used for JSON/YAML/CBOR export).
//!
//! The following concepts are modeled:
//!
//! * **`RavClass`** - The top-level representation of a playable class.
//! * **`Metrics`** - A set of performance indicators that can be used for
//! balancing decisions.
//! * **`SkillTier`** - A grouping of skills that are unlocked at a given level.
//! * **`Skill`** - An individual skill with its own cost, type, and effect
//! description.
//! * **`Cost`** - The resources required to cast a skill. The enum uses
//! `repr(C)` for ABI-compatibility with C-based tools.
//! * **`TType`** - A canonical representation of a skill's type (e.g. passive,
//! active, crowd-control). This enum is defined for readability but the
//! current `Skill::t_type` field uses raw `u8` values - see the note in
//! `Skill` for guidance on converting between the two.
//!
//! The module is free of external dependencies except for `facet`, which provides
//! the procedural macro used for deriving serialisation support.
use facet::Facet;
/// Represents a playable class in the game.
///
/// A `RavClass` contains the public metadata of a class (name, image, description),
/// a set of *metrics* that quantify its strengths and weaknesses, and a list of
/// `SkillTier`s that hold the actual abilities.
///
/// The metrics are interpreted as scores between `0.0` and `5.0`. They are used
/// by the balancing engine to calculate power-level, but the struct itself does
/// not enforce this range; callers must validate it if required.
#[derive(Facet, Debug, Clone, Default)]
pub struct RavClass {
/// Human-readable name of the class.
pub name: String,
/// Path or URL to the class icon.
pub image: String,
/// Short flavor description.
pub description: String,
/// Quantitative metrics used for balancing.
pub radar: Metrics,
/// Ordered list of skill tiers. Typically one tier per level.
pub techniques: Vec<SkillTier>,
}
/// Metrics that quantify a class's capabilities.
///
/// All fields are `f32` values that usually lie in the range `[0.0, 1.0]`. The
/// semantics of each metric are intentionally simple: higher values mean the
/// class is better at that aspect. The struct derives `Default` via `Facet`,
/// which sets every metric to `0.0`.
#[derive(Facet, Debug, Clone, Default)]
pub struct Metrics {
pub survivability: f32,
pub damage: f32,
pub mobility: f32,
pub alterations: f32,
pub support: f32,
pub crowd_control: f32,
pub quality_of_live: f32,
}
/// A grouping of skills unlocked at a particular level.
///
/// Each `SkillTier` contains a vector of `Skill`. The ordering of tiers matters
/// for progression; callers should keep the slice sorted by the level that the
/// tier unlocks.
#[derive(Facet, Debug, Clone, Default)]
pub struct SkillTier {
/// Skills available at the tier's level.
pub skills: Vec<Skill>,
}
/// A single skill that a class can use.
///
/// The struct is intentionally flexible: it stores the skill name, level,
/// type(s), cost(s), and an effect description. Some fields are stored as
/// primitive types to keep the data compact, but helper functions can
/// translate between those primitives and the more descriptive enums.
#[derive(Facet, Debug, Clone, Default)]
pub struct Skill {
/// The display name of the skill.
pub name: String,
/// The skill level (e.g. 1-10).
pub level: usize,
/// Raw type identifiers.
pub t_type: Vec<TType>,
/// List of costs required to activate the skill.
pub cost: Vec<Cost>,
/// Human-readable effect description.
pub effect: String,
}
/// The resource cost required to cast a skill.
#[derive(Facet, Debug, Clone, PartialEq, Eq)]
#[repr(C)]
pub enum Cost {
Energy(u8),
Blood(u8),
}
/// Canonical representation of a skill's type.
#[derive(Facet, Debug, Clone, PartialEq, Eq)]
#[repr(C)]
pub enum TType {
Passive,
Active,
Exclusive,
CC,
Grab,
Unique,
}
pub trait Exportable {
fn to_tex(&self) -> String;
}
pub trait Graphable {
fn to_graph(&self) -> String;
}
/// r[bulk.export]
pub fn add(left: u64, right: u64) -> u64 {
left + right
}
// Subcommands:
// dashboard [classes, alchemy, cooking, forge] --filter name=Archer
// export [classes, ] --filter name=Archer
// graph [classes, alch] --filter
//

View File

@ -0,0 +1,12 @@
[package]
name = "formatter"
version = "0.1.0"
edition = "2024"
[dependencies]
config = {path = "../config"}
cli_parser = {path = "../cli_parser"}
regex = "1.11.1"
serde = { version = "1.0.217", features = ["derive", "alloc"] }
toml = "0.8.20"
anyhow = "1.0.95"

View File

@ -0,0 +1,95 @@
//! A simple formatter that reads patterns from a TOML file,
//! applies them to stdin, and writes the formatted text to stdout.
use anyhow::{Context, Result};
use cli_parser::Config;
use config::formatter::FormatterConfig;
use regex::Regex;
use serde::Deserialize;
use std::fs;
use std::io::{self, Read};
/// The base config for the project
const SAMPLE_CONFIG: &str = r#"# Base config, loaded from .fmtconfig.tml
[[patterns]]
regex = "\\p{Pd}"
replacement = "-"
[[patterns]]
regex = "[\u2018\u2019\u201A\u201B\u02BC\u02BB\u00B4\uFF40\uFF07]"
replacement = "'"
[[patterns]]
regex = "[\\u00AD\\u200B\\u200C\\u200D\\uFEFF\\u2060-\\u2064\\uFE00-\\uFE0F]"
replacement = ""
[[patterns]]
regex = "[\\u202F]"
replacement = ""
"#;
#[derive(Debug, Deserialize)]
/// A simple regex replacement config
struct RegexConfig {
/// The list of pattterns of replacement
patterns: Vec<Pattern>,
}
#[derive(Debug, Deserialize)]
/// The inner structure for a regex replacement pattern
struct Pattern {
/// A regex matching a formatting error
regex: String,
/// The replacement string
replacement: String,
}
/// Format a file according to the formatting guidelines
pub fn format_file(args: &FormatterConfig, _config: &Config) -> Result<()> {
// If --config was requested, print the sample config and exit.
if args.config {
println!("{}", SAMPLE_CONFIG);
return Ok(());
}
// // ------------------------------------------------------------------
// // 1. Read and parse the .fmtconfig.toml file.
// // ------------------------------------------------------------------
let toml_text = fs::read_to_string(".fmtconfig.toml")
.context("Failed to read .fmtconfig.toml")
.unwrap_or(SAMPLE_CONFIG.to_string());
let config: RegexConfig =
toml::from_str(&toml_text).context("Failed to parse .fmtconfig.toml")?;
// ------------------------------------------------------------------
// 2. Read the entire stdin into a string.
// ------------------------------------------------------------------
let mut input = String::new();
if args.stdin {
io::stdin()
.read_to_string(&mut input)
.context("Failed to read stdin")?;
} else {
unimplemented!("Use --stdin")
}
// ------------------------------------------------------------------
// 3. Apply the patterns sequentially.
// ------------------------------------------------------------------
let mut output = input;
for pat in &config.patterns {
// Compile the regex lazily; panic on bad patterns in this demo.
let re = Regex::new(&pat.regex)?;
output = re
.replace_all(&output, pat.replacement.as_str())
.into_owned();
}
// ------------------------------------------------------------------
// 4. Write the result to stdout.
// ------------------------------------------------------------------
print!("{}", output);
Ok(())
}

View File

@ -0,0 +1,8 @@
//! This workspace_crate is a Rust library designed to Format latex documents on save.
#![warn(missing_docs, clippy::missing_docs_in_private_items)]
// Internal modules
mod formating;
//
// Re Export
pub use formating::format_file;

View File

@ -83,7 +83,7 @@ fn del_graphs(args: &GraphConfig) -> Result<()> {
/// Generate the graph and save it
fn gen_graph(args: &GraphConfig) -> Result<()> {
// Import CSV
let data = include_bytes!("../../data/lmroman8-regular.ttf") as &[u8];
let data = include_bytes!("../../../data/lmroman8-regular.ttf") as &[u8];
get_or_try_init_fonts(Some(vec![data])).unwrap();
let csv = import_csv(args)?;

View File

@ -330,10 +330,10 @@ impl LineType {
/// Tries to split the token and return two string
fn split_by(delim: &str, text: &str) -> Option<(String, String)> {
let mut slice = text.split(delim);
if let Some(one) = slice.next() {
if let Some(two) = slice.next() {
return Some((one.to_string(), two.trim_start().to_string()));
}
if let Some(one) = slice.next()
&& let Some(two) = slice.next()
{
return Some((one.to_string(), two.trim_start().to_string()));
}
None
}

View File

@ -11,6 +11,7 @@ cli_parser = {path = "../cli_parser"}
# config = {path = "../config"}
stats = {path = "../stats"}
make = {path = "../make"}
formatter = {path = "../formatter"}
anyhow = "1.0.95"
clap = { version = "4.5.28", features = ["derive"] }

View File

@ -6,6 +6,7 @@
#![warn(clippy::missing_docs_in_private_items)]
// Workspace
use formatter::format_file;
use graphs::make_graphs;
use make::make_pdf;
use stats::stat_solver;
@ -23,7 +24,7 @@ use std::{
fn main() -> Result<()> {
let args = ParserCLIArgs::parse();
let config_str = &fs::read_to_string("helper_config.toml")
.unwrap_or(include_str!("../../helper_config.toml").to_string());
.unwrap_or(include_str!("../../../helper_config.toml").to_string());
let config: Config = toml::from_str(config_str).expect("Coudln't read the config file");
match args.command {
Commands::Tablegen(args) => table_gen(&args, &config),
@ -31,6 +32,7 @@ fn main() -> Result<()> {
Commands::Stats(args) => stat_solver(&args, &config),
Commands::Make(args) => make_pdf(&args, &config),
Commands::Graphs(args) => make_graphs(&args, &config),
Commands::Format(args) => format_file(&args, &config),
}
}

View File

@ -8,8 +8,6 @@
//!
#![allow(dead_code)]
use rayon::iter::ParallelIterator;
/// Generation strategy, how to generate all the data, instead of a full permutation
pub enum EquipementStrategy {
/// Full permutation, generate all possible outcomes
@ -71,11 +69,7 @@ pub enum EquipementFilter {
/// Default full generation strategy
pub fn default_generation<T: Copy>(a: Vec<T>, b: Vec<T>) -> Vec<(T, T)> {
a.iter()
.flat_map(|e| {
b.iter()
.map(|f| ((e.clone()), (f.clone())))
.collect::<Vec<(T, T)>>()
})
.flat_map(|e| b.iter().map(|f| (*e, *f)).collect::<Vec<(T, T)>>())
// .collect::<Vec<Vec<(T, T)>>>()
// .flatten()
.collect()
@ -88,6 +82,6 @@ mod test {
fn test_creator() {
let t = default_generation(vec![1, 2, 3], vec![5, 6, 7]);
println!("{:?}", t);
panic!()
// panic!()
}
}

225
requirements/data.md Normal file
View File

@ -0,0 +1,225 @@
# Ravenous Tools - Spec-Schema
Each line defines a single requirement in a machine-readable format.
The token `r[category.subcategory.item]` identifies the requirement; the following paragraph gives a human-friendly description.
m Bulk Operations
r[bulk.export]
The `export` command must be able to generate classes, parts or objects as requested
## Dashboard
r[dashboard.metrics.display]
Dashboard must display aggregated statistics (total classes, average/SD for QOL, Damage, CC, Survivability, Mobility, Alterations, Support) in a terminal table.
r[dashboard.configuration]
Dashboard must be able to read a user configuration with generic thresholds for validation.
r[dashboard.warnings]
Dashboard must issue warnings for classes whose metrics exceed thresholds defined in the config (e.g., damage > 0.8).
r[dashboard.ascii-charts]
Dashboard must be able to render ASCII charts (e.g., bar chart of average damage) using a terminal rendering crate.
## TeX Export
r[tex.export]
The `tex` command must generate a LaTeX file for one or more classes, escaping special characters and including optional headers.
r[tex.template]
The `--template` flag must allow users to provide a custom LaTeX template that overrides the default.
r[tex.headers]
The `--no-headers` flag must omit LaTeX header/footer when appending to an existing document.
r[tex.output-format]
The `--out tex` option must write the output to the file system, respecting the target path and filename conventions.
## File Export
r[file.export.radar]
The tool must be able to display small inline graphs (radar) rendered to PNG/SVG for latex inclusion.
r[file.export]
All elements (classes, items) must be compairable and exportable as graph
r[file.export.html]
The tool must be able to export html graphs to compair elements
## Search / Filter
r[search.by-name]
The `search --name` flag must return class names matching a full or partial string.
r[search.by-tag]
The `search --tag` flag must filter classes containing a specified tag.
r[search.by-range]
The `search` command must support numeric range filters (e.g., `--max-damage 60`) and return classes, objects or parts within the bounds.
## Graph Generation
r[graph.damage-senarios]
The `graph` command must produce be able to produce several damage scenarios as graphs.
r[graph.comparison]
The `graph comparison` command must produce a chart comparing a user-supplied list of classes.
r[graph.embeddable]
Generated graph files must be referenceable from the TeX export via `\includegraphics`.
## Validation
r[validation.schema]
All JSON files used must be be validated befor being used.
r[validation.error-report]
Validation errors must identify the exact property and reason, formatted for readability.
r[validation.value-ranges]
The schema must enforce required fields, type constraints, and acceptable numeric ranges for each stat.
## Help & Auto-Completion
r[help.full]
`--help` for every sub-command must list all options, flags, and usage examples.
## Logging
r[logging.verbosity]
The CLI must accept `--verbose` and `--quiet` flags to control log level.
r[logging.levels]
Supported levels are `error`, `warn`, `info`, `debug`, and `trace`, matching the configuration defaults.
## Data Requirements
r[data.repo-path]
The repository root must be configurable via `config/ravenous_tools_data.toml` under `repo_path`.
r[data.file-format]
Each class must be stored as a single JSON file in `data/classes/`.
r[data.config]
Global settings are stored in `config/ravenous_tools_data.toml` with fields for thresholds, templates, etc.
## Non-Functional Requirements
r[nonfunctional.extensibility]
A plugin system exposing the `ravenous_tools_plugin` trait must allow third-party crates to add metrics or output formats.
r[nonfunctional.testing]
Unit and integration tests must cover ≥90 % of code paths, verified via CI.
r[nonfunctional.ci]
GitHub Actions workflow must run tests, linting, and build on each push/PR.
r[nonfunctional.documentation]
All public APIs must be documented, and a comprehensive README with examples must be provided.
r[nonfunctional.logging-structured]
All logs must be emitted in structured JSON-lines format for easy parsing.
## User-Story Requirements
r[userstory.balancer]
Balancers must view the aggregated damage-per-HP ratio across all classes in the dashboard.
r[userstory.writer]
Writers must export classes to LaTeX and embed graphs with minimal manual editing.
r[userstory.developer]
Developers must implement custom metric calculators via the plugin interface.
r[userstory.analyst]
Analysts must generate PNG graphs of damage curves directly from the terminal.
## Acceptance Criteria
r[acceptance.tex]
Generated `.tex` must compile without errors; templates and header flags must function.
r[acceptance.dashboard]
Dashboard must display at least five distinct metrics and render ASCII charts legibly.
r[acceptance.validation]
Invalid JSON files must be rejected with pinpointed error messages.
r[acceptance.help]
`--help` output must enumerate all sub-commands and examples; completion scripts install cleanly.
r[acceptance.graph]
PNG/SVG graph files must be created for each graph command and viewable in standard image viewers.
r[acceptance.logging]
Verbose/quiet modes and file logging must work as specified, with timestamps and levels.
r[acceptance.testing]
Code coverage must be ≥90 %; at least one end-to-end CLI test exercising create, export, and dashboard.
r[acceptance.documentation]
README, usage guide, and plugin development docs must be complete and up-to-date.
## Deliverables Checklist
r[deliverables.binary]
The CLI binary `ravenous-tools` must be distributable on crates.io and as a GitHub release.
r[deliverables.repo-skeleton]
The `data/` repository scaffold must be created empty with a README.
r[deliverables.config-sample]
`config/ravenous_tools_data.toml` (sample) must be provided with default values.
r[deliverables.latex-template]
`templates/default_template.toml` must be available and referenceable.
r[deliverables.tests]
Unit tests covering ≥90 % and integration tests for each sub-command must be included.
r[deliverables.ci-workflow]
A complete ci integration must be provided.
r[deliverables.documentation]
README, usage guide, API docs, and plugin interface docs must be comprehensive.
r[deliverables.plugin-interface]
`ravenous_tools_plugin` crate exposing the trait must be published.
r[deliverables.example-plugin]
An example plugin (e.g., custom metric calculator) must be distributed with the repo.
## Future Requirements
r[bulk.classes.export]
The `export` command must accept one or several class names and generate tex files containing all requested classes.
r[bulk.parts.export]
The `export` command must accept one or several parts types and generate tex files containing all requested parts.
r[bulk.objects.export]
The `export` command must accept one or several objects types and generate tex files containing all requested objects.
r[graph.supported-types]
Supported graph types include bar chart, line chart, heat-map, radar chart.
r[completion.bash]
Auto-completion scripts for Bash must be installable via `install-completion` sub-command.
r[completion.zsh]
Auto-completion scripts for Zsh must be installable via `install-completion` sub-command.
r[completion.fish]
Auto-completion scripts for Fish must be installable via `install-completion` sub-command.
r[completion.powershell]
Auto-completion scripts for PowerShell must be installable via `install-completion` sub-command.
r[logging.file]
The `--log <path>` option must write structured logs (JSON-lines) to the specified file.
r[userstory.designer]
Game designers must be able to add a new class with a single command and see it reflected immediately in exports.
r[acceptance.crud]
All CRUD commands must correctly manipulate JSON files, with clear errors when classes are missing.