Merge pull request 'dev-ci' (#20) from dev-ci into main
Build Successful The build was successful
Gitea/epoch_forge/pipeline/head This commit looks good Details

Reviewed-on: #20
This commit is contained in:
Dandaedre 2025-12-16 20:59:10 +01:00
commit f34548f331
17 changed files with 230 additions and 29 deletions

View File

@ -1,2 +1,3 @@
snapshots
*.svg
build.rs

View File

@ -1,8 +1,8 @@
[last_run_clean]
run_status = "Success"
lines_parsed = 110
coverage = 49.76
coverage = 48.83
[last_run_clean.run_duration]
secs = 26
nanos = 637749582
secs = 27
nanos = 30003945

View File

@ -1,7 +1,6 @@
[workspace]
resolver = "3"
members = ["bin_efo", "lib_efo"]
version = "0.1"
[workspace.dependencies]
serde = { version = "1.0.228", features = ["derive"] }

View File

@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="122" height="18" role="img" aria-label="test-coverage: 50%"><title>test-coverage: 50%</title><linearGradient id="bms-8fc2dc264327201c" x2="0" y2="100%"><stop offset="0" stop-color="#fff" stop-opacity=".7"/><stop offset=".1" stop-color="#aaa" stop-opacity=".1"/><stop offset=".9" stop-color="#000" stop-opacity=".3"/><stop offset="1" stop-color="#000" stop-opacity=".5"/></linearGradient><clipPath id="bmr-8fc2dc264327201c"><rect width="122" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-8fc2dc264327201c)"><rect width="87" height="18" fill="#555"/><rect x="87" width="35" height="18" fill="#97ca00"/><rect width="122" height="18" fill="url(#bms-8fc2dc264327201c)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="445" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="770">test-coverage</text><text x="445" y="130" transform="scale(.1)" fill="#fff" textLength="770">test-coverage</text><text aria-hidden="true" x="1035" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="250">50%</text><text x="1035" y="130" transform="scale(.1)" fill="#fff" textLength="250">50%</text></g></svg>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="122" height="18" role="img" aria-label="test-coverage: 49%"><title>test-coverage: 49%</title><linearGradient id="bms-8b2d5b6821598c64" x2="0" y2="100%"><stop offset="0" stop-color="#fff" stop-opacity=".7"/><stop offset=".1" stop-color="#aaa" stop-opacity=".1"/><stop offset=".9" stop-color="#000" stop-opacity=".3"/><stop offset="1" stop-color="#000" stop-opacity=".5"/></linearGradient><clipPath id="bmr-8b2d5b6821598c64"><rect width="122" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-8b2d5b6821598c64)"><rect width="87" height="18" fill="#555"/><rect x="87" width="35" height="18" fill="#97ca00"/><rect width="122" height="18" fill="url(#bms-8b2d5b6821598c64)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="445" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="770">test-coverage</text><text x="445" y="130" transform="scale(.1)" fill="#fff" textLength="770">test-coverage</text><text aria-hidden="true" x="1035" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="250">49%</text><text x="1035" y="130" transform="scale(.1)" fill="#fff" textLength="250">49%</text></g></svg>

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="78" height="18" role="img" aria-label="version: 0.1"><title>version: 0.1</title><linearGradient id="bms-e7c71dea3d331ef4" x2="0" y2="100%"><stop offset="0" stop-color="#fff" stop-opacity=".7"/><stop offset=".1" stop-color="#aaa" stop-opacity=".1"/><stop offset=".9" stop-color="#000" stop-opacity=".3"/><stop offset="1" stop-color="#000" stop-opacity=".5"/></linearGradient><clipPath id="bmr-e7c71dea3d331ef4"><rect width="78" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-e7c71dea3d331ef4)"><rect width="51" height="18" fill="#555"/><rect x="51" width="27" height="18" fill="#fe7d37"/><rect width="78" height="18" fill="url(#bms-e7c71dea3d331ef4)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="265" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="410">version</text><text x="265" y="130" transform="scale(.1)" fill="#fff" textLength="410">version</text><text aria-hidden="true" x="635" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="170">0.1</text><text x="635" y="130" transform="scale(.1)" fill="#fff" textLength="170">0.1</text></g></svg>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="104" height="18" role="img" aria-label="version: 1.0.228"><title>version: 1.0.228</title><linearGradient id="bms-ed89fff123285f2c" x2="0" y2="100%"><stop offset="0" stop-color="#fff" stop-opacity=".7"/><stop offset=".1" stop-color="#aaa" stop-opacity=".1"/><stop offset=".9" stop-color="#000" stop-opacity=".3"/><stop offset="1" stop-color="#000" stop-opacity=".5"/></linearGradient><clipPath id="bmr-ed89fff123285f2c"><rect width="104" height="18" rx="4" fill="#fff"/></clipPath><g clip-path="url(#bmr-ed89fff123285f2c)"><rect width="51" height="18" fill="#555"/><rect x="51" width="53" height="18" fill="#fe7d37"/><rect width="104" height="18" fill="url(#bms-ed89fff123285f2c)"/></g><g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="110"><text aria-hidden="true" x="265" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="410">version</text><text x="265" y="130" transform="scale(.1)" fill="#fff" textLength="410">version</text><text aria-hidden="true" x="765" y="140" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="430">1.0.228</text><text x="765" y="130" transform="scale(.1)" fill="#fff" textLength="430">1.0.228</text></g></svg>

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

66
bin_efo/build.rs Normal file
View File

@ -0,0 +1,66 @@
// build.rs
use std::process::Command;
use std::str;
/// Helper that runs a command and returns its stdout as a trimmed UTF‑8 string.
fn run_cmd(cmd: &mut Command) -> String {
let out = cmd.output().expect("failed to run command");
if !out.status.success() {
panic!(
"command {:?} failed with status {:?}\nstderr: {}",
cmd,
out.status,
String::from_utf8_lossy(&out.stderr)
);
}
str::from_utf8(&out.stdout)
.expect("command produced non‑UTF8 output")
.trim()
.to_owned()
}
fn main() {
let git_hash = run_cmd(Command::new("git").args(["rev-parse", "--short", "HEAD"]));
println!("cargo:rustc-env=GIT_HASH={}", git_hash);
let args = &["rev-parse", "--abbrev-ref", "HEAD"];
let git_branch = run_cmd(Command::new("git").args(args));
println!("cargo:rustc-env=GIT_BRANCH={}", git_branch);
// Prefer the explicit env var – it mirrors the real user choice
let toolchain = std::env::var("RUSTUP_TOOLCHAIN")
.map(|v| v.trim().to_owned())
.unwrap_or_else(|_| {
// Try rustup first; if that fails, fall back to rustc
let raw = run_cmd(Command::new("rustup").args(["show", "active-toolchain"]));
// rustup output may look like:
// stable-x86_64-unknown-linux-gnu (overridden by environment variable)
// We only want the part before the first '('
raw.split('(').next().unwrap().trim().to_owned()
});
println!("cargo:rustc-env=TOOLCHAIN={}", toolchain);
let rustc_version = run_cmd(Command::new("rustc").args(["--version"]));
println!("cargo:rustc-env=RUSTC_VERSION={}", rustc_version);
println!(
"cargo:rustc-env=EFO_SHORT_VERSION={} ({}{})",
env!("CARGO_PKG_VERSION"),
git_branch,
git_hash,
);
println!(
"cargo:rustc-env=EFO_FULL_VERSION={} ({}{})  {}  {}",
env!("CARGO_PKG_VERSION"),
git_branch,
git_hash,
toolchain,
rustc_version,
);
// println!("cargo:rerun-if-changed=.git/HEAD");
// println!("cargo:rerun-if-changed=.git/refs/heads");
// println!("cargo:rerun-if-changed=.git/refs/remotes");
}

View File

@ -365,7 +365,8 @@ pub(crate) fn handle_create_entity(
entity.entity_type.to_shortest(),
entity.id.to_string(),
);
// TODO: Rather bad
entity.update_metastats();
// TODO: Rather bad but faster that reloading without hashmaps
vec_entities.push(entity.clone());
entity.print_full(epoch_info);
@ -495,6 +496,7 @@ fn handle_edit_entity(
};
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.update_metastats();
entity.print_full(epoch_info);
// Only swap if a swap is needed
epoch_info.swap_entity(entity)?;

View File

@ -151,17 +151,20 @@ fn handle_diff(args: &cli_epoch::Diff) -> Result<(), AppError> {
///
/// This helper is internal to the `epoch` sub-command.
fn handle_log(args: &cli_epoch::Log, main_epoch: &mut EpochConfig) -> Result<(), AppError> {
let limit = args.limit;
let context = args.context;
let start_id = &main_epoch.epoch_id;
let mut list_id: Vec<EpochId> = main_epoch
.list_existing_epochs
.iter()
.filter(|(id, _)| id <= &start_id)
.map(|(id, _)| *id)
.collect();
let mut list_id: Vec<EpochId> = main_epoch.list_existing_epochs.keys().copied().collect();
list_id.sort();
main_epoch.log_elements(&list_id[..std::cmp::min(list_id.len(), limit)])?;
// list_id.reverse();
let pos = **list_id
.iter()
.find(|id| id == &start_id)
.ok_or(EpochError::EpochNotFound(start_id.to_string()))? as usize;
main_epoch.log_elements(
&list_id[(pos.saturating_sub(context))..std::cmp::min(pos + context + 1, list_id.len())],
)?;
Ok(())
}

View File

@ -57,8 +57,8 @@ pub enum EpochCmd {
#[derive(Args, Debug)]
pub struct Log {
/// (Optional) Limit the number of entries shown.
#[arg(short, long, default_value = "50")]
pub limit: usize,
#[arg(short, long, default_value = "20")]
pub context: usize,
}
/// Switches to the specified epoch. The target can be an integer,

View File

@ -43,6 +43,7 @@ mod success;
/// It uses `clap` to parse the top-level sub-commands (`init`, `epoch`, …)
/// and stores them in the `command` field.
#[derive(Parser, Debug)]
#[command(version = env!("EFO_SHORT_VERSION"))]
#[command(name = "efo")]
#[command(about = "Epoch Forge - manage organisations over time")]
struct Cli {
@ -101,6 +102,14 @@ enum TopLevelCmd {
fn main() -> miette::Result<()> {
env_logger::init();
log::trace!(
"System version: {} ({}{}) {} {}",
env!("CARGO_PKG_VERSION"),
env!("GIT_BRANCH"),
env!("GIT_HASH"),
env!("TOOLCHAIN"),
env!("RUSTC_VERSION"),
);
let cli = Cli::parse();
if let Err(e) = exec_dispatch(cli) {

66
lib_efo/build.rs Normal file
View File

@ -0,0 +1,66 @@
// build.rs
use std::process::Command;
use std::str;
/// Helper that runs a command and returns its stdout as a trimmed UTF‑8 string.
fn run_cmd(cmd: &mut Command) -> String {
let out = cmd.output().expect("failed to run command");
if !out.status.success() {
panic!(
"command {:?} failed with status {:?}\nstderr: {}",
cmd,
out.status,
String::from_utf8_lossy(&out.stderr)
);
}
str::from_utf8(&out.stdout)
.expect("command produced non‑UTF8 output")
.trim()
.to_owned()
}
fn main() {
let git_hash = run_cmd(Command::new("git").args(["rev-parse", "--short", "HEAD"]));
println!("cargo:rustc-env=GIT_HASH={}", git_hash);
let args = &["rev-parse", "--abbrev-ref", "HEAD"];
let git_branch = run_cmd(Command::new("git").args(args));
println!("cargo:rustc-env=GIT_BRANCH={}", git_branch);
// Prefer the explicit env var – it mirrors the real user choice
let toolchain = std::env::var("RUSTUP_TOOLCHAIN")
.map(|v| v.trim().to_owned())
.unwrap_or_else(|_| {
// Try rustup first; if that fails, fall back to rustc
let raw = run_cmd(Command::new("rustup").args(["show", "active-toolchain"]));
// rustup output may look like:
// stable-x86_64-unknown-linux-gnu (overridden by environment variable)
// We only want the part before the first '('
raw.split('(').next().unwrap().trim().to_owned()
});
println!("cargo:rustc-env=TOOLCHAIN={}", toolchain);
let rustc_version = run_cmd(Command::new("rustc").args(["--version"]));
println!("cargo:rustc-env=RUSTC_VERSION={}", rustc_version);
println!(
"cargo:rustc-env=EFO_SHORT_VERSION={} ({}{})",
env!("CARGO_PKG_VERSION"),
git_branch,
git_hash,
);
println!(
"cargo:rustc-env=EFO_FULL_VERSION={} ({}{})  {}  {}",
env!("CARGO_PKG_VERSION"),
git_branch,
git_hash,
toolchain,
rustc_version,
);
// println!("cargo:rerun-if-changed=.git/HEAD");
// println!("cargo:rerun-if-changed=.git/refs/heads");
// println!("cargo:rerun-if-changed=.git/refs/remotes");
}

View File

@ -250,6 +250,11 @@ impl Entity {
&self.metadata.position
}
/// Defer the update of all stats
pub fn update_metastats(&mut self) {
self.stats.update();
}
/// Returns whether the entity match an optionnal identifier
pub fn match_identifier(&self, entity_identifier: &Option<EntityIdentifier>) -> bool {
match entity_identifier {

View File

@ -15,8 +15,9 @@ use crate::{
EpochId, EpochIdentifier, EpochInfo, MAIN_NAME, SUBFOLDER_NAMING, SaveMode, TagList,
epoch_traits::ConfigWritable,
},
stats,
stats::{self, Symbols},
};
use colored::*;
use std::{
collections::HashMap,
fs::{read_to_string, remove_dir_all},
@ -26,7 +27,7 @@ use std::{
use log::{info, warn};
use serde::{Deserialize, Serialize};
use crate::{epoch::epoch_traits::Prettiable, error::EpochError};
use crate::error::EpochError;
/// The file written to *.epochconfig* that tells the CLI which
/// epoch folder is the “current” one.
@ -42,6 +43,9 @@ pub struct EpochConfig {
/// The epoch ID that the binary should consider “current”.
pub epoch_id: EpochId,
/// The version of the file loaded, and hopefully of all the project
pub version: String,
/// Optional human-friendly tags (e.g. `"winter-B"`, `"post-war"`).
pub tags: HashMap<String, EpochId>,
// TODO(6): Can become important
@ -60,6 +64,7 @@ impl Default for EpochConfig {
epoch_id: EpochId::new(0),
tags: HashMap::new(),
list_existing_epochs: HashMap::new(),
version: env!("EFO_SHORT_VERSION").to_string(),
}
}
}
@ -79,7 +84,7 @@ impl EpochConfig {
.map_err(|e| EpochError::Serde {
source: e,
file_name: path.to_string_lossy().to_string(),
help: None,
version: format!("Current version: {}", env!("EFO_SHORT_VERSION")),
})?;
Ok(config.initialize()?)
} else {
@ -89,6 +94,15 @@ impl EpochConfig {
}
}
/// Output the current version vs the filesystem version
pub fn version(&self) -> String {
format!(
"Program version {}.\nFilesystem version: {}.",
self.version,
env!("EFO_SHORT_VERSION")
)
}
/// Initialize the epoch structure in depth.
///
/// Scans the default configuration folder for sub-directories that are
@ -126,6 +140,7 @@ impl EpochConfig {
/// * `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 version = self.version();
let value = self
.list_existing_epochs
.get_mut(epoch_id)
@ -140,7 +155,7 @@ impl EpochConfig {
serde_json::from_str(&read_to_string?).map_err(|e| EpochError::Serde {
source: e,
file_name: path.to_string(),
help: None,
version,
})?;
log::info!("Fully loaded Epoch {:?}", epoch_id);
@ -421,7 +436,36 @@ impl EpochConfig {
items_to_log.push(info);
}
}
println!("{}", EpochInfo::as_table(items_to_log)?);
// TODO: Have this in a message and return a string
println!(
"{}",
"List of epoch, most recent shown first".bright_green()
);
// TODO: Make a method for this
for elt in items_to_log.iter().rev() {
let star = if elt.epoch_id == self.epoch_id {
""
} else {
" "
};
println!(
"{} {:>4} - {}{}{:10} {:50}",
star.green(),
elt.epoch_id.to_symbol().blue(),
"󰬌 ".yellow(),
(elt.events.len()
+ elt.characters.len()
+ elt.towns.len()
+ elt.calamities.len()
+ elt.blockers.len())
.to_string()
.yellow(),
elt.tags.join(","),
elt.summary
)
}
// println!("{}", EpochInfo::as_table(items_to_log)?);
Ok(())
}
}

View File

@ -19,7 +19,7 @@ use crate::{
epoch_traits::{ConfigWritable, Prettiable},
},
error::EpochError,
stats::{EntityType, Position, PositionIdentifier, TypedLink},
stats::{EntityType, Position, PositionIdentifier, Symbols, TypedLink},
};
/// The metadata file stored inside each epoch directory
@ -378,3 +378,9 @@ impl EpochInfo {
}
}
}
impl Symbols for EpochId {
fn to_symbol(&self) -> String {
format!("[󰹻 {:<2}]", self)
}
}

View File

@ -69,7 +69,7 @@ pub trait ConfigWritable: Serialize {
serde_json::to_string_pretty(self).map_err(|e| EpochError::Serde {
source: e,
file_name: action,
help: None,
version: format!("Current Version:{}", env!("EFO_SHORT_VERSION")),
})
}

View File

@ -180,15 +180,15 @@ pub enum EpochError {
/// Serialization / deserialization errors that are not caught above.
#[error("Serialization error from {file_name}")]
#[diagnostic(code(EpochError::SerdeError))]
#[diagnostic(help("You may have updated efo to an incompatible version.\n{version}"))]
Serde {
/// The source error
#[source]
source: serde_json::Error,
/// The file that was being written
file_name: String,
/// An optionnal help message
#[help]
help: Option<String>,
/// A version number vs file version number
version: String,
},
/// The epoch tree is in an incorrect state.

View File

@ -252,7 +252,6 @@ fn color_cell_categories(cell: CellStruct, value: &GenericStat) -> CellStruct {
impl OverallStats {
/// Create Stats with a given rng distribution
// TODO(6): Use an iterator over the stat enum
pub(crate) fn create_rng(
rng: &RngLevel,
mut rng_t: &mut ThreadRng,
@ -285,7 +284,8 @@ impl OverallStats {
}
/// Updates the inner meta values
fn update(&mut self) {
// TODO: Force the use of this ?
pub fn update(&mut self) {
self.demographics =
(*(self.population + self.growth_rate + self.happiness - self.crime) / 4).into();
self.economy = (*(self.food + self.industry + self.trade + self.science) / 4).into();