From cd7140822335edee443f8075bf91028d93cac65e Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 14 Dec 2025 02:37:58 +0100 Subject: [PATCH] Adds more sense in the Uuid --- bin_efo/src/commands/entity_generic.rs | 321 +++++------------- .../entity_generic/helper_functions.rs | 204 +++++++++++ bin_efo/src/error.rs | 8 +- lib_efo/src/entity.rs | 36 +- lib_efo/src/entity/implementations.rs | 9 +- ...entity__test__snapshot_entity_delta-2.snap | 2 +- ...entity__test__snapshot_entity_delta-3.snap | 2 +- ...__entity__test__snapshot_entity_delta.snap | 2 +- ...test__snapshot_full_oneline_display-2.snap | 4 +- ...__test__snapshot_full_oneline_display.snap | 2 +- ...ty__test__snapshot_meta_stats_delta-2.snap | 6 +- ...ty__test__snapshot_meta_stats_delta-3.snap | 2 +- ...tity__test__snapshot_meta_stats_delta.snap | 2 +- lib_efo/src/entity/test.rs | 22 +- lib_efo/src/epoch/epoch_config.rs | 1 - lib_efo/src/error.rs | 16 +- lib_efo/src/lib.rs | 2 +- lib_efo/src/stats.rs | 14 +- lib_efo/src/stats/implementations.rs | 197 ++++++++--- .../src/stats/implementations/from_impl.rs | 2 +- lib_efo/src/stats/implementations/test.rs | 18 +- 21 files changed, 523 insertions(+), 349 deletions(-) create mode 100644 bin_efo/src/commands/entity_generic/helper_functions.rs diff --git a/bin_efo/src/commands/entity_generic.rs b/bin_efo/src/commands/entity_generic.rs index 78df840..5ab2ed3 100644 --- a/bin_efo/src/commands/entity_generic.rs +++ b/bin_efo/src/commands/entity_generic.rs @@ -62,43 +62,79 @@ //! //! *All changes are persisted immediately to the epoch file after the command finishes.* -use lib_efo::entity::{EffectApplication, EffectBounds, EntityDuration, EntityIdentifier}; -use lib_efo::epoch::epoch_traits::{ConfigWritable, Diffable}; -use lib_efo::naming::NAMING; -use lib_efo::stats::{Position, Symbols}; - use clap::{Args, Subcommand}; -use lib_efo::Displayable; -use lib_efo::utils::RngLevel; use lib_efo::{ - entity::Entity, - epoch::EpochConfig, + Displayable, + entity::{EffectApplication, EffectBounds, Entity, EntityDuration, EntityIdentifier}, + epoch::{ + EpochConfig, EpochIdentifier, + epoch_traits::{ConfigWritable, Diffable}, + }, error::EpochError, - stats::{EntityType, StatPair}, + stats::{EntityType, FactionId, Position, StatPair, Symbols}, + utils::RngLevel, }; use log::info; use crate::error::AppError; use crate::success::display_success; +mod helper_functions; + /// Commands that operate on an entity. /// /// Each variant represents a different operation that can be performed on an /// entity. The variant holds the arguments that are common to all operations. #[derive(Subcommand, Debug)] -pub enum EntitySubCommands { +pub(crate) enum EntitySubCommands { /// Add an entity Add(EntityArgs), /// Delete an entity - Del(EntityArgs), + Del(DelArgs), /// Edit an existing entity Edit(EntityArgs), - /// Find an entity by its identifier - Find(EntityArgs), + // /// Find an entity by its identifier + // Find(EntityArgs), /// Show the details of an entity - Show(EntityArgs), + Show(ShowArgs), /// Show differences between two entities - Diff(EntityArgs), + Diff(DiffArgs), +} + +#[derive(Args, Debug)] +/// Arguments reserved for diffing +pub(crate) struct DiffArgs { + /// The identifier either a name or a @tag + identifier: EntityIdentifier, + + /// Another epoch than the previous + epoch_id: Option, +} + +#[derive(Args, Debug)] +/// Arguments required for any entity deletion +pub(crate) struct DelArgs { + /// The identifier either a name or a @tag + identifier: EntityIdentifier, +} + +#[derive(Args, Debug)] +/// Arguments required for showing any entity +pub(crate) struct ShowArgs { + /// The identifier either a name or a @tag + #[arg(long, short)] + identifier: Option, + + #[arg(long, short)] + /// Show only if belonging to faction + faction: Option, + // /// Show only if in a specific town + // #[arg(long, short)] + // town: Option, + // // + // /// Show only if not done + // #[arg(long, short, action = clap::ArgAction::SetTrue, default_value_t = Some(false))] + // valid: Option, } /// Arguments required for any entity operation. @@ -173,9 +209,9 @@ pub fn handle_entity_commands( EntitySubCommands::Edit(entity_args) => { handle_edit_entity(entity_args, e_type, &mut main_epoch) } - EntitySubCommands::Find(entity_args) => { - handle_find_entity(entity_args, e_type, &mut main_epoch) - } + // EntitySubCommands::Find(entity_args) => { + // handle_find_entity(entity_args, e_type, &mut main_epoch) + // } EntitySubCommands::Show(entity_args) => { handle_show_entity(entity_args, e_type, &mut main_epoch) } @@ -194,20 +230,20 @@ fn handle_create_entity( ) -> Result<(), EpochError> { let epoch_info = main_epoch.try_load_current_as_mut()?; - if find_entity(entity_args, e_type, epoch_info).is_ok() { + if helper_functions::find_entity(&entity_args.identifier, e_type, epoch_info).is_ok() { Err(EpochError::EntityAlreadyExist( entity_args.identifier.clone(), ))?; }; - let vec_entities: &mut Vec = vec_entities_mut(e_type, epoch_info); + let vec_entities: &mut Vec = helper_functions::vec_entities_mut(e_type, epoch_info); let mut entity = Entity::create_rng(e_type, &entity_args.rng)?; - update_stats(entity_args, &mut entity); + helper_functions::update_stats(entity_args, &mut entity); // Specifying a name means the name needs to be changed // Specifying an id however means nothing and should be ignored - update_defaults(entity_args, &mut entity); + helper_functions::update_defaults(entity_args, &mut entity); info!("Created character: {:#?}", entity); entity.print_full(); @@ -227,19 +263,20 @@ fn handle_create_entity( /// Function handler for the delete subcommand fn handle_delete_entity( - entity_args: &EntityArgs, + entity_args: &DelArgs, e_type: &EntityType, main_epoch: &mut EpochConfig, ) -> Result<(), EpochError> { let epoch_info = main_epoch.try_load_current_as_mut()?; - let vec_entities: &mut Vec = vec_entities_mut(e_type, epoch_info); + let entity_identifier = Some(entity_args.identifier.clone()); + let vec_entities: &mut Vec = helper_functions::vec_entities_mut(e_type, epoch_info); let index = vec_entities .iter() - .position(|e| find_by_args(e, entity_args)) + .position(|entity| helper_functions::find_by_args(entity, &entity_identifier)) .ok_or(EpochError::EntityNotFound( e_type.clone(), - entity_args.identifier.clone(), + entity_identifier, ))?; let entity = vec_entities.swap_remove(index); @@ -255,20 +292,25 @@ fn handle_delete_entity( /// Function handler for the diff subcommand fn handle_diff_entity( - entity_args: &EntityArgs, + entity_args: &DiffArgs, e_type: &EntityType, main_epoch: &mut EpochConfig, ) -> Result<(), EpochError> { // Load the epochs to diff let id = main_epoch.epoch_id; - let id2 = main_epoch.epoch_id.add_to_epoch(-1); + let id2 = if let Some(old_id) = &entity_args.epoch_id { + main_epoch.get_epoch_id(old_id)? + } else { + main_epoch.epoch_id.add_to_epoch(-1) + }; main_epoch.try_load(&id)?; main_epoch.try_load(&id2)?; let epoch_current = unsafe { main_epoch.try_load_id(id) }?; let epoch_past = unsafe { main_epoch.try_load_id(id2) }?; - let current_entity = find_entity(entity_args, e_type, epoch_current)?; - let past_entity = find_entity(entity_args, e_type, epoch_past)?; + let binding = Some(entity_args.identifier.clone()); + let current_entity = helper_functions::find_entity(&binding, e_type, epoch_current)?; + let past_entity = helper_functions::find_entity(&binding, e_type, epoch_past)?; let diff = current_entity.delta(past_entity); display_success(&crate::success::SuccessMessages::DiffBetweenEpoch(id, id2)); @@ -280,30 +322,30 @@ fn handle_diff_entity( /// Function handler for the show subcommand // TODO: Add filters else this will become very clustered fn handle_show_entity( - entity_args: &EntityArgs, + entity_args: &ShowArgs, e_type: &EntityType, main_epoch: &mut EpochConfig, ) -> Result<(), EpochError> { let epoch_info = main_epoch.try_load_current()?; if entity_args.identifier.is_none() { - for entity in vec_entities(e_type, epoch_info) { + for entity in helper_functions::vec_entities(e_type, epoch_info) { entity.print_oneline(); } } else { - let entity = find_entity(entity_args, e_type, epoch_info)?; + let entity = helper_functions::find_entity(&entity_args.identifier, e_type, epoch_info)?; entity.print_full(); } Ok(()) } -/// Function handler for the find subcommand -fn handle_find_entity( - entity_args: &EntityArgs, - e_type: &EntityType, - main_epoch: &mut EpochConfig, -) -> Result<(), EpochError> { - handle_show_entity(entity_args, e_type, main_epoch) -} +// /// Function handler for the find subcommand +// fn handle_find_entity( +// entity_args: &EntityArgs, +// e_type: &EntityType, +// main_epoch: &mut EpochConfig, +// ) -> Result<(), EpochError> { +// handle_show_entity(entity_args, e_type, main_epoch) +// } /// Function handler for the edit subcommand fn handle_edit_entity( @@ -312,10 +354,10 @@ fn handle_edit_entity( main_epoch: &mut EpochConfig, ) -> Result<(), EpochError> { let epoch_info = main_epoch.try_load_current_as_mut()?; - let vec_entities = vec_entities_mut(e_type, epoch_info); + let vec_entities = helper_functions::vec_entities_mut(e_type, epoch_info); let entity = vec_entities .iter_mut() - .find(|e| find_by_args(e, entity_args)) + .find(|entity| helper_functions::find_by_args(entity, &entity_args.identifier)) .ok_or(EpochError::EntityNotFound( e_type.clone(), entity_args.identifier.clone(), @@ -351,194 +393,3 @@ fn handle_edit_entity( display_success(message); Ok(()) } - -/// Update the given stats with the given argumenbts -/// Note that this function will not change name & id due to the usage variance between caller -fn update_stats(entity_args: &EntityArgs, e: &mut Entity) { - if entity_args.delta { - for stat in &entity_args.stats { - e.delta_stat(stat.clone()); - } - } else { - for stat in &entity_args.stats { - e.change_stat(stat.clone()); - } - } -} - -/// Looks up an entity inside the given `epoch_info` according to the -/// supplied arguments. -/// -/// The function returns a reference to the matching entity or an -/// `EpochError::EntityNotFound` if no entity matches. -/// -/// # Arguments -/// * `entity_args` - The arguments that identify the entity. -/// * `e_type` - The type of entity to look for. -/// * `epoch_info` - The epoch that contains all entities. -/// -/// # Returns -/// * `Ok(&Entity)` - The entity that matches the arguments. -/// * `Err(EpochError::EntityNotFound)` - No matching entity was found. -fn find_entity<'a>( - entity_args: &'a EntityArgs, - e_type: &'a EntityType, - epoch_info: &'a lib_efo::epoch::EpochInfo, -) -> Result<&'a Entity, EpochError> { - vec_entities(e_type, epoch_info) - .iter() - .find(|&e| find_by_args(e, entity_args)) - .ok_or(EpochError::EntityNotFound( - e_type.clone(), - entity_args.identifier.clone(), - )) -} - -/// Returns a slice over the entities of the requested type from the given `EpochInfo`. -/// -/// The function matches the supplied `e_type` to the appropriate collection -/// inside `epoch_info`. For unimplemented entity types the call will panic -/// because of the `todo!()` placeholder. -/// -/// # Arguments -/// * `e_type` - The type of entities to retrieve. -/// * `epoch_info` - The epoch information containing the collections. -/// -/// # Returns -/// A reference to the vector containing the requested entities. -/// The lifetime of the returned slice is tied to that of `epoch_info`. -#[inline] -fn vec_entities<'a>( - e_type: &'a EntityType, - epoch_info: &'a lib_efo::epoch::EpochInfo, -) -> &'a Vec { - match e_type { - EntityType::Character => &epoch_info.characters, - EntityType::Player => todo!(), - EntityType::Town => &epoch_info.towns, - EntityType::Monster => &epoch_info.calamities, - EntityType::Blocker => &epoch_info.blockers, - EntityType::Event => &epoch_info.events, - } -} - -#[inline] -/// Returns a mutable slice over the entities of the requested type from the given -/// `EpochInfo`. -/// -/// Like `vec_entities`, this function selects the appropriate collection -/// based on `e_type`. Unimplemented variants will panic due to the `todo!()`. -/// -/// # Arguments -/// * `e_type` - The type of entities to retrieve. -/// * `epoch_info` - The epoch information containing the collections. -/// -/// # Returns -/// A mutable reference to the vector containing the requested entities. -/// The lifetime of the returned slice is tied to that of `epoch_info`. -fn vec_entities_mut<'a>( - e_type: &'a EntityType, - epoch_info: &'a mut lib_efo::epoch::EpochInfo, -) -> &'a mut Vec { - match e_type { - EntityType::Character => &mut epoch_info.characters, - EntityType::Player => todo!(), - EntityType::Town => &mut epoch_info.towns, - EntityType::Monster => &mut epoch_info.calamities, - EntityType::Blocker => &mut epoch_info.blockers, - EntityType::Event => &mut epoch_info.events, - } -} - -/// Helper function finding by name, note that a lot more helpers could be done to find by other criterias -fn find_by_args(entity: &Entity, entity_args: &EntityArgs) -> bool { - match entity_args.identifier { - Some(EntityIdentifier::Name(ref name)) => entity.name.starts_with(name), - Some(EntityIdentifier::Id(ref id)) => entity.id.hyphenated().to_string().starts_with(id), - None => false, - } -} - -/// Find an entity matching a tag -#[allow(dead_code)] -fn find_by_id<'a>(entities: &'a [Entity], id: &'a String) -> Option<&'a Entity> { - entities - .iter() - .find(|e| e.id.hyphenated().to_string().starts_with(id)) -} - -/// Find an entity matching a name -#[allow(dead_code)] -fn find_by_name<'a>(entities: &'a [Entity], id: &'a String) -> Option<&'a Entity> { - entities.iter().find(|e| e.name.starts_with(id)) -} - -/// Update the default values of the entity with sensible defaults -fn update_defaults(entity_args: &EntityArgs, e: &mut Entity) { - let entity_type = &e.entity_type; - - let (duration, effect, bounds, name) = match entity_type { - EntityType::Character => ( - lib_efo::entity::EntityDuration::Permanent, - lib_efo::entity::EffectApplication::WhenPresent, - EffectBounds { min: 20, max: 110 }, - NAMING.generate_character_name(), - ), - EntityType::Player => ( - lib_efo::entity::EntityDuration::Permanent, - lib_efo::entity::EffectApplication::WhenPresent, - EffectBounds { min: 0, max: 120 }, - NAMING.generate_exotic_character_name(), - ), - EntityType::Town => ( - lib_efo::entity::EntityDuration::Permanent, - lib_efo::entity::EffectApplication::WhenPresent, - EffectBounds { min: 20, max: 60 }, - NAMING.generate_town_name(), - ), - EntityType::Monster => ( - lib_efo::entity::EntityDuration::Permanent, - lib_efo::entity::EffectApplication::WhenPresent, - EffectBounds { min: 20, max: 80 }, - NAMING.generate_calamity_name(), - ), - EntityType::Blocker => ( - lib_efo::entity::EntityDuration::Permanent, - lib_efo::entity::EffectApplication::WhenPresent, - EffectBounds { min: 0, max: 120 }, - NAMING.generate_blocker_name(), - ), - EntityType::Event => ( - lib_efo::entity::EntityDuration::Duration(1), - lib_efo::entity::EffectApplication::PermanentEffectToApply, - EffectBounds { min: 10, max: 80 }, - NAMING.random_event_name(), - ), - }; - // This is the sensible default for all creatures & characters - if let Some(duration) = &entity_args.duration { - e.modify_duration(duration.clone()); - } else { - e.modify_duration(duration); - } - - if let Some(EntityIdentifier::Name(name)) = &entity_args.identifier { - e.name = name.clone() - } else { - e.name = name - } - - // This is the sensible default for all creatures & characters - if let Some(effect) = &entity_args.effect { - e.modify_effect_application(effect.clone()); - } else { - e.modify_effect_application(effect); - } - - // This is the sensible default for characters - if let Some(bounds) = &entity_args.bounds { - e.modify_effect_bounds(bounds.clone()); - } else { - e.modify_effect_bounds(bounds); - } -} diff --git a/bin_efo/src/commands/entity_generic/helper_functions.rs b/bin_efo/src/commands/entity_generic/helper_functions.rs new file mode 100644 index 0000000..fa135d5 --- /dev/null +++ b/bin_efo/src/commands/entity_generic/helper_functions.rs @@ -0,0 +1,204 @@ +//! All helper functions + +use lib_efo::{ + entity::{EffectBounds, Entity, EntityIdentifier}, + error::EpochError, + naming::NAMING, + stats::EntityType, +}; + +use super::EntityArgs; + +/// Update the given stats with the given argumenbts +/// Note that this function will not change name & id due to the usage variance between caller +pub(crate) fn update_stats(entity_args: &EntityArgs, e: &mut Entity) { + if entity_args.delta { + for stat in &entity_args.stats { + e.delta_stat(stat.clone()); + } + } else { + for stat in &entity_args.stats { + e.change_stat(stat.clone()); + } + } +} + +/// Looks up an entity inside the given `epoch_info` according to the +/// supplied arguments. +/// +/// The function returns a reference to the matching entity or an +/// `EpochError::EntityNotFound` if no entity matches. +/// +/// # Arguments +/// * `entity_args` - The arguments that identify the entity. +/// * `e_type` - The type of entity to look for. +/// * `epoch_info` - The epoch that contains all entities. +/// +/// # Returns +/// * `Ok(&Entity)` - The entity that matches the arguments. +/// * `Err(EpochError::EntityNotFound)` - No matching entity was found. +pub(crate) fn find_entity<'a>( + entity_to_find: &'a Option, + e_type: &'a EntityType, + epoch_info: &'a lib_efo::epoch::EpochInfo, +) -> Result<&'a Entity, EpochError> { + vec_entities(e_type, epoch_info) + .iter() + .find(|&entity| find_by_args(entity, entity_to_find)) + .ok_or(EpochError::EntityNotFound( + e_type.clone(), + entity_to_find.clone(), + )) +} + +/// Returns a slice over the entities of the requested type from the given `EpochInfo`. +/// +/// The function matches the supplied `e_type` to the appropriate collection +/// inside `epoch_info`. For unimplemented entity types the call will panic +/// because of the `todo!()` placeholder. +/// +/// # Arguments +/// * `e_type` - The type of entities to retrieve. +/// * `epoch_info` - The epoch information containing the collections. +/// +/// # Returns +/// A reference to the vector containing the requested entities. +/// The lifetime of the returned slice is tied to that of `epoch_info`. +#[inline] +pub(crate) fn vec_entities<'a>( + e_type: &'a EntityType, + epoch_info: &'a lib_efo::epoch::EpochInfo, +) -> &'a Vec { + match e_type { + EntityType::Character => &epoch_info.characters, + EntityType::Player => todo!(), + EntityType::Town => &epoch_info.towns, + EntityType::Monster => &epoch_info.calamities, + EntityType::Blocker => &epoch_info.blockers, + EntityType::Event => &epoch_info.events, + } +} + +#[inline] +/// Returns a mutable slice over the entities of the requested type from the given +/// `EpochInfo`. +/// +/// Like `vec_entities`, this function selects the appropriate collection +/// based on `e_type`. Unimplemented variants will panic due to the `todo!()`. +/// +/// # Arguments +/// * `e_type` - The type of entities to retrieve. +/// * `epoch_info` - The epoch information containing the collections. +/// +/// # Returns +/// A mutable reference to the vector containing the requested entities. +/// The lifetime of the returned slice is tied to that of `epoch_info`. +pub(crate) fn vec_entities_mut<'a>( + e_type: &'a EntityType, + epoch_info: &'a mut lib_efo::epoch::EpochInfo, +) -> &'a mut Vec { + match e_type { + EntityType::Character => &mut epoch_info.characters, + EntityType::Player => todo!(), + EntityType::Town => &mut epoch_info.towns, + EntityType::Monster => &mut epoch_info.calamities, + EntityType::Blocker => &mut epoch_info.blockers, + EntityType::Event => &mut epoch_info.events, + } +} + +/// Helper function finding by name, note that a lot more helpers could be done to find by other criterias +pub(crate) fn find_by_args( + entity_to_match: &Entity, + entity_identifier: &Option, +) -> bool { + match entity_identifier { + Some(EntityIdentifier::Name(name)) => entity_to_match.name.starts_with(name), + Some(EntityIdentifier::Id(id)) => { + entity_to_match.id.hyphenated().to_string().starts_with(id) + } + None => false, + } +} + +// /// Find an entity matching a tag +// pub(crate) fn find_by_id<'a>(entities: &'a [Entity], id: &'a String) -> Option<&'a Entity> { +// entities +// .iter() +// .find(|e| e.id.hyphenated().to_string().starts_with(id)) +// } + +// /// Find an entity matching a name +// pub(crate) fn find_by_name<'a>(entities: &'a [Entity], id: &'a String) -> Option<&'a Entity> { +// entities.iter().find(|e| e.name.starts_with(id)) +// } + +/// Update the default values of the entity with sensible defaults +pub(crate) fn update_defaults(entity_args: &EntityArgs, e: &mut Entity) { + let entity_type = &e.entity_type; + + let (duration, effect, bounds, name) = match entity_type { + EntityType::Character => ( + lib_efo::entity::EntityDuration::Permanent, + lib_efo::entity::EffectApplication::WhenPresent, + EffectBounds { min: 20, max: 110 }, + NAMING.generate_character_name(), + ), + EntityType::Player => ( + lib_efo::entity::EntityDuration::Permanent, + lib_efo::entity::EffectApplication::WhenPresent, + EffectBounds { min: 0, max: 120 }, + NAMING.generate_exotic_character_name(), + ), + EntityType::Town => ( + lib_efo::entity::EntityDuration::Permanent, + lib_efo::entity::EffectApplication::WhenPresent, + EffectBounds { min: 20, max: 60 }, + NAMING.generate_town_name(), + ), + EntityType::Monster => ( + lib_efo::entity::EntityDuration::Permanent, + lib_efo::entity::EffectApplication::WhenPresent, + EffectBounds { min: 20, max: 80 }, + NAMING.generate_calamity_name(), + ), + EntityType::Blocker => ( + lib_efo::entity::EntityDuration::Permanent, + lib_efo::entity::EffectApplication::WhenPresent, + EffectBounds { min: 0, max: 120 }, + NAMING.generate_blocker_name(), + ), + EntityType::Event => ( + lib_efo::entity::EntityDuration::Duration(1), + lib_efo::entity::EffectApplication::PermanentEffectToApply, + EffectBounds { min: 10, max: 80 }, + NAMING.random_event_name(), + ), + }; + // This is the sensible default for all creatures & characters + if let Some(duration) = &entity_args.duration { + e.modify_duration(duration.clone()); + } else { + e.modify_duration(duration); + } + + if let Some(EntityIdentifier::Name(name)) = &entity_args.identifier { + e.name = name.clone() + } else { + e.name = name + } + + // This is the sensible default for all creatures & characters + if let Some(effect) = &entity_args.effect { + e.modify_effect_application(effect.clone()); + } else { + e.modify_effect_application(effect); + } + + // This is the sensible default for characters + if let Some(bounds) = &entity_args.bounds { + e.modify_effect_bounds(bounds.clone()); + } else { + e.modify_effect_bounds(bounds); + } +} diff --git a/bin_efo/src/error.rs b/bin_efo/src/error.rs index cf2e886..dfc063f 100644 --- a/bin_efo/src/error.rs +++ b/bin_efo/src/error.rs @@ -11,7 +11,6 @@ use thiserror::Error; /// All errors that can bubble up to the CLI. #[derive(Debug, Error, Diagnostic)] -#[allow(dead_code)] pub enum AppError { /// Generic “invalid command / missing flag” - emitted by clap. #[error("Command-line error: {0}")] @@ -32,8 +31,7 @@ pub enum AppError { #[error("Storage error: {0}")] // #[diagnostic(transparent)] Storage(#[from] StorageError), - - /// Anything else we didn't anticipate. - #[error("Unknown error: {0}")] - Other(String), + // /// Anything else we didn't anticipate. + // #[error("Unknown error: {0}")] + // Other(String), } diff --git a/lib_efo/src/entity.rs b/lib_efo/src/entity.rs index f99eddd..ca0fcea 100644 --- a/lib_efo/src/entity.rs +++ b/lib_efo/src/entity.rs @@ -11,12 +11,17 @@ //! logic that distinguishes creatures, items, terrain, etc. //! +use std::str::FromStr; + use clap::ValueEnum; use derive_more::{Add, Display, Sub}; use serde::{Deserialize, Serialize}; use uuid::Uuid; -use crate::stats::{EntityType, MetaStats, OverallStats}; +use crate::{ + error::EpochError, + stats::{EntityType, MetaStats, OverallStats}, +}; pub mod implementations; /// An entity that can be present in the game world. @@ -90,26 +95,39 @@ pub struct EffectBounds { #[derive(Debug, Serialize, Deserialize, Clone, Default, ValueEnum)] pub enum EffectApplication { /// Repeatedly applied every turn while the entity is present. - /// Use with caution, as this can produce catastrophic results - /// (e.g., an ever-erupting terrain). Recurring, /// Modifies the attached entity's stats only while present. - /// Removed when the entity is removed. Common for leaders, - /// temporary events, or terrain. WhenPresent, - /// Permanently modifies stats; the change persists after - /// the event ends. + /// Permanently modifies stats #[default] PermanentEffectToApply, /// Indicates that a permanent effect has already been applied. - /// Useful for bookkeeping when a long-lasting event applies - /// its effect only once. PermanentEffectApplied, } +impl FromStr for EffectApplication { + type Err = EpochError; + + fn from_str(s: &str) -> Result { + match s { + _ if s.starts_with("re") => Ok(EffectApplication::Recurring), + _ if s.starts_with("wh") => Ok(EffectApplication::WhenPresent), + _ if s.contains("present") => Ok(EffectApplication::WhenPresent), + _ if s.contains("toap") => Ok(EffectApplication::WhenPresent), + _ if s.starts_with("appl") => Ok(EffectApplication::WhenPresent), + "done" | "ok" => Ok(EffectApplication::PermanentEffectApplied), + "todo" => Ok(EffectApplication::PermanentEffectToApply), + _ => Err(EpochError::ParsingArgument { + argument_parsed: s.to_string(), + while_parsing: "The argument could't be made into a EffectApplication", + }), + } + } +} + /// Represents how long an entity remains active in the world. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default)] pub enum EntityDuration { diff --git a/lib_efo/src/entity/implementations.rs b/lib_efo/src/entity/implementations.rs index dadcb22..7715044 100644 --- a/lib_efo/src/entity/implementations.rs +++ b/lib_efo/src/entity/implementations.rs @@ -29,7 +29,7 @@ impl Displayable for Entity { .metadata .capital .as_ref() - .map(|c| format!(" 󰻾[{:>2}] ", c).green()) + .map(|c| format!(" {} ", c.to_symbol()).green()) .unwrap_or_default(); let governor = self @@ -161,7 +161,10 @@ impl Entity { &format!( "├─ {}: {:?}\n", "capital".bright_green(), - self.metadata.capital + self.metadata + .capital + .map(|c| c.to_symbol()) + .unwrap_or_default() ), )); } @@ -192,7 +195,7 @@ impl Entity { let symbol = if last { "└─" } else { "├─" }; out.push_str(&indent( 1, - &format!("{} 󰻾[{}]\n", symbol, link.to_string().yellow()), + &format!("{} {}\n", symbol, link.to_symbol().yellow()), )); } } diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta-2.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta-2.snap index 58a59f3..a813809 100644 --- a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta-2.snap +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta-2.snap @@ -145,7 +145,7 @@ Entity { ), links: [ TownId( - 6, + 00000000-0000-0000-0000-000000000079, ), ], prestige: GenericStat( diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta-3.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta-3.snap index 548c7f5..ec02a33 100644 --- a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta-3.snap +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta-3.snap @@ -138,7 +138,7 @@ Entity { ), capital: Some( TownId( - 5000, + 00000000-0000-0000-0000-00000000007c, ), ), governor: Some( diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta.snap index bfc612a..a688a9a 100644 --- a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta.snap +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta.snap @@ -138,7 +138,7 @@ Entity { ), capital: Some( TownId( - 3000, + 00000000-0000-0000-0000-000000000079, ), ), governor: Some( diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_oneline_display-2.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_oneline_display-2.snap index f9b9836..c0c47bb 100644 --- a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_oneline_display-2.snap +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_oneline_display-2.snap @@ -4,11 +4,11 @@ expression: e.to_pretty_tree() --- [ Hero 󰻾[0c000000-0000-0000-0000-000000000000]] ├─ metadata - │ ├─ capital: Some(TownId(50)) + │ ├─ capital: "\u{f0efe}[0000000]" │ ├─ prestige: 3 │ └─ position: ( 2, 4)⚓ ├─ links - │ └─ 󰻾[3] + │ └─ 󰻾[0000000] ├─ duration: ⧗10 ├─ effect_nature: Recurring └─ effect_bounds: (1 ⭾ 5) diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_oneline_display.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_oneline_display.snap index 091b449..428bbca 100644 --- a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_oneline_display.snap +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_oneline_display.snap @@ -4,5 +4,5 @@ expression: e.oneline_display() --- ├──┬─ 0c00000 Hero  ──────> ( 2, 4)⚓ ⧗10 │ ├─ Faction: 2 │ Effect: ⟳ (1 ⭾ 5), Stats: 0 0💰 0 0󰡢 3 -│ └─  󰻾[50]  󰻾[11] +│ └─  󰻾[0000000]  󰻾[11] │ diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta-2.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta-2.snap index 3beae88..6eed292 100644 --- a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta-2.snap +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta-2.snap @@ -14,11 +14,7 @@ MetaStats { 33, ), ), - links: [ - TownId( - 55, - ), - ], + links: [], prestige: GenericStat( 0, ), diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta-3.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta-3.snap index 63e30c0..51a88db 100644 --- a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta-3.snap +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta-3.snap @@ -16,7 +16,7 @@ MetaStats { ), links: [ TownId( - 55, + 00000000-0000-0000-0000-000000000002, ), ], prestige: GenericStat( diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta.snap index 6d39112..21a0f97 100644 --- a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta.snap +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta.snap @@ -9,7 +9,7 @@ MetaStats { ), capital: Some( TownId( - 1500, + 00000000-0000-0000-0000-00000000000c, ), ), governor: Some( diff --git a/lib_efo/src/entity/test.rs b/lib_efo/src/entity/test.rs index 22fc8bd..a4ae504 100644 --- a/lib_efo/src/entity/test.rs +++ b/lib_efo/src/entity/test.rs @@ -232,12 +232,12 @@ fn full_entity() -> Entity { name: "Hero".into(), entity_type: EntityType::Character, metadata: MetaStats { - capital: Some(stats::TownId(50)), + capital: Some(stats::TownId(Uuid::from_u128(121))), governor: Some(stats::CharacterId(11)), prestige: stats::GenericStat(3), position: Position::from((2, 4)), faction: Some(crate::stats::FactionId(2)), - links: vec![TownId(3)], + links: vec![TownId(Uuid::from_u128(121))], }, duration: EntityDuration::Duration(10), effect_nature: EffectApplication::Recurring, @@ -369,10 +369,10 @@ fn snapshot_entity_delta() { temp_stats: None, metadata: MetaStats { position: Position::from((44, 666)), - capital: Some(stats::TownId(5000)), + capital: Some(stats::TownId(Uuid::from_u128(124))), governor: Some(stats::CharacterId(2000)), faction: Some(stats::FactionId(44)), - links: vec![TownId(33)], + links: vec![TownId(Uuid::from_u128(141))], prestige: stats::GenericStat(3), }, entity_type: EntityType::Monster, @@ -388,10 +388,10 @@ fn snapshot_entity_delta() { temp_stats: Some(OverallStats::linear(4)), metadata: MetaStats { position: Position::from_str("33,4").unwrap(), - capital: Some(stats::TownId(3000)), + capital: Some(stats::TownId(Uuid::from_u128(121))), governor: Some(stats::CharacterId(1500)), faction: Some(stats::FactionId(5)), - links: vec![TownId(6)], + links: vec![TownId(Uuid::from_u128(121))], prestige: stats::GenericStat(5), }, entity_type: EntityType::Town, @@ -452,19 +452,19 @@ fn snapshot_meta_stats_delta() { let meta1 = MetaStats { position: Position::from((1, 11)), - capital: Some(stats::TownId(1000)), + capital: Some(stats::TownId(Uuid::from_u128(1000))), governor: Some(stats::CharacterId(500)), faction: Some(stats::FactionId(1)), - links: vec![TownId(22)], + links: vec![TownId(Uuid::from_u128(12))], prestige: stats::GenericStat(3), }; let meta2 = MetaStats { position: Position::from((44, 555)), - capital: Some(stats::TownId(1500)), + capital: Some(stats::TownId(Uuid::from_u128(12))), governor: Some(stats::CharacterId(400)), faction: Some(stats::FactionId(33)), - links: vec![TownId::from(55)], + links: vec![TownId::from(Uuid::from_u128(42))], prestige: stats::GenericStat(1), }; let meta3 = MetaStats { @@ -472,7 +472,7 @@ fn snapshot_meta_stats_delta() { capital: None, governor: Some(stats::CharacterId(400)), faction: Some(stats::FactionId(33)), - links: vec![TownId::from(55)], + links: vec![TownId::from(Uuid::from_u128(2))], prestige: stats::GenericStat(1), }; diff --git a/lib_efo/src/epoch/epoch_config.rs b/lib_efo/src/epoch/epoch_config.rs index 754fdac..d501510 100644 --- a/lib_efo/src/epoch/epoch_config.rs +++ b/lib_efo/src/epoch/epoch_config.rs @@ -392,7 +392,6 @@ impl EpochConfig { /// supplied UUID exists in the epoch. /// #[allow(dead_code)] - // TODO: Add to a generic show unsafe fn find_entity(&self, id: Uuid) -> Result<&Entity, EpochError> { let epoch_info = unsafe { self.try_load_id(self.epoch_id) }?; let predicate = |entity: &&Entity| entity.id == id; diff --git a/lib_efo/src/error.rs b/lib_efo/src/error.rs index d524de7..290fe63 100644 --- a/lib_efo/src/error.rs +++ b/lib_efo/src/error.rs @@ -49,7 +49,6 @@ pub enum StorageError { /// to the user (and to the test-suite). // TODO(2): Split effectively user errors to avoid the usage of advice and such #[derive(Error, Debug, Diagnostic)] -#[allow(dead_code, unused_assignments)] pub enum EpochError { /// Problems with the `.epochconfig` file. #[error("Failed to read epoch configuration")] @@ -219,7 +218,7 @@ pub enum EpochError { UnknownStatAcronim(String), /// The user gave a stat:identifier pair that was incorrect - #[error("Expected a stat and a number, got: {0}")] + #[error("Expected a stat and a number (e.g. fod:12 or mil=22), got: {0}")] #[diagnostic(code(EpochError::IllFormedStatQualifier))] IllFormedStatQualifier(String), @@ -327,6 +326,19 @@ pub enum EpochError { You may need to delete or rename the existing entity." ))] EntityAlreadyExist(Option), + /// The argument could not be parsed. + #[error("Failed to parse argument '{argument_parsed}': {while_parsing}")] + #[diagnostic(code(EntityError::ParsingArgument))] + #[diagnostic(help( + "Verify that the value supplied for the argument '{argument_parsed}' matches the expected format. \ + Refer to the command reference for the correct syntax and examples." + ))] + ParsingArgument { + /// The argument that was being parsed + argument_parsed: String, + /// The thing that was being parsed + while_parsing: &'static str, + }, } /// A small enum of explicit user-facing error messages. diff --git a/lib_efo/src/lib.rs b/lib_efo/src/lib.rs index 4551e92..45ea9bf 100644 --- a/lib_efo/src/lib.rs +++ b/lib_efo/src/lib.rs @@ -10,7 +10,7 @@ #![deny(clippy::unwrap_used)] #[macro_use] -#[allow(dead_code, unused_assignments)] +#[allow(unused_assignments)] pub mod error; pub mod entity; pub mod epoch; diff --git a/lib_efo/src/stats.rs b/lib_efo/src/stats.rs index b1a5ee0..635e2cf 100644 --- a/lib_efo/src/stats.rs +++ b/lib_efo/src/stats.rs @@ -9,15 +9,15 @@ //! * **Effect** - Gameplay consequence of the stat. //! * **Source** - Formula or function that generates the stat value. -#![allow(dead_code)] #![deny(clippy::missing_docs_in_private_items)] - +#![allow(dead_code)] use crate::{error::EpochError, thin_newtype, utils::RngLevel}; use cli_table::{CellStruct, Color, Style, Table}; use colored::Colorize; use derive_more::{Add, Display, Sub}; use rand::{Rng, distr::Distribution, rngs::ThreadRng}; use serde::{Deserialize, Serialize}; +use uuid::Uuid; mod implementations; /// Aggregated statistics for a single entity. @@ -299,6 +299,7 @@ impl OverallStats { /// Updates with leader /// etc. // TODO: Fill this + #[allow(dead_code)] fn apply_exteriors(&mut self) {} #[cfg(test)] @@ -443,7 +444,6 @@ impl Position { /// Create a random position /// None that there is no concept to either city or continent making this position rather unrelyable - // TODO(2): Make a create_rng_from_town & create_rng_from_continents pub fn create_rng(r: &mut ThreadRng) -> Result { let x = r.random_range(0..GRID_SIZE.0); let y = r.random_range(0..GRID_SIZE.1); @@ -540,10 +540,10 @@ pub trait Symbols { // } // A stat that is shown to the player *and* can be modified manually. -thin_newtype!(GenericStat, isize); -thin_newtype!(TownId, usize); -thin_newtype!(CharacterId, usize); -thin_newtype!(FactionId, usize); +thin_newtype!(GenericStat, isize, derives: [Add, Sub]); +thin_newtype!(TownId, Uuid); +thin_newtype!(CharacterId, usize, derives: [Add, Sub]); +thin_newtype!(FactionId, usize, derives: [Add, Sub]); // --- TRAITS --------------------------------------------------------------- /// A stat is a *game value* that can be converted to two different diff --git a/lib_efo/src/stats/implementations.rs b/lib_efo/src/stats/implementations.rs index bddb4a1..df2a2c1 100644 --- a/lib_efo/src/stats/implementations.rs +++ b/lib_efo/src/stats/implementations.rs @@ -1,6 +1,7 @@ //! All traits implementatition for the main structs are deffered here +#![allow(dead_code)] -use crate::stats::GameStat; +use crate::stats::{GameStat, TownId}; use colored::Colorize; use std::str::FromStr; @@ -10,58 +11,6 @@ use crate::stats::{ EntityType, FactionId, GenericStat, ListStats, OverallStats, Position, Symbols, }; -/// Creates a thin, deref-able wrapper around an inner type. -#[macro_export] -macro_rules! thin_newtype { - ($name:ident, $inner:ty) => { - /// Thin wrapper that derefs to the inner type. - /// Ideal for zero-overhead new-type patterns. - #[repr(transparent)] - #[derive( - Debug, - Clone, - Copy, - Default, - PartialEq, - Eq, - PartialOrd, - Ord, - Hash, - Serialize, - Deserialize, - Display, - Add, - Sub, - )] - pub struct $name(pub $inner); - - impl std::ops::Deref for $name { - type Target = $inner; - fn deref(&self) -> &Self::Target { - &self.0 - } - } - - impl std::ops::DerefMut for $name { - fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.0 - } - } - - impl From<$inner> for $name { - fn from(v: $inner) -> Self { - $name(v) - } - } - - impl From<$name> for $inner { - fn from(v: $name) -> Self { - v.0 - } - } - }; -} - /// Generates an `impl GameStat for ` where the only difference between /// multiple implementations is the visibility level. /// @@ -449,6 +398,148 @@ impl Symbols for Option { } } +impl Symbols for TownId { + fn to_symbol(&self) -> String { + format!("󰻾[{}]", self.0.to_string().split_at(7).0) + } + + fn to_shortest(&self) -> String { + self.0.to_string().split_at(7).0.to_string() + } +} + +impl FromStr for FactionId { + type Err = EpochError; // the error we get from `usize::parse` + + /// Parse a string slice into a `FactionId`. + fn from_str(s: &str) -> Result { + // Trim whitespace just in case and attempt to parse. + let inner = s + .trim() + .parse::() + .map_err(|_| EpochError::ParsingArgument { + argument_parsed: s.to_string(), + while_parsing: "The argument could't be made into a FactionId", + })?; + Ok(FactionId(inner)) + } +} + +/// Thin wrapper that derefs to the inner type. +/// +/// By default the wrapper derives a common set of traits (`Debug`, `Clone`, `Copy`, +/// …). You can optionally provide an extra list of derives – e.g. `Add`, +/// `Sub`, `FromStr`, or any custom derive – by writing: +/// ``` +/// thin_newtype!(MyInt, i32, derives: [Add, Sub]); +/// ``` +/// (you’ll need the corresponding crates – e.g. `derive_more` for `Add`, `Sub`). +#[macro_export] +macro_rules! thin_newtype { + /* ---- no custom derives ------------------------------------------------- */ + ($name:ident, $inner:ty) => { + + /// Thin wrapper that derefs to the inner type. + /// Ideal for zero-overhead new-type patterns. + #[repr(transparent)] + #[derive( + Debug, + Clone, + Copy, + Default, + PartialEq, + Eq, + PartialOrd, + Ord, + Hash, + Serialize, + Deserialize, + Display, + )] + pub struct $name(pub $inner); + + impl std::ops::Deref for $name { + type Target = $inner; + #[inline] + fn deref(&self) -> &Self::Target { + &self.0 + } + } + + impl std::ops::DerefMut for $name { + #[inline] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } + } + + impl From<$inner> for $name { + #[inline] + fn from(v: $inner) -> Self { + $name(v) + } + } + + impl From<$name> for $inner { + #[inline] + fn from(v: $name) -> Self { + v.0 + } + } + }; + + /* ---- with a custom derive list ---------------------------------------- */ + ($name:ident, $inner:ty, derives: [ $( $derive:ident ),* $(,)? ]) => { + /// Thin wrapper that derefs to the inner type. + /// Ideal for zero-overhead new-type patterns. + #[repr(transparent)] + #[derive( + Debug, + Clone, + Copy, + Default, + PartialEq, + Eq, + PartialOrd, + Ord, + Hash, + serde::Serialize, + serde::Deserialize, + derive_more::Display, + $( $derive ),* + )] + pub struct $name(pub $inner); + + impl std::ops::Deref for $name { + type Target = $inner; + #[inline] + fn deref(&self) -> &Self::Target { + &self.0 + } + } + + impl std::ops::DerefMut for $name { + #[inline] + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } + } + + impl From<$inner> for $name { + #[inline] + fn from(v: $inner) -> Self { + $name(v) + } + } + + impl From<$name> for $inner { + #[inline] + fn from(v: $name) -> Self { + v.0 + } + } + }; +} mod from_impl; #[cfg(test)] diff --git a/lib_efo/src/stats/implementations/from_impl.rs b/lib_efo/src/stats/implementations/from_impl.rs index fe89c42..3675655 100644 --- a/lib_efo/src/stats/implementations/from_impl.rs +++ b/lib_efo/src/stats/implementations/from_impl.rs @@ -15,7 +15,7 @@ impl FromStr for StatPair { /// If the format is invalid, an `EpochError::IllFormedStatQualifier` /// is returned. fn from_str(s: &str) -> Result { - let (stat_str, val_str) = if let Some(idx) = s.find(':') { + let (stat_str, val_str) = if let Some(idx) = s.find([':', '=']) { (&s[..idx], &s[idx + 1..]) } else { let parts: Vec<&str> = s.split_whitespace().collect(); diff --git a/lib_efo/src/stats/implementations/test.rs b/lib_efo/src/stats/implementations/test.rs index 8fab056..55ceb9b 100644 --- a/lib_efo/src/stats/implementations/test.rs +++ b/lib_efo/src/stats/implementations/test.rs @@ -13,26 +13,28 @@ struct Person { email: GenericStat, } -/// Helper that asserts that a string parses to the expected ListStats variant. -fn assert_stat_ok(input: &str, expected: ListStats) { - let parsed = ListStats::from_str(input).expect("should parse"); - assert_eq!(parsed, expected, "input `{}` parsed incorrectly", input); -} +// /// Helper that asserts that a string parses to the expected ListStats variant. +// fn assert_stat_ok(input: &str, expected: ListStats) { +// let parsed = ListStats::from_str(input).expect("should parse"); +// assert_eq!(parsed, expected, "input `{}` parsed incorrectly", input); +// } field_accessor!(Person { name, age, email }); #[test] fn test_field_accessors() { - let person = Person { + let mut person = Person { name: GenericStat(10), age: GenericStat(20), email: GenericStat(120), }; + + let age = person.get_field_mut_from_str("age").unwrap(); + assert_eq!(age.to_100(), 10); + let name = person.get_field_from_str("name").unwrap(); let email = person.get_field_from_str("email").unwrap(); - let age = person.get_field_from_str("age").unwrap(); assert_eq!(name.to_100(), 0); - assert_eq!(age.to_100(), 10); assert_eq!(email.to_100(), 100); }