diff --git a/Cargo.lock b/Cargo.lock index 1d8352a..d7d9682 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -100,23 +100,6 @@ dependencies = [ "backtrace", ] -[[package]] -name = "bin_efo" -version = "0.1.0" -dependencies = [ - "clap", - "colored", - "derive_more", - "env_logger", - "insta", - "lib_efo", - "log", - "miette", - "serde", - "serde_json", - "thiserror", -] - [[package]] name = "bitflags" version = "2.10.0" @@ -278,6 +261,23 @@ dependencies = [ "unicode-xid", ] +[[package]] +name = "efo" +version = "0.1.0" +dependencies = [ + "clap", + "colored", + "derive_more", + "env_logger", + "insta", + "lib_efo", + "log", + "miette", + "serde", + "serde_json", + "thiserror", +] + [[package]] name = "encode_unicode" version = "1.0.0" diff --git a/bin_efo/Cargo.toml b/bin_efo/Cargo.toml index 1accc67..652059b 100644 --- a/bin_efo/Cargo.toml +++ b/bin_efo/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "bin_efo" +name = "efo" version = "0.1.0" edition = "2024" diff --git a/bin_efo/src/commands/entity_generic.rs b/bin_efo/src/commands/entity_generic.rs index 53654f0..78df840 100644 --- a/bin_efo/src/commands/entity_generic.rs +++ b/bin_efo/src/commands/entity_generic.rs @@ -117,7 +117,7 @@ pub struct EntityArgs { #[arg(long, short, action = clap::ArgAction::SetTrue, default_value_t = false)] pub delta: bool, - /// Non specified stat Repartition + /// The type of rng stat repartition #[arg(value_enum, long, default_value_t = RngLevel::Zero)] pub rng: RngLevel, diff --git a/bin_efo/src/commands/epoch.rs b/bin_efo/src/commands/epoch.rs index ed7937c..4305b22 100644 --- a/bin_efo/src/commands/epoch.rs +++ b/bin_efo/src/commands/epoch.rs @@ -175,13 +175,14 @@ fn handle_log(args: &cli_epoch::Log, main_epoch: &mut EpochConfig) -> Result<(), fn handle_switch(args: &cli_epoch::Switch, main_epoch: &mut EpochConfig) -> Result<(), AppError> { let target = main_epoch.get_epoch_id(&args.target)?; main_epoch.try_load(&target)?; + let message = &SuccessMessages::EpochSwitchSuccess(target, main_epoch.epoch_id); main_epoch.epoch_id = target; main_epoch.save_with_context( "Saving modified epoch config", &lib_efo::epoch::SaveMode::Erase, )?; - display_success(&SuccessMessages::EpochSwitchSuccess(target)); + display_success(message); Ok(()) } @@ -286,6 +287,7 @@ fn handle_taging(args: &cli_epoch::Tag, main_epoch: &mut EpochConfig) -> Result< .get_mut(&main_epoch.epoch_id) .ok_or(EpochError::EpochHashingImpossible(file!(), line!()))? { + let message = &SuccessMessages::TagAdded(args.tag.clone(), current_epoch_info.epoch_id); current_epoch_info.tags.push(args.tag.clone()); current_epoch_info .save_with_context("Saving modified epoch", &lib_efo::epoch::SaveMode::Erase)?; @@ -296,6 +298,7 @@ fn handle_taging(args: &cli_epoch::Tag, main_epoch: &mut EpochConfig) -> Result< "Saving modified main config", &lib_efo::epoch::SaveMode::Erase, )?; + display_success(message); Ok(()) } else { Err(AppError::Epoch(lib_efo::error::EpochError::Unknown( diff --git a/bin_efo/src/commands/epoch/cli_epoch.rs b/bin_efo/src/commands/epoch/cli_epoch.rs index bb7aa2f..74f5c60 100644 --- a/bin_efo/src/commands/epoch/cli_epoch.rs +++ b/bin_efo/src/commands/epoch/cli_epoch.rs @@ -15,7 +15,7 @@ #![warn(missing_docs, clippy::missing_docs_in_private_items)] -use clap::{Args, Subcommand}; +use clap::{Args, Subcommand, builder::ValueParser}; use lib_efo::epoch::EpochIdentifier; /// Top-level sub-command for the `efo epoch` command. @@ -109,11 +109,23 @@ pub struct Diff { /// * `tag` - The tag to tag the current epoch with. #[derive(Args, Debug)] pub struct Tag { - #[arg(required = true)] + #[arg(required = true, value_parser = ValueParser::from(validate_tag))] #[allow(clippy::missing_docs_in_private_items)] pub tag: String, } +/// Return an error if the supplied tag contains only digits. +/// +/// Clap will call this for every value it parses, so we can abort +/// parsing immediately when an invalid tag is encountered. +fn validate_tag(tag: &str) -> Result { + if tag.chars().all(|c| c.is_ascii_digit()) { + Err(format!("Tag '{}' cannot be purely numeric", tag)) + } else { + Ok(tag.to_string()) + } +} + /// Performs basic filesystem level maintenance. #[derive(Debug, Args)] pub struct Fsck {} diff --git a/bin_efo/src/commands/init.rs b/bin_efo/src/commands/init.rs index 2f9d759..17c4539 100644 --- a/bin_efo/src/commands/init.rs +++ b/bin_efo/src/commands/init.rs @@ -65,9 +65,9 @@ pub fn init(args: &InitCmd) -> Result<(), AppError> { let epoch_config = EpochConfig::default(); let root = epoch_config.save_folder(); - if read_dir(root)?.count() != 0 { + if read_dir(&root)?.count() != 0 { Err(EpochError::FolderNotEmpty { - name: None, + name: root, show_label: None, })?; } diff --git a/bin_efo/src/success.rs b/bin_efo/src/success.rs index 702b1af..568832a 100644 --- a/bin_efo/src/success.rs +++ b/bin_efo/src/success.rs @@ -7,11 +7,11 @@ use lib_efo::epoch::EpochId; #[derive(Display, Clone, Debug)] #[allow(missing_docs, clippy::missing_docs_in_private_items)] pub enum SuccessMessages { - #[display("Switched to epoch {_0}")] - EpochSwitchSuccess(lib_efo::epoch::EpochId), + #[display("Switched to epoch {_0} (was {_1})")] + EpochSwitchSuccess(EpochId, EpochId), #[display("All future events deleted - back to epoch {_0}")] - DeletedAllFutureEvents(lib_efo::epoch::EpochId), + DeletedAllFutureEvents(EpochId), #[display("The folder was initialized as an epoch folder")] FolderInitializedSuccessfully(&'static str), @@ -31,7 +31,9 @@ pub enum SuccessMessages { #[display("Successfully edited the entity {_0} ({_1} ๓ฐปพ[{_2}])")] EditedEntity(String, String, String), #[display("Showing delta between Epoch ({_0} & {_1})")] - DiffBetweenEpoch(lib_efo::epoch::EpochId, lib_efo::epoch::EpochId), + DiffBetweenEpoch(lib_efo::epoch::EpochId, EpochId), + #[display("Added tag {_0} to epoch {_1}")] + TagAdded(String, EpochId), } /// Display the success message to stdout diff --git a/lib_efo/src/entity/implementations.rs b/lib_efo/src/entity/implementations.rs index 99afaa1..dadcb22 100644 --- a/lib_efo/src/entity/implementations.rs +++ b/lib_efo/src/entity/implementations.rs @@ -6,12 +6,12 @@ use colored::*; use rand::distr::Distribution; use uuid::Uuid; // [3] - colored-rs examples -use crate::Displayable; use crate::entity::{EffectApplication, EffectBounds, Entity, EntityDuration}; use crate::epoch::epoch_traits::Diffable; use crate::error::EpochError; use crate::stats::{EntityType, GenericStat, MetaStats, OverallStats, Position, StatPair, Symbols}; use crate::utils::RngLevel; +use crate::{Displayable, items_table}; // ---------- Implementation ---------- impl Displayable for Entity { @@ -40,7 +40,7 @@ impl Displayable for Entity { .unwrap_or_default(); let prestige = if *self.metadata.prestige > 0 { - format!(" {:2}{}", self.metadata.prestige, "๐Ÿ“ˆ".yellow()) + format!(" {:2}{}", self.metadata.prestige, "๎ทซ ".yellow()) } else { String::new() }; @@ -125,29 +125,7 @@ impl Entity { &self, items: Vec<&OverallStats>, ) -> Result { - items - .with_title() - .bold(true) - .border( - Border::builder() - .top(HorizontalLine::new('โ”Œ', 'โ”', 'โ”ฌ', 'โ”€')) - .bottom(HorizontalLine::new('โ””', 'โ”˜', 'โ”ด', 'โ”€')) - .left(VerticalLine::new('โ”‚')) - .right(VerticalLine::new('โ”‚')) - .build(), - ) - .separator( - Separator::builder() - .column(Some(VerticalLine::new('โ”‚'))) - .row(Some(HorizontalLine::new('โ”œ', 'โ”ค', 'โ”ผ', 'โ”€'))) - .build(), - ) - // .foreground_color(Some(cli_table::Color::Blue)) // Border Color - .display() - .map_err(|_e| EpochError::TableStringConversionError { - name: self.name.clone(), - id: self.id, - }) + items_table!(items, self.name.clone(), self.id) } /// Pretty-print the entity as a coloured tree. diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_oneline_display.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_oneline_display.snap index 3f3d182..091b449 100644 --- a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_oneline_display.snap +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_oneline_display.snap @@ -3,6 +3,6 @@ source: lib_efo/src/entity/test.rs expression: e.oneline_display() --- โ”œโ”€โ”€โ”ฌโ”€ 0c00000 Hero ๏†ƒ โ”€โ”€โ”€โ”€โ”€โ”€> ( 2, 4)โš“ โง—10 -โ”‚ โ”œโ”€ Faction: 2 โ”‚ Effect: โŸณ (1 โญพ 5), Stats: 0๏“ฝ 0๐Ÿ’ฐ 0๏„ฒ 0๓ฐกข 3๐Ÿ“ˆ +โ”‚ โ”œโ”€ Faction: 2 โ”‚ Effect: โŸณ (1 โญพ 5), Stats: 0๏“ฝ 0๐Ÿ’ฐ 0๏„ฒ 0๓ฐกข 3๎ทซ โ”‚ โ””โ”€ ๏†œ ๓ฐปพ[50] ๏“Š ๓ฐปพ[11] โ”‚ diff --git a/lib_efo/src/epoch/epoch_config.rs b/lib_efo/src/epoch/epoch_config.rs index c83d0b3..754fdac 100644 --- a/lib_efo/src/epoch/epoch_config.rs +++ b/lib_efo/src/epoch/epoch_config.rs @@ -365,7 +365,7 @@ impl EpochConfig { items_to_log.push(info); } } - EpochInfo::show_as_table(items_to_log); + println!("{}", EpochInfo::as_table(items_to_log)?); Ok(()) } diff --git a/lib_efo/src/epoch/epoch_traits.rs b/lib_efo/src/epoch/epoch_traits.rs index 94b2346..9fd4488 100644 --- a/lib_efo/src/epoch/epoch_traits.rs +++ b/lib_efo/src/epoch/epoch_traits.rs @@ -5,11 +5,15 @@ //! common to many of the library's element types. #![warn(clippy::missing_docs_in_private_items)] -use cli_table::{Style, Table, WithTitle}; +use cli_table::{ + Style, Table, WithTitle, + format::{Border, HorizontalLine, Separator, VerticalLine}, +}; use serde::Serialize; use std::{fmt::Display, fs::File, io::Write}; +use uuid::Uuid; -use crate::{epoch::SaveMode, error::EpochError}; +use crate::{epoch::SaveMode, error::EpochError, items_table}; /// Elements that can be compared with another instance to produce a diff. pub trait Diffable { @@ -29,17 +33,11 @@ pub trait Nextable {} /// Elements that can be rendered into a pretty, human-readable form. pub trait Prettiable: Display { /// Shows many items as a table. - /// - /// The table is printed to `stdout` using the `cli_table` crate. - /// - /// # Panics - /// Panics if printing the table to stdout fails. - fn show_as_table(list: Vec<&Self>) + fn as_table(list: Vec<&Self>) -> std::result::Result where for<'a> Vec<&'a Self>: Table + WithTitle, { - #[allow(clippy::unwrap_used)] // There is no recovery of not being able to print a table - cli_table::print_stdout(list.with_title().bold(true)).unwrap(); + items_table!(list, "Converting to table".to_string(), Uuid::nil()) } /// Displays the struct as a log entry by printing the output of diff --git a/lib_efo/src/error.rs b/lib_efo/src/error.rs index c503ed4..d524de7 100644 --- a/lib_efo/src/error.rs +++ b/lib_efo/src/error.rs @@ -63,7 +63,7 @@ pub enum EpochError { /// Failed to create the epoch configuration. #[error("Failed to create the epoch configuration")] - #[help("Make sure the path is writable")] + #[diagnostic(help("Make sure the path is writable"))] #[diagnostic(code(EpochError::ConfigCreation))] ConfigCreation(String, #[source] std::io::Error), @@ -77,13 +77,13 @@ pub enum EpochError { }, /// This directory isn't empty and thus cannot be initialized. - #[error("This directory {name:?} isn't empty and thus cannot be initialized")] + #[error("This directory {name} isn't empty and thus cannot be initialized")] #[diagnostic(code(EpochError::FolderNotEmpty))] - #[diagnostic(help("Empty the folder or remove its content first"))] + #[diagnostic(help("Empty the folder contents first"))] FolderNotEmpty { #[source_code] /// Name of the file causing problem - name: Option, + name: String, /// Trick used to have a cute line showing the following error message #[label("This file is present and forbid the command to execute properly")] show_label: Option<(usize, usize)>, @@ -123,6 +123,9 @@ pub enum EpochError { /// The epoch folder for the target id is missing. #[error("Missing directory for epoch {0} at `{1}`")] #[diagnostic(code(EpochError::EpochFolderMissing))] + #[diagnostic(help( + "Ensure that the epoch was initialized and {0} refers to an existing epoch" + ))] EpochFolderMissing(EpochId, PathBuf), /// A future epoch exists, forbidding you to compute `next` and overriding them. @@ -243,48 +246,50 @@ pub enum EpochError { /// given epoch index. #[error("Epoch hashing failed for `{0}` (index {1})")] #[diagnostic(code(EpochError::EpochHashingImpossible))] - #[help("This is an internal error. Please file a bug report.")] + #[diagnostic(help("This is an internal error. Please file a bug report."))] EpochHashingImpossible(&'static str, u32), /// The entity with id **`{0}`** could not be found. #[error("Entity of type with id {0:?} not found")] #[diagnostic(code(epoch::entity_not_found_by_id))] - #[help( + #[diagnostic(help( "Verify that the identifier is correct and that the entity exists in the current epoch." - )] + ))] EntityNotFoundById(Uuid), /// The entity could not be found #[error("Entity of type {0:?} with name {1:?} not found")] #[diagnostic(code(epoch::entity_not_found))] - #[help( + #[diagnostic(help( "Verify that the identifier is correct and that the entity exists in the current epoch." - )] + ))] EntityNotFound(EntityType, Option), /// The requested uniform RNG could not be created because the supplied /// distribution parameters were invalid. #[error("Failed to create uniform RNG: {0}")] #[diagnostic(code(EpochError::UniformRngCreation))] - #[help("Ensure that the supplied range bounds satisfy `min < max`.")] + #[diagnostic(help("Ensure that the supplied range bounds satisfy `min < max`."))] UniformRngCreation(#[from] rand::distr::uniform::Error), /// The string did not contain exactly two comma-separated values. #[error("Invalid position format: expected \"x,y\" found {0}")] #[diagnostic(code(EpochError::InvalidPositionFormat))] - #[help("Provide exactly two numbers separated by a comma.")] + #[diagnostic(help("Provide exactly two numbers separated by a comma."))] InvalidPositionFormat(String), /// One of the components failed to parse as an `isize`. #[error("Failed to parse integer: {0}")] #[diagnostic(code(EpochError::ParsePositionError))] - #[help("Ensure that the input is a valid integer.")] + #[diagnostic(help("Ensure that the input is a valid integer."))] ParsePositionError(String), /// Failed to render a table into its string representation. #[error("Failed to render table {name} [{id}] as string")] #[diagnostic(code(EpochError::TableStringConversion))] - #[help("Verify that the table data and schema are compatible with string rendering.")] + #[diagnostic(help( + "Verify that the table data and schema are compatible with string rendering." + ))] TableStringConversionError { /// The logical name of the table that failed to convert. name: String, @@ -295,30 +300,32 @@ pub enum EpochError { /// Failed to parse a duration string. #[error("Failed to parse duration: {0}:{1}")] #[diagnostic(code(EpochError::ParsingDuration))] - #[help( + #[diagnostic(help( "Verify that the duration string follows the expected syntax, `permanent` or `duration:X` or `done`." - )] + ))] ParsingDuration(&'static str, String), /// Failed to parse a bounds string. #[error("Failed to parse bounds: {0}:{1}")] #[diagnostic(code(EpochError::ParsingBounds))] - #[help("Verify that the bounds string follows the expected syntax, `X-X` or `X:X`.")] + #[diagnostic(help( + "Verify that the bounds string follows the expected syntax, `X-X` or `X:X`." + ))] ParsingBounds(&'static str, String), /// The value started with `@` but the remainder was not a valid id or the name was empty. #[error("Failed to parse identifier or name")] #[diagnostic(code(EntityIdentifierError::InvalidIdentifier))] - #[help("Verify that the UUID after `@` is a valid id.")] + #[diagnostic(help("Verify that the UUID after `@` is a valid id."))] EmptyIdentifier, /// The entity already exists. #[error("Failed to create entity: {0:?} already exists")] #[diagnostic(code(EntityError::EntityAlreadyExist))] - #[help( + #[diagnostic(help( "Ensure that the entity name or ID is unique before creating a new one. \ You may need to delete or rename the existing entity." - )] + ))] EntityAlreadyExist(Option), } diff --git a/lib_efo/src/utils.rs b/lib_efo/src/utils.rs index fc965cd..7d6c46e 100644 --- a/lib_efo/src/utils.rs +++ b/lib_efo/src/utils.rs @@ -52,3 +52,39 @@ impl RngLevel { Ok(Uniform::try_from(self.to_range())?) } } + +/// Build a table with the exact border / separator style you posted +/// and return the rendered string. +/// +/// # Parameters +/// * `$items` โ€“ A table builder that implements the `Table` trait +/// (e.g. `Vec>.into_table()`, `items.into_table()`, โ€ฆ). +/// * `$name` โ€“ The name that should be stored in `EpochError::TableStringConversionError`. +/// * `$id` โ€“ The id that should be stored in `EpochError::TableStringConversionError`. +#[macro_export] +macro_rules! items_table { + ($items:expr, $name:expr, $id:expr) => {{ + $items + .with_title() + .bold(true) + .border( + Border::builder() + .top(HorizontalLine::new('โ”Œ', 'โ”', 'โ”ฌ', 'โ”€')) + .bottom(HorizontalLine::new('โ””', 'โ”˜', 'โ”ด', 'โ”€')) + .left(VerticalLine::new('โ”‚')) + .right(VerticalLine::new('โ”‚')) + .build(), + ) + .separator( + Separator::builder() + .column(Some(VerticalLine::new('โ”‚'))) + .row(Some(HorizontalLine::new('โ”œ', 'โ”ค', 'โ”ผ', 'โ”€'))) + .build(), + ) + .display() + .map_err(|_e| EpochError::TableStringConversionError { + name: $name.clone(), + id: $id, + }) + }}; +}