diff --git a/bin_efo/src/commands/entity_generic.rs b/bin_efo/src/commands/entity_generic.rs index e897f4c..253772d 100644 --- a/bin_efo/src/commands/entity_generic.rs +++ b/bin_efo/src/commands/entity_generic.rs @@ -83,7 +83,7 @@ use lib_efo::{ use log::info; use crate::error::AppError; -use crate::success::display_success; +use crate::success::{SuccessMessages, display_success}; mod helper_functions; @@ -195,7 +195,7 @@ pub struct CommonArgs { pub bounds: Option, /// New effect application mode. - #[arg(short = 's', long)] + #[arg(short = 'e', long)] pub effect: Option, /// One or more `key:value` pairs that modify the entity’s stats. @@ -206,7 +206,7 @@ pub struct CommonArgs { /// The faction to which the entity should belong. pub faction: Option, - #[arg(short = 'n', long, action = clap::ArgAction::SetTrue, default_value_t = false, group="faction_group")] + #[arg(short = 'N', long, action = clap::ArgAction::SetTrue, default_value_t = false, group="faction_group")] /// The entity doens't belong to any faction. pub no_faction: bool, @@ -215,8 +215,33 @@ pub struct CommonArgs { pub reach: Option, /// The description of the Entity - #[arg(long, short = 'D')] + #[arg(long, long = "desc")] pub description: Option, + + /// Link to a governor + #[arg(long, short = 'g', group = "governor_group")] + pub governor: Option, + + #[arg(long, action = clap::ArgAction::SetTrue, default_value_t = false, group="governor_group")] + /// The entity doens't belong to any faction. + pub no_governor: bool, + + /// Link to a town to set as capital + #[arg(long, short = 'c', group = "capital_group")] + pub capital: Option, + + /// The entity doens't have a capital. + #[arg(long, action = clap::ArgAction::SetTrue, default_value_t = false, group="capital_group")] + pub no_capital: bool, + // /// Add a link to another location + // /// This is currently unused and important for early testing + // #[arg(long, short = 'l')] + // pub add_link: Vec, + + // /// Add a link to another location + // /// This is currently unused and important for early testing + // #[arg(long)] + // pub del_link: Vec, } /// Handles an entity subcommand. @@ -289,6 +314,7 @@ pub(crate) fn handle_create_entity( entity.modify_position(epoch_info.resolve_position(position)?); } helper_functions::update_common_values(&entity_args.common_args, position, &mut entity); + helper_functions::update_advanced_values(&entity_args.common_args, &mut entity, epoch_info)?; // Show success let vec_entities: &mut Vec = epoch_info.vec_entities_mut(e_type); @@ -356,9 +382,10 @@ fn handle_diff_entity( 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 = epoch_current.find_entity_of_type(&binding, e_type)?; - let past_entity = epoch_past.find_entity_of_type(&binding, e_type)?; + let current_entity = + epoch_current.find_entity_of_type(&Some(entity_args.identifier.clone()), e_type)?; + let past_entity = + epoch_past.find_entity_of_type(&Some(entity_args.identifier.clone()), e_type)?; let diff = current_entity.delta(past_entity); display_success(&crate::success::SuccessMessages::DiffBetweenEpoch(id, id2)); @@ -393,39 +420,40 @@ fn handle_edit_entity( main_epoch: &mut EpochConfig, ) -> Result<(), EpochError> { let epoch_info = main_epoch.try_load_current_as_mut()?; - let epoch_info1 = &epoch_info.clone(); // Very expensive save of all variables + let mut entity = epoch_info + .find_entity_of_type(&Some(entity_args.identifier.clone()), e_type)? + .clone(); + // TODO(9): Use COW and a flag + // let mut entity = std::borrow::Cow::Borrowed( + // epoch_info.find_entity_of_type(&Some(entity_args.identifier.clone()), e_type)?, + // ); + + let edited_entity = SuccessMessages::EditedEntity( + entity.name.clone(), + entity.entity_type.to_shortest(), + entity.id.to_string(), + ); + // Update name if needed + if let Some(ref name) = entity_args.new_name { + entity.name = name.clone(); + } + helper_functions::update_stats( + &entity_args.common_args.stats, + entity_args.delta, + &mut entity, + ); let position = if let Some(position) = &entity_args.common_args.position { Some(epoch_info.resolve_position(position)?) } else { None }; - - let entity = epoch_info - .vec_entities_mut(e_type) - .iter_mut() - .find(|entity| entity.match_identifier(&Some(entity_args.identifier.clone()))) - .ok_or(EpochError::EntityNotFound( - e_type.clone(), - Some(entity_args.identifier.clone()), - ))?; - - helper_functions::update_stats(&entity_args.common_args.stats, entity_args.delta, entity); - // Update name if needed - if let Some(ref name) = entity_args.new_name { - entity.name = name.clone(); - } - - helper_functions::update_common_values(&entity_args.common_args, position, entity); - - let message = &crate::success::SuccessMessages::EditedEntity( - entity.name.clone(), - entity.entity_type.to_shortest(), - entity.id.to_string(), - ); - entity.print_full(epoch_info1); + helper_functions::update_common_values(&entity_args.common_args, position, &mut entity); + helper_functions::update_advanced_values(&entity_args.common_args, &mut entity, epoch_info)?; + entity.print_full(epoch_info); + // Only swap if a swap is needed + epoch_info.swap_entity(entity)?; epoch_info.save_with_context("Deleted entity", &lib_efo::epoch::SaveMode::Erase)?; - // let epoch_info = main_epoch.try_load_current()?; - display_success(message); + display_success(&edited_entity); Ok(()) } diff --git a/bin_efo/src/commands/entity_generic/helper_functions.rs b/bin_efo/src/commands/entity_generic/helper_functions.rs index 4af7e92..86f00c4 100644 --- a/bin_efo/src/commands/entity_generic/helper_functions.rs +++ b/bin_efo/src/commands/entity_generic/helper_functions.rs @@ -2,6 +2,8 @@ use lib_efo::{ entity::{EffectBounds, Entity}, + epoch::EpochInfo, + error::EpochError, naming::NAMING, stats::{self, EntityType, StatPair}, }; @@ -119,7 +121,30 @@ pub fn update_common_values( if let Some(reach) = &entity_args.reach { entity.modify_reach(reach.clone()); } - if let Some(desciption) = &entity_args.description { - entity.modify_description(desciption.clone()); + if let Some(description) = &entity_args.description { + entity.modify_description(description.clone()); } } + +/// Try to update all advanced values +pub fn update_advanced_values( + entity_args: &CommonArgs, + entity: &mut Entity, + epoch_info: &EpochInfo, +) -> Result<(), EpochError> { + if let Some(governor) = &entity_args.governor { + let governor = + epoch_info.find_entity_of_type(&Some(governor.clone()), &EntityType::Character)?; + entity.change_governor(stats::CharacterId(governor.id)); + } else if entity_args.no_governor { + entity.remove_governor(); + } + if let Some(capital) = &entity_args.capital { + let capital = epoch_info.find_entity_of_type(&Some(capital.clone()), &EntityType::Town)?; + entity.change_capital(stats::TownId(capital.id)); + } else if entity_args.no_capital { + entity.remove_capital(); + } + // Remove links if needed, updating two ways + Ok(()) +} diff --git a/lib_efo/src/entity/implementations.rs b/lib_efo/src/entity/implementations.rs index e052b68..65ba8c8 100644 --- a/lib_efo/src/entity/implementations.rs +++ b/lib_efo/src/entity/implementations.rs @@ -5,6 +5,7 @@ use std::cmp::{max, min}; use cli_table::format::{Border, HorizontalLine, Separator, VerticalLine}; use cli_table::{Style, WithTitle}; use colored::*; +use log::debug; use rand::distr::Distribution; use rand::seq::{IndexedRandom, IteratorRandom}; use uuid::Uuid; // [3] - colored-rs examples @@ -164,16 +165,24 @@ impl Entity { // ── Metadata section out.push_str(&indent(0, &format!("├─ {}\n", "metadata".green()))); - if self.metadata.capital.is_some() { + if let Some(capital) = self.metadata.capital { out.push_str(&indent( 1, &format!( - "├─ {}: {:?}\n", + "├─ {}: {}\n", "capital".bright_green(), - self.metadata - .capital - .map(|c| c.to_symbol()) - .unwrap_or_default() + uuid_to_symbol(*capital, epoch_info, &EntityType::Town) + ), + )); + } + out.push_str(&indent(0, &format!("├─ {}\n", "metadata".green()))); + if let Some(governor) = self.metadata.governor { + out.push_str(&indent( + 1, + &format!( + "├─ {}: {}\n", + "governor".bright_green(), + uuid_to_symbol(*governor, epoch_info, &EntityType::Character) ), )); } @@ -204,7 +213,11 @@ impl Entity { let symbol = if last { "└─" } else { "├─" }; out.push_str(&indent( 1, - &format!("{} {}\n", symbol, link.to_symbol().yellow()), + &format!( + "{} {}\n", + symbol, + uuid_to_symbol(**link, epoch_info, &EntityType::Town).yellow() + ), )); } } @@ -462,6 +475,26 @@ impl Entity { self.description = descritption; } + /// Add a governor to the entity if the id exists + pub fn change_governor(&mut self, governor: stats::CharacterId) { + debug!("Swapping the governor with {}", governor.to_symbol()); + self.metadata.governor = Some(governor); + } + /// Remove the entity's governor and return it + pub fn remove_governor(&mut self) -> Option { + self.metadata.governor.take() + } + + /// Add a governor to the entity if the id exists + pub fn change_capital(&mut self, capital: stats::TownId) { + debug!("Swapping the capital with {}", capital.to_symbol()); + self.metadata.capital = Some(capital); + } + /// Remove the entity's governor and return it + pub fn remove_capital(&mut self) -> Option { + self.metadata.capital.take() + } + /// Returns a **read‑only reference** to the entity’s current position. pub fn position(&self) -> &Position { &self.metadata.position @@ -477,6 +510,19 @@ impl Entity { } } +/// Short utility to make a symbol for an entity from it's Uuid +fn uuid_to_symbol(id: Uuid, epoch_info: &EpochInfo, e_type: &EntityType) -> String { + epoch_info + .find_entity_strict(id, Some(e_type.clone())) + .map(|e| e.to_symbol()) + .unwrap_or(format!( + "{}{} is missing {}", + " ".red(), + id.to_symbol().red(), + e_type.clone().to_shortest().blue() + )) +} + // impl Entity { // /// Create a new Event // fn new_event(name: String, description: String){} @@ -575,3 +621,24 @@ impl Diffable for MetaStats { } } } + +impl Symbols for Entity { + fn to_symbol(&self) -> String { + format!( + "{} {} {}", + self.entity_type.to_symbol().blue(), + self.id.to_symbol().blue(), + self.name + ) + } +} + +impl Symbols for Uuid { + fn to_symbol(&self) -> String { + format!("󰻾[{}]", self.to_string().split_at(7).0) + } + + fn to_shortest(&self) -> String { + self.to_string().split_at(7).0.to_string() + } +} 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 af4e455..2073729 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 @@ -1,14 +1,16 @@ --- source: lib_efo/src/entity/test.rs -expression: e.to_pretty_tree() +expression: e.to_pretty_tree(&epoch_info) --- [ Hero 󰻾[0c000000-0000-0000-0000-000000000000]] ├─ metadata - │ ├─ capital: "\u{f0efe}[7900000]" + │ ├─ capital: "\u{ea86} \u{f0efe}[7c00000] Bobpital" │ ├─ prestige: 3 │ └─ position: ( 2, 4)⚓ ├─ links - │ └─ 󰻾[7900000] + │ ├─  󰻾[bc04000] is missing [T] + │ ├─  󰻾[7900000] Bobtown + │ └─  󰻾[7900000] Bobtown ├─ 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 34a1d49..e992685 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 -│ └─  󰻾[7900000]  󰻾[0b00000] +│ └─  󰻾[7c00000]  󰻾[0b00000] │ diff --git a/lib_efo/src/entity/test.rs b/lib_efo/src/entity/test.rs index 343dcbb..b378536 100644 --- a/lib_efo/src/entity/test.rs +++ b/lib_efo/src/entity/test.rs @@ -233,12 +233,16 @@ fn full_entity() -> Entity { name: "Hero".into(), entity_type: EntityType::Character, metadata: MetaStats { - capital: Some(stats::TownId(Uuid::from_u128_le(121))), + capital: Some(stats::TownId(Uuid::from_u128_le(124))), governor: Some(stats::CharacterId(Uuid::from_u128_le(11))), prestige: stats::GenericStat(3), position: Position::from((2, 4)), faction: Some(crate::stats::FactionId(2)), - links: vec![TownId(Uuid::from_u128_le(121))], + links: vec![ + TownId(Uuid::from_u128_le(1212)), + TownId(Uuid::from_u128_le(121)), + TownId(Uuid::from_u128_le(121)), + ], reach: stats::Reach::Global, }, duration: EntityDuration::Duration(10), @@ -265,7 +269,19 @@ fn effect_bound_testing() { fn snapshot_full_oneline_display() { init_snapshot_env(); let e = full_entity(); - let epoch_info = EpochInfo::default(); + let mut epoch_info = EpochInfo::default(); + let e2 = Entity { + id: Uuid::from_u128_le(121), + name: "Bobtown".to_string(), + ..Default::default() + }; + let e3 = Entity { + id: Uuid::from_u128_le(124), + name: "Bobpital".to_string(), + ..Default::default() + }; + epoch_info.towns.push(e2); + epoch_info.towns.push(e3); assert_snapshot!(e.oneline_display()); assert_snapshot!(e.to_pretty_tree(&epoch_info)); } diff --git a/lib_efo/src/epoch/epoch_info.rs b/lib_efo/src/epoch/epoch_info.rs index 9e08b4b..808569e 100644 --- a/lib_efo/src/epoch/epoch_info.rs +++ b/lib_efo/src/epoch/epoch_info.rs @@ -10,6 +10,7 @@ use cli_table::Table; use derive_more::Display; use serde::{Deserialize, Serialize}; use std::fs::create_dir_all; +use uuid::Uuid; use crate::{ entity::{Entity, EntityIdentifier}, @@ -173,6 +174,35 @@ impl EpochInfo { .or(self.calamities.iter().find(predicate)) .ok_or(EpochError::EntityNotFoundById(id)) } + /// Find an entity from an Uuid + pub fn find_entity_strict( + &self, + id: Uuid, + strict: Option, + ) -> Result<&Entity, EpochError> { + let predicate = |entity: &&Entity| entity.id == id; + if let Some(e_type) = strict { + self.vec_entities(&e_type) + .iter() + .find(|entity| entity.id == id) + .ok_or(EpochError::EntityNotFound( + e_type.clone(), + Some(EntityIdentifier::Id(id.to_string())), + )) + } else { + self.events + .iter() + .find(predicate) + .or(self.characters.iter().find(predicate)) + .or(self.towns.iter().find(predicate)) + .or(self.blockers.iter().find(predicate)) + .or(self.calamities.iter().find(predicate)) + .ok_or(EpochError::EntityNotFound( + EntityType::Player.clone(), + Some(EntityIdentifier::Id(id.to_string())), + )) + } + } /// 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 @@ -196,6 +226,29 @@ impl EpochInfo { } } + /// Removes an entity from the epoch's collection and returns it. + /// + /// The function looks up the entity that matches the supplied `entity_identifier` + /// in the collection corresponding to `e_type`. If the entity is found, it + /// is removed using `swap_remove` and returned. When the entity cannot be + /// located, an `EpochError::EntityNotFound` is returned. + pub fn remove_entity( + &mut self, + entity_identifier: &Option, + e_type: &EntityType, + ) -> Result { + let vec_entities: &mut Vec = self.vec_entities_mut(e_type); + let index = vec_entities + .iter() + .position(|entity| entity.match_identifier(entity_identifier)) + .ok_or(EpochError::EntityNotFound( + e_type.clone(), + entity_identifier.clone(), + ))?; + + let entity = vec_entities.swap_remove(index); + Ok(entity) + } /// Returns a mutable slice over the entities of the requested type from the given /// `EpochInfo`. /// @@ -230,4 +283,24 @@ impl EpochInfo { } }) } + + /// Swap an entity with an updated one + pub fn swap_entity(&mut self, entity: Entity) -> Result { + // Get a mutable reference to the vector that holds the entities of `e_type` + let entities = self.vec_entities_mut(&entity.entity_type); + + // Locate the index of the entity that we want to replace + let idx_opt = entities.iter().position(|e| e.id == entity.id); + + match idx_opt { + Some(idx) => { + // Replace the old entity with the new one, returning the old entity + Ok(std::mem::replace(&mut entities[idx], entity)) + } + None => Err(EpochError::EntityNotFound( + entity.entity_type.clone(), + Some(EntityIdentifier::Id(entity.id.to_string())), + )), + } + } } diff --git a/lib_efo/src/stats/implementations.rs b/lib_efo/src/stats/implementations.rs index a48fe1c..44dbec0 100644 --- a/lib_efo/src/stats/implementations.rs +++ b/lib_efo/src/stats/implementations.rs @@ -400,21 +400,21 @@ impl Symbols for Option { impl Symbols for TownId { fn to_symbol(&self) -> String { - format!("󰻾[{}]", self.0.to_string().split_at(7).0) + self.0.to_symbol() } fn to_shortest(&self) -> String { - self.0.to_string().split_at(7).0.to_string() + self.0.to_shortest() } } impl Symbols for CharacterId { fn to_symbol(&self) -> String { - format!("󰻾[{}]", self.0.to_string().split_at(7).0) + self.0.to_symbol() } fn to_shortest(&self) -> String { - self.0.to_string().split_at(7).0.to_string() + self.0.to_shortest() } }