From ec4c930bfcf5da675e058e5227b4462997c54aa5 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sat, 13 Dec 2025 19:49:21 +0100 Subject: [PATCH 1/7] Adds documentation, updates the CI --- .ignore | 1 + Jenkinsfile | 11 +- README.md | 124 ++++++++++++------ bin_efo/src/commands.rs | 2 +- .../commands/{chr.rs => entity_generic.rs} | 65 ++++++++- bin_efo/src/commands/epoch.rs | 49 ++++++- bin_efo/src/commands/generate.rs | 91 ++++++++++++- bin_efo/src/commands/init.rs | 23 +++- bin_efo/src/main.rs | 54 ++++---- lib_efo/src/entity/implementations.rs | 2 +- lib_efo/src/epoch.rs | 2 +- lib_efo/src/epoch/epoch_config.rs | 8 +- lib_efo/src/epoch/epoch_info.rs | 2 +- lib_efo/src/error.rs | 4 +- lib_efo/src/lib.rs | 11 -- lib_efo/src/stats.rs | 8 +- 16 files changed, 360 insertions(+), 97 deletions(-) create mode 100644 .ignore rename bin_efo/src/commands/{chr.rs => entity_generic.rs} (83%) diff --git a/.ignore b/.ignore new file mode 100644 index 0000000..bd01d04 --- /dev/null +++ b/.ignore @@ -0,0 +1 @@ +snapshots diff --git a/Jenkinsfile b/Jenkinsfile index 6d40fcd..bf197c1 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -7,7 +7,8 @@ pipeline { ================== */ environment { - DEPLOY_DIR = "/mnt/books/" // Important, all books are in /mnt/book + DEPLOY_DIR = "/mnt/books/rust_doc/efo/" // Important, all books are in /mnt/book + MDBOOK_BUILD_DIR = "target/doc/" } stages { @@ -33,8 +34,16 @@ pipeline { script { if (env.BRANCH_NAME == 'origin/review' || env.BRANCH_NAME == 'review' || env.BRANCH_NAME == 'origin/dev-ci' || env.BRANCH_NAME == 'dev-ci') { sh 'cargo test' + sh 'cargo doc' + sh 'echo "Deploying to ${DEPLOY_DIR}"' + sh 'mkdir -p ${DEPLOY_DIR}' + sh 'rsync -a --delete ${MDBOOK_BUILD_DIR}/ ${DEPLOY_DIR}' } else if (env.BRANCH_NAME == 'origin/master' || env.BRANCH_NAME == 'master') { sh 'cargo test' + sh 'cargo doc' + sh 'echo "Deploying to ${DEPLOY_DIR}"' + sh 'mkdir -p ${DEPLOY_DIR}' + sh 'rsync -a --delete ${MDBOOK_BUILD_DIR}/ ${DEPLOY_DIR}' } else { echo "Unknown branch: ${env.BRANCH_NAME} - skipping build." } diff --git a/README.md b/README.md index 8bf7e8d..8ab393f 100644 --- a/README.md +++ b/README.md @@ -1,65 +1,115 @@ -# 📦 Epoch Forge (`epoch_forge`) +# 📦 Epoch Forge (`epoch_forge`) – *early alpha* ![code coverage](badges/coverage.svg) ![version](badges/version.svg) ![code coverage](badges/test.svg) +![📚 Online Documentation](https://books.dandaedre.com/rust_doc/efo/bin_efo/index.html) + > **A Rust-powered CLI for managing fantasy organisations across time.** > *Think of it as a living, breathing world-state engine that lets you “rewind”, “fast-forward”, and **alter** the history of guilds, towns, wars, and characters.* -> 🚀 *Fast, type-safe, and fully testable.* +> **Epoch Forge** is a Rust‑powered command‑line tool that lets you build and manipulate a living fantasy world. +> It is **in early alpha** – the API is subject to change, some features are missing, and stability is **not guaranteed**. +> **Stats & analytics are not yet implemented** – most commands operate only on the raw data model. ## ✨ Quick start ```bash -# clone the repo +# Clone the repository git clone https://github.com/yourname/epoch_forge.git cd epoch_forge -# install the binary +# Build & install the binary cargo install --path . -# initialise an empty world (epoch 0) -efo epoch --init +# Initialise an empty world (epoch 0) +efo init -# add a guild -efo org add --name "The Iron Horde" --leader "Gorun" +# Add an organisation +efo org add "The Iron Horde" -# add a town -efo town add --name "Durn" --population 350 +# Add a town +efo town add "Durn" --stat pop:32 -# create an alliance -efo link add --type alliance --org "Iron Horde" --town "Durn" - -# advance the timeline -efo epoch --advance 3 - -# inspect the world +# Inspect the current world state +efo show > world.json cat world.json + +# Show the epoch timeline +efo epoch log + +# Create the next scheduled epoch +efo epoch next + +# Switch back to epoch 5 (if it exists) +efo epoch switch 5 + +# Tag the current epoch +efo epoch tag milestone1 + +# Add a short-lived event +efo event add "Storm" \ + --duration Duration(1) \ + --effect permanent-effect-to-apply \ + --stats damage=20 ``` -## 🏆 Project Highlights +> **Tip:** The `show` command can print JSON, which you can pipe to `jq` or any other tooling. -| Feature | What it gives you | Where it lives | -|---------|------------------|----------------| -| **Epoch management** | Switch, advance, or rewind the timeline | `core::epoch` | -| **Event handling** | Add/remove world-shaping events (storms, festivals, wars) | `core::event` | -| **Organisation CRUD** | Guilds, factions, corporations | `core::org` | -| **Character CRUD** | Heroes, villains, NPCs | `core::character` | -| **Town CRUD** | Villages, cities, trade hubs | `core::town` | +## 🏆 Project Highlights + +| Feature | Description | Where to find it | +|---------|-------------|-----------------| +| **Epoch management** | Switch, advance, or rewind the global timeline | `core::epoch` | +| **Persistence** | JSON/YAML stores, pluggable back-ends | `core::epoch` | +| **Event handling** | Add/remove world-shaping events (storms, festivals, wars) | `core::entities` | +| **Organisation CRUD** | Guilds, factions, corporations | `core::entities` | +| **Character CRUD** | Heroes, villains, NPCs | `core::entities` | +| **Town CRUD** | Villages, cities, trade hubs | `core::entities` | | **Link network** | Alliances, wars, roads, trade routes | `core::link` | -| **Persistence** | JSON/YAML stores, pluggable back-ends | `core::storage` | | **CLI** | `efo` binary with sub-commands | `efo` crate | -| **Tests** | Unit & integration coverage | `tests/` | +> *Statistics, analytics, and the `act` feature are still a work in progress.* -### 📃 Quick reference table +## Unimplemented / WIP -| Sub-command | Usage | What it changes | -|-------------|-------|-----------------| -| `epoch` | `efo epoch --init`
`efo epoch --advance N`
`efo epoch --target ID` | Creates a world; moves time forward or back. | -| `event` | `efo event add ...`
`efo event remove ...` | Adds or removes an event. | -| `org` | `efo org add ...`
`efo org remove ...` | Manages guilds/factions. | -| `chr` | `efo chr add ...`
`efo chr remove ...` | Handles characters. | -| `town` | `efo town add ...`
`efo town remove ...` | Town CRUD. | -| `link` | `efo link add ...`
`efo link remove ...` | Relations: alliances, wars, roads, trade. | +| Feature | Status | Where it lives | +|---------|--------|----------------| +| **Act** | Planned, not yet implemented | `core::act` | +| **Stats** | Missing – no aggregated data | – | + +## Quick reference table + +| Sub‑command | Usage example | What it changes | +|-------------|---------------|-----------------| +| **`init`** | `efo init`
`efo init --force` | Creates an empty epoch repository (epoch 0) in the current directory. | +| **`epoch log`** | `efo epoch log --limit 20` | Prints a chronological list of epochs up to the current one. | +| **`epoch switch`** | `efo epoch switch 5` | Sets the current epoch to the specified `` (must already exist). | +| **`epoch next`** | `efo epoch next` | Generates the next scheduled epoch and inserts it. | +| **`epoch reset`** | `efo epoch reset` | Deletes all epochs with an identifier greater than the current one. | +| **`epoch diff`** | `efo epoch diff 2 4` | *Unimplemented* – placeholder for future diffing logic. | +| **`epoch tag`** | `efo epoch tag milestone1` | Adds a unique tag to the current epoch, updating the global tag map. | +| **`epoch fsck`** | `efo epoch fsck` | *Unimplemented* – intended to run a consistency check. | +| **`epoch summary`** | `efo epoch summary "Reached the new frontier"` | Replaces the `summary` field of the current epoch with ``. | +| **`show`** | `efo show` | Prints the current world state (JSON). | +| **`gen`** | `efo gen character -n 5 --short`
`efo gen town -n 2`
`efo gen event -n 3 --name` | Prints generated names/ideas; useful for scripting. | +| **`chr add`** | `efo chr add "Aria" --pos 5,12 --stats strength=12 agility=9` | Creates a new entity (character, town, event, etc.) and writes the epoch. | +| **`chr del`** | `efo chr del "Aria"` | Removes the matching entity from the epoch. | +| **`chr edit`** | `efo chr edit "Storm" --duration Duration(2)` | Modifies an existing entity’s stats, position, duration, etc. | +| **`chr find`** | `efo chr find "Aria"` | Prints full details of a single entity. | +| **`chr show`** | `efo chr show` | Lists all entities, or `efo chr show "Aria"` shows one in full detail. | +| **`chr diff`** | `efo chr diff "Aria"` | Prints the difference between the current and previous epoch for that entity. | +| **`event add` / `event remove`** | `efo event add ...`
`efo event remove ...` | Adds or removes an event. | +| **`org add` / `org remove`** | `efo org add ...`
`efo org remove ...` | Manages organisations (guilds, factions). | +| **`town add` / `town remove`** | `efo town add ...`
`efo town remove ...` | CRUD for towns. | +| **`monster add` / `monster remove`** | `efo monster add ...`
`efo monster remove ...` | CRUD for monsters. | +| **`act`** | *Not yet implemented* | Planned for future action handling. | + +> All changes are persisted immediately to the epoch file after the command finishes. + +## Contributions & Feedback + +Because the project is in early alpha, any feedback, bug reports, or pull requests are welcome. +Please remember that **stability is not guaranteed**, so use it in a versionned environnement. + +Happy forging! ✨ -Happy forging! 🔨✨ diff --git a/bin_efo/src/commands.rs b/bin_efo/src/commands.rs index 2786614..bfdc0da 100644 --- a/bin_efo/src/commands.rs +++ b/bin_efo/src/commands.rs @@ -8,7 +8,7 @@ #![warn(missing_docs, clippy::missing_docs_in_private_items)] -pub mod chr; +pub mod entity_generic; pub mod epoch; pub mod generate; pub mod init; diff --git a/bin_efo/src/commands/chr.rs b/bin_efo/src/commands/entity_generic.rs similarity index 83% rename from bin_efo/src/commands/chr.rs rename to bin_efo/src/commands/entity_generic.rs index d34e841..6f4dcfe 100644 --- a/bin_efo/src/commands/chr.rs +++ b/bin_efo/src/commands/entity_generic.rs @@ -1,4 +1,66 @@ -//! Module handling the creation of characters +//! ## Guide +//! +//! The **entity** command manipulates the lists of game objects that live inside an *epoch*. +//! An *epoch* is a snapshot of the game state that can be written to disk or rolled back to an earlier one. +//! Every entity type (`character`, `town`, `event`, …) has the same set of operations: +//! +//! ## Summary +//! +//! | Sub‑command | Usage | What it changes | +//! |-------------|-------|-----------------| +//! | **add** | ` add [OPTIONS] [IDENTIFIER]` | Creates a new ``, pushes it to the epoch’s list, and writes the epoch. | +//! | **del** | ` del ` | Removes the matching `` from the list and writes the epoch. | +//! | **edit** | ` edit [OPTIONS]` | Modifies the stats/position/duration/effect/bounds of the chosen `` and writes the epoch. | +//! | **find** | ` find ` | Prints full details of a single ``. | +//! | **show** | ` show []` | Lists all entities on one line, or shows one `` in full detail. | +//! | **diff** | ` diff ` | Prints the difference between the current and previous epoch for that ``. | +//! +//! *`IDENTIFIER`* is either a **name** or a **@tag** (`@1234`). +//! If omitted, a random name is generated for the type you are working on. +//! +//! ### Options +//! +//! | Flag | Description | +//! |------|-------------| +//! | `-d, --delta` | Apply a delta to the supplied stats (add or subtract) instead of overwriting them. | +//! | `-v, --verbose…` | Increase output verbosity. | +//! | `--rng ` | How to fill unspecified stats.
Possible values: `zero`, `low`, `med`, `high`, `legendary`, `mixed`, `flawed`. Default: `zero`. | +//! | `--pos-exact ` / `--pos ` | Place the new entity at a specific `x,y` coordinate (the epoch must be in a map context). | +//! | `--duration ` | Lifespan of the entity (e.g. `Permanent`, `Temporary`, `Duration(1)` for a one‑turn event). | +//! | `--bounds ` | Effect limits, given as `min,max` (e.g. `10,80`). | +//! | `--effect ` | How the effect is applied:
`recurring`, `when-present`, `permanent-effect-to-apply`, `permanent-effect-applied`. | +//! | `-s, --stats ` | One or more `key:value` pairs, e.g. `fod,10 military:8`. | +//! +//! ## Usage +//! All the following example use `chr` as a choice of entity but can be safely substitued to any entity: `event`, `town`, `blocker` etc... +//! +//! ```bash +//! # Create a character named “Aria” +//! chr add Aria \ +//! --stats fod:10 mil:8 \ +//! --rng mixed +//! +//! # Edit that character: bump military, shorten duration +//! chr edit Aria \ +//! --stats mil:5 \ +//! --duration Duration:5 +//! +//! # Show all characters +//! chr show +//! +//! # Show one character in detail +//! chr show Aria +//! +//! # Delete a character +//! chr del Aria +//! +//! # Diff a character between two epochs +//! chr diff Aria +//! ``` +//! +//! > **Tip** – ` diff` automatically loads the current epoch and the previous one, so you don’t need to specify epoch numbers. +//! +//! *All changes are persisted immediately to the epoch file after the command finishes.* use lib_efo::entity::{EffectApplication, EffectBounds, EntityDuration, EntityIdentifier}; use lib_efo::epoch::epoch_traits::{ConfigWritable, Diffable}; @@ -80,6 +142,7 @@ pub struct EntityArgs { pub effect: Option, /// All stats pairs involved + #[arg(short, long)] pub stats: Vec, } diff --git a/bin_efo/src/commands/epoch.rs b/bin_efo/src/commands/epoch.rs index b426aea..ed7937c 100644 --- a/bin_efo/src/commands/epoch.rs +++ b/bin_efo/src/commands/epoch.rs @@ -1,7 +1,50 @@ //! # `epoch` sub-command //! -//! Handles all epoch-related logic - logging, switching, computing the -//! next epoch, and resetting future events. +//! The `epoch` sub‑command is the single entry point for all epoch‑related +//! operations in **efo**. +//! An *epoch* represents a point in the simulated world’s history. +//! The command lets you inspect, advance, modify and sanity‑check the epoch +//! timeline. +//! +//! ### Usage +//! +//! ```bash +//! # Show log of epochs (last 20 by default) +//! efo epoch log --limit 20 +//! +//! # Switch to an existing epoch +//! efo epoch switch 5 +//! +//! # Create the next epoch if none exist in the future +//! efo epoch next +//! +//! # Delete all future epochs, returning to the present +//! efo epoch reset +//! +//! # Add a unique tag to the current epoch +//! efo epoch tag milestone1 +//! +//! # Replace the current epoch’s summary +//! efo epoch summary "Reached the new frontier" +//! +//! # (Future) Check consistency +//! efo epoch fsck +//! ``` +//! +//! ### Summary +//! +//! | Sub‑command | Usage | What it changes | +//! |-------------|-------|-----------------| +//! | `log` | `efo epoch log [--limit N]` | Prints the chronological list of epochs up to the current one. | +//! | `switch` | `efo epoch switch ` | Sets the current epoch to the specified `` (must already exist). | +//! | `next` | `efo epoch next` | Generates the next scheduled epoch and inserts it. | +//! | `reset` | `efo epoch reset` | Deletes all epochs with an identifier greater than the current one. | +//! | `diff` | `efo epoch diff ` | *Unimplemented* – placeholder for future diffing logic. | +//! | `tag` | `efo epoch tag ` | Adds a unique tag to the current epoch, updating the global tag map. | +//! | `fsck` | `efo epoch fsck` | *Unimplemented* – intended to run a consistency check. | +//! | `summary` | `efo epoch summary ` | Replaces the `summary` field of the current epoch with ``. | +//! + #![warn(missing_docs, clippy::missing_docs_in_private_items)] use crate::{ @@ -40,7 +83,7 @@ pub mod cli_epoch; /// reported via the returned `Result`. pub fn handle_cmd(cmd: &cli_epoch::EpochCmd) -> Result<(), AppError> { let mut main_epoch = EpochConfig::new_from_path(None)?; - // // TODO[2]: Remove this debug + // TODO(2): Remove this debug debug!("The main epoch befor any action is {:#?}", main_epoch); match cmd { cli_epoch::EpochCmd::Log(args) => handle_log(args, &mut main_epoch), diff --git a/bin_efo/src/commands/generate.rs b/bin_efo/src/commands/generate.rs index dc37aee..a9046e5 100644 --- a/bin_efo/src/commands/generate.rs +++ b/bin_efo/src/commands/generate.rs @@ -1,20 +1,65 @@ //! # Generation Sub-command //! //! This module implements the `gen` sub-command used to quickly produce -//! sample data for the various generators in *lib_efo*. The command has no +//! sample data for the various generators in *lib_efo*. The command has no //! side-effects beyond printing the generated data; it is intended for //! interactive use or for embedding in scripts. //! //! ## Available sub-commands //! -//! * `character` - Generate character names (long or short). -//! * `event` - Generate event ideas. -//! * `town` - Generate town names. -//! * `exotic` - Generate exotic character names. +//! | Sub‑command | What it prints | Typical output | +//! |-------------|----------------|----------------| +//! | `character` | Character names (short or long) | `Eldric the Bold` | +//! | `event` | Random event ideas | `A mysterious fog descends over the town` | +//! | `town` | Town names | `Glimmerdale` | +//! | `exotic` | Exotic character names | `Zar‑nith the Wanderer` | +//! | `calamity` | Calamity names | `Great Plague of 1743` | +//! | `blocker` | Blocker names | `Stone Wall of the North` | //! -//! Each sub-command accepts a set of common options (see [`Qty`]) that -//! control how many items are produced and how they are displayed. +//! All sub‑commands share the same options: //! +//! * `-n / --number` – how many items to generate (default = 1) +//! * `--short` – print the short form when applicable (ignored for `event`, `exotic`, +//! `calamity`, `blocker`) +//! * `--name` – output only the name string, no extra formatting (good for scripting) +//! +//! # Usage +//! ```bash +//! # 3 long character names +//! gen character -n 3 +//! +//! # 1 short town name +//! gen town -n 1 --short +//! +//! # 5 event ideas, only the names +//! gen event -n 5 --name +//! +//! # A single exotic character name +//! gen exotic -n 1 +//! +//! # 2 calamity names +//! gen calamity -n 2 +//! +//! # 4 blocker names, short form +//! gen blocker -n 4 --short +//! ``` +//! +//! > **Tip** – redirect or pipe the output: +//! > `gen character -n 10 > chars.txt` +//! +//! --- +//! +//! # Summary +//! | Sub‑command | Usage example | What it does | +//! |-------------|---------------|-----------------| +//! | `character` | `gen character -n 5 --short` | Prints 5 short (or long if `--short` omitted) character names | +//! | `event` | `gen event -n 3 --name` | Prints 3 event names only | +//! | `town` | `gen town -n 2` | Prints 2 town names (short form by default) | +//! | `exotic` | `gen exotic -n 1` | Prints 1 exotic character name | +//! | `calamity` | `gen calamity -n 2` | Prints 2 calamity names | +//! | `blocker` | `gen blocker -n 4 --short` | Prints 4 blocker names (short form) | +//! +//! *All sub‑commands simply output the generated data; they do not alter any files or state.* use clap::{Args, Subcommand}; use lib_efo::{Displayable, error::EpochError, naming::NAMING}; @@ -33,6 +78,10 @@ pub enum GenCmd { Town(Qty), /// Exotic name Exotic(Qty), + /// Calamity + Calamity(Qty), + /// Blocker + Blocker(Qty), } #[derive(Args, Debug)] @@ -74,6 +123,34 @@ pub fn gen_handler(cmd: &GenCmd) -> Result<(), AppError> { GenCmd::Event(args) => handle_event(args)?, GenCmd::Town(args) => handle_town(args)?, GenCmd::Exotic(args) => handle_exotic(args)?, + GenCmd::Calamity(args) => handle_calamity(args)?, + GenCmd::Blocker(args) => handle_blocker(args)?, + } + Ok(()) +} + +/// Print a calamity name +fn handle_calamity(args: &Qty) -> Result<(), EpochError> { + for _ in 0..args.number { + let name = NAMING.generate_calamity_name(); + if args.name_only { + println!("{}", name); + } else { + unimplemented!("DEPENS ON : CHARACTER CREATION") + } + } + Ok(()) +} + +/// Print a blocker name +fn handle_blocker(args: &Qty) -> Result<(), EpochError> { + for _ in 0..args.number { + let name = NAMING.generate_blocker_name(); + if args.name_only { + println!("{}", name); + } else { + unimplemented!("DEPENS ON : CHARACTER CREATION") + } } Ok(()) } diff --git a/bin_efo/src/commands/init.rs b/bin_efo/src/commands/init.rs index f6bea46..2f9d759 100644 --- a/bin_efo/src/commands/init.rs +++ b/bin_efo/src/commands/init.rs @@ -8,6 +8,27 @@ //! The main public API consists of: //! //! * `InitCmd` - a struct containing the command-line arguments. +//! +//! ## Guide +//! +//! The `init` sub‑command bootstraps a new epoch repository: +//! +//! * It creates the default `.epoch` configuration file in the current directory. +//! * It creates an empty **epoch 0** folder (with its metadata file). +//! * It refuses to run if the target directory already contains files unless the user supplies `--force`. +//! +//! ### How to use +//! +//! ```bash +//! epoch init # normal init – directory must be empty +//! epoch init --force # skip the empty‑folder check +//! ``` +//! +//! ### Table Entry +//! +//! | Sub‑command | Usage | What it changes | +//! |-------------|-------|-----------------| +//! | `init` | `epoch init [--force]` | Initialize the current folder as an epoch folder | #![warn(missing_docs, clippy::missing_docs_in_private_items)] @@ -39,7 +60,7 @@ pub struct InitCmd { /// /// Creates the default `EpochConfig`, verifies that the target directory /// is empty, and writes the initial configuration and epoch data. -//TODO[5]: Upholster the logic behind force and empty detection +//TODO(5): Upholster the logic behind force and empty detection pub fn init(args: &InitCmd) -> Result<(), AppError> { let epoch_config = EpochConfig::default(); let root = epoch_config.save_folder(); diff --git a/bin_efo/src/main.rs b/bin_efo/src/main.rs index f656027..652a527 100644 --- a/bin_efo/src/main.rs +++ b/bin_efo/src/main.rs @@ -1,24 +1,25 @@ -//! # `efo` +//! # `epoch_forge` CLI //! -//! The **command-line interface** for `epoch_forge`. It exposes a single -//! binary `efo` that supports the following sub-commands: +//! The **command‑line interface** for `epoch_forge`. It exposes a single +//! binary `efo` that supports the following sub‑commands: //! -//! - `epoch` - switch / advance time -//! - `event` - add / remove events -//! - `org` - add / remove organisations -//! - `chr` - add / remove characters -//! - `town` - add / remove towns -//! - `link` - add / remove links (alliances, wars, roads, etc.) +//! ## Sub‑modules //! -//! Each sub-command is implemented in its own module under `commands/`. +//! * [`epoch`](crate::commands::epoch) - switch / advance time +//! * [`event`](crate::commands::entity_generic) - add / remove events +//! * [`org`](crate::commands::entity_generic) - add / remove organisations +//! * [`chr`](crate::commands::entity_generic) - add / remove characters +//! * [`town`](crate::commands::entity_generic) - add / remove towns +//! * [`blocker`](crate::commands::entity_generic) - add / remove blockers +//! * [`calamity`](crate::commands::entity_generic) - add / remove calamities +//! * [`link`](crate::commands::link) - add / remove links (alliances, wars, roads, etc.) +//! +//! Each sub‑command is implemented in its own module under `commands/`. //! The `main.rs` file simply parses arguments with `clap` and dispatches //! to the appropriate handler. The handlers share a common `World` //! instance that they load from / persist to disk. //! -//! ## Usage -//! ```sh -//! efo epoch switch 5 -//! ``` +//! Each module exposes a `handle` function that receives the parsed arguments #![warn(missing_docs, clippy::missing_docs_in_private_items)] #![deny(clippy::unwrap_used)] @@ -29,8 +30,8 @@ use clap::{ArgAction, Parser, Subcommand}; use crate::{ commands::{ - chr::EntitySubCommands, epoch::cli_epoch::EpochCmd, generate::GenCmd, init::InitCmd, - show::ShowCmd, + entity_generic::EntitySubCommands, epoch::cli_epoch::EpochCmd, generate::GenCmd, + init::InitCmd, show::ShowCmd, }, error::AppError, }; @@ -72,9 +73,13 @@ enum TopLevelCmd { /// Handle characters #[command(subcommand)] Chr(EntitySubCommands), - // Event(commands::event::EventCmd), - // Org(commands::org::OrgCmd), - // Town(commands::town::TownCmd), + /// Handle events + #[command(subcommand)] + Event(EntitySubCommands), + // #[command(subcommand)] + // Org(commands::org::OrgCmd), + // #[command(subcommand)] + // Town(commands::town::TownCmd), // Link(commands::link::LinkCmd), /// Generate random structures and display them #[command(subcommand)] @@ -117,8 +122,13 @@ fn exec_dispatch(cli: Cli) -> Result<(), AppError> { TopLevelCmd::Epoch(cmd) => commands::epoch::handle_cmd(&cmd), TopLevelCmd::Show(cmd) => commands::show::handle_show_cmd(&cmd), TopLevelCmd::Gen(cmd) => commands::generate::gen_handler(&cmd), - TopLevelCmd::Chr(cmd) => { - commands::chr::handle_entity_commands(&cmd, &lib_efo::stats::EntityType::Character) - } + TopLevelCmd::Chr(cmd) => commands::entity_generic::handle_entity_commands( + &cmd, + &lib_efo::stats::EntityType::Character, + ), + TopLevelCmd::Event(cmd) => commands::entity_generic::handle_entity_commands( + &cmd, + &lib_efo::stats::EntityType::Event, + ), } } diff --git a/lib_efo/src/entity/implementations.rs b/lib_efo/src/entity/implementations.rs index c87d3fd..99afaa1 100644 --- a/lib_efo/src/entity/implementations.rs +++ b/lib_efo/src/entity/implementations.rs @@ -23,7 +23,7 @@ impl Displayable for Entity { } } - /// One-liner used for auto-generation of Vec displays + /// One-liner used for auto-generation of `Vec` displays fn oneline_display(&self) -> String { let capital = self .metadata diff --git a/lib_efo/src/epoch.rs b/lib_efo/src/epoch.rs index d18f433..404bae4 100644 --- a/lib_efo/src/epoch.rs +++ b/lib_efo/src/epoch.rs @@ -35,7 +35,7 @@ pub mod epoch_info; pub use epoch_info::EpochInfo; pub mod epoch_traits; -// TODO[5]: Try to load from a config and have it inserted as a backup +// TODO(5): Try to load from a config and have it inserted as a backup /// The subfolder naming convention static SUBFOLDER_NAMING: &str = "epoch"; /// The main name of the epoch diff --git a/lib_efo/src/epoch/epoch_config.rs b/lib_efo/src/epoch/epoch_config.rs index 8ffe7ab..5836979 100644 --- a/lib_efo/src/epoch/epoch_config.rs +++ b/lib_efo/src/epoch/epoch_config.rs @@ -45,7 +45,7 @@ pub struct EpochConfig { /// Optional human-friendly tags (e.g. `"winter-B"`, `"post-war"`). pub tags: HashMap, - // TODO[6]: Can become important + // TODO(6): Can become important // #[serde(skip)] // /// Absolute path to `epoch//`. // pub path: PathBuf, @@ -71,7 +71,7 @@ impl EpochConfig { let path = Path::new(MAIN_NAME); if path.is_file() { - // TODO[6]: write a trait for this + // TODO(6): write a trait for this let config: EpochConfig = serde_json::from_str(&io_err_with_help!( read_to_string(path), "Reading config from path {:?}", @@ -279,7 +279,7 @@ impl EpochConfig { /// The function removes the directory, deletes all references to the /// epoch from `list_existing_epochs` and `tags`, and then writes the /// updated configuration to disk. - // TODO[9]: Create a delete_ids taking an iterator for added performance on huge deletions + // TODO(9): Create a delete_ids taking an iterator for added performance on huge deletions pub fn delete_id(&mut self, id: EpochId) -> Result<(), EpochError> { if !self.list_existing_epochs.contains_key(&id) { warn!( @@ -306,7 +306,7 @@ impl EpochConfig { /// is deferred to the `EpochInfo -> World` subsystem. pub fn compute_next(&mut self) -> Result { // unimplemented!() - // TODO[1]: Implement this + // TODO(1): Implement this warn!("DEBUG LINE: COMPUTING NEXT EPOCH"); // New fake epoch let mut new_epoch = self.try_load_current()?.clone(); diff --git a/lib_efo/src/epoch/epoch_info.rs b/lib_efo/src/epoch/epoch_info.rs index cdbe376..bd37874 100644 --- a/lib_efo/src/epoch/epoch_info.rs +++ b/lib_efo/src/epoch/epoch_info.rs @@ -53,7 +53,7 @@ pub struct EpochInfo { /// Human-readable description or summary, useful for the `log` command. #[table(title = "Summary")] pub summary: String, - // TODO[9]: Store world separately + // TODO(9): Store world separately #[table(skip)] /// The list of events currently in progress pub events: Vec, diff --git a/lib_efo/src/error.rs b/lib_efo/src/error.rs index 440e444..fa0e869 100644 --- a/lib_efo/src/error.rs +++ b/lib_efo/src/error.rs @@ -22,7 +22,7 @@ use miette::Diagnostic; /// /// The variants are intentionally small - each one carries all the /// information required to surface a helpful message to the user. -// TODO[2]: Remove or rethink these errors +// TODO(2): Remove or rethink these errors #[derive(Debug, Error, Diagnostic)] pub enum StorageError { /// Problems with serialisation / deserialisation. @@ -47,7 +47,7 @@ pub enum StorageError { /// The enum is deliberately _small_ - each variant is self-contained and /// carries the information you need to surface a friendly message /// to the user (and to the test-suite). -// TODO[2]: Split effectively user errors to avoid the usage of advice and such +// TODO(2): Split effectively user errors to avoid the usage of advice and such #[derive(Error, Debug, Diagnostic)] #[allow(dead_code, unused_assignments)] pub enum EpochError { diff --git a/lib_efo/src/lib.rs b/lib_efo/src/lib.rs index 12aa6d0..4551e92 100644 --- a/lib_efo/src/lib.rs +++ b/lib_efo/src/lib.rs @@ -2,17 +2,6 @@ //! //! The **engine** that drives *Epoch Forge*. It contains a pure, representation of a fantasy world and all the logic needed to manipulate it. //! -//! The crate is split into the following domains, each exposed as a public module: -//! - TODO[1]: `world` - holds the global state (`World`) and a lightweight snapshot (`Context`). -//! - TODO[0]: `epoch` - manages the passage of time and epoch switching. -//! - TODO[1]: `event` - CRUD and evaluation of events that affect the world. -//! - TODO[4]: `org` - organisations, guilds, factions and their history. -//! - TODO[2]: `character` - individual characters, traits and lineage. -//! - TODO[1]: `town` - towns, cities, trade hubs and their populations. -//! - TODO[2]: `link` - relations such as wars, alliances, roads, commerce. -//! - TODO[3]: `storage` - generic persistence layer (`Store`) with JSON/YAML back-ends. -//! - TODO[4]: `util` - small helpers, ID generation, error types, etc. -//! //! All public types implement `serde::Serialize / Deserialize` so that they can //! be persisted easily. The `World` struct also offers a convenient //! `World::load()` / `World::save()` API that uses the default JSON file diff --git a/lib_efo/src/stats.rs b/lib_efo/src/stats.rs index 8b830f1..b1a5ee0 100644 --- a/lib_efo/src/stats.rs +++ b/lib_efo/src/stats.rs @@ -252,7 +252,7 @@ fn color_cell_categories(cell: CellStruct, value: &GenericStat) -> CellStruct { impl OverallStats { /// Create Stats with a given rng distribution - // TODO[6]: Use an iterator over the stat enum + // TODO(6): Use an iterator over the stat enum pub(crate) fn create_rng( rng: &RngLevel, mut rng_t: &mut ThreadRng, @@ -425,7 +425,7 @@ pub struct StatPair { pub struct Position(isize, isize); /// The grid size, as a static like a degenerate -// TODO[9]: Change to be at least initialized with the world ? +// TODO(9): Change to be at least initialized with the world ? const GRID_SIZE: (i32, i32) = (1920, 1080); /// The size the map is divided into const CHUNK_SIZE: isize = 200; @@ -443,7 +443,7 @@ impl Position { /// Create a random position /// None that there is no concept to either city or continent making this position rather unrelyable - // TODO[2]: Make a create_rng_from_town & create_rng_from_continents + // TODO(2): Make a create_rng_from_town & create_rng_from_continents pub fn create_rng(r: &mut ThreadRng) -> Result { let x = r.random_range(0..GRID_SIZE.0); let y = r.random_range(0..GRID_SIZE.1); @@ -551,7 +551,7 @@ thin_newtype!(FactionId, usize); /// 10-point range for “roll & UI” logic. The trait also exposes the /// underlying raw value and its visibility. /// -// TODO[7]: Change this with Deref+From +// TODO(7): Change this with Deref+From pub trait GameStat { /// Convert the raw integer to a 50-point scale. fn to_100(&self) -> isize { -- 2.45.1 From 7263d3ab72ac11c73267b50e36967d32f17ab74e Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sat, 13 Dec 2025 20:21:47 +0100 Subject: [PATCH 2/7] Adds boc/user doc --- .ignore | 1 + .run_status.toml | 6 ++--- badges/coverage.svg | 2 +- bin_efo/src/commands/entity_generic.rs | 15 ++++++++--- bin_efo/src/main.rs | 33 +++++++++++++++++------ lib_efo/src/epoch/epoch_config.rs | 4 +++ lib_efo/src/epoch/epoch_info.rs | 8 ++++++ lib_efo/src/error.rs | 9 +++++++ lib_efo/src/stats/implementations/test.rs | 2 -- 9 files changed, 62 insertions(+), 18 deletions(-) diff --git a/.ignore b/.ignore index bd01d04..73f8d72 100644 --- a/.ignore +++ b/.ignore @@ -1 +1,2 @@ snapshots +*.svg diff --git a/.run_status.toml b/.run_status.toml index 553a8af..12ed86c 100644 --- a/.run_status.toml +++ b/.run_status.toml @@ -1,8 +1,8 @@ [last_run_clean] run_status = "Success" lines_parsed = 83 -coverage = 51.17 +coverage = 50.17 [last_run_clean.run_duration] -secs = 24 -nanos = 975426411 +secs = 25 +nanos = 72743368 diff --git a/badges/coverage.svg b/badges/coverage.svg index 8819e8f..d697e70 100644 --- a/badges/coverage.svg +++ b/badges/coverage.svg @@ -1 +1 @@ -test-coverage: 51%test-coverage51% \ No newline at end of file +test-coverage: 50%test-coverage50% \ No newline at end of file diff --git a/bin_efo/src/commands/entity_generic.rs b/bin_efo/src/commands/entity_generic.rs index 6f4dcfe..53654f0 100644 --- a/bin_efo/src/commands/entity_generic.rs +++ b/bin_efo/src/commands/entity_generic.rs @@ -193,6 +193,13 @@ fn handle_create_entity( main_epoch: &mut EpochConfig, ) -> Result<(), EpochError> { let epoch_info = main_epoch.try_load_current_as_mut()?; + + if find_entity(entity_args, e_type, epoch_info).is_ok() { + Err(EpochError::EntityAlreadyExist( + entity_args.identifier.clone(), + ))?; + }; + let vec_entities: &mut Vec = vec_entities_mut(e_type, epoch_info); let mut entity = Entity::create_rng(e_type, &entity_args.rng)?; @@ -409,8 +416,8 @@ fn vec_entities<'a>( EntityType::Character => &epoch_info.characters, EntityType::Player => todo!(), EntityType::Town => &epoch_info.towns, - EntityType::Monster => todo!(), - EntityType::Blocker => todo!(), + EntityType::Monster => &epoch_info.calamities, + EntityType::Blocker => &epoch_info.blockers, EntityType::Event => &epoch_info.events, } } @@ -437,8 +444,8 @@ fn vec_entities_mut<'a>( EntityType::Character => &mut epoch_info.characters, EntityType::Player => todo!(), EntityType::Town => &mut epoch_info.towns, - EntityType::Monster => todo!(), - EntityType::Blocker => todo!(), + EntityType::Monster => &mut epoch_info.calamities, + EntityType::Blocker => &mut epoch_info.blockers, EntityType::Event => &mut epoch_info.events, } } diff --git a/bin_efo/src/main.rs b/bin_efo/src/main.rs index 652a527..90958c4 100644 --- a/bin_efo/src/main.rs +++ b/bin_efo/src/main.rs @@ -7,7 +7,6 @@ //! //! * [`epoch`](crate::commands::epoch) - switch / advance time //! * [`event`](crate::commands::entity_generic) - add / remove events -//! * [`org`](crate::commands::entity_generic) - add / remove organisations //! * [`chr`](crate::commands::entity_generic) - add / remove characters //! * [`town`](crate::commands::entity_generic) - add / remove towns //! * [`blocker`](crate::commands::entity_generic) - add / remove blockers @@ -26,7 +25,7 @@ use std::fmt::Debug; -use clap::{ArgAction, Parser, Subcommand}; +use clap::{Parser, Subcommand}; use crate::{ commands::{ @@ -47,10 +46,9 @@ mod success; #[command(name = "efo")] #[command(about = "Epoch Forge - manage organisations over time")] struct Cli { - /// The level of verbosity - #[arg(short, long, action = ArgAction::Count, global = true)] - verbose: u8, - + // /// The level of verbosity + // #[arg(short, long, action = ArgAction::Count, global = true)] + // verbose: u8, #[command(subcommand)] /// The top level command to be executed command: TopLevelCmd, @@ -78,8 +76,15 @@ enum TopLevelCmd { Event(EntitySubCommands), // #[command(subcommand)] // Org(commands::org::OrgCmd), - // #[command(subcommand)] - // Town(commands::town::TownCmd), + /// Handle Towns + #[command(subcommand)] + Town(EntitySubCommands), + /// Handle Calamities + #[command(subcommand)] + Calamity(EntitySubCommands), + /// Handle Blocker + #[command(subcommand)] + Blocker(EntitySubCommands), // Link(commands::link::LinkCmd), /// Generate random structures and display them #[command(subcommand)] @@ -130,5 +135,17 @@ fn exec_dispatch(cli: Cli) -> Result<(), AppError> { &cmd, &lib_efo::stats::EntityType::Event, ), + TopLevelCmd::Town(cmd) => commands::entity_generic::handle_entity_commands( + &cmd, + &lib_efo::stats::EntityType::Town, + ), + TopLevelCmd::Calamity(cmd) => commands::entity_generic::handle_entity_commands( + &cmd, + &lib_efo::stats::EntityType::Monster, + ), + TopLevelCmd::Blocker(cmd) => commands::entity_generic::handle_entity_commands( + &cmd, + &lib_efo::stats::EntityType::Blocker, + ), } } diff --git a/lib_efo/src/epoch/epoch_config.rs b/lib_efo/src/epoch/epoch_config.rs index 5836979..c83d0b3 100644 --- a/lib_efo/src/epoch/epoch_config.rs +++ b/lib_efo/src/epoch/epoch_config.rs @@ -391,6 +391,8 @@ impl EpochConfig { /// * `Err(EpochError::EntityNotFoundById(id))` - No entity with the /// supplied UUID exists in the epoch. /// + #[allow(dead_code)] + // TODO: Add to a generic show unsafe fn find_entity(&self, id: Uuid) -> Result<&Entity, EpochError> { let epoch_info = unsafe { self.try_load_id(self.epoch_id) }?; let predicate = |entity: &&Entity| entity.id == id; @@ -400,6 +402,8 @@ impl EpochConfig { .find(predicate) .or(epoch_info.characters.iter().find(predicate)) .or(epoch_info.towns.iter().find(predicate)) + .or(epoch_info.blockers.iter().find(predicate)) + .or(epoch_info.calamities.iter().find(predicate)) .ok_or(EpochError::EntityNotFoundById(id)) } } diff --git a/lib_efo/src/epoch/epoch_info.rs b/lib_efo/src/epoch/epoch_info.rs index bd37874..918015c 100644 --- a/lib_efo/src/epoch/epoch_info.rs +++ b/lib_efo/src/epoch/epoch_info.rs @@ -63,6 +63,12 @@ pub struct EpochInfo { #[table(skip)] /// The list of towns currently present pub towns: Vec, + #[table(skip)] + /// The list of calamities currently present + pub calamities: Vec, + #[table(skip)] + /// The list of blockers currently present + pub blockers: Vec, } impl Prettiable for EpochInfo {} @@ -77,6 +83,8 @@ impl Default for EpochInfo { events: Vec::new(), characters: Vec::new(), towns: Vec::new(), + calamities: Vec::new(), + blockers: Vec::new(), } } } diff --git a/lib_efo/src/error.rs b/lib_efo/src/error.rs index fa0e869..c503ed4 100644 --- a/lib_efo/src/error.rs +++ b/lib_efo/src/error.rs @@ -311,6 +311,15 @@ pub enum EpochError { #[diagnostic(code(EntityIdentifierError::InvalidIdentifier))] #[help("Verify that the UUID after `@` is a valid id.")] EmptyIdentifier, + + /// The entity already exists. + #[error("Failed to create entity: {0:?} already exists")] + #[diagnostic(code(EntityError::EntityAlreadyExist))] + #[help( + "Ensure that the entity name or ID is unique before creating a new one. \ + You may need to delete or rename the existing entity." + )] + EntityAlreadyExist(Option), } /// A small enum of explicit user-facing error messages. diff --git a/lib_efo/src/stats/implementations/test.rs b/lib_efo/src/stats/implementations/test.rs index c331dda..8fab056 100644 --- a/lib_efo/src/stats/implementations/test.rs +++ b/lib_efo/src/stats/implementations/test.rs @@ -1,9 +1,7 @@ #![allow(clippy::unwrap_used)] -use insta::assert_debug_snapshot; use insta::assert_snapshot; use super::*; -use crate::entity::Entity; use crate::stats::GameStat; use crate::stats::GenericStat; use crate::stats::StatPair; -- 2.45.1 From 8b9df96a5aacf89f8f71461c4af5be94952bec4b Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sat, 13 Dec 2025 23:39:01 +0100 Subject: [PATCH 3/7] Adds the results of alpha testing fixes --- Cargo.lock | 34 +++++++------- bin_efo/Cargo.toml | 2 +- bin_efo/src/commands/entity_generic.rs | 2 +- bin_efo/src/commands/epoch.rs | 5 ++- bin_efo/src/commands/epoch/cli_epoch.rs | 16 ++++++- bin_efo/src/commands/init.rs | 4 +- bin_efo/src/success.rs | 10 +++-- lib_efo/src/entity/implementations.rs | 28 ++---------- ...__test__snapshot_full_oneline_display.snap | 2 +- lib_efo/src/epoch/epoch_config.rs | 2 +- lib_efo/src/epoch/epoch_traits.rs | 18 ++++---- lib_efo/src/error.rs | 45 +++++++++++-------- lib_efo/src/utils.rs | 36 +++++++++++++++ 13 files changed, 120 insertions(+), 84 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1d8352a..d7d9682 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -100,23 +100,6 @@ dependencies = [ "backtrace", ] -[[package]] -name = "bin_efo" -version = "0.1.0" -dependencies = [ - "clap", - "colored", - "derive_more", - "env_logger", - "insta", - "lib_efo", - "log", - "miette", - "serde", - "serde_json", - "thiserror", -] - [[package]] name = "bitflags" version = "2.10.0" @@ -278,6 +261,23 @@ dependencies = [ "unicode-xid", ] +[[package]] +name = "efo" +version = "0.1.0" +dependencies = [ + "clap", + "colored", + "derive_more", + "env_logger", + "insta", + "lib_efo", + "log", + "miette", + "serde", + "serde_json", + "thiserror", +] + [[package]] name = "encode_unicode" version = "1.0.0" diff --git a/bin_efo/Cargo.toml b/bin_efo/Cargo.toml index 1accc67..652059b 100644 --- a/bin_efo/Cargo.toml +++ b/bin_efo/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "bin_efo" +name = "efo" version = "0.1.0" edition = "2024" diff --git a/bin_efo/src/commands/entity_generic.rs b/bin_efo/src/commands/entity_generic.rs index 53654f0..78df840 100644 --- a/bin_efo/src/commands/entity_generic.rs +++ b/bin_efo/src/commands/entity_generic.rs @@ -117,7 +117,7 @@ pub struct EntityArgs { #[arg(long, short, action = clap::ArgAction::SetTrue, default_value_t = false)] pub delta: bool, - /// Non specified stat Repartition + /// The type of rng stat repartition #[arg(value_enum, long, default_value_t = RngLevel::Zero)] pub rng: RngLevel, diff --git a/bin_efo/src/commands/epoch.rs b/bin_efo/src/commands/epoch.rs index ed7937c..4305b22 100644 --- a/bin_efo/src/commands/epoch.rs +++ b/bin_efo/src/commands/epoch.rs @@ -175,13 +175,14 @@ fn handle_log(args: &cli_epoch::Log, main_epoch: &mut EpochConfig) -> Result<(), fn handle_switch(args: &cli_epoch::Switch, main_epoch: &mut EpochConfig) -> Result<(), AppError> { let target = main_epoch.get_epoch_id(&args.target)?; main_epoch.try_load(&target)?; + let message = &SuccessMessages::EpochSwitchSuccess(target, main_epoch.epoch_id); main_epoch.epoch_id = target; main_epoch.save_with_context( "Saving modified epoch config", &lib_efo::epoch::SaveMode::Erase, )?; - display_success(&SuccessMessages::EpochSwitchSuccess(target)); + display_success(message); Ok(()) } @@ -286,6 +287,7 @@ fn handle_taging(args: &cli_epoch::Tag, main_epoch: &mut EpochConfig) -> Result< .get_mut(&main_epoch.epoch_id) .ok_or(EpochError::EpochHashingImpossible(file!(), line!()))? { + let message = &SuccessMessages::TagAdded(args.tag.clone(), current_epoch_info.epoch_id); current_epoch_info.tags.push(args.tag.clone()); current_epoch_info .save_with_context("Saving modified epoch", &lib_efo::epoch::SaveMode::Erase)?; @@ -296,6 +298,7 @@ fn handle_taging(args: &cli_epoch::Tag, main_epoch: &mut EpochConfig) -> Result< "Saving modified main config", &lib_efo::epoch::SaveMode::Erase, )?; + display_success(message); Ok(()) } else { Err(AppError::Epoch(lib_efo::error::EpochError::Unknown( diff --git a/bin_efo/src/commands/epoch/cli_epoch.rs b/bin_efo/src/commands/epoch/cli_epoch.rs index bb7aa2f..74f5c60 100644 --- a/bin_efo/src/commands/epoch/cli_epoch.rs +++ b/bin_efo/src/commands/epoch/cli_epoch.rs @@ -15,7 +15,7 @@ #![warn(missing_docs, clippy::missing_docs_in_private_items)] -use clap::{Args, Subcommand}; +use clap::{Args, Subcommand, builder::ValueParser}; use lib_efo::epoch::EpochIdentifier; /// Top-level sub-command for the `efo epoch` command. @@ -109,11 +109,23 @@ pub struct Diff { /// * `tag` - The tag to tag the current epoch with. #[derive(Args, Debug)] pub struct Tag { - #[arg(required = true)] + #[arg(required = true, value_parser = ValueParser::from(validate_tag))] #[allow(clippy::missing_docs_in_private_items)] pub tag: String, } +/// Return an error if the supplied tag contains only digits. +/// +/// Clap will call this for every value it parses, so we can abort +/// parsing immediately when an invalid tag is encountered. +fn validate_tag(tag: &str) -> Result { + if tag.chars().all(|c| c.is_ascii_digit()) { + Err(format!("Tag '{}' cannot be purely numeric", tag)) + } else { + Ok(tag.to_string()) + } +} + /// Performs basic filesystem level maintenance. #[derive(Debug, Args)] pub struct Fsck {} diff --git a/bin_efo/src/commands/init.rs b/bin_efo/src/commands/init.rs index 2f9d759..17c4539 100644 --- a/bin_efo/src/commands/init.rs +++ b/bin_efo/src/commands/init.rs @@ -65,9 +65,9 @@ pub fn init(args: &InitCmd) -> Result<(), AppError> { let epoch_config = EpochConfig::default(); let root = epoch_config.save_folder(); - if read_dir(root)?.count() != 0 { + if read_dir(&root)?.count() != 0 { Err(EpochError::FolderNotEmpty { - name: None, + name: root, show_label: None, })?; } diff --git a/bin_efo/src/success.rs b/bin_efo/src/success.rs index 702b1af..568832a 100644 --- a/bin_efo/src/success.rs +++ b/bin_efo/src/success.rs @@ -7,11 +7,11 @@ use lib_efo::epoch::EpochId; #[derive(Display, Clone, Debug)] #[allow(missing_docs, clippy::missing_docs_in_private_items)] pub enum SuccessMessages { - #[display("Switched to epoch {_0}")] - EpochSwitchSuccess(lib_efo::epoch::EpochId), + #[display("Switched to epoch {_0} (was {_1})")] + EpochSwitchSuccess(EpochId, EpochId), #[display("All future events deleted - back to epoch {_0}")] - DeletedAllFutureEvents(lib_efo::epoch::EpochId), + DeletedAllFutureEvents(EpochId), #[display("The folder was initialized as an epoch folder")] FolderInitializedSuccessfully(&'static str), @@ -31,7 +31,9 @@ pub enum SuccessMessages { #[display("Successfully edited the entity {_0} ({_1} 󰻾[{_2}])")] EditedEntity(String, String, String), #[display("Showing delta between Epoch ({_0} & {_1})")] - DiffBetweenEpoch(lib_efo::epoch::EpochId, lib_efo::epoch::EpochId), + DiffBetweenEpoch(lib_efo::epoch::EpochId, EpochId), + #[display("Added tag {_0} to epoch {_1}")] + TagAdded(String, EpochId), } /// Display the success message to stdout diff --git a/lib_efo/src/entity/implementations.rs b/lib_efo/src/entity/implementations.rs index 99afaa1..dadcb22 100644 --- a/lib_efo/src/entity/implementations.rs +++ b/lib_efo/src/entity/implementations.rs @@ -6,12 +6,12 @@ use colored::*; use rand::distr::Distribution; use uuid::Uuid; // [3] - colored-rs examples -use crate::Displayable; use crate::entity::{EffectApplication, EffectBounds, Entity, EntityDuration}; use crate::epoch::epoch_traits::Diffable; use crate::error::EpochError; use crate::stats::{EntityType, GenericStat, MetaStats, OverallStats, Position, StatPair, Symbols}; use crate::utils::RngLevel; +use crate::{Displayable, items_table}; // ---------- Implementation ---------- impl Displayable for Entity { @@ -40,7 +40,7 @@ impl Displayable for Entity { .unwrap_or_default(); let prestige = if *self.metadata.prestige > 0 { - format!(" {:2}{}", self.metadata.prestige, "📈".yellow()) + format!(" {:2}{}", self.metadata.prestige, " ".yellow()) } else { String::new() }; @@ -125,29 +125,7 @@ impl Entity { &self, items: Vec<&OverallStats>, ) -> Result { - items - .with_title() - .bold(true) - .border( - Border::builder() - .top(HorizontalLine::new('┌', '┐', '┬', '─')) - .bottom(HorizontalLine::new('└', '┘', '┴', '─')) - .left(VerticalLine::new('│')) - .right(VerticalLine::new('│')) - .build(), - ) - .separator( - Separator::builder() - .column(Some(VerticalLine::new('│'))) - .row(Some(HorizontalLine::new('├', '┤', '┼', '─'))) - .build(), - ) - // .foreground_color(Some(cli_table::Color::Blue)) // Border Color - .display() - .map_err(|_e| EpochError::TableStringConversionError { - name: self.name.clone(), - id: self.id, - }) + items_table!(items, self.name.clone(), self.id) } /// Pretty-print the entity as a coloured tree. diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_oneline_display.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_oneline_display.snap index 3f3d182..091b449 100644 --- a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_oneline_display.snap +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_oneline_display.snap @@ -3,6 +3,6 @@ source: lib_efo/src/entity/test.rs expression: e.oneline_display() --- ├──┬─ 0c00000 Hero  ──────> ( 2, 4)⚓ ⧗10 -│ ├─ Faction: 2 │ Effect: ⟳ (1 ⭾ 5), Stats: 0 0💰 0 0󰡢 3📈 +│ ├─ Faction: 2 │ Effect: ⟳ (1 ⭾ 5), Stats: 0 0💰 0 0󰡢 3 │ └─  󰻾[50]  󰻾[11] │ diff --git a/lib_efo/src/epoch/epoch_config.rs b/lib_efo/src/epoch/epoch_config.rs index c83d0b3..754fdac 100644 --- a/lib_efo/src/epoch/epoch_config.rs +++ b/lib_efo/src/epoch/epoch_config.rs @@ -365,7 +365,7 @@ impl EpochConfig { items_to_log.push(info); } } - EpochInfo::show_as_table(items_to_log); + println!("{}", EpochInfo::as_table(items_to_log)?); Ok(()) } diff --git a/lib_efo/src/epoch/epoch_traits.rs b/lib_efo/src/epoch/epoch_traits.rs index 94b2346..9fd4488 100644 --- a/lib_efo/src/epoch/epoch_traits.rs +++ b/lib_efo/src/epoch/epoch_traits.rs @@ -5,11 +5,15 @@ //! common to many of the library's element types. #![warn(clippy::missing_docs_in_private_items)] -use cli_table::{Style, Table, WithTitle}; +use cli_table::{ + Style, Table, WithTitle, + format::{Border, HorizontalLine, Separator, VerticalLine}, +}; use serde::Serialize; use std::{fmt::Display, fs::File, io::Write}; +use uuid::Uuid; -use crate::{epoch::SaveMode, error::EpochError}; +use crate::{epoch::SaveMode, error::EpochError, items_table}; /// Elements that can be compared with another instance to produce a diff. pub trait Diffable { @@ -29,17 +33,11 @@ pub trait Nextable {} /// Elements that can be rendered into a pretty, human-readable form. pub trait Prettiable: Display { /// Shows many items as a table. - /// - /// The table is printed to `stdout` using the `cli_table` crate. - /// - /// # Panics - /// Panics if printing the table to stdout fails. - fn show_as_table(list: Vec<&Self>) + fn as_table(list: Vec<&Self>) -> std::result::Result where for<'a> Vec<&'a Self>: Table + WithTitle, { - #[allow(clippy::unwrap_used)] // There is no recovery of not being able to print a table - cli_table::print_stdout(list.with_title().bold(true)).unwrap(); + items_table!(list, "Converting to table".to_string(), Uuid::nil()) } /// Displays the struct as a log entry by printing the output of diff --git a/lib_efo/src/error.rs b/lib_efo/src/error.rs index c503ed4..d524de7 100644 --- a/lib_efo/src/error.rs +++ b/lib_efo/src/error.rs @@ -63,7 +63,7 @@ pub enum EpochError { /// Failed to create the epoch configuration. #[error("Failed to create the epoch configuration")] - #[help("Make sure the path is writable")] + #[diagnostic(help("Make sure the path is writable"))] #[diagnostic(code(EpochError::ConfigCreation))] ConfigCreation(String, #[source] std::io::Error), @@ -77,13 +77,13 @@ pub enum EpochError { }, /// This directory isn't empty and thus cannot be initialized. - #[error("This directory {name:?} isn't empty and thus cannot be initialized")] + #[error("This directory {name} isn't empty and thus cannot be initialized")] #[diagnostic(code(EpochError::FolderNotEmpty))] - #[diagnostic(help("Empty the folder or remove its content first"))] + #[diagnostic(help("Empty the folder contents first"))] FolderNotEmpty { #[source_code] /// Name of the file causing problem - name: Option, + name: String, /// Trick used to have a cute line showing the following error message #[label("This file is present and forbid the command to execute properly")] show_label: Option<(usize, usize)>, @@ -123,6 +123,9 @@ pub enum EpochError { /// The epoch folder for the target id is missing. #[error("Missing directory for epoch {0} at `{1}`")] #[diagnostic(code(EpochError::EpochFolderMissing))] + #[diagnostic(help( + "Ensure that the epoch was initialized and {0} refers to an existing epoch" + ))] EpochFolderMissing(EpochId, PathBuf), /// A future epoch exists, forbidding you to compute `next` and overriding them. @@ -243,48 +246,50 @@ pub enum EpochError { /// given epoch index. #[error("Epoch hashing failed for `{0}` (index {1})")] #[diagnostic(code(EpochError::EpochHashingImpossible))] - #[help("This is an internal error. Please file a bug report.")] + #[diagnostic(help("This is an internal error. Please file a bug report."))] EpochHashingImpossible(&'static str, u32), /// The entity with id **`{0}`** could not be found. #[error("Entity of type with id {0:?} not found")] #[diagnostic(code(epoch::entity_not_found_by_id))] - #[help( + #[diagnostic(help( "Verify that the identifier is correct and that the entity exists in the current epoch." - )] + ))] EntityNotFoundById(Uuid), /// The entity could not be found #[error("Entity of type {0:?} with name {1:?} not found")] #[diagnostic(code(epoch::entity_not_found))] - #[help( + #[diagnostic(help( "Verify that the identifier is correct and that the entity exists in the current epoch." - )] + ))] EntityNotFound(EntityType, Option), /// The requested uniform RNG could not be created because the supplied /// distribution parameters were invalid. #[error("Failed to create uniform RNG: {0}")] #[diagnostic(code(EpochError::UniformRngCreation))] - #[help("Ensure that the supplied range bounds satisfy `min < max`.")] + #[diagnostic(help("Ensure that the supplied range bounds satisfy `min < max`."))] UniformRngCreation(#[from] rand::distr::uniform::Error), /// The string did not contain exactly two comma-separated values. #[error("Invalid position format: expected \"x,y\" found {0}")] #[diagnostic(code(EpochError::InvalidPositionFormat))] - #[help("Provide exactly two numbers separated by a comma.")] + #[diagnostic(help("Provide exactly two numbers separated by a comma."))] InvalidPositionFormat(String), /// One of the components failed to parse as an `isize`. #[error("Failed to parse integer: {0}")] #[diagnostic(code(EpochError::ParsePositionError))] - #[help("Ensure that the input is a valid integer.")] + #[diagnostic(help("Ensure that the input is a valid integer."))] ParsePositionError(String), /// Failed to render a table into its string representation. #[error("Failed to render table {name} [{id}] as string")] #[diagnostic(code(EpochError::TableStringConversion))] - #[help("Verify that the table data and schema are compatible with string rendering.")] + #[diagnostic(help( + "Verify that the table data and schema are compatible with string rendering." + ))] TableStringConversionError { /// The logical name of the table that failed to convert. name: String, @@ -295,30 +300,32 @@ pub enum EpochError { /// Failed to parse a duration string. #[error("Failed to parse duration: {0}:{1}")] #[diagnostic(code(EpochError::ParsingDuration))] - #[help( + #[diagnostic(help( "Verify that the duration string follows the expected syntax, `permanent` or `duration:X` or `done`." - )] + ))] ParsingDuration(&'static str, String), /// Failed to parse a bounds string. #[error("Failed to parse bounds: {0}:{1}")] #[diagnostic(code(EpochError::ParsingBounds))] - #[help("Verify that the bounds string follows the expected syntax, `X-X` or `X:X`.")] + #[diagnostic(help( + "Verify that the bounds string follows the expected syntax, `X-X` or `X:X`." + ))] ParsingBounds(&'static str, String), /// The value started with `@` but the remainder was not a valid id or the name was empty. #[error("Failed to parse identifier or name")] #[diagnostic(code(EntityIdentifierError::InvalidIdentifier))] - #[help("Verify that the UUID after `@` is a valid id.")] + #[diagnostic(help("Verify that the UUID after `@` is a valid id."))] EmptyIdentifier, /// The entity already exists. #[error("Failed to create entity: {0:?} already exists")] #[diagnostic(code(EntityError::EntityAlreadyExist))] - #[help( + #[diagnostic(help( "Ensure that the entity name or ID is unique before creating a new one. \ You may need to delete or rename the existing entity." - )] + ))] EntityAlreadyExist(Option), } diff --git a/lib_efo/src/utils.rs b/lib_efo/src/utils.rs index fc965cd..7d6c46e 100644 --- a/lib_efo/src/utils.rs +++ b/lib_efo/src/utils.rs @@ -52,3 +52,39 @@ impl RngLevel { Ok(Uniform::try_from(self.to_range())?) } } + +/// Build a table with the exact border / separator style you posted +/// and return the rendered string. +/// +/// # Parameters +/// * `$items` – A table builder that implements the `Table` trait +/// (e.g. `Vec>.into_table()`, `items.into_table()`, …). +/// * `$name` – The name that should be stored in `EpochError::TableStringConversionError`. +/// * `$id` – The id that should be stored in `EpochError::TableStringConversionError`. +#[macro_export] +macro_rules! items_table { + ($items:expr, $name:expr, $id:expr) => {{ + $items + .with_title() + .bold(true) + .border( + Border::builder() + .top(HorizontalLine::new('┌', '┐', '┬', '─')) + .bottom(HorizontalLine::new('└', '┘', '┴', '─')) + .left(VerticalLine::new('│')) + .right(VerticalLine::new('│')) + .build(), + ) + .separator( + Separator::builder() + .column(Some(VerticalLine::new('│'))) + .row(Some(HorizontalLine::new('├', '┤', '┼', '─'))) + .build(), + ) + .display() + .map_err(|_e| EpochError::TableStringConversionError { + name: $name.clone(), + id: $id, + }) + }}; +} -- 2.45.1 From cd7140822335edee443f8075bf91028d93cac65e Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 14 Dec 2025 02:37:58 +0100 Subject: [PATCH 4/7] Adds more sense in the Uuid --- bin_efo/src/commands/entity_generic.rs | 321 +++++------------- .../entity_generic/helper_functions.rs | 204 +++++++++++ bin_efo/src/error.rs | 8 +- lib_efo/src/entity.rs | 36 +- lib_efo/src/entity/implementations.rs | 9 +- ...entity__test__snapshot_entity_delta-2.snap | 2 +- ...entity__test__snapshot_entity_delta-3.snap | 2 +- ...__entity__test__snapshot_entity_delta.snap | 2 +- ...test__snapshot_full_oneline_display-2.snap | 4 +- ...__test__snapshot_full_oneline_display.snap | 2 +- ...ty__test__snapshot_meta_stats_delta-2.snap | 6 +- ...ty__test__snapshot_meta_stats_delta-3.snap | 2 +- ...tity__test__snapshot_meta_stats_delta.snap | 2 +- lib_efo/src/entity/test.rs | 22 +- lib_efo/src/epoch/epoch_config.rs | 1 - lib_efo/src/error.rs | 16 +- lib_efo/src/lib.rs | 2 +- lib_efo/src/stats.rs | 14 +- lib_efo/src/stats/implementations.rs | 197 ++++++++--- .../src/stats/implementations/from_impl.rs | 2 +- lib_efo/src/stats/implementations/test.rs | 18 +- 21 files changed, 523 insertions(+), 349 deletions(-) create mode 100644 bin_efo/src/commands/entity_generic/helper_functions.rs diff --git a/bin_efo/src/commands/entity_generic.rs b/bin_efo/src/commands/entity_generic.rs index 78df840..5ab2ed3 100644 --- a/bin_efo/src/commands/entity_generic.rs +++ b/bin_efo/src/commands/entity_generic.rs @@ -62,43 +62,79 @@ //! //! *All changes are persisted immediately to the epoch file after the command finishes.* -use lib_efo::entity::{EffectApplication, EffectBounds, EntityDuration, EntityIdentifier}; -use lib_efo::epoch::epoch_traits::{ConfigWritable, Diffable}; -use lib_efo::naming::NAMING; -use lib_efo::stats::{Position, Symbols}; - use clap::{Args, Subcommand}; -use lib_efo::Displayable; -use lib_efo::utils::RngLevel; use lib_efo::{ - entity::Entity, - epoch::EpochConfig, + Displayable, + entity::{EffectApplication, EffectBounds, Entity, EntityDuration, EntityIdentifier}, + epoch::{ + EpochConfig, EpochIdentifier, + epoch_traits::{ConfigWritable, Diffable}, + }, error::EpochError, - stats::{EntityType, StatPair}, + stats::{EntityType, FactionId, Position, StatPair, Symbols}, + utils::RngLevel, }; use log::info; use crate::error::AppError; use crate::success::display_success; +mod helper_functions; + /// Commands that operate on an entity. /// /// Each variant represents a different operation that can be performed on an /// entity. The variant holds the arguments that are common to all operations. #[derive(Subcommand, Debug)] -pub enum EntitySubCommands { +pub(crate) enum EntitySubCommands { /// Add an entity Add(EntityArgs), /// Delete an entity - Del(EntityArgs), + Del(DelArgs), /// Edit an existing entity Edit(EntityArgs), - /// Find an entity by its identifier - Find(EntityArgs), + // /// Find an entity by its identifier + // Find(EntityArgs), /// Show the details of an entity - Show(EntityArgs), + Show(ShowArgs), /// Show differences between two entities - Diff(EntityArgs), + Diff(DiffArgs), +} + +#[derive(Args, Debug)] +/// Arguments reserved for diffing +pub(crate) struct DiffArgs { + /// The identifier either a name or a @tag + identifier: EntityIdentifier, + + /// Another epoch than the previous + epoch_id: Option, +} + +#[derive(Args, Debug)] +/// Arguments required for any entity deletion +pub(crate) struct DelArgs { + /// The identifier either a name or a @tag + identifier: EntityIdentifier, +} + +#[derive(Args, Debug)] +/// Arguments required for showing any entity +pub(crate) struct ShowArgs { + /// The identifier either a name or a @tag + #[arg(long, short)] + identifier: Option, + + #[arg(long, short)] + /// Show only if belonging to faction + faction: Option, + // /// Show only if in a specific town + // #[arg(long, short)] + // town: Option, + // // + // /// Show only if not done + // #[arg(long, short, action = clap::ArgAction::SetTrue, default_value_t = Some(false))] + // valid: Option, } /// Arguments required for any entity operation. @@ -173,9 +209,9 @@ pub fn handle_entity_commands( EntitySubCommands::Edit(entity_args) => { handle_edit_entity(entity_args, e_type, &mut main_epoch) } - EntitySubCommands::Find(entity_args) => { - handle_find_entity(entity_args, e_type, &mut main_epoch) - } + // EntitySubCommands::Find(entity_args) => { + // handle_find_entity(entity_args, e_type, &mut main_epoch) + // } EntitySubCommands::Show(entity_args) => { handle_show_entity(entity_args, e_type, &mut main_epoch) } @@ -194,20 +230,20 @@ fn handle_create_entity( ) -> Result<(), EpochError> { let epoch_info = main_epoch.try_load_current_as_mut()?; - if find_entity(entity_args, e_type, epoch_info).is_ok() { + if helper_functions::find_entity(&entity_args.identifier, e_type, epoch_info).is_ok() { Err(EpochError::EntityAlreadyExist( entity_args.identifier.clone(), ))?; }; - let vec_entities: &mut Vec = vec_entities_mut(e_type, epoch_info); + let vec_entities: &mut Vec = helper_functions::vec_entities_mut(e_type, epoch_info); let mut entity = Entity::create_rng(e_type, &entity_args.rng)?; - update_stats(entity_args, &mut entity); + helper_functions::update_stats(entity_args, &mut entity); // Specifying a name means the name needs to be changed // Specifying an id however means nothing and should be ignored - update_defaults(entity_args, &mut entity); + helper_functions::update_defaults(entity_args, &mut entity); info!("Created character: {:#?}", entity); entity.print_full(); @@ -227,19 +263,20 @@ fn handle_create_entity( /// Function handler for the delete subcommand fn handle_delete_entity( - entity_args: &EntityArgs, + entity_args: &DelArgs, e_type: &EntityType, main_epoch: &mut EpochConfig, ) -> Result<(), EpochError> { let epoch_info = main_epoch.try_load_current_as_mut()?; - let vec_entities: &mut Vec = vec_entities_mut(e_type, epoch_info); + let entity_identifier = Some(entity_args.identifier.clone()); + let vec_entities: &mut Vec = helper_functions::vec_entities_mut(e_type, epoch_info); let index = vec_entities .iter() - .position(|e| find_by_args(e, entity_args)) + .position(|entity| helper_functions::find_by_args(entity, &entity_identifier)) .ok_or(EpochError::EntityNotFound( e_type.clone(), - entity_args.identifier.clone(), + entity_identifier, ))?; let entity = vec_entities.swap_remove(index); @@ -255,20 +292,25 @@ fn handle_delete_entity( /// Function handler for the diff subcommand fn handle_diff_entity( - entity_args: &EntityArgs, + entity_args: &DiffArgs, e_type: &EntityType, main_epoch: &mut EpochConfig, ) -> Result<(), EpochError> { // Load the epochs to diff let id = main_epoch.epoch_id; - let id2 = main_epoch.epoch_id.add_to_epoch(-1); + let id2 = if let Some(old_id) = &entity_args.epoch_id { + main_epoch.get_epoch_id(old_id)? + } else { + main_epoch.epoch_id.add_to_epoch(-1) + }; main_epoch.try_load(&id)?; main_epoch.try_load(&id2)?; let epoch_current = unsafe { main_epoch.try_load_id(id) }?; let epoch_past = unsafe { main_epoch.try_load_id(id2) }?; - let current_entity = find_entity(entity_args, e_type, epoch_current)?; - let past_entity = find_entity(entity_args, e_type, epoch_past)?; + let binding = Some(entity_args.identifier.clone()); + let current_entity = helper_functions::find_entity(&binding, e_type, epoch_current)?; + let past_entity = helper_functions::find_entity(&binding, e_type, epoch_past)?; let diff = current_entity.delta(past_entity); display_success(&crate::success::SuccessMessages::DiffBetweenEpoch(id, id2)); @@ -280,30 +322,30 @@ fn handle_diff_entity( /// Function handler for the show subcommand // TODO: Add filters else this will become very clustered fn handle_show_entity( - entity_args: &EntityArgs, + entity_args: &ShowArgs, e_type: &EntityType, main_epoch: &mut EpochConfig, ) -> Result<(), EpochError> { let epoch_info = main_epoch.try_load_current()?; if entity_args.identifier.is_none() { - for entity in vec_entities(e_type, epoch_info) { + for entity in helper_functions::vec_entities(e_type, epoch_info) { entity.print_oneline(); } } else { - let entity = find_entity(entity_args, e_type, epoch_info)?; + let entity = helper_functions::find_entity(&entity_args.identifier, e_type, epoch_info)?; entity.print_full(); } Ok(()) } -/// Function handler for the find subcommand -fn handle_find_entity( - entity_args: &EntityArgs, - e_type: &EntityType, - main_epoch: &mut EpochConfig, -) -> Result<(), EpochError> { - handle_show_entity(entity_args, e_type, main_epoch) -} +// /// Function handler for the find subcommand +// fn handle_find_entity( +// entity_args: &EntityArgs, +// e_type: &EntityType, +// main_epoch: &mut EpochConfig, +// ) -> Result<(), EpochError> { +// handle_show_entity(entity_args, e_type, main_epoch) +// } /// Function handler for the edit subcommand fn handle_edit_entity( @@ -312,10 +354,10 @@ fn handle_edit_entity( main_epoch: &mut EpochConfig, ) -> Result<(), EpochError> { let epoch_info = main_epoch.try_load_current_as_mut()?; - let vec_entities = vec_entities_mut(e_type, epoch_info); + let vec_entities = helper_functions::vec_entities_mut(e_type, epoch_info); let entity = vec_entities .iter_mut() - .find(|e| find_by_args(e, entity_args)) + .find(|entity| helper_functions::find_by_args(entity, &entity_args.identifier)) .ok_or(EpochError::EntityNotFound( e_type.clone(), entity_args.identifier.clone(), @@ -351,194 +393,3 @@ fn handle_edit_entity( display_success(message); Ok(()) } - -/// Update the given stats with the given argumenbts -/// Note that this function will not change name & id due to the usage variance between caller -fn update_stats(entity_args: &EntityArgs, e: &mut Entity) { - if entity_args.delta { - for stat in &entity_args.stats { - e.delta_stat(stat.clone()); - } - } else { - for stat in &entity_args.stats { - e.change_stat(stat.clone()); - } - } -} - -/// Looks up an entity inside the given `epoch_info` according to the -/// supplied arguments. -/// -/// The function returns a reference to the matching entity or an -/// `EpochError::EntityNotFound` if no entity matches. -/// -/// # Arguments -/// * `entity_args` - The arguments that identify the entity. -/// * `e_type` - The type of entity to look for. -/// * `epoch_info` - The epoch that contains all entities. -/// -/// # Returns -/// * `Ok(&Entity)` - The entity that matches the arguments. -/// * `Err(EpochError::EntityNotFound)` - No matching entity was found. -fn find_entity<'a>( - entity_args: &'a EntityArgs, - e_type: &'a EntityType, - epoch_info: &'a lib_efo::epoch::EpochInfo, -) -> Result<&'a Entity, EpochError> { - vec_entities(e_type, epoch_info) - .iter() - .find(|&e| find_by_args(e, entity_args)) - .ok_or(EpochError::EntityNotFound( - e_type.clone(), - entity_args.identifier.clone(), - )) -} - -/// Returns a slice over the entities of the requested type from the given `EpochInfo`. -/// -/// The function matches the supplied `e_type` to the appropriate collection -/// inside `epoch_info`. For unimplemented entity types the call will panic -/// because of the `todo!()` placeholder. -/// -/// # Arguments -/// * `e_type` - The type of entities to retrieve. -/// * `epoch_info` - The epoch information containing the collections. -/// -/// # Returns -/// A reference to the vector containing the requested entities. -/// The lifetime of the returned slice is tied to that of `epoch_info`. -#[inline] -fn vec_entities<'a>( - e_type: &'a EntityType, - epoch_info: &'a lib_efo::epoch::EpochInfo, -) -> &'a Vec { - match e_type { - EntityType::Character => &epoch_info.characters, - EntityType::Player => todo!(), - EntityType::Town => &epoch_info.towns, - EntityType::Monster => &epoch_info.calamities, - EntityType::Blocker => &epoch_info.blockers, - EntityType::Event => &epoch_info.events, - } -} - -#[inline] -/// Returns a mutable slice over the entities of the requested type from the given -/// `EpochInfo`. -/// -/// Like `vec_entities`, this function selects the appropriate collection -/// based on `e_type`. Unimplemented variants will panic due to the `todo!()`. -/// -/// # Arguments -/// * `e_type` - The type of entities to retrieve. -/// * `epoch_info` - The epoch information containing the collections. -/// -/// # Returns -/// A mutable reference to the vector containing the requested entities. -/// The lifetime of the returned slice is tied to that of `epoch_info`. -fn vec_entities_mut<'a>( - e_type: &'a EntityType, - epoch_info: &'a mut lib_efo::epoch::EpochInfo, -) -> &'a mut Vec { - match e_type { - EntityType::Character => &mut epoch_info.characters, - EntityType::Player => todo!(), - EntityType::Town => &mut epoch_info.towns, - EntityType::Monster => &mut epoch_info.calamities, - EntityType::Blocker => &mut epoch_info.blockers, - EntityType::Event => &mut epoch_info.events, - } -} - -/// Helper function finding by name, note that a lot more helpers could be done to find by other criterias -fn find_by_args(entity: &Entity, entity_args: &EntityArgs) -> bool { - match entity_args.identifier { - Some(EntityIdentifier::Name(ref name)) => entity.name.starts_with(name), - Some(EntityIdentifier::Id(ref id)) => entity.id.hyphenated().to_string().starts_with(id), - None => false, - } -} - -/// Find an entity matching a tag -#[allow(dead_code)] -fn find_by_id<'a>(entities: &'a [Entity], id: &'a String) -> Option<&'a Entity> { - entities - .iter() - .find(|e| e.id.hyphenated().to_string().starts_with(id)) -} - -/// Find an entity matching a name -#[allow(dead_code)] -fn find_by_name<'a>(entities: &'a [Entity], id: &'a String) -> Option<&'a Entity> { - entities.iter().find(|e| e.name.starts_with(id)) -} - -/// Update the default values of the entity with sensible defaults -fn update_defaults(entity_args: &EntityArgs, e: &mut Entity) { - let entity_type = &e.entity_type; - - let (duration, effect, bounds, name) = match entity_type { - EntityType::Character => ( - lib_efo::entity::EntityDuration::Permanent, - lib_efo::entity::EffectApplication::WhenPresent, - EffectBounds { min: 20, max: 110 }, - NAMING.generate_character_name(), - ), - EntityType::Player => ( - lib_efo::entity::EntityDuration::Permanent, - lib_efo::entity::EffectApplication::WhenPresent, - EffectBounds { min: 0, max: 120 }, - NAMING.generate_exotic_character_name(), - ), - EntityType::Town => ( - lib_efo::entity::EntityDuration::Permanent, - lib_efo::entity::EffectApplication::WhenPresent, - EffectBounds { min: 20, max: 60 }, - NAMING.generate_town_name(), - ), - EntityType::Monster => ( - lib_efo::entity::EntityDuration::Permanent, - lib_efo::entity::EffectApplication::WhenPresent, - EffectBounds { min: 20, max: 80 }, - NAMING.generate_calamity_name(), - ), - EntityType::Blocker => ( - lib_efo::entity::EntityDuration::Permanent, - lib_efo::entity::EffectApplication::WhenPresent, - EffectBounds { min: 0, max: 120 }, - NAMING.generate_blocker_name(), - ), - EntityType::Event => ( - lib_efo::entity::EntityDuration::Duration(1), - lib_efo::entity::EffectApplication::PermanentEffectToApply, - EffectBounds { min: 10, max: 80 }, - NAMING.random_event_name(), - ), - }; - // This is the sensible default for all creatures & characters - if let Some(duration) = &entity_args.duration { - e.modify_duration(duration.clone()); - } else { - e.modify_duration(duration); - } - - if let Some(EntityIdentifier::Name(name)) = &entity_args.identifier { - e.name = name.clone() - } else { - e.name = name - } - - // This is the sensible default for all creatures & characters - if let Some(effect) = &entity_args.effect { - e.modify_effect_application(effect.clone()); - } else { - e.modify_effect_application(effect); - } - - // This is the sensible default for characters - if let Some(bounds) = &entity_args.bounds { - e.modify_effect_bounds(bounds.clone()); - } else { - e.modify_effect_bounds(bounds); - } -} diff --git a/bin_efo/src/commands/entity_generic/helper_functions.rs b/bin_efo/src/commands/entity_generic/helper_functions.rs new file mode 100644 index 0000000..fa135d5 --- /dev/null +++ b/bin_efo/src/commands/entity_generic/helper_functions.rs @@ -0,0 +1,204 @@ +//! All helper functions + +use lib_efo::{ + entity::{EffectBounds, Entity, EntityIdentifier}, + error::EpochError, + naming::NAMING, + stats::EntityType, +}; + +use super::EntityArgs; + +/// Update the given stats with the given argumenbts +/// Note that this function will not change name & id due to the usage variance between caller +pub(crate) fn update_stats(entity_args: &EntityArgs, e: &mut Entity) { + if entity_args.delta { + for stat in &entity_args.stats { + e.delta_stat(stat.clone()); + } + } else { + for stat in &entity_args.stats { + e.change_stat(stat.clone()); + } + } +} + +/// Looks up an entity inside the given `epoch_info` according to the +/// supplied arguments. +/// +/// The function returns a reference to the matching entity or an +/// `EpochError::EntityNotFound` if no entity matches. +/// +/// # Arguments +/// * `entity_args` - The arguments that identify the entity. +/// * `e_type` - The type of entity to look for. +/// * `epoch_info` - The epoch that contains all entities. +/// +/// # Returns +/// * `Ok(&Entity)` - The entity that matches the arguments. +/// * `Err(EpochError::EntityNotFound)` - No matching entity was found. +pub(crate) fn find_entity<'a>( + entity_to_find: &'a Option, + e_type: &'a EntityType, + epoch_info: &'a lib_efo::epoch::EpochInfo, +) -> Result<&'a Entity, EpochError> { + vec_entities(e_type, epoch_info) + .iter() + .find(|&entity| find_by_args(entity, entity_to_find)) + .ok_or(EpochError::EntityNotFound( + e_type.clone(), + entity_to_find.clone(), + )) +} + +/// Returns a slice over the entities of the requested type from the given `EpochInfo`. +/// +/// The function matches the supplied `e_type` to the appropriate collection +/// inside `epoch_info`. For unimplemented entity types the call will panic +/// because of the `todo!()` placeholder. +/// +/// # Arguments +/// * `e_type` - The type of entities to retrieve. +/// * `epoch_info` - The epoch information containing the collections. +/// +/// # Returns +/// A reference to the vector containing the requested entities. +/// The lifetime of the returned slice is tied to that of `epoch_info`. +#[inline] +pub(crate) fn vec_entities<'a>( + e_type: &'a EntityType, + epoch_info: &'a lib_efo::epoch::EpochInfo, +) -> &'a Vec { + match e_type { + EntityType::Character => &epoch_info.characters, + EntityType::Player => todo!(), + EntityType::Town => &epoch_info.towns, + EntityType::Monster => &epoch_info.calamities, + EntityType::Blocker => &epoch_info.blockers, + EntityType::Event => &epoch_info.events, + } +} + +#[inline] +/// Returns a mutable slice over the entities of the requested type from the given +/// `EpochInfo`. +/// +/// Like `vec_entities`, this function selects the appropriate collection +/// based on `e_type`. Unimplemented variants will panic due to the `todo!()`. +/// +/// # Arguments +/// * `e_type` - The type of entities to retrieve. +/// * `epoch_info` - The epoch information containing the collections. +/// +/// # Returns +/// A mutable reference to the vector containing the requested entities. +/// The lifetime of the returned slice is tied to that of `epoch_info`. +pub(crate) fn vec_entities_mut<'a>( + e_type: &'a EntityType, + epoch_info: &'a mut lib_efo::epoch::EpochInfo, +) -> &'a mut Vec { + match e_type { + EntityType::Character => &mut epoch_info.characters, + EntityType::Player => todo!(), + EntityType::Town => &mut epoch_info.towns, + EntityType::Monster => &mut epoch_info.calamities, + EntityType::Blocker => &mut epoch_info.blockers, + EntityType::Event => &mut epoch_info.events, + } +} + +/// Helper function finding by name, note that a lot more helpers could be done to find by other criterias +pub(crate) fn find_by_args( + entity_to_match: &Entity, + entity_identifier: &Option, +) -> bool { + match entity_identifier { + Some(EntityIdentifier::Name(name)) => entity_to_match.name.starts_with(name), + Some(EntityIdentifier::Id(id)) => { + entity_to_match.id.hyphenated().to_string().starts_with(id) + } + None => false, + } +} + +// /// Find an entity matching a tag +// pub(crate) fn find_by_id<'a>(entities: &'a [Entity], id: &'a String) -> Option<&'a Entity> { +// entities +// .iter() +// .find(|e| e.id.hyphenated().to_string().starts_with(id)) +// } + +// /// Find an entity matching a name +// pub(crate) fn find_by_name<'a>(entities: &'a [Entity], id: &'a String) -> Option<&'a Entity> { +// entities.iter().find(|e| e.name.starts_with(id)) +// } + +/// Update the default values of the entity with sensible defaults +pub(crate) fn update_defaults(entity_args: &EntityArgs, e: &mut Entity) { + let entity_type = &e.entity_type; + + let (duration, effect, bounds, name) = match entity_type { + EntityType::Character => ( + lib_efo::entity::EntityDuration::Permanent, + lib_efo::entity::EffectApplication::WhenPresent, + EffectBounds { min: 20, max: 110 }, + NAMING.generate_character_name(), + ), + EntityType::Player => ( + lib_efo::entity::EntityDuration::Permanent, + lib_efo::entity::EffectApplication::WhenPresent, + EffectBounds { min: 0, max: 120 }, + NAMING.generate_exotic_character_name(), + ), + EntityType::Town => ( + lib_efo::entity::EntityDuration::Permanent, + lib_efo::entity::EffectApplication::WhenPresent, + EffectBounds { min: 20, max: 60 }, + NAMING.generate_town_name(), + ), + EntityType::Monster => ( + lib_efo::entity::EntityDuration::Permanent, + lib_efo::entity::EffectApplication::WhenPresent, + EffectBounds { min: 20, max: 80 }, + NAMING.generate_calamity_name(), + ), + EntityType::Blocker => ( + lib_efo::entity::EntityDuration::Permanent, + lib_efo::entity::EffectApplication::WhenPresent, + EffectBounds { min: 0, max: 120 }, + NAMING.generate_blocker_name(), + ), + EntityType::Event => ( + lib_efo::entity::EntityDuration::Duration(1), + lib_efo::entity::EffectApplication::PermanentEffectToApply, + EffectBounds { min: 10, max: 80 }, + NAMING.random_event_name(), + ), + }; + // This is the sensible default for all creatures & characters + if let Some(duration) = &entity_args.duration { + e.modify_duration(duration.clone()); + } else { + e.modify_duration(duration); + } + + if let Some(EntityIdentifier::Name(name)) = &entity_args.identifier { + e.name = name.clone() + } else { + e.name = name + } + + // This is the sensible default for all creatures & characters + if let Some(effect) = &entity_args.effect { + e.modify_effect_application(effect.clone()); + } else { + e.modify_effect_application(effect); + } + + // This is the sensible default for characters + if let Some(bounds) = &entity_args.bounds { + e.modify_effect_bounds(bounds.clone()); + } else { + e.modify_effect_bounds(bounds); + } +} diff --git a/bin_efo/src/error.rs b/bin_efo/src/error.rs index cf2e886..dfc063f 100644 --- a/bin_efo/src/error.rs +++ b/bin_efo/src/error.rs @@ -11,7 +11,6 @@ use thiserror::Error; /// All errors that can bubble up to the CLI. #[derive(Debug, Error, Diagnostic)] -#[allow(dead_code)] pub enum AppError { /// Generic “invalid command / missing flag” - emitted by clap. #[error("Command-line error: {0}")] @@ -32,8 +31,7 @@ pub enum AppError { #[error("Storage error: {0}")] // #[diagnostic(transparent)] Storage(#[from] StorageError), - - /// Anything else we didn't anticipate. - #[error("Unknown error: {0}")] - Other(String), + // /// Anything else we didn't anticipate. + // #[error("Unknown error: {0}")] + // Other(String), } diff --git a/lib_efo/src/entity.rs b/lib_efo/src/entity.rs index f99eddd..ca0fcea 100644 --- a/lib_efo/src/entity.rs +++ b/lib_efo/src/entity.rs @@ -11,12 +11,17 @@ //! logic that distinguishes creatures, items, terrain, etc. //! +use std::str::FromStr; + use clap::ValueEnum; use derive_more::{Add, Display, Sub}; use serde::{Deserialize, Serialize}; use uuid::Uuid; -use crate::stats::{EntityType, MetaStats, OverallStats}; +use crate::{ + error::EpochError, + stats::{EntityType, MetaStats, OverallStats}, +}; pub mod implementations; /// An entity that can be present in the game world. @@ -90,26 +95,39 @@ pub struct EffectBounds { #[derive(Debug, Serialize, Deserialize, Clone, Default, ValueEnum)] pub enum EffectApplication { /// Repeatedly applied every turn while the entity is present. - /// Use with caution, as this can produce catastrophic results - /// (e.g., an ever-erupting terrain). Recurring, /// Modifies the attached entity's stats only while present. - /// Removed when the entity is removed. Common for leaders, - /// temporary events, or terrain. WhenPresent, - /// Permanently modifies stats; the change persists after - /// the event ends. + /// Permanently modifies stats #[default] PermanentEffectToApply, /// Indicates that a permanent effect has already been applied. - /// Useful for bookkeeping when a long-lasting event applies - /// its effect only once. PermanentEffectApplied, } +impl FromStr for EffectApplication { + type Err = EpochError; + + fn from_str(s: &str) -> Result { + match s { + _ if s.starts_with("re") => Ok(EffectApplication::Recurring), + _ if s.starts_with("wh") => Ok(EffectApplication::WhenPresent), + _ if s.contains("present") => Ok(EffectApplication::WhenPresent), + _ if s.contains("toap") => Ok(EffectApplication::WhenPresent), + _ if s.starts_with("appl") => Ok(EffectApplication::WhenPresent), + "done" | "ok" => Ok(EffectApplication::PermanentEffectApplied), + "todo" => Ok(EffectApplication::PermanentEffectToApply), + _ => Err(EpochError::ParsingArgument { + argument_parsed: s.to_string(), + while_parsing: "The argument could't be made into a EffectApplication", + }), + } + } +} + /// Represents how long an entity remains active in the world. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default)] pub enum EntityDuration { diff --git a/lib_efo/src/entity/implementations.rs b/lib_efo/src/entity/implementations.rs index dadcb22..7715044 100644 --- a/lib_efo/src/entity/implementations.rs +++ b/lib_efo/src/entity/implementations.rs @@ -29,7 +29,7 @@ impl Displayable for Entity { .metadata .capital .as_ref() - .map(|c| format!(" 󰻾[{:>2}] ", c).green()) + .map(|c| format!(" {} ", c.to_symbol()).green()) .unwrap_or_default(); let governor = self @@ -161,7 +161,10 @@ impl Entity { &format!( "├─ {}: {:?}\n", "capital".bright_green(), - self.metadata.capital + self.metadata + .capital + .map(|c| c.to_symbol()) + .unwrap_or_default() ), )); } @@ -192,7 +195,7 @@ impl Entity { let symbol = if last { "└─" } else { "├─" }; out.push_str(&indent( 1, - &format!("{} 󰻾[{}]\n", symbol, link.to_string().yellow()), + &format!("{} {}\n", symbol, link.to_symbol().yellow()), )); } } diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta-2.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta-2.snap index 58a59f3..a813809 100644 --- a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta-2.snap +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta-2.snap @@ -145,7 +145,7 @@ Entity { ), links: [ TownId( - 6, + 00000000-0000-0000-0000-000000000079, ), ], prestige: GenericStat( diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta-3.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta-3.snap index 548c7f5..ec02a33 100644 --- a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta-3.snap +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta-3.snap @@ -138,7 +138,7 @@ Entity { ), capital: Some( TownId( - 5000, + 00000000-0000-0000-0000-00000000007c, ), ), governor: Some( diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta.snap index bfc612a..a688a9a 100644 --- a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta.snap +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta.snap @@ -138,7 +138,7 @@ Entity { ), capital: Some( TownId( - 3000, + 00000000-0000-0000-0000-000000000079, ), ), governor: Some( diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_oneline_display-2.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_oneline_display-2.snap index f9b9836..c0c47bb 100644 --- a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_oneline_display-2.snap +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_oneline_display-2.snap @@ -4,11 +4,11 @@ expression: e.to_pretty_tree() --- [ Hero 󰻾[0c000000-0000-0000-0000-000000000000]] ├─ metadata - │ ├─ capital: Some(TownId(50)) + │ ├─ capital: "\u{f0efe}[0000000]" │ ├─ prestige: 3 │ └─ position: ( 2, 4)⚓ ├─ links - │ └─ 󰻾[3] + │ └─ 󰻾[0000000] ├─ duration: ⧗10 ├─ effect_nature: Recurring └─ effect_bounds: (1 ⭾ 5) diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_oneline_display.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_oneline_display.snap index 091b449..428bbca 100644 --- a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_oneline_display.snap +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_oneline_display.snap @@ -4,5 +4,5 @@ expression: e.oneline_display() --- ├──┬─ 0c00000 Hero  ──────> ( 2, 4)⚓ ⧗10 │ ├─ Faction: 2 │ Effect: ⟳ (1 ⭾ 5), Stats: 0 0💰 0 0󰡢 3 -│ └─  󰻾[50]  󰻾[11] +│ └─  󰻾[0000000]  󰻾[11] │ diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta-2.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta-2.snap index 3beae88..6eed292 100644 --- a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta-2.snap +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta-2.snap @@ -14,11 +14,7 @@ MetaStats { 33, ), ), - links: [ - TownId( - 55, - ), - ], + links: [], prestige: GenericStat( 0, ), diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta-3.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta-3.snap index 63e30c0..51a88db 100644 --- a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta-3.snap +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta-3.snap @@ -16,7 +16,7 @@ MetaStats { ), links: [ TownId( - 55, + 00000000-0000-0000-0000-000000000002, ), ], prestige: GenericStat( diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta.snap index 6d39112..21a0f97 100644 --- a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta.snap +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta.snap @@ -9,7 +9,7 @@ MetaStats { ), capital: Some( TownId( - 1500, + 00000000-0000-0000-0000-00000000000c, ), ), governor: Some( diff --git a/lib_efo/src/entity/test.rs b/lib_efo/src/entity/test.rs index 22fc8bd..a4ae504 100644 --- a/lib_efo/src/entity/test.rs +++ b/lib_efo/src/entity/test.rs @@ -232,12 +232,12 @@ fn full_entity() -> Entity { name: "Hero".into(), entity_type: EntityType::Character, metadata: MetaStats { - capital: Some(stats::TownId(50)), + capital: Some(stats::TownId(Uuid::from_u128(121))), governor: Some(stats::CharacterId(11)), prestige: stats::GenericStat(3), position: Position::from((2, 4)), faction: Some(crate::stats::FactionId(2)), - links: vec![TownId(3)], + links: vec![TownId(Uuid::from_u128(121))], }, duration: EntityDuration::Duration(10), effect_nature: EffectApplication::Recurring, @@ -369,10 +369,10 @@ fn snapshot_entity_delta() { temp_stats: None, metadata: MetaStats { position: Position::from((44, 666)), - capital: Some(stats::TownId(5000)), + capital: Some(stats::TownId(Uuid::from_u128(124))), governor: Some(stats::CharacterId(2000)), faction: Some(stats::FactionId(44)), - links: vec![TownId(33)], + links: vec![TownId(Uuid::from_u128(141))], prestige: stats::GenericStat(3), }, entity_type: EntityType::Monster, @@ -388,10 +388,10 @@ fn snapshot_entity_delta() { temp_stats: Some(OverallStats::linear(4)), metadata: MetaStats { position: Position::from_str("33,4").unwrap(), - capital: Some(stats::TownId(3000)), + capital: Some(stats::TownId(Uuid::from_u128(121))), governor: Some(stats::CharacterId(1500)), faction: Some(stats::FactionId(5)), - links: vec![TownId(6)], + links: vec![TownId(Uuid::from_u128(121))], prestige: stats::GenericStat(5), }, entity_type: EntityType::Town, @@ -452,19 +452,19 @@ fn snapshot_meta_stats_delta() { let meta1 = MetaStats { position: Position::from((1, 11)), - capital: Some(stats::TownId(1000)), + capital: Some(stats::TownId(Uuid::from_u128(1000))), governor: Some(stats::CharacterId(500)), faction: Some(stats::FactionId(1)), - links: vec![TownId(22)], + links: vec![TownId(Uuid::from_u128(12))], prestige: stats::GenericStat(3), }; let meta2 = MetaStats { position: Position::from((44, 555)), - capital: Some(stats::TownId(1500)), + capital: Some(stats::TownId(Uuid::from_u128(12))), governor: Some(stats::CharacterId(400)), faction: Some(stats::FactionId(33)), - links: vec![TownId::from(55)], + links: vec![TownId::from(Uuid::from_u128(42))], prestige: stats::GenericStat(1), }; let meta3 = MetaStats { @@ -472,7 +472,7 @@ fn snapshot_meta_stats_delta() { capital: None, governor: Some(stats::CharacterId(400)), faction: Some(stats::FactionId(33)), - links: vec![TownId::from(55)], + links: vec![TownId::from(Uuid::from_u128(2))], prestige: stats::GenericStat(1), }; diff --git a/lib_efo/src/epoch/epoch_config.rs b/lib_efo/src/epoch/epoch_config.rs index 754fdac..d501510 100644 --- a/lib_efo/src/epoch/epoch_config.rs +++ b/lib_efo/src/epoch/epoch_config.rs @@ -392,7 +392,6 @@ impl EpochConfig { /// supplied UUID exists in the epoch. /// #[allow(dead_code)] - // TODO: Add to a generic show unsafe fn find_entity(&self, id: Uuid) -> Result<&Entity, EpochError> { let epoch_info = unsafe { self.try_load_id(self.epoch_id) }?; let predicate = |entity: &&Entity| entity.id == id; diff --git a/lib_efo/src/error.rs b/lib_efo/src/error.rs index d524de7..290fe63 100644 --- a/lib_efo/src/error.rs +++ b/lib_efo/src/error.rs @@ -49,7 +49,6 @@ pub enum StorageError { /// to the user (and to the test-suite). // TODO(2): Split effectively user errors to avoid the usage of advice and such #[derive(Error, Debug, Diagnostic)] -#[allow(dead_code, unused_assignments)] pub enum EpochError { /// Problems with the `.epochconfig` file. #[error("Failed to read epoch configuration")] @@ -219,7 +218,7 @@ pub enum EpochError { UnknownStatAcronim(String), /// The user gave a stat:identifier pair that was incorrect - #[error("Expected a stat and a number, got: {0}")] + #[error("Expected a stat and a number (e.g. fod:12 or mil=22), got: {0}")] #[diagnostic(code(EpochError::IllFormedStatQualifier))] IllFormedStatQualifier(String), @@ -327,6 +326,19 @@ pub enum EpochError { You may need to delete or rename the existing entity." ))] EntityAlreadyExist(Option), + /// The argument could not be parsed. + #[error("Failed to parse argument '{argument_parsed}': {while_parsing}")] + #[diagnostic(code(EntityError::ParsingArgument))] + #[diagnostic(help( + "Verify that the value supplied for the argument '{argument_parsed}' matches the expected format. \ + Refer to the command reference for the correct syntax and examples." + ))] + ParsingArgument { + /// The argument that was being parsed + argument_parsed: String, + /// The thing that was being parsed + while_parsing: &'static str, + }, } /// A small enum of explicit user-facing error messages. diff --git a/lib_efo/src/lib.rs b/lib_efo/src/lib.rs index 4551e92..45ea9bf 100644 --- a/lib_efo/src/lib.rs +++ b/lib_efo/src/lib.rs @@ -10,7 +10,7 @@ #![deny(clippy::unwrap_used)] #[macro_use] -#[allow(dead_code, unused_assignments)] +#[allow(unused_assignments)] pub mod error; pub mod entity; pub mod epoch; diff --git a/lib_efo/src/stats.rs b/lib_efo/src/stats.rs index b1a5ee0..635e2cf 100644 --- a/lib_efo/src/stats.rs +++ b/lib_efo/src/stats.rs @@ -9,15 +9,15 @@ //! * **Effect** - Gameplay consequence of the stat. //! * **Source** - Formula or function that generates the stat value. -#![allow(dead_code)] #![deny(clippy::missing_docs_in_private_items)] - +#![allow(dead_code)] use crate::{error::EpochError, thin_newtype, utils::RngLevel}; use cli_table::{CellStruct, Color, Style, Table}; use colored::Colorize; use derive_more::{Add, Display, Sub}; use rand::{Rng, distr::Distribution, rngs::ThreadRng}; use serde::{Deserialize, Serialize}; +use uuid::Uuid; mod implementations; /// Aggregated statistics for a single entity. @@ -299,6 +299,7 @@ impl OverallStats { /// Updates with leader /// etc. // TODO: Fill this + #[allow(dead_code)] fn apply_exteriors(&mut self) {} #[cfg(test)] @@ -443,7 +444,6 @@ impl Position { /// Create a random position /// None that there is no concept to either city or continent making this position rather unrelyable - // TODO(2): Make a create_rng_from_town & create_rng_from_continents pub fn create_rng(r: &mut ThreadRng) -> Result { let x = r.random_range(0..GRID_SIZE.0); let y = r.random_range(0..GRID_SIZE.1); @@ -540,10 +540,10 @@ pub trait Symbols { // } // A stat that is shown to the player *and* can be modified manually. -thin_newtype!(GenericStat, isize); -thin_newtype!(TownId, usize); -thin_newtype!(CharacterId, usize); -thin_newtype!(FactionId, usize); +thin_newtype!(GenericStat, isize, derives: [Add, Sub]); +thin_newtype!(TownId, Uuid); +thin_newtype!(CharacterId, usize, derives: [Add, Sub]); +thin_newtype!(FactionId, usize, derives: [Add, Sub]); // --- TRAITS --------------------------------------------------------------- /// A stat is a *game value* that can be converted to two different diff --git a/lib_efo/src/stats/implementations.rs b/lib_efo/src/stats/implementations.rs index bddb4a1..df2a2c1 100644 --- a/lib_efo/src/stats/implementations.rs +++ b/lib_efo/src/stats/implementations.rs @@ -1,6 +1,7 @@ //! All traits implementatition for the main structs are deffered here +#![allow(dead_code)] -use crate::stats::GameStat; +use crate::stats::{GameStat, TownId}; use colored::Colorize; use std::str::FromStr; @@ -10,58 +11,6 @@ use crate::stats::{ EntityType, FactionId, GenericStat, ListStats, OverallStats, Position, Symbols, }; -/// Creates a thin, deref-able wrapper around an inner type. -#[macro_export] -macro_rules! thin_newtype { - ($name:ident, $inner:ty) => { - /// Thin wrapper that derefs to the inner type. - /// Ideal for zero-overhead new-type patterns. - #[repr(transparent)] - #[derive( - Debug, - Clone, - Copy, - Default, - PartialEq, - Eq, - PartialOrd, - Ord, - Hash, - Serialize, - Deserialize, - Display, - Add, - Sub, - )] - pub struct $name(pub $inner); - - impl std::ops::Deref for $name { - type Target = $inner; - fn deref(&self) -> &Self::Target { - &self.0 - } - } - - impl std::ops::DerefMut for $name { - fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.0 - } - } - - impl From<$inner> for $name { - fn from(v: $inner) -> Self { - $name(v) - } - } - - impl From<$name> for $inner { - fn from(v: $name) -> Self { - v.0 - } - } - }; -} - /// Generates an `impl GameStat for ` where the only difference between /// multiple implementations is the visibility level. /// @@ -449,6 +398,148 @@ impl Symbols for Option { } } +impl Symbols for TownId { + fn to_symbol(&self) -> String { + format!("󰻾[{}]", self.0.to_string().split_at(7).0) + } + + fn to_shortest(&self) -> String { + self.0.to_string().split_at(7).0.to_string() + } +} + +impl FromStr for FactionId { + type Err = EpochError; // the error we get from `usize::parse` + + /// Parse a string slice into a `FactionId`. + fn from_str(s: &str) -> Result { + // Trim whitespace just in case and attempt to parse. + let inner = s + .trim() + .parse::() + .map_err(|_| EpochError::ParsingArgument { + argument_parsed: s.to_string(), + while_parsing: "The argument could't be made into a FactionId", + })?; + Ok(FactionId(inner)) + } +} + +/// Thin wrapper that derefs to the inner type. +/// +/// By default the wrapper derives a common set of traits (`Debug`, `Clone`, `Copy`, +/// …). You can optionally provide an extra list of derives – e.g. `Add`, +/// `Sub`, `FromStr`, or any custom derive – by writing: +/// ``` +/// thin_newtype!(MyInt, i32, derives: [Add, Sub]); +/// ``` +/// (you’ll need the corresponding crates – e.g. `derive_more` for `Add`, `Sub`). +#[macro_export] +macro_rules! thin_newtype { + /* ---- no custom derives ------------------------------------------------- */ + ($name:ident, $inner:ty) => { + + /// Thin wrapper that derefs to the inner type. + /// Ideal for zero-overhead new-type patterns. + #[repr(transparent)] + #[derive( + Debug, + Clone, + Copy, + Default, + PartialEq, + Eq, + PartialOrd, + Ord, + Hash, + Serialize, + Deserialize, + Display, + )] + pub struct $name(pub $inner); + + impl std::ops::Deref for $name { + type Target = $inner; + #[inline] + fn deref(&self) -> &Self::Target { + &self.0 + } + } + + impl std::ops::DerefMut for $name { + #[inline] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } + } + + impl From<$inner> for $name { + #[inline] + fn from(v: $inner) -> Self { + $name(v) + } + } + + impl From<$name> for $inner { + #[inline] + fn from(v: $name) -> Self { + v.0 + } + } + }; + + /* ---- with a custom derive list ---------------------------------------- */ + ($name:ident, $inner:ty, derives: [ $( $derive:ident ),* $(,)? ]) => { + /// Thin wrapper that derefs to the inner type. + /// Ideal for zero-overhead new-type patterns. + #[repr(transparent)] + #[derive( + Debug, + Clone, + Copy, + Default, + PartialEq, + Eq, + PartialOrd, + Ord, + Hash, + serde::Serialize, + serde::Deserialize, + derive_more::Display, + $( $derive ),* + )] + pub struct $name(pub $inner); + + impl std::ops::Deref for $name { + type Target = $inner; + #[inline] + fn deref(&self) -> &Self::Target { + &self.0 + } + } + + impl std::ops::DerefMut for $name { + #[inline] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } + } + + impl From<$inner> for $name { + #[inline] + fn from(v: $inner) -> Self { + $name(v) + } + } + + impl From<$name> for $inner { + #[inline] + fn from(v: $name) -> Self { + v.0 + } + } + }; +} mod from_impl; #[cfg(test)] diff --git a/lib_efo/src/stats/implementations/from_impl.rs b/lib_efo/src/stats/implementations/from_impl.rs index fe89c42..3675655 100644 --- a/lib_efo/src/stats/implementations/from_impl.rs +++ b/lib_efo/src/stats/implementations/from_impl.rs @@ -15,7 +15,7 @@ impl FromStr for StatPair { /// If the format is invalid, an `EpochError::IllFormedStatQualifier` /// is returned. fn from_str(s: &str) -> Result { - let (stat_str, val_str) = if let Some(idx) = s.find(':') { + let (stat_str, val_str) = if let Some(idx) = s.find([':', '=']) { (&s[..idx], &s[idx + 1..]) } else { let parts: Vec<&str> = s.split_whitespace().collect(); diff --git a/lib_efo/src/stats/implementations/test.rs b/lib_efo/src/stats/implementations/test.rs index 8fab056..55ceb9b 100644 --- a/lib_efo/src/stats/implementations/test.rs +++ b/lib_efo/src/stats/implementations/test.rs @@ -13,26 +13,28 @@ struct Person { email: GenericStat, } -/// Helper that asserts that a string parses to the expected ListStats variant. -fn assert_stat_ok(input: &str, expected: ListStats) { - let parsed = ListStats::from_str(input).expect("should parse"); - assert_eq!(parsed, expected, "input `{}` parsed incorrectly", input); -} +// /// Helper that asserts that a string parses to the expected ListStats variant. +// fn assert_stat_ok(input: &str, expected: ListStats) { +// let parsed = ListStats::from_str(input).expect("should parse"); +// assert_eq!(parsed, expected, "input `{}` parsed incorrectly", input); +// } field_accessor!(Person { name, age, email }); #[test] fn test_field_accessors() { - let person = Person { + let mut person = Person { name: GenericStat(10), age: GenericStat(20), email: GenericStat(120), }; + + let age = person.get_field_mut_from_str("age").unwrap(); + assert_eq!(age.to_100(), 10); + let name = person.get_field_from_str("name").unwrap(); let email = person.get_field_from_str("email").unwrap(); - let age = person.get_field_from_str("age").unwrap(); assert_eq!(name.to_100(), 0); - assert_eq!(age.to_100(), 10); assert_eq!(email.to_100(), 100); } -- 2.45.1 From a4275b494d6d4c2df70c262d62715be47caaaa48 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 14 Dec 2025 03:00:12 +0100 Subject: [PATCH 5/7] Adds a descritption --- bin_efo/src/commands/entity_generic.rs | 3 +- bin_efo/src/commands/generate.rs | 70 +++++++++---------- lib_efo/src/entity.rs | 3 + lib_efo/src/entity/implementations.rs | 30 ++++++++ ...y__test__snapshot_delta_stat_positive.snap | 1 + ...entity__test__snapshot_entity_delta-2.snap | 1 + ...entity__test__snapshot_entity_delta-3.snap | 1 + ...__entity__test__snapshot_entity_delta.snap | 1 + ...ntity__test__snapshot_modify_duration.snap | 1 + ...t__snapshot_modify_effect_application.snap | 1 + ...__test__snapshot_modify_effect_bounds.snap | 1 + lib_efo/src/entity/test.rs | 3 + lib_efo/src/naming.rs | 10 ++- 13 files changed, 86 insertions(+), 40 deletions(-) diff --git a/bin_efo/src/commands/entity_generic.rs b/bin_efo/src/commands/entity_generic.rs index 5ab2ed3..18147bf 100644 --- a/bin_efo/src/commands/entity_generic.rs +++ b/bin_efo/src/commands/entity_generic.rs @@ -122,7 +122,6 @@ pub(crate) struct DelArgs { /// Arguments required for showing any entity pub(crate) struct ShowArgs { /// The identifier either a name or a @tag - #[arg(long, short)] identifier: Option, #[arg(long, short)] @@ -223,7 +222,7 @@ pub fn handle_entity_commands( } /// Function handler for the create subcommand -fn handle_create_entity( +pub(crate) fn handle_create_entity( entity_args: &EntityArgs, e_type: &EntityType, main_epoch: &mut EpochConfig, diff --git a/bin_efo/src/commands/generate.rs b/bin_efo/src/commands/generate.rs index a9046e5..f715a31 100644 --- a/bin_efo/src/commands/generate.rs +++ b/bin_efo/src/commands/generate.rs @@ -99,12 +99,12 @@ pub struct Qty { /// If set to `false` the generator will produce a *short* representation #[arg(long, action = clap::ArgAction::SetFalse, default_value_t = true)] short: bool, - /// Generate only a name, no underlying structure. - /// - /// When this flag is present the generator prints only the name string - /// rather than any additional data or formatting. - #[arg(long="name", action = clap::ArgAction::SetTrue, default_value_t = false)] - name_only: bool, + // /// Generate only a name, no underlying structure. + // /// + // /// When this flag is present the generator prints only the name string + // /// rather than any additional data or formatting. + // #[arg(long="dry", action = clap::ArgAction::SetFalse, default_value_t = true)] + // dry: bool, } /// Handles the subcommand for generating various kinds of entities. @@ -133,11 +133,9 @@ pub fn gen_handler(cmd: &GenCmd) -> Result<(), AppError> { fn handle_calamity(args: &Qty) -> Result<(), EpochError> { for _ in 0..args.number { let name = NAMING.generate_calamity_name(); - if args.name_only { - println!("{}", name); - } else { - unimplemented!("DEPENS ON : CHARACTER CREATION") - } + // if args.dry { + println!("{}", name); + // } } Ok(()) } @@ -146,11 +144,11 @@ fn handle_calamity(args: &Qty) -> Result<(), EpochError> { fn handle_blocker(args: &Qty) -> Result<(), EpochError> { for _ in 0..args.number { let name = NAMING.generate_blocker_name(); - if args.name_only { - println!("{}", name); - } else { - unimplemented!("DEPENS ON : CHARACTER CREATION") - } + // if args.name_only { + println!("{}", name); + // } else { + // unimplemented!("DEPENS ON : CHARACTER CREATION") + // } } Ok(()) } @@ -159,11 +157,11 @@ fn handle_blocker(args: &Qty) -> Result<(), EpochError> { fn handle_exotic(args: &Qty) -> Result<(), EpochError> { for _ in 0..args.number { let name = NAMING.generate_exotic_character_name(); - if args.name_only { - println!("{}", name); - } else { - unimplemented!("DEPENS ON : CHARACTER CREATION") - } + // if args.name_only { + println!("{}", name); + // } else { + // unimplemented!("DEPENS ON : CHARACTER CREATION") + // } } Ok(()) } @@ -172,11 +170,11 @@ fn handle_exotic(args: &Qty) -> Result<(), EpochError> { fn handle_town(args: &Qty) -> Result<(), EpochError> { for _ in 0..args.number { let name = NAMING.generate_town_name(); - if args.name_only { - println!("{}", name); - } else { - unimplemented!("DEPENS ON : TOWN CREATION") - } + // if args.name_only { + println!("{}", name); + // } else { + // unimplemented!("DEPENS ON : TOWN CREATION") + // } } Ok(()) } @@ -185,11 +183,11 @@ fn handle_town(args: &Qty) -> Result<(), EpochError> { fn handle_event(args: &Qty) -> Result<(), EpochError> { for _ in 0..args.number { let event = NAMING.random_event_idea()?; - if args.name_only { - println!("{}", event.name); - } else { - println!("{}", event.oneline_display()); - } + // if args.name_only { + // println!("{}", event.name); + // } else { + println!("{}", event.oneline_display()); + // } } Ok(()) } @@ -203,11 +201,11 @@ fn handle_chr(args: &Qty) -> Result<(), EpochError> { NAMING.generate_character_name() }; - if args.name_only { - println!("{}", name); - } else { - unimplemented!("DEPENS ON : CHARACTER CREATION") - } + // if args.name_only { + println!("{}", name); + // } else { + // unimplemented!("DEPENS ON : CHARACTER CREATION") + // } } Ok(()) } diff --git a/lib_efo/src/entity.rs b/lib_efo/src/entity.rs index ca0fcea..be7c9f9 100644 --- a/lib_efo/src/entity.rs +++ b/lib_efo/src/entity.rs @@ -33,6 +33,9 @@ pub struct Entity { /// The name of the entity pub name: String, + /// A short description of the entity + pub description: String, + /// The global identifier for the entity pub id: Uuid, diff --git a/lib_efo/src/entity/implementations.rs b/lib_efo/src/entity/implementations.rs index 7715044..cb359b5 100644 --- a/lib_efo/src/entity/implementations.rs +++ b/lib_efo/src/entity/implementations.rs @@ -265,6 +265,30 @@ impl Entity { overwrite_stat(&mut self.stats, pair); } + /// Change the entity's duration. + /// + /// This simply replaces the current `EntityDuration` with the one supplied. + /// No validation or transformation is performed; it is a direct overwrite. + /// + /// # Arguments + /// * `duration` - The new `EntityDuration` to assign to the entity. + /// + pub fn change_duration(&mut self, duration: EntityDuration) { + self.duration = duration + } + + /// Change the entity's description. + /// + /// Replaces the current description string with the new one supplied. + /// This method performs a direct overwrite; the previous description is dropped. + /// + /// # Arguments + /// * `descritption` - The new description string for the entity. + /// + pub fn change_description(&mut self, descritption: String) { + self.description = descritption + } + /// Apply a delta to all of the entity's statistics. /// /// The delta specified by `pair` is added to each of the statistics in @@ -306,6 +330,11 @@ impl Entity { } } +// impl Entity { +// /// Create a new Event +// fn new_event(name: String, description: String){} +// } + /// Replace a statistic in `stats` with the value from `pair`. /// /// This function performs a direct overwrite: the existing value is @@ -357,6 +386,7 @@ impl Diffable for Entity { effect_nature: other.effect_nature.clone(), effect_bounds: other.effect_bounds.clone(), id: Uuid::new_v4(), + description: other.description.clone(), } } } diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_delta_stat_positive.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_delta_stat_positive.snap index c0df3e1..ee4827b 100644 --- a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_delta_stat_positive.snap +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_delta_stat_positive.snap @@ -4,6 +4,7 @@ expression: "format!(\"{:#?}\", e)" --- Entity { name: "", + description: "", id: 00000000-0000-0000-0000-000000000000, stats: OverallStats { demographics: GenericStat( diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta-2.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta-2.snap index a813809..07a4d68 100644 --- a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta-2.snap +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta-2.snap @@ -4,6 +4,7 @@ expression: "format!(\"{:#?}{}\", delta2, delta2.full_stats_to_table().unwrap()) --- Entity { name: "Bob", + description: "Ilo", id: 00000000-0000-0000-0000-000000000000, stats: OverallStats { demographics: GenericStat( diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta-3.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta-3.snap index ec02a33..6f1174c 100644 --- a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta-3.snap +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta-3.snap @@ -4,6 +4,7 @@ expression: "format!(\"{:#?}{}\", delta3, delta3.full_stats_to_table().unwrap()) --- Entity { name: "Bob->Alice", + description: "Ello", id: 00000000-0000-0000-0000-000000000000, stats: OverallStats { demographics: GenericStat( diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta.snap index a688a9a..8b7671c 100644 --- a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta.snap +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta.snap @@ -4,6 +4,7 @@ expression: "format!(\"{:#?}{}\", &delta, delta.full_stats_to_table().unwrap())" --- Entity { name: "Alice->Bob", + description: "Ilo", id: 00000000-0000-0000-0000-000000000000, stats: OverallStats { demographics: GenericStat( diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_modify_duration.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_modify_duration.snap index 61f463d..f997384 100644 --- a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_modify_duration.snap +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_modify_duration.snap @@ -4,6 +4,7 @@ expression: "format!(\"{:#?}\", e)" --- Entity { name: "", + description: "", id: 00000000-0000-0000-0000-000000000000, stats: OverallStats { demographics: GenericStat( diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_modify_effect_application.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_modify_effect_application.snap index 3fffbfd..da16fa0 100644 --- a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_modify_effect_application.snap +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_modify_effect_application.snap @@ -4,6 +4,7 @@ expression: "format!(\"{:#?}\", e)" --- Entity { name: "", + description: "", id: 00000000-0000-0000-0000-000000000000, stats: OverallStats { demographics: GenericStat( diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_modify_effect_bounds.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_modify_effect_bounds.snap index 7ce3de6..3138636 100644 --- a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_modify_effect_bounds.snap +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_modify_effect_bounds.snap @@ -4,6 +4,7 @@ expression: "format!(\"{:#?}\", e)" --- Entity { name: "", + description: "", id: 00000000-0000-0000-0000-000000000000, stats: OverallStats { demographics: GenericStat( diff --git a/lib_efo/src/entity/test.rs b/lib_efo/src/entity/test.rs index a4ae504..d5c6f9e 100644 --- a/lib_efo/src/entity/test.rs +++ b/lib_efo/src/entity/test.rs @@ -244,6 +244,7 @@ fn full_entity() -> Entity { effect_bounds: EffectBounds::from((1, 5)), stats: stats::OverallStats::default(), temp_stats: Some(stats::OverallStats::default()), + description: String::from("Bob"), } } @@ -379,6 +380,7 @@ fn snapshot_entity_delta() { duration: EntityDuration::Permanent, effect_nature: EffectApplication::Recurring, effect_bounds: EffectBounds::from(0..33), + description: "Ello".to_string(), }; let e2 = Entity { @@ -398,6 +400,7 @@ fn snapshot_entity_delta() { duration: EntityDuration::Permanent, effect_nature: EffectApplication::Recurring, effect_bounds: EffectBounds::from(0..3), + description: "Ilo".to_string(), }; // Compute the delta diff --git a/lib_efo/src/naming.rs b/lib_efo/src/naming.rs index d2d2913..f972228 100644 --- a/lib_efo/src/naming.rs +++ b/lib_efo/src/naming.rs @@ -145,12 +145,18 @@ impl NamingData { #[allow(clippy::unwrap_used)] pub fn random_event_idea(&self) -> Result<&EventDescription, EpochError> { let mut rng = rand::rng(); - self.event_ideas + let event_desc = self + .event_ideas .choose(&mut rng) .ok_or(EpochError::RNGPickError { cause: "Picking a random event".into(), help: None, - }) + })?; + // let mut e = Entity::default(); + + // e.name = event_desc.name.clone(); + // e.change_description(event_desc.description.clone()); + Ok(event_desc) } /// Pick a random event name -- 2.45.1 From 6e593f8ac99eb0783cd1690e469b237b59ae0132 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 14 Dec 2025 03:37:03 +0100 Subject: [PATCH 6/7] Clap shenenigans --- bin_efo/src/commands/entity_generic.rs | 211 ++++++++++-------- .../entity_generic/helper_functions.rs | 17 +- 2 files changed, 132 insertions(+), 96 deletions(-) diff --git a/bin_efo/src/commands/entity_generic.rs b/bin_efo/src/commands/entity_generic.rs index 18147bf..1e530d8 100644 --- a/bin_efo/src/commands/entity_generic.rs +++ b/bin_efo/src/commands/entity_generic.rs @@ -20,17 +20,21 @@ //! //! ### Options //! -//! | Flag | Description | -//! |------|-------------| -//! | `-d, --delta` | Apply a delta to the supplied stats (add or subtract) instead of overwriting them. | -//! | `-v, --verbose…` | Increase output verbosity. | -//! | `--rng ` | How to fill unspecified stats.
Possible values: `zero`, `low`, `med`, `high`, `legendary`, `mixed`, `flawed`. Default: `zero`. | -//! | `--pos-exact ` / `--pos ` | Place the new entity at a specific `x,y` coordinate (the epoch must be in a map context). | -//! | `--duration ` | Lifespan of the entity (e.g. `Permanent`, `Temporary`, `Duration(1)` for a one‑turn event). | -//! | `--bounds ` | Effect limits, given as `min,max` (e.g. `10,80`). | -//! | `--effect ` | How the effect is applied:
`recurring`, `when-present`, `permanent-effect-to-apply`, `permanent-effect-applied`. | -//! | `-s, --stats ` | One or more `key:value` pairs, e.g. `fod,10 military:8`. | +//! | Flag | Group | Description | +//! |------|-------|-------------| +//! | `-d, --delta` | *edit* | Treat the supplied `stats` values as a delta (add/subtract) +//! instead of an absolute overwrite. | +//! | `-v, --verbose…` | *global* | Increases the amount of diagnostic output. | +//! | `--rng ` | *add/edit* | How to initialise *missing* stats. Possible values: `zero`, `low`, `med`, `high`, `legendary`, `mixed`, `flawed`. Default: `zero`. | +//! | `--pos-exact ` / `--pos ` | *add/edit* | Set the entity’s coordinates. `--pos-exact` forces the coordinates to be used verbatim; `--pos` applies the map’s current position transformation (if any). | +//! | `--duration ` | *add/edit* | Lifespan of the entity – e.g. `Permanent`, `Temporary` or `Duration(1)` for a one‑turn event. | +//! | `--bounds ` | *add/edit* | Effect limits in the form `min,max` (e.g. `10,80`). | +//! | `--effect ` | *add/edit* | How the effect is applied: `recurring`, `when-present`, `permanent-effect-to-apply`, `permanent-effect-applied`. | +//! | `-s, --stats ` | *add/edit* | One or more `key:value` pairs – e.g. `fod:10 military:8`. | +//! | `--rng-name` | *add* | If set, the tool generates a random name instead of using the supplied identifier. | //! +//! All changes are **persisted immediately** to the epoch file after the +//! command completes.//! //! ## Usage //! All the following example use `chr` as a choice of entity but can be safely substitued to any entity: `event`, `town`, `blocker` etc... //! @@ -81,106 +85,141 @@ use crate::success::display_success; mod helper_functions; -/// Commands that operate on an entity. -/// -/// Each variant represents a different operation that can be performed on an -/// entity. The variant holds the arguments that are common to all operations. +/// All operations that can be performed on an entity. +/// +/// Each variant contains the arguments that are common to that +/// operation. The enum itself is used by `clap` to dispatch +/// the user‑provided sub‑command. #[derive(Subcommand, Debug)] pub(crate) enum EntitySubCommands { - /// Add an entity - Add(EntityArgs), - /// Delete an entity - Del(DelArgs), - /// Edit an existing entity - Edit(EntityArgs), // /// Find an entity by its identifier // Find(EntityArgs), - /// Show the details of an entity + /// Create a new entity + Add(AddArgs), + /// Remove an existing entity + Del(DelArgs), + /// Update fields of an existing entity + Edit(EditArgs), + /// Show one or more entities Show(ShowArgs), - /// Show differences between two entities + /// Show the difference between two epochs Diff(DiffArgs), } +/// Arguments used only for the `diff` sub‑command. #[derive(Args, Debug)] -/// Arguments reserved for diffing pub(crate) struct DiffArgs { - /// The identifier either a name or a @tag - identifier: EntityIdentifier, + /// Identifier (name or `@tag`) of the entity to diff + pub identifier: EntityIdentifier, - /// Another epoch than the previous - epoch_id: Option, + /// Optional epoch to compare against. + /// If omitted the previous epoch is used. + #[arg(long, short = 'i')] + pub epoch_id: Option, } +/// Arguments for deleting an entity. #[derive(Args, Debug)] -/// Arguments required for any entity deletion pub(crate) struct DelArgs { - /// The identifier either a name or a @tag - identifier: EntityIdentifier, + /// Identifier (name or `@tag`) of the entity to delete + pub identifier: EntityIdentifier, } +/// Arguments for showing entities. #[derive(Args, Debug)] -/// Arguments required for showing any entity pub(crate) struct ShowArgs { - /// The identifier either a name or a @tag - identifier: Option, - - #[arg(long, short)] - /// Show only if belonging to faction - faction: Option, - // /// Show only if in a specific town - // #[arg(long, short)] - // town: Option, - // // - // /// Show only if not done - // #[arg(long, short, action = clap::ArgAction::SetTrue, default_value_t = Some(false))] - // valid: Option, -} - -/// Arguments required for any entity operation. -/// -/// All fields are required. The `rng` field determines how unspecified stat -/// values are handled when an entity is created or edited. -#[derive(Args, Debug)] -pub struct EntityArgs { - /// The identifier either a name or a @tag + /// Optional identifier – when omitted all entities are listed. pub identifier: Option, - // /// A name to change to - // #[arg(long, group = "identifier")] - // pub new_name: Option, - /// Applies a delta to stats instead of setting the values - #[arg(long, short, action = clap::ArgAction::SetTrue, default_value_t = false)] - pub delta: bool, + /// Filter by faction id (used only when an identifier is supplied) + #[arg(long, short)] + pub faction: Option, +} - /// The type of rng stat repartition - #[arg(value_enum, long, default_value_t = RngLevel::Zero)] +/// Common arguments used for *add* and *edit* operations. +#[derive(Args, Debug)] +pub struct AddArgs { + /// The desired name of the new entity. If omitted a random + /// name will be generated unless `--rng-name` is set. + #[arg(group = "name")] + pub identifier: Option, + + /// If true a random name will be generated *regardless* of + /// `identifier`. Useful when you want a quick anonymous test. + #[arg(long, action = clap::ArgAction::SetTrue, default_value_t = false, group = "name")] + pub rng_name: bool, + + /// How to initialise *missing* stats. See the `--rng` option + /// description for the valid values. + #[arg(value_enum, long, short, default_value_t = RngLevel::Zero)] pub rng: RngLevel, - /// Adds at a specific position - #[arg(long, group = "position")] + /// Place the new entity at an exact position – this ignores + /// any map‑specific coordinate transformations. + #[arg(long, short = 'P', group = "position")] pub pos_exact: Option, - /// Adds at a specific position - #[arg(long, group = "position")] + /// Place the new entity using the map’s position rules. + #[arg(long, short = 'p', group = "position")] pub pos: Option, - /// The duration of the entity - #[arg(long)] + /// Lifespan of the entity – see the `--duration` description. + #[arg(long, short)] pub duration: Option, - /// The bounds of the effect of the entity - #[arg(long)] + /// Effect bounds in the form `min,max`. See the `--bounds` + /// description for details. + #[arg(long, short)] pub bounds: Option, - /// How is the effect of the entity applied - #[arg(long)] + /// How the effect is applied – see the `--effect` description. + #[arg(long, short)] pub effect: Option, - /// All stats pairs involved + /// One or more `key:value` pairs that set the entity’s stats. #[arg(short, long)] pub stats: Vec, } +#[derive(Args, Debug)] +pub struct EditArgs { + /// Identifier (name or `@tag`) of the entity to edit + pub identifier: EntityIdentifier, + + /// New name for the entity (optional). + #[arg(long, short)] + pub new_name: Option, + + /// Treat the supplied `stats` as a delta (add/subtract) + /// rather than an absolute overwrite. + #[arg(long, short='D', action = clap::ArgAction::SetTrue, default_value_t = false)] + pub delta: bool, + + /// Update the entity’s exact position – ignores map transforms. + #[arg(long, short = 'P', group = "position")] + pub pos_exact: Option, + + /// Update the entity’s position using the map rules. + #[arg(long, short = 'p', group = "position")] + pub pos: Option, + + /// New duration for the entity. + #[arg(long, short)] + pub duration: Option, + + /// New effect bounds. + #[arg(long, short)] + pub bounds: Option, + + /// New effect application mode. + #[arg(short, long)] + pub effect: Option, + + /// One or more `key:value` pairs that modify the entity’s stats. + #[arg(short, long, num_args = 1..)] + pub stats: Vec, +} + /// Handles an entity subcommand. /// /// This function loads the main epoch configuration, then dispatches the @@ -223,22 +262,21 @@ pub fn handle_entity_commands( /// Function handler for the create subcommand pub(crate) fn handle_create_entity( - entity_args: &EntityArgs, + entity_args: &AddArgs, e_type: &EntityType, main_epoch: &mut EpochConfig, ) -> Result<(), EpochError> { let epoch_info = main_epoch.try_load_current_as_mut()?; + let ident = entity_args.identifier.clone().map(EntityIdentifier::Name); - if helper_functions::find_entity(&entity_args.identifier, e_type, epoch_info).is_ok() { - Err(EpochError::EntityAlreadyExist( - entity_args.identifier.clone(), - ))?; + if helper_functions::find_entity(&ident, e_type, epoch_info).is_ok() { + Err(EpochError::EntityAlreadyExist(ident))?; }; let vec_entities: &mut Vec = helper_functions::vec_entities_mut(e_type, epoch_info); let mut entity = Entity::create_rng(e_type, &entity_args.rng)?; - helper_functions::update_stats(entity_args, &mut entity); + helper_functions::update_stats(&entity_args.stats, false, &mut entity); // Specifying a name means the name needs to be changed // Specifying an id however means nothing and should be ignored @@ -348,7 +386,7 @@ fn handle_show_entity( /// Function handler for the edit subcommand fn handle_edit_entity( - entity_args: &EntityArgs, + entity_args: &EditArgs, e_type: &EntityType, main_epoch: &mut EpochConfig, ) -> Result<(), EpochError> { @@ -356,10 +394,12 @@ fn handle_edit_entity( let vec_entities = helper_functions::vec_entities_mut(e_type, epoch_info); let entity = vec_entities .iter_mut() - .find(|entity| helper_functions::find_by_args(entity, &entity_args.identifier)) + .find(|entity| { + helper_functions::find_by_args(entity, &Some(entity_args.identifier.clone())) + }) .ok_or(EpochError::EntityNotFound( e_type.clone(), - entity_args.identifier.clone(), + Some(entity_args.identifier.clone()), ))?; for stat in &entity_args.stats { @@ -368,12 +408,9 @@ fn handle_edit_entity( if let Some(duration) = &entity_args.duration { entity.modify_duration(duration.clone()); } - // // Only update the name if an id was given - // if entity_args.id.is_some() - // && let Some(name) = &entity_args.name - // { - // entity.name = name.clone(); - // } + if let Some(ref name) = entity_args.new_name { + entity.name = name.clone(); + } if let Some(effect) = &entity_args.effect { entity.modify_effect_application(effect.clone()); } diff --git a/bin_efo/src/commands/entity_generic/helper_functions.rs b/bin_efo/src/commands/entity_generic/helper_functions.rs index fa135d5..dd20b44 100644 --- a/bin_efo/src/commands/entity_generic/helper_functions.rs +++ b/bin_efo/src/commands/entity_generic/helper_functions.rs @@ -4,20 +4,19 @@ use lib_efo::{ entity::{EffectBounds, Entity, EntityIdentifier}, error::EpochError, naming::NAMING, - stats::EntityType, + stats::{EntityType, StatPair}, }; -use super::EntityArgs; - +use crate::commands::entity_generic::AddArgs; /// Update the given stats with the given argumenbts /// Note that this function will not change name & id due to the usage variance between caller -pub(crate) fn update_stats(entity_args: &EntityArgs, e: &mut Entity) { - if entity_args.delta { - for stat in &entity_args.stats { +pub(crate) fn update_stats(pair_list: &Vec, is_a_delta: bool, e: &mut Entity) { + if is_a_delta { + for stat in pair_list { e.delta_stat(stat.clone()); } } else { - for stat in &entity_args.stats { + for stat in pair_list { e.change_stat(stat.clone()); } } @@ -134,7 +133,7 @@ pub(crate) fn find_by_args( // } /// Update the default values of the entity with sensible defaults -pub(crate) fn update_defaults(entity_args: &EntityArgs, e: &mut Entity) { +pub(crate) fn update_defaults(entity_args: &AddArgs, e: &mut Entity) { let entity_type = &e.entity_type; let (duration, effect, bounds, name) = match entity_type { @@ -182,7 +181,7 @@ pub(crate) fn update_defaults(entity_args: &EntityArgs, e: &mut Entity) { e.modify_duration(duration); } - if let Some(EntityIdentifier::Name(name)) = &entity_args.identifier { + if let Some(name) = &entity_args.identifier { e.name = name.clone() } else { e.name = name -- 2.45.1 From de70b6e4402081547e828eb89cd117a1e836acc6 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 14 Dec 2025 03:40:41 +0100 Subject: [PATCH 7/7] Doc example not passing --- lib_efo/src/stats/implementations.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib_efo/src/stats/implementations.rs b/lib_efo/src/stats/implementations.rs index df2a2c1..09c1376 100644 --- a/lib_efo/src/stats/implementations.rs +++ b/lib_efo/src/stats/implementations.rs @@ -431,6 +431,8 @@ impl FromStr for FactionId { /// …). You can optionally provide an extra list of derives – e.g. `Add`, /// `Sub`, `FromStr`, or any custom derive – by writing: /// ``` +/// # use lib_efo::thin_newtype; +/// use derive_more::{Add, Sub}; /// thin_newtype!(MyInt, i32, derives: [Add, Sub]); /// ``` /// (you’ll need the corresponding crates – e.g. `derive_more` for `Add`, `Sub`). -- 2.45.1