Merge pull request 'dev-ci' (#5) from dev-ci into main
Build Successful The build was successful
Gitea/epoch_forge/pipeline/head This commit looks good Details

Reviewed-on: #5
This commit is contained in:
Dandaedre 2025-12-14 03:43:47 +01:00
commit 7050ec2c8e
45 changed files with 1403 additions and 802 deletions

2
.ignore Normal file
View File

@ -0,0 +1,2 @@
snapshots
*.svg

View File

@ -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

34
Cargo.lock generated
View File

@ -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"

11
Jenkinsfile vendored
View File

@ -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."
}

124
README.md
View File

@ -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`<br>`efo epoch --advance N`<br>`efo epoch --target ID` | Creates a world; moves time forward or back. |
| `event` | `efo event add ...`<br>`efo event remove ...` | Adds or removes an event. |
| `org` | `efo org add ...`<br>`efo org remove ...` | Manages guilds/factions. |
| `chr` | `efo chr add ...`<br>`efo chr remove ...` | Handles characters. |
| `town` | `efo town add ...`<br>`efo town remove ...` | Town CRUD. |
| `link` | `efo link add ...`<br>`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`<br>`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 `<id>` (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 `<text>`. |
| **`show`** | `efo show` | Prints the current world state (JSON). |
| **`gen`** | `efo gen character -n 5 --short`<br>`efo gen town -n 2`<br>`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 ...`<br>`efo event remove ...` | Adds or removes an event. |
| **`org add` / `org remove`** | `efo org add ...`<br>`efo org remove ...` | Manages organisations (guilds, factions). |
| **`town add` / `town remove`** | `efo town add ...`<br>`efo town remove ...` | CRUD for towns. |
| **`monster add` / `monster remove`** | `efo monster add ...`<br>`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! 🔨✨

View File

@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="122" height="18" role="img" aria-label="test-coverage: 51%"><title>test-coverage: 51%</title><linearGradient id="bms-4635e915b4180cf4" x2="0" y2="100%"><stop offset="0" stop-color="#fff" stop-opacity=".7"/><stop offset=".1" stop-color="#aaa" stop-opacity=".1"/><stop offset=".9" stop-color="#000" stop-opacity=".3"/><stop offset="1" stop-color="#000" stop-opacity=".5"/></linearGradient><clipPath id="bmr-4635e915b4180cf4"><rect width="122" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-4635e915b4180cf4)"><rect width="87" height="18" fill="#555"/><rect x="87" width="35" height="18" fill="#97ca00"/><rect width="122" height="18" fill="url(#bms-4635e915b4180cf4)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="445" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="770">test-coverage</text><text x="445" y="130" transform="scale(.1)" fill="#fff" textLength="770">test-coverage</text><text aria-hidden="true" x="1035" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="250">51%</text><text x="1035" y="130" transform="scale(.1)" fill="#fff" textLength="250">51%</text></g></svg>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="122" height="18" role="img" aria-label="test-coverage: 50%"><title>test-coverage: 50%</title><linearGradient id="bms-8fc2dc264327201c" x2="0" y2="100%"><stop offset="0" stop-color="#fff" stop-opacity=".7"/><stop offset=".1" stop-color="#aaa" stop-opacity=".1"/><stop offset=".9" stop-color="#000" stop-opacity=".3"/><stop offset="1" stop-color="#000" stop-opacity=".5"/></linearGradient><clipPath id="bmr-8fc2dc264327201c"><rect width="122" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-8fc2dc264327201c)"><rect width="87" height="18" fill="#555"/><rect x="87" width="35" height="18" fill="#97ca00"/><rect width="122" height="18" fill="url(#bms-8fc2dc264327201c)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="445" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="770">test-coverage</text><text x="445" y="130" transform="scale(.1)" fill="#fff" textLength="770">test-coverage</text><text aria-hidden="true" x="1035" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="250">50%</text><text x="1035" y="130" transform="scale(.1)" fill="#fff" textLength="250">50%</text></g></svg>

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@ -1,5 +1,5 @@
[package]
name = "bin_efo"
name = "efo"
version = "0.1.0"
edition = "2024"

View File

@ -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;

View File

@ -1,474 +0,0 @@
//! Module handling the creation of characters
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,
error::EpochError,
stats::{EntityType, StatPair},
};
use log::info;
use crate::error::AppError;
use crate::success::display_success;
/// 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 {
/// Add an entity
Add(EntityArgs),
/// Delete an entity
Del(EntityArgs),
/// Edit an existing entity
Edit(EntityArgs),
/// Find an entity by its identifier
Find(EntityArgs),
/// Show the details of an entity
Show(EntityArgs),
/// Show differences between two entities
Diff(EntityArgs),
}
/// 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
pub identifier: Option<EntityIdentifier>,
// /// A name to change to
// #[arg(long, group = "identifier")]
// pub new_name: Option<String>,
/// Applies a delta to stats instead of setting the values
#[arg(long, short, action = clap::ArgAction::SetTrue, default_value_t = false)]
pub delta: bool,
/// Non specified stat Repartition
#[arg(value_enum, long, default_value_t = RngLevel::Zero)]
pub rng: RngLevel,
/// Adds at a specific position
#[arg(long, group = "position")]
pub pos_exact: Option<Position>,
/// Adds at a specific position
#[arg(long, group = "position")]
pub pos: Option<Position>,
/// The duration of the entity
#[arg(long)]
pub duration: Option<EntityDuration>,
/// The bounds of the effect of the entity
#[arg(long)]
pub bounds: Option<EffectBounds>,
/// How is the effect of the entity applied
#[arg(long)]
pub effect: Option<EffectApplication>,
/// All stats pairs involved
pub stats: Vec<StatPair>,
}
/// Handles an entity subcommand.
///
/// This function loads the main epoch configuration, then dispatches the
/// provided subcommand to the appropriate handler. It returns an
/// `AppError` if any operation fails.
///
/// # Arguments
/// * `entity_sub_commands` - The subcommand chosen by the user.
/// * `e_type` - The type of entity to operate on.
///
/// # Returns
/// A `Result` indicating success (`Ok(())`) or the encountered `AppError`.
pub fn handle_entity_commands(
entity_sub_commands: &EntitySubCommands,
e_type: &EntityType,
) -> Result<(), AppError> {
let mut main_epoch = EpochConfig::new_from_path(None)?;
match entity_sub_commands {
EntitySubCommands::Add(entity_args) => {
handle_create_entity(entity_args, e_type, &mut main_epoch)
}
EntitySubCommands::Del(entity_args) => {
handle_delete_entity(entity_args, e_type, &mut main_epoch)
}
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::Show(entity_args) => {
handle_show_entity(entity_args, e_type, &mut main_epoch)
}
EntitySubCommands::Diff(entity_args) => {
handle_diff_entity(entity_args, e_type, &mut main_epoch)
}
}?;
Ok(())
}
/// Function handler for the create subcommand
fn handle_create_entity(
entity_args: &EntityArgs,
e_type: &EntityType,
main_epoch: &mut EpochConfig,
) -> Result<(), EpochError> {
let epoch_info = main_epoch.try_load_current_as_mut()?;
let vec_entities: &mut Vec<Entity> = vec_entities_mut(e_type, epoch_info);
let mut entity = Entity::create_rng(e_type, &entity_args.rng)?;
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);
info!("Created character: {:#?}", entity);
entity.print_full();
let message = &crate::success::SuccessMessages::CreatedEntity(
entity.name.clone(),
entity.entity_type.to_shortest(),
entity.id.to_string(),
);
vec_entities.push(entity);
// No need to change main epoch that didn't change a serialized field
epoch_info.save_with_context("Created entity", &lib_efo::epoch::SaveMode::Erase)?;
display_success(message);
Ok(())
}
/// Function handler for the delete subcommand
fn handle_delete_entity(
entity_args: &EntityArgs,
e_type: &EntityType,
main_epoch: &mut EpochConfig,
) -> Result<(), EpochError> {
let epoch_info = main_epoch.try_load_current_as_mut()?;
let vec_entities: &mut Vec<Entity> = vec_entities_mut(e_type, epoch_info);
let index = vec_entities
.iter()
.position(|e| find_by_args(e, entity_args))
.ok_or(EpochError::EntityNotFound(
e_type.clone(),
entity_args.identifier.clone(),
))?;
let entity = vec_entities.swap_remove(index);
epoch_info.save_with_context("Deleted entity", &lib_efo::epoch::SaveMode::Erase)?;
display_success(&crate::success::SuccessMessages::DeletedEntity(
entity.name,
entity.entity_type.to_shortest(),
entity.id.to_string(),
));
Ok(())
}
/// Function handler for the diff subcommand
fn handle_diff_entity(
entity_args: &EntityArgs,
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);
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 diff = current_entity.delta(past_entity);
display_success(&crate::success::SuccessMessages::DiffBetweenEpoch(id, id2));
diff.print_full();
Ok(())
}
/// Function handler for the show subcommand
// TODO: Add filters else this will become very clustered
fn handle_show_entity(
entity_args: &EntityArgs,
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) {
entity.print_oneline();
}
} else {
let entity = find_entity(entity_args, 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 edit subcommand
fn handle_edit_entity(
entity_args: &EntityArgs,
e_type: &EntityType,
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 entity = vec_entities
.iter_mut()
.find(|e| find_by_args(e, entity_args))
.ok_or(EpochError::EntityNotFound(
e_type.clone(),
entity_args.identifier.clone(),
))?;
for stat in &entity_args.stats {
entity.change_stat(stat.clone());
}
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(effect) = &entity_args.effect {
entity.modify_effect_application(effect.clone());
}
if let Some(bounds) = &entity_args.bounds {
entity.modify_effect_bounds(bounds.clone());
}
entity.print_full();
let message = &crate::success::SuccessMessages::EditedEntity(
entity.name.clone(),
entity.entity_type.to_shortest(),
entity.id.to_string(),
);
epoch_info.save_with_context("Deleted entity", &lib_efo::epoch::SaveMode::Erase)?;
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<Entity> {
match e_type {
EntityType::Character => &epoch_info.characters,
EntityType::Player => todo!(),
EntityType::Town => &epoch_info.towns,
EntityType::Monster => todo!(),
EntityType::Blocker => todo!(),
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<Entity> {
match e_type {
EntityType::Character => &mut epoch_info.characters,
EntityType::Player => todo!(),
EntityType::Town => &mut epoch_info.towns,
EntityType::Monster => todo!(),
EntityType::Blocker => todo!(),
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);
}
}

View File

@ -0,0 +1,431 @@
//! ## 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** | `<entity> add [OPTIONS] [IDENTIFIER]` | Creates a new `<entity>`, pushes it to the epoch’s list, and writes the epoch. |
//! | **del** | `<entity> del <IDENTIFIER>` | Removes the matching `<entity>` from the list and writes the epoch. |
//! | **edit** | `<entity> edit <IDENTIFIER> [OPTIONS]` | Modifies the stats/position/duration/effect/bounds of the chosen `<entity>` and writes the epoch. |
//! | **find** | `<entity> find <IDENTIFIER>` | Prints full details of a single `<entity>`. |
//! | **show** | `<entity> show [<IDENTIFIER>]` | Lists all entities on one line, or shows one `<entity>` in full detail. |
//! | **diff** | `<entity> diff <IDENTIFIER>` | Prints the difference between the current and previous epoch for that `<entity>`. |
//!
//! *`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 | 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 <RNG>` | *add/edit* | How to initialise *missing* stats. Possible values: `zero`, `low`, `med`, `high`, `legendary`, `mixed`, `flawed`. Default: `zero`. |
//! | `--pos-exact <POS>` / `--pos <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 <DURATION>` | *add/edit* | Lifespan of the entity – e.g. `Permanent`, `Temporary` or `Duration(1)` for a one‑turn event. |
//! | `--bounds <BOUNDS>` | *add/edit* | Effect limits in the form `min,max` (e.g. `10,80`). |
//! | `--effect <EFFECT>` | *add/edit* | How the effect is applied: `recurring`, `when-present`, `permanent-effect-to-apply`, `permanent-effect-applied`. |
//! | `-s, --stats <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...
//!
//! ```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** – `<entity> 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 clap::{Args, Subcommand};
use lib_efo::{
Displayable,
entity::{EffectApplication, EffectBounds, Entity, EntityDuration, EntityIdentifier},
epoch::{
EpochConfig, EpochIdentifier,
epoch_traits::{ConfigWritable, Diffable},
},
error::EpochError,
stats::{EntityType, FactionId, Position, StatPair, Symbols},
utils::RngLevel,
};
use log::info;
use crate::error::AppError;
use crate::success::display_success;
mod helper_functions;
/// 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 {
// /// Find an entity by its identifier
// Find(EntityArgs),
/// 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 the difference between two epochs
Diff(DiffArgs),
}
/// Arguments used only for the `diff` sub‑command.
#[derive(Args, Debug)]
pub(crate) struct DiffArgs {
/// Identifier (name or `@tag`) of the entity to diff
pub identifier: EntityIdentifier,
/// Optional epoch to compare against.
/// If omitted the previous epoch is used.
#[arg(long, short = 'i')]
pub epoch_id: Option<EpochIdentifier>,
}
/// Arguments for deleting an entity.
#[derive(Args, Debug)]
pub(crate) struct DelArgs {
/// Identifier (name or `@tag`) of the entity to delete
pub identifier: EntityIdentifier,
}
/// Arguments for showing entities.
#[derive(Args, Debug)]
pub(crate) struct ShowArgs {
/// Optional identifier – when omitted all entities are listed.
pub identifier: Option<EntityIdentifier>,
/// Filter by faction id (used only when an identifier is supplied)
#[arg(long, short)]
pub faction: Option<FactionId>,
}
/// 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<String>,
/// 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,
/// 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<Position>,
/// Place the new entity using the map’s position rules.
#[arg(long, short = 'p', group = "position")]
pub pos: Option<Position>,
/// Lifespan of the entity – see the `--duration` description.
#[arg(long, short)]
pub duration: Option<EntityDuration>,
/// Effect bounds in the form `min,max`. See the `--bounds`
/// description for details.
#[arg(long, short)]
pub bounds: Option<EffectBounds>,
/// How the effect is applied – see the `--effect` description.
#[arg(long, short)]
pub effect: Option<EffectApplication>,
/// One or more `key:value` pairs that set the entity’s stats.
#[arg(short, long)]
pub stats: Vec<StatPair>,
}
#[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<String>,
/// 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<Position>,
/// Update the entity’s position using the map rules.
#[arg(long, short = 'p', group = "position")]
pub pos: Option<Position>,
/// New duration for the entity.
#[arg(long, short)]
pub duration: Option<EntityDuration>,
/// New effect bounds.
#[arg(long, short)]
pub bounds: Option<EffectBounds>,
/// New effect application mode.
#[arg(short, long)]
pub effect: Option<EffectApplication>,
/// One or more `key:value` pairs that modify the entity’s stats.
#[arg(short, long, num_args = 1..)]
pub stats: Vec<StatPair>,
}
/// Handles an entity subcommand.
///
/// This function loads the main epoch configuration, then dispatches the
/// provided subcommand to the appropriate handler. It returns an
/// `AppError` if any operation fails.
///
/// # Arguments
/// * `entity_sub_commands` - The subcommand chosen by the user.
/// * `e_type` - The type of entity to operate on.
///
/// # Returns
/// A `Result` indicating success (`Ok(())`) or the encountered `AppError`.
pub fn handle_entity_commands(
entity_sub_commands: &EntitySubCommands,
e_type: &EntityType,
) -> Result<(), AppError> {
let mut main_epoch = EpochConfig::new_from_path(None)?;
match entity_sub_commands {
EntitySubCommands::Add(entity_args) => {
handle_create_entity(entity_args, e_type, &mut main_epoch)
}
EntitySubCommands::Del(entity_args) => {
handle_delete_entity(entity_args, e_type, &mut main_epoch)
}
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::Show(entity_args) => {
handle_show_entity(entity_args, e_type, &mut main_epoch)
}
EntitySubCommands::Diff(entity_args) => {
handle_diff_entity(entity_args, e_type, &mut main_epoch)
}
}?;
Ok(())
}
/// Function handler for the create subcommand
pub(crate) fn handle_create_entity(
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(&ident, e_type, epoch_info).is_ok() {
Err(EpochError::EntityAlreadyExist(ident))?;
};
let vec_entities: &mut Vec<Entity> = 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.stats, false, &mut entity);
// Specifying a name means the name needs to be changed
// Specifying an id however means nothing and should be ignored
helper_functions::update_defaults(entity_args, &mut entity);
info!("Created character: {:#?}", entity);
entity.print_full();
let message = &crate::success::SuccessMessages::CreatedEntity(
entity.name.clone(),
entity.entity_type.to_shortest(),
entity.id.to_string(),
);
vec_entities.push(entity);
// No need to change main epoch that didn't change a serialized field
epoch_info.save_with_context("Created entity", &lib_efo::epoch::SaveMode::Erase)?;
display_success(message);
Ok(())
}
/// Function handler for the delete subcommand
fn handle_delete_entity(
entity_args: &DelArgs,
e_type: &EntityType,
main_epoch: &mut EpochConfig,
) -> Result<(), EpochError> {
let epoch_info = main_epoch.try_load_current_as_mut()?;
let entity_identifier = Some(entity_args.identifier.clone());
let vec_entities: &mut Vec<Entity> = helper_functions::vec_entities_mut(e_type, epoch_info);
let index = vec_entities
.iter()
.position(|entity| helper_functions::find_by_args(entity, &entity_identifier))
.ok_or(EpochError::EntityNotFound(
e_type.clone(),
entity_identifier,
))?;
let entity = vec_entities.swap_remove(index);
epoch_info.save_with_context("Deleted entity", &lib_efo::epoch::SaveMode::Erase)?;
display_success(&crate::success::SuccessMessages::DeletedEntity(
entity.name,
entity.entity_type.to_shortest(),
entity.id.to_string(),
));
Ok(())
}
/// Function handler for the diff subcommand
fn handle_diff_entity(
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 = 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 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));
diff.print_full();
Ok(())
}
/// Function handler for the show subcommand
// TODO: Add filters else this will become very clustered
fn handle_show_entity(
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 helper_functions::vec_entities(e_type, epoch_info) {
entity.print_oneline();
}
} else {
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 edit subcommand
fn handle_edit_entity(
entity_args: &EditArgs,
e_type: &EntityType,
main_epoch: &mut EpochConfig,
) -> Result<(), EpochError> {
let epoch_info = main_epoch.try_load_current_as_mut()?;
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, &Some(entity_args.identifier.clone()))
})
.ok_or(EpochError::EntityNotFound(
e_type.clone(),
Some(entity_args.identifier.clone()),
))?;
for stat in &entity_args.stats {
entity.change_stat(stat.clone());
}
if let Some(duration) = &entity_args.duration {
entity.modify_duration(duration.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());
}
if let Some(bounds) = &entity_args.bounds {
entity.modify_effect_bounds(bounds.clone());
}
entity.print_full();
let message = &crate::success::SuccessMessages::EditedEntity(
entity.name.clone(),
entity.entity_type.to_shortest(),
entity.id.to_string(),
);
epoch_info.save_with_context("Deleted entity", &lib_efo::epoch::SaveMode::Erase)?;
display_success(message);
Ok(())
}

View File

@ -0,0 +1,203 @@
//! All helper functions
use lib_efo::{
entity::{EffectBounds, Entity, EntityIdentifier},
error::EpochError,
naming::NAMING,
stats::{EntityType, StatPair},
};
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(pair_list: &Vec<StatPair>, 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 pair_list {
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<EntityIdentifier>,
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<Entity> {
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<Entity> {
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<EntityIdentifier>,
) -> 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: &AddArgs, 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(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);
}
}

View File

@ -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 <id>` | Sets the current epoch to the specified `<id>` (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 <id1> <id2>` | *Unimplemented* – placeholder for future diffing logic. |
//! | `tag` | `efo epoch tag <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 <text>` | Replaces the `summary` field of the current epoch with `<text>`. |
//!
#![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),
@ -132,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(())
}
@ -243,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)?;
@ -253,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(

View File

@ -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<String, String> {
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 {}

View File

@ -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)]
@ -50,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.
@ -74,6 +123,32 @@ 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.dry {
println!("{}", name);
// }
}
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(())
}
@ -82,11 +157,11 @@ pub fn gen_handler(cmd: &GenCmd) -> Result<(), AppError> {
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(())
}
@ -95,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(())
}
@ -108,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(())
}
@ -126,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(())
}

View File

@ -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,14 +60,14 @@ 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();
if read_dir(root)?.count() != 0 {
if read_dir(&root)?.count() != 0 {
Err(EpochError::FolderNotEmpty {
name: None,
name: root,
show_label: None,
})?;
}

View File

@ -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),
}

View File

@ -1,36 +1,36 @@
//! # `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
//! * [`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)]
use std::fmt::Debug;
use clap::{ArgAction, Parser, Subcommand};
use clap::{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,
};
@ -46,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,
@ -72,9 +71,20 @@ 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),
/// 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)]
@ -117,8 +127,25 @@ 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,
),
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,
),
}
}

View File

@ -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

View File

@ -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.
@ -28,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,
@ -90,26 +98,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<Self, Self::Err> {
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 {

View File

@ -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 {
@ -23,13 +23,13 @@ impl Displayable for Entity {
}
}
/// One-liner used for auto-generation of Vec<T> displays
/// One-liner used for auto-generation of `Vec<T>` displays
fn oneline_display(&self) -> String {
let capital = self
.metadata
.capital
.as_ref()
.map(|c| format!("󰻾[{:>2}] ", c).green())
.map(|c| format!("{} ", c.to_symbol()).green())
.unwrap_or_default();
let governor = self
@ -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<cli_table::TableDisplay, EpochError> {
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.
@ -183,7 +161,10 @@ impl Entity {
&format!(
"├─ {}: {:?}\n",
"capital".bright_green(),
self.metadata.capital
self.metadata
.capital
.map(|c| c.to_symbol())
.unwrap_or_default()
),
));
}
@ -214,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()),
));
}
}
@ -284,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
@ -325,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
@ -376,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(),
}
}
}

View File

@ -4,6 +4,7 @@ expression: "format!(\"{:#?}\", e)"
---
Entity {
name: "",
description: "",
id: 00000000-0000-0000-0000-000000000000,
stats: OverallStats {
demographics: GenericStat(

View File

@ -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(
@ -145,7 +146,7 @@ Entity {
),
links: [
TownId(
6,
00000000-0000-0000-0000-000000000079,
),
],
prestige: GenericStat(

View File

@ -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(
@ -138,7 +139,7 @@ Entity {
),
capital: Some(
TownId(
5000,
00000000-0000-0000-0000-00000000007c,
),
),
governor: Some(

View File

@ -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(
@ -138,7 +139,7 @@ Entity {
),
capital: Some(
TownId(
3000,
00000000-0000-0000-0000-000000000079,
),
),
governor: Some(

View File

@ -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)

View File

@ -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📈
│ └─  󰻾[50]  󰻾[11]
│ ├─ Faction: 2 │ Effect: ⟳ (1 ⭾ 5), Stats: 0 0💰 0 0󰡢 3
│ └─  󰻾[0000000]  󰻾[11]
│

View File

@ -14,11 +14,7 @@ MetaStats {
33,
),
),
links: [
TownId(
55,
),
],
links: [],
prestige: GenericStat(
0,
),

View File

@ -16,7 +16,7 @@ MetaStats {
),
links: [
TownId(
55,
00000000-0000-0000-0000-000000000002,
),
],
prestige: GenericStat(

View File

@ -9,7 +9,7 @@ MetaStats {
),
capital: Some(
TownId(
1500,
00000000-0000-0000-0000-00000000000c,
),
),
governor: Some(

View File

@ -4,6 +4,7 @@ expression: "format!(\"{:#?}\", e)"
---
Entity {
name: "",
description: "",
id: 00000000-0000-0000-0000-000000000000,
stats: OverallStats {
demographics: GenericStat(

View File

@ -4,6 +4,7 @@ expression: "format!(\"{:#?}\", e)"
---
Entity {
name: "",
description: "",
id: 00000000-0000-0000-0000-000000000000,
stats: OverallStats {
demographics: GenericStat(

View File

@ -4,6 +4,7 @@ expression: "format!(\"{:#?}\", e)"
---
Entity {
name: "",
description: "",
id: 00000000-0000-0000-0000-000000000000,
stats: OverallStats {
demographics: GenericStat(

View File

@ -232,18 +232,19 @@ 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,
effect_bounds: EffectBounds::from((1, 5)),
stats: stats::OverallStats::default(),
temp_stats: Some(stats::OverallStats::default()),
description: String::from("Bob"),
}
}
@ -369,16 +370,17 @@ 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,
duration: EntityDuration::Permanent,
effect_nature: EffectApplication::Recurring,
effect_bounds: EffectBounds::from(0..33),
description: "Ello".to_string(),
};
let e2 = Entity {
@ -388,16 +390,17 @@ 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,
duration: EntityDuration::Permanent,
effect_nature: EffectApplication::Recurring,
effect_bounds: EffectBounds::from(0..3),
description: "Ilo".to_string(),
};
// Compute the delta
@ -452,19 +455,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 +475,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),
};

View File

@ -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

View File

@ -45,7 +45,7 @@ pub struct EpochConfig {
/// Optional human-friendly tags (e.g. `"winter-B"`, `"post-war"`).
pub tags: HashMap<String, EpochId>,
// TODO[6]: Can become important
// TODO(6): Can become important
// #[serde(skip)]
// /// Absolute path to `epoch/<epoch_id>/`.
// 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<EpochInfo, EpochError> {
// 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();
@ -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(())
}
@ -391,6 +391,7 @@ impl EpochConfig {
/// * `Err(EpochError::EntityNotFoundById(id))` - No entity with the
/// supplied UUID exists in the epoch.
///
#[allow(dead_code)]
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 +401,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))
}
}

View File

@ -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<Entity>,
@ -63,6 +63,12 @@ pub struct EpochInfo {
#[table(skip)]
/// The list of towns currently present
pub towns: Vec<Entity>,
#[table(skip)]
/// The list of calamities currently present
pub calamities: Vec<Entity>,
#[table(skip)]
/// The list of blockers currently present
pub blockers: Vec<Entity>,
}
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(),
}
}
}

View File

@ -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<cli_table::TableDisplay, EpochError>
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

View File

@ -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,9 +47,8 @@ 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 {
/// Problems with the `.epochconfig` file.
#[error("Failed to read epoch configuration")]
@ -63,7 +62,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 +76,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<String>,
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 +122,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.
@ -216,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),
@ -243,48 +245,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<EntityIdentifier>),
/// 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,22 +299,46 @@ 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))]
#[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<EntityIdentifier>),
/// 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.

View File

@ -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<T>`) 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
@ -21,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;

View File

@ -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

View File

@ -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.
@ -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,
@ -299,6 +299,7 @@ impl OverallStats {
/// Updates with leader
/// etc.
// TODO: Fill this
#[allow(dead_code)]
fn apply_exteriors(&mut self) {}
#[cfg(test)]
@ -425,7 +426,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 +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<Self, EpochError> {
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
@ -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 {

View File

@ -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 <TYPE>` where the only difference between
/// multiple implementations is the visibility level.
///
@ -449,6 +398,150 @@ impl Symbols for Option<FactionId> {
}
}
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<Self, Self::Err> {
// Trim whitespace just in case and attempt to parse.
let inner = s
.trim()
.parse::<usize>()
.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:
/// ```
/// # 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`).
#[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)]

View File

@ -15,7 +15,7 @@ impl FromStr for StatPair {
/// If the format is invalid, an `EpochError::IllFormedStatQualifier`
/// is returned.
fn from_str(s: &str) -> Result<Self, Self::Err> {
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();

View File

@ -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;
@ -15,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);
}

View File

@ -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<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,
})
}};
}