From 08c2a8578c39c9d2c99f45dc291f8eed51e58b70 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Fri, 28 Nov 2025 22:36:22 +0100 Subject: [PATCH] Adds some traits, debug, and logging --- Cargo.lock | 16 +++++ bin_efo/src/commands.rs | 5 ++ bin_efo/src/commands/epoch.rs | 33 ++++++--- bin_efo/src/commands/init.rs | 2 +- bin_efo/src/main.rs | 13 ++-- lib_efo/Cargo.toml | 1 + lib_efo/src/epoch_struct.rs | 129 +++++++++++++++++++++++++++++----- lib_efo/src/epoch_traits.rs | 40 +++++++++++ lib_efo/src/error.rs | 4 +- lib_efo/src/lib.rs | 19 ++--- 10 files changed, 214 insertions(+), 48 deletions(-) create mode 100644 lib_efo/src/epoch_traits.rs diff --git a/Cargo.lock b/Cargo.lock index b2e6278..d50fee9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -192,6 +192,15 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "fancy-table" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cca3bc2bf46d82914b5308d05b12053e79079429ae2b13267238718033ae1eb7" +dependencies = [ + "smallvec", +] + [[package]] name = "gimli" version = "0.32.3" @@ -228,6 +237,7 @@ version = "0.1.0" dependencies = [ "clap", "derive_more", + "fancy-table", "miette", "serde", "serde_json", @@ -398,6 +408,12 @@ dependencies = [ "serde_core", ] +[[package]] +name = "smallvec" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" + [[package]] name = "strsim" version = "0.11.1" diff --git a/bin_efo/src/commands.rs b/bin_efo/src/commands.rs index a9861be..3bbee69 100644 --- a/bin_efo/src/commands.rs +++ b/bin_efo/src/commands.rs @@ -10,3 +10,8 @@ pub mod epoch; pub mod init; +// pub mod diff; +// pub mod utils; +// pub mod event; +// pub mod town; +// pub mod chr; diff --git a/bin_efo/src/commands/epoch.rs b/bin_efo/src/commands/epoch.rs index 1717cd8..34da5a6 100644 --- a/bin_efo/src/commands/epoch.rs +++ b/bin_efo/src/commands/epoch.rs @@ -16,10 +16,10 @@ pub mod cli_epoch; /// handler that lives in `crate::world::EpochManager`. pub fn handle_cmd(cmd: cli_epoch::EpochCmd) -> Result<(), AppError> { let mut main_epoch = EpochConfig::new_from_path(None)?; - // TODO: Remove this debug - println!("The main epoch is {:#?}", main_epoch); + // // TODO[2]: Remove this debug + // println!("The main epoch is {:#?}", main_epoch); match cmd { - cli_epoch::EpochCmd::Log(args) => handle_log(args), + cli_epoch::EpochCmd::Log(args) => handle_log(args, &mut main_epoch), cli_epoch::EpochCmd::Switch(args) => handle_switch(args, &mut main_epoch), cli_epoch::EpochCmd::Next(args) => handle_next(args, &mut main_epoch), cli_epoch::EpochCmd::Reset(args) => handle_reset(args, &mut main_epoch), @@ -28,8 +28,8 @@ pub fn handle_cmd(cmd: cli_epoch::EpochCmd) -> Result<(), AppError> { cli_epoch::EpochCmd::Fsck(args) => handle_fsck(args, &mut main_epoch), }?; - // TODO: Remove this debug - println!("The main epoch is {:#?}", main_epoch); + // // TODO[2]: Remove this debug + // println!("The main epoch is {:#?}", main_epoch); Ok(()) } @@ -40,9 +40,24 @@ fn handle_diff(args: cli_epoch::Diff) -> Result<(), AppError> { } /// Show a log of all different epochs -fn handle_log(_args: cli_epoch::Log) -> Result<(), AppError> { +fn handle_log(args: cli_epoch::Log, main_epoch: &mut EpochConfig) -> Result<(), AppError> { println!("Epoch log (most recent first):"); - unimplemented!("Just needs for the epoch to implement lvels of displays trait: DisplayLevels"); + let limit = args.limit; + let start_id = &main_epoch.epoch_id; + + let list_id = main_epoch + .list_existing_epochs + .iter() + .filter(|(id, _)| id <= &start_id) + .take(limit) + .map(|(id, _)| id) + .copied() + .collect::>(); + + // TODO[8]: Consider other ways to log than one element at a time + main_epoch.log_elements(&list_id)?; + + Ok(()) } /// Switches the current epoch to the one specified by the user. @@ -93,13 +108,11 @@ fn handle_next(_args: cli_epoch::Next, main_epoch: &mut EpochConfig) -> Result<( Err(AppError::Epoch(EpochError::FutureEpochExist)) } else { let new_epoch = main_epoch.compute_next()?; - // This epoch is not used or checked in this command, just directly inserted and saved - // TODO: Finish + // Insert new epoch main_epoch .insert_and_save(new_epoch, &lib_efo::epoch_struct::SaveMode::DoNotErase) .unwrap(); - // TODO: Does main save or do we save, I feel like we should save Ok(()) } } diff --git a/bin_efo/src/commands/init.rs b/bin_efo/src/commands/init.rs index 9cfa55d..d91f635 100644 --- a/bin_efo/src/commands/init.rs +++ b/bin_efo/src/commands/init.rs @@ -34,11 +34,11 @@ 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 pub fn init(args: &InitCmd) -> Result<(), AppError> { let epoch_config = EpochConfig::default(); let root = epoch_config.save_folder(); - //TODO: This can be really deceiving when only .epoch is present if read_dir(root)?.count() != 0 { Err(EpochError::FolderNotEmpty { name: None, diff --git a/bin_efo/src/main.rs b/bin_efo/src/main.rs index a7afd47..21fc81c 100644 --- a/bin_efo/src/main.rs +++ b/bin_efo/src/main.rs @@ -21,7 +21,7 @@ //! ``` #![warn(missing_docs, clippy::missing_docs_in_private_items)] -use clap::{Parser, Subcommand}; +use clap::{ArgAction, Parser, Subcommand}; use crate::commands::init::InitCmd; use crate::{commands::epoch::cli_epoch::EpochCmd, error::AppError}; @@ -36,6 +36,10 @@ mod error; #[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, + #[command(subcommand)] /// The top level command to be executed command: TopLevelCmd, @@ -68,13 +72,6 @@ fn main() -> miette::Result<()> { let cli = Cli::parse(); if let Err(e) = exec_dispatch(cli) { - // match e{ - // AppError::Clap(error) => todo!(), - // AppError::Io(error) => todo!(), - // AppError::Epoch(epoch_error) => todo!(), - // AppError::Storage(storage_error) => todo!(), - // AppError::Other(_) => todo!(), - // } Err(e)?; } diff --git a/lib_efo/Cargo.toml b/lib_efo/Cargo.toml index 734b55e..e856615 100644 --- a/lib_efo/Cargo.toml +++ b/lib_efo/Cargo.toml @@ -10,3 +10,4 @@ thiserror = {workspace = true} clap = {workspace = true} miette = {workspace = true} derive_more = { version = "2.0.1", features = ["display"] } +fancy-table = "0.4.1" diff --git a/lib_efo/src/epoch_struct.rs b/lib_efo/src/epoch_struct.rs index fb9d488..84212f5 100644 --- a/lib_efo/src/epoch_struct.rs +++ b/lib_efo/src/epoch_struct.rs @@ -19,21 +19,21 @@ //! files, just like a git repository tracks its commits and //! `HEAD` pointer. #![warn(missing_docs, clippy::missing_docs_in_private_items)] - use clap::error::ErrorKind; +use derive_more::Display; use serde::{Deserialize, Serialize}; +use std::io::Write; use std::{ collections::HashMap, fmt, fs::{File, create_dir_all, read_to_string, remove_dir_all}, - io::Write, path::Path, str::FromStr, }; -use crate::{epoch_struct, error::EpochError, io_err_with_help}; +use crate::{epoch_struct, epoch_traits::Prettiable, error::EpochError, io_err_with_help}; -// TODO: 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 @@ -57,7 +57,7 @@ pub struct EpochConfig { /// Optional human‑friendly tags (e.g. `"winter‑B"`, `"post‑war"`). pub tags: HashMap, - // TODO: Can become important + // TODO[6]: Can become important // #[serde(skip)] // /// Absolute path to `epoch//`. // pub path: PathBuf, @@ -83,7 +83,7 @@ impl EpochConfig { let path = Path::new(MAIN_NAME); if path.is_file() { - // TODO: 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 {:?}", @@ -111,14 +111,26 @@ impl EpochConfig { let elt = io_err_with_help!(elt, "Opening file in main config folder")?; if io_err_with_help!(elt.file_type(), "Determining file type of {:?}", elt)?.is_dir() { let id = elt.file_name().to_string_lossy().parse::(); - println!("{:?}", id); + // TODO: Logging + // println!("Initialized {:?}", id); self.list_existing_epochs.insert(id.unwrap(), None); } } Ok(self) } - /// Try to load into memory the given epoch id + /// Loads the metadata for an epoch from disk into the in‑memory cache. + /// + /// The epoch identified by `epoch_id` must exist in `list_existing_epochs`. + /// The JSON file on disk is read, deserialized into an `EpochInfo`, and + /// stored in the map. Any existing value for that epoch is overwritten. + /// + /// # Returns + /// * `Ok(())` when the epoch was successfully read and cached. + /// * `Err(EpochError::EpochNotFound(..))` if the epoch is not present in the + /// internal map. + /// * `Err(EpochError::Serde { .. })` if the JSON file could not be parsed. + /// * `Err(EpochError::Io { .. })` if the file could not be read. pub fn try_load(&mut self, epoch_id: &EpochId) -> Result<(), EpochError> { // Preload the epoch let value = self @@ -143,7 +155,20 @@ impl EpochConfig { Ok(()) } - /// Get an identifier or returns None + /// Retrieves the internal epoch ID for a given identifier. + /// + /// The identifier can be either a *tag* string (`EpochIdentifier::Tag`) or an + /// explicit epoch ID (`EpochIdentifier::Id`). + /// * When a tag is supplied the function looks up the corresponding epoch ID in + /// the `tags` map. + /// * When an ID is supplied it verifies that an epoch with that ID exists in + /// `list_existing_epochs` and returns it. + /// + /// # Returns + /// * `Ok(epoch_id)` when the identifier is successfully resolved. + /// * `Err(EpochError::AmbiguousTag(tag))` if a supplied tag does not exist. + /// * `Err(EpochError::EpochFolderMissing(id, path))` if an ID does not have an + /// associated epoch folder. pub fn get(&self, id: &EpochIdentifier) -> Result { match id { EpochIdentifier::Tag(s) => self @@ -169,7 +194,7 @@ impl EpochConfig { } /// Tries to delete an entire epoch folder by Id - // TODO: 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) { println!( @@ -192,7 +217,7 @@ impl EpochConfig { /// Return the id of the next (and now present) epoch pub fn compute_next(&mut self) -> Result { // unimplemented!() - // TODO: Implement this + // TODO[1]: Implement this print!("DEBUG LINE: COMPUTING NEXT EPOCH"); // New fake epoch Ok(EpochInfo::with_id(&self.epoch_id.next())) @@ -214,11 +239,35 @@ impl EpochConfig { // Add the epoch to the list of epochs, not doing so will still have it added // at the next iteration since the command always parse the files to determine it's state rater that the list // not doing so would likely create errors if insert is used before another command - self.list_existing_epochs - .insert(new_epoch.epoch_id, Some(new_epoch)); + let new_id = new_epoch.epoch_id; + self.list_existing_epochs.insert(new_id, Some(new_epoch)); + self.epoch_id = new_id; self.save_with_context("Saving after insert_and_save", &SaveMode::Erase)?; Ok(()) } + + /// Loads into memory all elements to show them as log + pub fn log_elements(&mut self, list_ids: &[EpochId]) -> Result<(), EpochError> { + let mut items_to_log = Vec::with_capacity(list_ids.len()); + for id in list_ids { + self.try_load(id)?; + } + for id in list_ids { + if let Some(info) = self + .list_existing_epochs + .get(id) + .ok_or(EpochError::EpochNotFound(id.to_string()))? + { + items_to_log.push(info); + } + } + // items_to_log[0].as_log() + for item in items_to_log { + item.show_as_log(); + } + // let table = FancyTable::create();! + Ok(()) + } } /// Trait representing a serialisable / writable config @@ -266,14 +315,12 @@ pub trait ConfigWritable: Serialize { /// reconstruct the state *of that particular epoch* (seed, selected /// events, parent link, etc.). The full world data is kept in /// separate storage (e.g. `world.json`). -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, Serialize, Deserialize, Display)] +#[display("Epoch {epoch_id:>5} | seed {rng_seed:<10} | tags {tags:?} | summary {summary:?}")] pub struct EpochInfo { /// The ID of this epoch – should match the directory name. pub epoch_id: EpochId, - /// The ID of the parent (previous) epoch, if not a root. - pub parent_id: Option, - /// RNG seed that was used to generate randomised data for /// this epoch. Keeping it in the file guarantees repeatable /// behaviour when replaying the same epoch. @@ -290,11 +337,57 @@ pub struct EpochInfo { pub summary: Option, } +impl Prettiable for EpochInfo { + // fn show_as_table(list: &[Self]) + // where + // Self: std::marker::Sized, + // { + // let table = fancy_table::FancyTable::create(fancy_table::FancyTableOpts { + // charset: fancy_table::charset::Charset::Modern, + // ..Default::default() + // }) + // .add_title_with_align("log", fancy_table::TitleAlign::RightOffset(1)) + // .add_column_named("ID", fancy_table::Layout::Slim) + // .add_column_named("RNG SEED", fancy_table::Layout::Fixed(16)) + // .add_column_named_wrapping_with_align( + // "TAGS", + // fancy_table::Layout::Fixed(25), + // fancy_table::Align::Center, + // ) + // .add_column_named_with_align( + // "SUMMARY", + // fancy_table::Layout::Expandable(150), + // fancy_table::Align::Right, + // ) + // .hseparator(Some(fancy_table::Separator::Double)) + // .padding(3) + // .width(102) + // .build(); + + // // table.render( + // let list: Vec<&[&str]> = list + // .iter() + // .map(|info| { + // [ + // info.epoch_id.to_string().as_str(), + // info.rng_seed.to_string().as_str(), + // info.tags.join(",").as_str(), + // info.summary.unwrap_or("".to_string()).as_str(), + // ] + // }) + // .collect(); + // // ); + // } + + fn as_log(&self) -> String { + format!("{}", self) + } +} + impl Default for EpochInfo { fn default() -> Self { Self { epoch_id: epoch_struct::EpochId::new(0), - parent_id: None, rng_seed: 0, tags: Vec::new(), summary: None, diff --git a/lib_efo/src/epoch_traits.rs b/lib_efo/src/epoch_traits.rs new file mode 100644 index 0000000..ade1775 --- /dev/null +++ b/lib_efo/src/epoch_traits.rs @@ -0,0 +1,40 @@ +//! epoch_traits.rs +//! +//! All traits used by the `lib_efo` library. +//! These traits are marker traits that describe behaviour +//! common to many of the library’s element types. +#![warn(clippy::missing_docs_in_private_items)] + +/// Elements that can be compared with another instance to produce a diff. +pub trait Diffable {} + +/// Elements that can be applied to the current world state. +pub trait Applyable {} + +/// Elements that can advance to a next state over time. +/// +/// Implementors usually provide a `.next()` method that returns the +/// element’s state after a time step (e.g., fading or diminishing). +pub trait Nextable {} + +/// Elements that can be rendered into a pretty, human‑readable form. +pub trait Prettiable { + // TODO: Doc + /// Show many as a table + fn show_as_table(list: &[Self]) + where + Self: std::marker::Sized, + { + list.iter().for_each(|e| { + e.show_as_log(); + }); + } + + /// Print function as a log + fn show_as_log(&self) { + println!("{}", self.as_log()) + } + + /// Convert the struct into a pretty log + fn as_log(&self) -> String; +} diff --git a/lib_efo/src/error.rs b/lib_efo/src/error.rs index 7f8ed38..dd660b4 100644 --- a/lib_efo/src/error.rs +++ b/lib_efo/src/error.rs @@ -21,7 +21,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: Remove or rethink these errors +// TODO[2]: Remove or rethink these errors #[derive(Debug, Error, Diagnostic)] pub enum StorageError { /// Problems with serialisation / deserialisation. @@ -46,7 +46,7 @@ pub enum StorageError { /// The enum is deliberately _small_ – each variant is self‑contained and /// carries the information you need to surface a friendly message /// to the user (and to the test‑suite). -// TODO: 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)] pub enum EpochError { /// Problems with the `.epochconfig` file. diff --git a/lib_efo/src/lib.rs b/lib_efo/src/lib.rs index 069ce41..ee2acc6 100644 --- a/lib_efo/src/lib.rs +++ b/lib_efo/src/lib.rs @@ -3,15 +3,15 @@ //! 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: `world` – holds the global state (`World`) and a lightweight snapshot (`Context`). -//! - TODO: `epoch` – manages the passage of time and epoch switching. -//! - TODO: `event` – CRUD and evaluation of events that affect the world. -//! - TODO: `org` – organisations, guilds, factions and their history. -//! - TODO: `character` – individual characters, traits and lineage. -//! - TODO: `town` – towns, cities, trade hubs and their populations. -//! - TODO: `link` – relations such as wars, alliances, roads, commerce. -//! - TODO: `storage` – generic persistence layer (`Store`) with JSON/YAML back‑ends. -//! - TODO: `util` – small helpers, ID generation, error types, etc. +//! - TODO[1]: `world` – holds the global state (`World`) and a lightweight snapshot (`Context`). +//! - TODO[0]: `epoch` – manages the passage of time and epoch switching. +//! - TODO[1]: `event` – CRUD and evaluation of events that affect the world. +//! - TODO[4]: `org` – organisations, guilds, factions and their history. +//! - TODO[2]: `character` – individual characters, traits and lineage. +//! - TODO[1]: `town` – towns, cities, trade hubs and their populations. +//! - TODO[2]: `link` – relations such as wars, alliances, roads, commerce. +//! - TODO[3]: `storage` – generic persistence layer (`Store`) with JSON/YAML back‑ends. +//! - TODO[4]: `util` – small helpers, ID generation, error types, etc. //! //! All public types implement `serde::Serialize / Deserialize` so that they can //! be persisted easily. The `World` struct also offers a convenient @@ -20,6 +20,7 @@ #![warn(missing_docs, clippy::missing_docs_in_private_items)] pub mod epoch_struct; +pub mod epoch_traits; #[macro_use] pub mod error; pub mod utils;