Fixes show and add
Build Failed The build failed
Gitea/epoch_forge/pipeline/head There was a failure building this commit Details

This commit is contained in:
Dandaedre 2025-12-12 17:22:04 +01:00
parent c07f554b38
commit 58f22fb0c0
13 changed files with 211 additions and 61 deletions

1
.gitignore vendored
View File

@ -29,3 +29,4 @@ Cargo.lock
testepo*
naming.json
config.toml
tarpaulin-report.html

74
Cargo.lock generated
View File

@ -135,9 +135,9 @@ checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
[[package]]
name = "clap"
version = "4.5.51"
version = "4.5.53"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4c26d721170e0295f191a69bd9a1f93efcdb0aff38684b61ab5750468972e5f5"
checksum = "c9e340e012a1bf4935f5282ed1436d1489548e8f72308207ea5df0e23d2d03f8"
dependencies = [
"clap_builder",
"clap_derive",
@ -145,9 +145,9 @@ dependencies = [
[[package]]
name = "clap_builder"
version = "4.5.51"
version = "4.5.53"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "75835f0c7bf681bfd05abe44e965760fea999a5286c6eb2d59883634fd02011a"
checksum = "d76b5d13eaa18c901fd2f7fca939fefe3a0727a953561fefdf3b2922b8569d00"
dependencies = [
"anstream",
"anstyle",
@ -211,6 +211,15 @@ dependencies = [
"windows-sys 0.59.0",
]
[[package]]
name = "convert_case"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "633458d4ef8c78b72454de2d54fd6ab2e60f9e02be22f3c6104cdc8a4e0fceb9"
dependencies = [
"unicode-segmentation",
]
[[package]]
name = "csv"
version = "1.4.0"
@ -234,21 +243,23 @@ dependencies = [
[[package]]
name = "derive_more"
version = "2.0.1"
version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "093242cf7570c207c83073cf82f79706fe7b8317e98620a47d5be7c3d8497678"
checksum = "10b768e943bed7bf2cab53df09f4bc34bfd217cdb57d971e769874c9a6710618"
dependencies = [
"derive_more-impl",
]
[[package]]
name = "derive_more-impl"
version = "2.0.1"
version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bda628edc44c4bb645fbe0f758797143e4e07926f7ebf4e9bdfbd3d2ce621df3"
checksum = "6d286bfdaf75e988b4a78e013ecd79c581e06399ab53fbacd2d916c2f904f30b"
dependencies = [
"convert_case",
"proc-macro2",
"quote",
"rustc_version",
"syn",
"unicode-xid",
]
@ -383,9 +394,9 @@ dependencies = [
[[package]]
name = "libc"
version = "0.2.177"
version = "0.2.178"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2874a2af47a2325c2001a6e6fad9b16a53b802102b528163885171cf92b15976"
checksum = "37c93d8daa9d8a012fd8ab92f088405fb202ea0b6ab73ee2482ae66af4f42091"
[[package]]
name = "linux-raw-sys"
@ -395,9 +406,9 @@ checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039"
[[package]]
name = "log"
version = "0.4.28"
version = "0.4.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34080505efa8e45a4b816c349525ebe327ceaa8559756f0356cba97ef3bf7432"
checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
[[package]]
name = "memchr"
@ -583,6 +594,15 @@ version = "0.1.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56f7d92ca342cea22a06f2121d944b4fd82af56988c270852495420f961d4ace"
[[package]]
name = "rustc_version"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
dependencies = [
"semver",
]
[[package]]
name = "rustix"
version = "1.1.2"
@ -608,6 +628,12 @@ version = "1.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f"
[[package]]
name = "semver"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2"
[[package]]
name = "serde"
version = "1.0.228"
@ -680,9 +706,9 @@ checksum = "b7401a30af6cb5818bb64852270bb722533397edcfc7344954a38f420819ece2"
[[package]]
name = "syn"
version = "2.0.110"
version = "2.0.111"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a99801b5bd34ede4cf3fc688c5919368fea4e4814a4664359503e6015b280aea"
checksum = "390cc9a294ab71bdb1aa2e99d13be9c753cd2d7bd6560c77118597410c4d2e87"
dependencies = [
"proc-macro2",
"quote",
@ -750,6 +776,12 @@ version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b09c83c3c29d37506a3e260c08c03743a6bb66a9cd432c6934ab501a190571f"
[[package]]
name = "unicode-segmentation"
version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6ccf251212114b54433ec949fd6a7841275f9ada20dddd2f29e9ceea4501493"
[[package]]
name = "unicode-width"
version = "0.1.14"
@ -776,13 +808,13 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
[[package]]
name = "uuid"
version = "1.18.1"
version = "1.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f87b8aa10b915a06587d0dec516c282ff295b475d94abf425d62b57710070a2"
checksum = "e2e054861b4bd027cd373e18e8d8d8e6548085000e41290d95ce0c373a654b4a"
dependencies = [
"getrandom",
"js-sys",
"serde",
"serde_core",
"wasm-bindgen",
]
@ -1019,18 +1051,18 @@ checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59"
[[package]]
name = "zerocopy"
version = "0.8.30"
version = "0.8.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ea879c944afe8a2b25fef16bb4ba234f47c694565e97383b36f3a878219065c"
checksum = "fd74ec98b9250adb3ca554bdde269adf631549f51d8a8f8f0a10b50f1cb298c3"
dependencies = [
"zerocopy-derive",
]
[[package]]
name = "zerocopy-derive"
version = "0.8.30"
version = "0.8.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf955aa904d6040f70dc8e9384444cb1030aed272ba3cb09bbc4ab9e7c1f34f5"
checksum = "d8a8d209fdf45cf5138cbb5a506f6b52522a25afccc534d1475dad8e31105c6a"
dependencies = [
"proc-macro2",
"quote",

4
Jenkinsfile vendored
View File

@ -25,9 +25,9 @@ pipeline {
steps {
script {
if (env.BRANCH_NAME == 'origin/review' || env.BRANCH_NAME == 'review' || env.BRANCH_NAME == 'origin/dev-ci' || env.BRANCH_NAME == 'dev-ci') {
sh 'cargo test'
sh 'cargo +nightly test'
} else if (env.BRANCH_NAME == 'origin/master' || env.BRANCH_NAME == 'master') {
sh 'cargo test'
sh 'cargo +nightly test'
} else {
echo "Unknown branch: ${env.BRANCH_NAME} - skipping build."
}

View File

@ -1,7 +1,8 @@
//! Module handling the creation of characters
use lib_efo::epoch::epoch_traits::{ConfigWritable, Diffable};
use lib_efo::stats::Symbols;
use lib_efo::naming::NAMING;
use lib_efo::stats::{Position, Symbols};
use clap::{Args, Subcommand};
use lib_efo::Displayable;
@ -54,9 +55,19 @@ pub struct EntityArgs {
/// An optional Uuid to either set or get
#[arg(long, group = "identifier")]
pub id: Option<String>,
/// Non specified stat Repartition
#[arg(value_enum, default_value_t = RngLevel::Zero)]
#[arg(value_enum, long, default_value_t = RngLevel::Zero)]
pub rng: RngLevel,
/// Adds at a specific position
#[arg(long, group = "position")]
pub pos_exact: Option<Position>,
/// Adds at a specific position
#[arg(long, group = "position")]
pub pos: Option<Position>,
/// All stats pairs involved
pub stats: Vec<StatPair>,
}
@ -113,7 +124,6 @@ fn handle_diff_entity(
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)?;
@ -132,8 +142,14 @@ fn handle_show_entity(
main_epoch: &mut EpochConfig,
) -> Result<(), EpochError> {
let epoch_info = main_epoch.try_load_current()?;
let e = find_entity(entity_args, e_type, epoch_info)?;
e.print_full();
if entity_args.name.is_none() && entity_args.id.is_none() {
for e in vec_entities(e_type, epoch_info) {
e.print_oneline();
}
} else {
let e = find_entity(entity_args, e_type, epoch_info)?;
e.print_full();
}
Ok(())
}
@ -213,15 +229,14 @@ fn handle_create_entity(
let epoch_info = main_epoch.try_load_current_as_mut()?;
let vec_entities: &mut Vec<Entity> = vec_entities_mut(e_type, epoch_info);
// TODO: Create real entity
// TODO: Add name, add stats repartition to clap
// TODO: Load stats to entity from clap
let mut e = Entity::create_rng(e_type, &RngLevel::Flawed)?;
let mut e = Entity::create_rng(e_type, &entity_args.rng)?;
update_stats(entity_args, &mut e);
// Specifying a name means the name needs to be changed
// Specifying an id however means nothing and should be ignored
if let Some(name) = &entity_args.name {
e.name = name.clone();
} else {
e.name = NAMING.generate_exotic_character_name();
}
info!("Created character: {:#?}", e);
@ -352,6 +367,7 @@ fn find_by_args(entity: &Entity, entity_args: &EntityArgs) -> bool {
}
/// 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()
@ -359,6 +375,7 @@ fn find_by_id<'a>(entities: &'a [Entity], id: &'a String) -> Option<&'a Entity>
}
/// 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))
}

View File

@ -40,6 +40,7 @@ pub struct Entity {
///
/// `temp_stats` is recalculated each turn and does not persist
/// beyond the entity's lifetime.
#[serde(skip)]
temp_stats: OverallStats,
/// Non-statistical metadata such as name, rarity, and faction.

View File

@ -49,43 +49,48 @@ impl Displayable for Entity {
.metadata
.capital
.as_ref()
.map(|c| format!(" | 💰 {}", c))
.map(|c| format!(" | 💰 {:>2}", c))
.unwrap_or_default();
let governor = self
.metadata
.governor
.as_ref()
.map(|g| format!(" | 👑 {}", g))
.map(|g| format!(" | 👑 {:>2}", g))
.unwrap_or_default();
let prestige = if self.metadata.prestige > 0 {
format!(" | 📈 {}", self.metadata.prestige)
format!(" {:2}{}", self.metadata.prestige, "📈".yellow())
} else {
String::new()
};
// ---- build the two lines ----
let line1 = format!(
"├─ {} {} ──────> {} {}",
self.name,
"├──┬─ {} {:23} {} ──────> {} {}",
self.id.to_string().split_at(7).0.blue(),
self.name.green(),
self.entity_type.to_symbol(),
self.metadata.position.to_symbol(),
self.duration.to_symbol()
self.duration.to_symbol().yellow(),
);
let (junction, line3) = if !capital.is_empty() | !governor.is_empty() {
("├", format!("│ └─ {}{}\n", capital, governor,))
} else {
("└", "".to_string())
};
let line2 = format!(
"│ └─ Faction: {:?}{}{}{} │ Effect: {} {}, Stats: {}",
self.metadata.faction,
capital,
governor,
prestige,
"│ {}─ Faction: {} │ Effect: {} {}, Stats: {}{}",
junction,
self.metadata.faction.to_symbol(),
self.effect_nature.to_symbol(),
self.effect_bounds.to_symbol(),
self.stats.to_symbol()
self.stats.to_symbol(),
prestige,
);
format!("{}\n{}", line1, line2)
format!("{}\n{}\n{}│", line1, line2, line3)
}
}
@ -169,7 +174,7 @@ fn overwrite_stat(stats: &mut OverallStats, pair: StatPair) {
/// Add to a stat in a table
fn add_to_stat(stats: &mut OverallStats, pair: StatPair) {
let affected_stat = stats.get_field_mut(&pair.stat);
let current_value = affected_stat.clone();
let current_value = *affected_stat;
*affected_stat = GenericStat(current_value.saturating_add(*pair.value));
}
@ -218,9 +223,9 @@ impl Diffable for MetaStats {
faction: {
match (self.faction.as_ref(), other.faction.as_ref()) {
(None, None) => None,
(None, Some(a)) => Some(a.clone()),
(Some(a), None) => Some(a.clone()),
(Some(a), Some(b)) => Some(a.clone() - b.clone()),
(None, Some(a)) => Some(*a),
(Some(a), None) => Some(*a),
(Some(a), Some(b)) => Some(*a - *b),
}
},
links: self

View File

@ -23,7 +23,7 @@ use std::{
use log::{info, warn};
use serde::{Deserialize, Serialize};
use crate::{epoch::epoch_traits::Prettiable, error::EpochError, io_err_with_help};
use crate::{epoch::epoch_traits::Prettiable, error::EpochError};
/// The file written to *.epochconfig* that tells the CLI which
/// epoch folder is the “current” one.

View File

@ -18,7 +18,6 @@ use crate::{
epoch_traits::{ConfigWritable, Prettiable},
},
error::EpochError,
io_err_with_help,
};
/// The metadata file stored inside each epoch directory

View File

@ -48,6 +48,7 @@ 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")]
@ -75,7 +76,7 @@ pub enum EpochError {
},
/// This directory isn't empty and thus cannot be initialized.
#[error("This directory 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"))]
FolderNotEmpty {
@ -258,6 +259,18 @@ pub enum EpochError {
#[diagnostic(code(EpochError::UniformRngCreation))]
#[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.")]
InvalidPositionFormat(String),
/// One of the components failed to parse as an `isize`.
#[error("Failed to parse integer: {0}")]
#[diagnostic(code(EpochError::ParseInt))]
#[help("Ensure that the input is a valid integer.")]
ParsePositionError(String),
}
/// A small enum of explicit user-facing error messages.

View File

@ -21,6 +21,7 @@
#![deny(clippy::unwrap_used)]
#[macro_use]
#[allow(dead_code, unused_assignments)]
pub mod error;
pub mod entity;
pub mod epoch;

View File

@ -387,6 +387,8 @@ pub struct Position(isize, isize);
/// The grid size, as a static like a degenerate
// TODO[9]: Change to be at least initialized with the world ?
const GRID_SIZE: (i32, i32) = (1920, 1080);
/// The size the map is divided into
const CHUNK_SIZE: isize = 200;
impl Position {
/// The euclidian distance between two points
@ -396,7 +398,7 @@ impl Position {
/// The position in grid coordinates
fn to_grid_distance(&self) -> (isize, isize) {
(self.0 / 200, self.1 / 200)
(self.0 / CHUNK_SIZE, self.1 / CHUNK_SIZE)
}
/// Create a random position

View File

@ -6,7 +6,8 @@ use std::str::FromStr;
use crate::entity::{EffectApplication, EffectBounds, EntityDuration};
use crate::error::EpochError;
use crate::stats::{
self, EntityType, GameStat, GenericStat, ListStats, OverallStats, Position, StatPair, Symbols,
self, EntityType, FactionId, GameStat, GenericStat, ListStats, OverallStats, Position,
StatPair, Symbols,
};
/// Creates a thin, deref-able wrapper around an inner type.
@ -211,8 +212,20 @@ impl From<ListStats> for &str {
}
impl OverallStats {
//TODO: Redoc
/// Get a field by a given liststat and return a reference to it
/// Retrieve a reference to a statistic field by its `ListStats` key.
///
/// # Arguments
///
/// * `field` – The `ListStats` variant that selects which statistic to return.
///
/// # Returns
///
/// A reference to the selected `GenericStat`.
///
/// # Panics
///
/// Panics if `field` is one of the variants that are not yet implemented
/// (`Social`, `Culture`, `Education`, `Tourism`, `Influence`).
pub fn get_field(&self, field: &ListStats) -> &GenericStat {
match field {
ListStats::Demographics => &self.demographics,
@ -243,7 +256,20 @@ impl OverallStats {
}
}
/// Get a field by a given liststat and return a reference to it
/// Retrieve a mutable reference to a statistic field by its `ListStats` key.
///
/// # Arguments
///
/// * `field` – The `ListStats` variant that selects which statistic to modify.
///
/// # Returns
///
/// A mutable reference to the selected `GenericStat`.
///
/// # Panics
///
/// Panics if `field` is one of the variants that are not yet implemented
/// (`Social`, `Culture`, `Education`, `Tourism`, `Influence`).
pub fn get_field_mut(&mut self, field: &ListStats) -> &mut GenericStat {
match field {
ListStats::Demographics => &mut self.demographics,
@ -278,6 +304,11 @@ impl OverallStats {
impl FromStr for StatPair {
type Err = EpochError;
/// Parse a string into a `StatPair`.
///
/// The input can be either in the form `"stat:value"` or `"stat value"`.
/// If the format is invalid, an `EpochError::IllFormedStatQualifier`
/// is returned.
fn from_str(s: &str) -> Result<Self, Self::Err> {
let (stat_str, val_str) = if let Some(idx) = s.find(':') {
(&s[..idx], &s[idx + 1..])
@ -300,6 +331,38 @@ impl FromStr for StatPair {
}
}
/// Parse a string into a `Position`.
///
/// The input must be two signed integers separated by a comma, optionally
/// surrounded by whitespace. Leading and trailing whitespace around each
/// component is ignored.
///
/// # Errors
///
/// * `ParsePositionError::InvalidFormat` – the string does not contain
/// exactly one comma or there are not exactly two components.
/// * `ParsePositionError::ParseIntError` – one of the components cannot be
/// parsed as an `isize`.
impl std::str::FromStr for Position {
type Err = EpochError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let parts: Vec<&str> = s.split(',').collect();
if parts.len() != 2 {
return Err(EpochError::InvalidPositionFormat(s.to_string()));
}
let x: isize = parts[0]
.trim()
.parse()
.map_err(|_| EpochError::ParsePositionError(s.to_string()))?;
let y: isize = parts[1]
.trim()
.parse()
.map_err(|_| EpochError::ParsePositionError(s.to_string()))?;
Ok(Position(x, y))
}
}
impl Symbols for EntityType {
fn to_shortest(&self) -> String {
match self {
@ -336,7 +399,7 @@ impl Symbols for EffectApplication {
impl Symbols for Position {
fn to_symbol(&self) -> String {
format!("⚓({},{})", self.0, self.1)
format!("({:4},{:4})⚓", self.0, self.1)
}
fn to_shortest(&self) -> String {
format!("{},{}", self.0, self.1)
@ -362,8 +425,15 @@ impl Symbols for EffectBounds {
impl Symbols for OverallStats {
fn to_symbol(&self) -> String {
format!(
" {} |💰 {} | {} |󰡢 {}",
self.demographics, self.economy, self.military, self.infrastructure
"{:2}{} {:2}{} {:2}{} {:2}{}",
self.demographics,
"".green(),
self.economy,
"💰".yellow(),
self.military,
"".red(),
self.infrastructure,
"󰡢".cyan(),
)
}
}
@ -431,5 +501,14 @@ impl Symbols for ListStats {
}
}
impl Symbols for Option<FactionId> {
fn to_symbol(&self) -> String {
if let Some(faction) = self {
format!("{faction}")
} else {
"Ø".to_string()
}
}
}
#[cfg(test)]
pub(crate) mod test;

View File

@ -37,7 +37,7 @@ impl RngLevel {
/// Turn into a range for rng generation
pub fn to_range(&self) -> std::ops::Range<i32> {
match self {
RngLevel::Zero => 0..0,
RngLevel::Zero => 0..1,
RngLevel::Low => 0..20,
RngLevel::Med => 10..40,
RngLevel::High => 20..50,