Adds the results of alpha testing fixes
Build Successful The build was successful
Gitea/epoch_forge/pipeline/head This commit looks good Details

This commit is contained in:
Dandaedre 2025-12-13 23:39:01 +01:00
parent 7263d3ab72
commit 8b9df96a5a
13 changed files with 120 additions and 84 deletions

34
Cargo.lock generated
View File

@ -100,23 +100,6 @@ dependencies = [
"backtrace",
]
[[package]]
name = "bin_efo"
version = "0.1.0"
dependencies = [
"clap",
"colored",
"derive_more",
"env_logger",
"insta",
"lib_efo",
"log",
"miette",
"serde",
"serde_json",
"thiserror",
]
[[package]]
name = "bitflags"
version = "2.10.0"
@ -278,6 +261,23 @@ dependencies = [
"unicode-xid",
]
[[package]]
name = "efo"
version = "0.1.0"
dependencies = [
"clap",
"colored",
"derive_more",
"env_logger",
"insta",
"lib_efo",
"log",
"miette",
"serde",
"serde_json",
"thiserror",
]
[[package]]
name = "encode_unicode"
version = "1.0.0"

View File

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

View File

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

View File

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

View File

@ -15,7 +15,7 @@
#![warn(missing_docs, clippy::missing_docs_in_private_items)]
use clap::{Args, Subcommand};
use clap::{Args, Subcommand, builder::ValueParser};
use lib_efo::epoch::EpochIdentifier;
/// Top-level sub-command for the `efo epoch` command.
@ -109,11 +109,23 @@ pub struct Diff {
/// * `tag` - The tag to tag the current epoch with.
#[derive(Args, Debug)]
pub struct Tag {
#[arg(required = true)]
#[arg(required = true, value_parser = ValueParser::from(validate_tag))]
#[allow(clippy::missing_docs_in_private_items)]
pub tag: String,
}
/// Return an error if the supplied tag contains only digits.
///
/// Clap will call this for every value it parses, so we can abort
/// parsing immediately when an invalid tag is encountered.
fn validate_tag(tag: &str) -> Result<String, String> {
if tag.chars().all(|c| c.is_ascii_digit()) {
Err(format!("Tag '{}' cannot be purely numeric", tag))
} else {
Ok(tag.to_string())
}
}
/// Performs basic filesystem level maintenance.
#[derive(Debug, Args)]
pub struct Fsck {}

View File

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

View File

@ -7,11 +7,11 @@ use lib_efo::epoch::EpochId;
#[derive(Display, Clone, Debug)]
#[allow(missing_docs, clippy::missing_docs_in_private_items)]
pub enum SuccessMessages {
#[display("Switched to epoch {_0}")]
EpochSwitchSuccess(lib_efo::epoch::EpochId),
#[display("Switched to epoch {_0} (was {_1})")]
EpochSwitchSuccess(EpochId, EpochId),
#[display("All future events deleted - back to epoch {_0}")]
DeletedAllFutureEvents(lib_efo::epoch::EpochId),
DeletedAllFutureEvents(EpochId),
#[display("The folder was initialized as an epoch folder")]
FolderInitializedSuccessfully(&'static str),
@ -31,7 +31,9 @@ pub enum SuccessMessages {
#[display("Successfully edited the entity {_0} ({_1} 󰻾[{_2}])")]
EditedEntity(String, String, String),
#[display("Showing delta between Epoch ({_0} & {_1})")]
DiffBetweenEpoch(lib_efo::epoch::EpochId, lib_efo::epoch::EpochId),
DiffBetweenEpoch(lib_efo::epoch::EpochId, EpochId),
#[display("Added tag {_0} to epoch {_1}")]
TagAdded(String, EpochId),
}
/// Display the success message to stdout

View File

@ -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<cli_table::TableDisplay, EpochError> {
items
.with_title()
.bold(true)
.border(
Border::builder()
.top(HorizontalLine::new('┌', '┐', '┬', '─'))
.bottom(HorizontalLine::new('└', '┘', '┴', '─'))
.left(VerticalLine::new('│'))
.right(VerticalLine::new('│'))
.build(),
)
.separator(
Separator::builder()
.column(Some(VerticalLine::new('│')))
.row(Some(HorizontalLine::new('├', '┤', '┼', '─')))
.build(),
)
// .foreground_color(Some(cli_table::Color::Blue)) // Border Color
.display()
.map_err(|_e| EpochError::TableStringConversionError {
name: self.name.clone(),
id: self.id,
})
items_table!(items, self.name.clone(), self.id)
}
/// Pretty-print the entity as a coloured tree.

View File

@ -3,6 +3,6 @@ source: lib_efo/src/entity/test.rs
expression: e.oneline_display()
---
├──┬─ 0c00000 Hero  ──────> ( 2, 4)⚓ ⧗10
│ ├─ Faction: 2 │ Effect: ⟳ (1 ⭾ 5), Stats: 0 0💰 0 0󰡢 3📈
│ ├─ Faction: 2 │ Effect: ⟳ (1 ⭾ 5), Stats: 0 0💰 0 0󰡢 3
│ └─  󰻾[50]  󰻾[11]
│

View File

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

View File

@ -5,11 +5,15 @@
//! common to many of the library's element types.
#![warn(clippy::missing_docs_in_private_items)]
use cli_table::{Style, Table, WithTitle};
use cli_table::{
Style, Table, WithTitle,
format::{Border, HorizontalLine, Separator, VerticalLine},
};
use serde::Serialize;
use std::{fmt::Display, fs::File, io::Write};
use uuid::Uuid;
use crate::{epoch::SaveMode, error::EpochError};
use crate::{epoch::SaveMode, error::EpochError, items_table};
/// Elements that can be compared with another instance to produce a diff.
pub trait Diffable {
@ -29,17 +33,11 @@ pub trait Nextable {}
/// Elements that can be rendered into a pretty, human-readable form.
pub trait Prettiable: Display {
/// Shows many items as a table.
///
/// The table is printed to `stdout` using the `cli_table` crate.
///
/// # Panics
/// Panics if printing the table to stdout fails.
fn show_as_table(list: Vec<&Self>)
fn as_table(list: Vec<&Self>) -> std::result::Result<cli_table::TableDisplay, EpochError>
where
for<'a> Vec<&'a Self>: Table + WithTitle,
{
#[allow(clippy::unwrap_used)] // There is no recovery of not being able to print a table
cli_table::print_stdout(list.with_title().bold(true)).unwrap();
items_table!(list, "Converting to table".to_string(), Uuid::nil())
}
/// Displays the struct as a log entry by printing the output of

View File

@ -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<String>,
name: String,
/// Trick used to have a cute line showing the following error message
#[label("This file is present and forbid the command to execute properly")]
show_label: Option<(usize, usize)>,
@ -123,6 +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<EntityIdentifier>),
/// The requested uniform RNG could not be created because the supplied
/// distribution parameters were invalid.
#[error("Failed to create uniform RNG: {0}")]
#[diagnostic(code(EpochError::UniformRngCreation))]
#[help("Ensure that the supplied range bounds satisfy `min < max`.")]
#[diagnostic(help("Ensure that the supplied range bounds satisfy `min < max`."))]
UniformRngCreation(#[from] rand::distr::uniform::Error),
/// The string did not contain exactly two comma-separated values.
#[error("Invalid position format: expected \"x,y\" found {0}")]
#[diagnostic(code(EpochError::InvalidPositionFormat))]
#[help("Provide exactly two numbers separated by a comma.")]
#[diagnostic(help("Provide exactly two numbers separated by a comma."))]
InvalidPositionFormat(String),
/// One of the components failed to parse as an `isize`.
#[error("Failed to parse integer: {0}")]
#[diagnostic(code(EpochError::ParsePositionError))]
#[help("Ensure that the input is a valid integer.")]
#[diagnostic(help("Ensure that the input is a valid integer."))]
ParsePositionError(String),
/// Failed to render a table into its string representation.
#[error("Failed to render table {name} [{id}] as string")]
#[diagnostic(code(EpochError::TableStringConversion))]
#[help("Verify that the table data and schema are compatible with string rendering.")]
#[diagnostic(help(
"Verify that the table data and schema are compatible with string rendering."
))]
TableStringConversionError {
/// The logical name of the table that failed to convert.
name: String,
@ -295,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<EntityIdentifier>),
}

View File

@ -52,3 +52,39 @@ impl RngLevel {
Ok(Uniform::try_from(self.to_range())?)
}
}
/// Build a table with the exact border / separator style you posted
/// and return the rendered string.
///
/// # Parameters
/// * `$items` – A table builder that implements the `Table` trait
/// (e.g. `Vec<Vec<...>>.into_table()`, `items.into_table()`, …).
/// * `$name` – The name that should be stored in `EpochError::TableStringConversionError`.
/// * `$id` – The id that should be stored in `EpochError::TableStringConversionError`.
#[macro_export]
macro_rules! items_table {
($items:expr, $name:expr, $id:expr) => {{
$items
.with_title()
.bold(true)
.border(
Border::builder()
.top(HorizontalLine::new('┌', '┐', '┬', '─'))
.bottom(HorizontalLine::new('└', '┘', '┴', '─'))
.left(VerticalLine::new('│'))
.right(VerticalLine::new('│'))
.build(),
)
.separator(
Separator::builder()
.column(Some(VerticalLine::new('│')))
.row(Some(HorizontalLine::new('├', '┤', '┼', '─')))
.build(),
)
.display()
.map_err(|_e| EpochError::TableStringConversionError {
name: $name.clone(),
id: $id,
})
}};
}