Refactors epoch_info
Build Failed The build failed
Gitea/epoch_forge/pipeline/head There was a failure building this commit
Details
Build Failed The build failed
Gitea/epoch_forge/pipeline/head There was a failure building this commit
Details
This commit is contained in:
parent
4b7a838eb7
commit
1edd0ea67e
|
|
@ -5,10 +5,7 @@
|
|||
#![warn(missing_docs, clippy::missing_docs_in_private_items)]
|
||||
|
||||
use crate::error::AppError;
|
||||
use lib_efo::{
|
||||
epoch_struct::{ConfigWritable, EpochConfig},
|
||||
error::EpochError,
|
||||
};
|
||||
use lib_efo::{epoch_struct::EpochConfig, epoch_traits::ConfigWritable, error::EpochError};
|
||||
|
||||
pub mod cli_epoch;
|
||||
|
||||
|
|
|
|||
|
|
@ -12,8 +12,11 @@
|
|||
#![warn(missing_docs, clippy::missing_docs_in_private_items)]
|
||||
|
||||
use clap::Args;
|
||||
use lib_efo::epoch_struct::{ConfigWritable, EpochConfig, EpochInfo};
|
||||
use lib_efo::error::EpochError;
|
||||
use lib_efo::{
|
||||
epoch_struct::{EpochConfig, EpochInfo},
|
||||
epoch_traits::ConfigWritable,
|
||||
error::EpochError,
|
||||
};
|
||||
use std::fs::read_dir;
|
||||
|
||||
use crate::error::AppError;
|
||||
|
|
|
|||
|
|
@ -20,19 +20,19 @@
|
|||
//! `HEAD` pointer.
|
||||
#![warn(missing_docs, clippy::missing_docs_in_private_items)]
|
||||
use clap::error::ErrorKind;
|
||||
use cli_table::Table;
|
||||
use derive_more::Display;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
fs::{File, create_dir_all},
|
||||
ops::{Deref, DerefMut},
|
||||
str::FromStr,
|
||||
};
|
||||
use std::{
|
||||
io::Write,
|
||||
ops::{Deref, DerefMut},
|
||||
};
|
||||
|
||||
use crate::{epoch_struct, epoch_traits::Prettiable, error::EpochError, io_err_with_help};
|
||||
use crate::error::EpochError;
|
||||
pub mod epoch_config;
|
||||
pub use epoch_config::EpochConfig;
|
||||
|
||||
pub mod epoch_info;
|
||||
pub use epoch_info::EpochInfo;
|
||||
|
||||
// TODO[5]: Try to load from a config and have it inserted as a backup
|
||||
/// The subfolder naming convention
|
||||
|
|
@ -42,83 +42,6 @@ static MAIN_NAME: &str = ".epoch";
|
|||
/// The subname of the epochinfo
|
||||
static SUB_NAME: &str = ".epochinfo";
|
||||
|
||||
pub mod epoch_config;
|
||||
pub use epoch_config::EpochConfig;
|
||||
|
||||
/// Trait representing a serialisable / writable config
|
||||
pub trait ConfigWritable: Serialize {
|
||||
/// The full path indicating where to save the config
|
||||
fn save_path(&self) -> String;
|
||||
|
||||
/// The folder where to save the file to save the config
|
||||
fn save_folder(&self) -> String;
|
||||
|
||||
/// Have the config as JSON
|
||||
fn as_json(&self, action: String) -> Result<String, EpochError> {
|
||||
serde_json::to_string_pretty(self).map_err(|e| EpochError::Serde {
|
||||
source: e,
|
||||
file_name: action,
|
||||
help: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Save the config into it's nominal path
|
||||
///
|
||||
/// This command will NOT create all subdirectories
|
||||
fn save_with_context(
|
||||
&self,
|
||||
// Very unsure about this versus a macro
|
||||
action_description: &str,
|
||||
do_not_erase: &SaveMode,
|
||||
// advice: Option<String>,
|
||||
) -> Result<(), EpochError> {
|
||||
let mut f = match *do_not_erase {
|
||||
SaveMode::Erase => File::create(self.save_path()),
|
||||
SaveMode::DoNotErase => File::create_new(self.save_path()),
|
||||
}
|
||||
.map_err(|e| EpochError::ConfigCreation(self.save_path(), e))?;
|
||||
write!(f, "{}", self.as_json(action_description.to_owned())?)
|
||||
.map_err(EpochError::ConfigWrite)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// The metadata file stored inside each epoch directory
|
||||
/// (`epoch/<epoch_id>/.epochinfo`).
|
||||
///
|
||||
/// It contains only the information that is needed for the engine to
|
||||
/// 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, Display)]
|
||||
#[display(
|
||||
"Epoch ({epoch_id:>5}) | seed ({rng_seed:<10}) | tags ({tags:<10}) | summary ({summary:<20})"
|
||||
)]
|
||||
#[derive(Table)]
|
||||
pub struct EpochInfo {
|
||||
/// The ID of this epoch – should match the directory name.
|
||||
#[table(title = "ID")]
|
||||
pub epoch_id: EpochId,
|
||||
|
||||
/// 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.
|
||||
#[table(title = "Seed")]
|
||||
pub rng_seed: u64,
|
||||
|
||||
// /// List of event IDs that were accepted for this epoch.
|
||||
// /// The engine uses this to replay the world from the
|
||||
// /// parent epoch to the current one.
|
||||
// pub selected_events: Vec<u64>,
|
||||
/// Optional tags that help identify the epoch (e.g. `"Winter‑B"`).
|
||||
#[table(title = "Tags")]
|
||||
pub tags: TagList,
|
||||
|
||||
/// Human‑readable description or summary, useful for the `log` command.
|
||||
#[table(title = "Summary")]
|
||||
pub summary: String,
|
||||
}
|
||||
|
||||
/// A lightweight wrapper around a list of tags.
|
||||
///
|
||||
/// The wrapper exists mainly to give the collection a semantic type
|
||||
|
|
@ -150,30 +73,6 @@ impl DerefMut for TagList {
|
|||
}
|
||||
}
|
||||
|
||||
impl Prettiable for EpochInfo {
|
||||
fn show_as_table(list: Vec<Self>)
|
||||
where
|
||||
Self: std::marker::Sized,
|
||||
{
|
||||
cli_table::print_stdout(list).unwrap();
|
||||
}
|
||||
|
||||
fn as_log(&self) -> String {
|
||||
format!("{}", self)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for EpochInfo {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
epoch_id: epoch_struct::EpochId::new(0),
|
||||
rng_seed: 0,
|
||||
tags: TagList::new(),
|
||||
summary: String::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Which save mode to use
|
||||
#[allow(missing_docs)]
|
||||
pub enum SaveMode {
|
||||
|
|
@ -181,23 +80,6 @@ pub enum SaveMode {
|
|||
Erase,
|
||||
}
|
||||
|
||||
impl EpochInfo {
|
||||
/// Create all subfolders as needed
|
||||
///
|
||||
/// This command can be safely used even if the folder already exists
|
||||
pub fn create_subfolders(&self) -> Result<(), EpochError> {
|
||||
io_err_with_help!(create_dir_all(self.save_folder()), "Creating subfolders")
|
||||
}
|
||||
|
||||
/// Create an epoch with only an Id, please note that this function doesn't load the epoch at all
|
||||
fn with_id(epoch_id: &EpochId) -> Self {
|
||||
Self {
|
||||
epoch_id: *epoch_id,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Thin type to handle EpochIds
|
||||
#[derive(
|
||||
Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Display,
|
||||
|
|
@ -236,16 +118,6 @@ impl std::ops::Deref for EpochId {
|
|||
}
|
||||
}
|
||||
|
||||
impl ConfigWritable for EpochInfo {
|
||||
fn save_path(&self) -> String {
|
||||
format!("{}/{}/{}", SUBFOLDER_NAMING, self.epoch_id, SUB_NAME)
|
||||
}
|
||||
|
||||
fn save_folder(&self) -> String {
|
||||
format!("{}/{}/", SUBFOLDER_NAMING, self.epoch_id)
|
||||
}
|
||||
}
|
||||
|
||||
/// A flexible identifier for *any* epoch – the world may be
|
||||
/// addressed by a numeric ID or by a friendly tag (e.g. `"winter‑b"`).
|
||||
///
|
||||
|
|
|
|||
|
|
@ -1,5 +1,16 @@
|
|||
//! Module containing all the EpochConfig functions
|
||||
//! Management of the *current‑epoch* configuration.
|
||||
//!
|
||||
//! The configuration is stored in a file named `.epoch` and contains only
|
||||
//! the lightweight information needed for the CLI to switch between epochs
|
||||
//! quickly:
|
||||
//! * the numeric ID of the current epoch,
|
||||
//! * a map of human‑friendly tags to epoch IDs,
|
||||
//! * a map of known epoch IDs to unloaded metadata (`EpochInfo`).
|
||||
//!
|
||||
//! The world data and all event logs belong to the individual epoch
|
||||
//! directories and are **not** part of this file.
|
||||
|
||||
use crate::epoch_traits::ConfigWritable;
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
fs::{read_to_string, remove_dir_all},
|
||||
|
|
@ -10,7 +21,7 @@ use serde::{Deserialize, Serialize};
|
|||
|
||||
use crate::{
|
||||
epoch_struct::{
|
||||
ConfigWritable, EpochId, EpochIdentifier, EpochInfo, MAIN_NAME, SUBFOLDER_NAMING, SaveMode,
|
||||
EpochId, EpochIdentifier, MAIN_NAME, SUBFOLDER_NAMING, SaveMode, epoch_info::EpochInfo,
|
||||
},
|
||||
epoch_traits::Prettiable,
|
||||
error::EpochError,
|
||||
|
|
@ -169,7 +180,11 @@ impl EpochConfig {
|
|||
format!("{}/", SUBFOLDER_NAMING)
|
||||
}
|
||||
|
||||
/// Tries to delete an entire epoch folder by Id
|
||||
/// Delete an entire epoch folder by its ID.
|
||||
///
|
||||
/// The function removes the directory, deletes all references to the
|
||||
/// epoch from `list_existing_epochs` and `tags`, and then writes the
|
||||
/// updated configuration to disk.
|
||||
// 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) {
|
||||
|
|
@ -189,8 +204,11 @@ impl EpochConfig {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
/// Compute the next epoch, by defering the work to the Epochinfo -> World
|
||||
/// Return the id of the next (and now present) epoch
|
||||
/// Compute the next epoch.
|
||||
///
|
||||
/// Currently this function is a placeholder that creates a new epoch
|
||||
/// with the ID immediately following the current one. The actual logic
|
||||
/// is deferred to the `EpochInfo -> World` subsystem.
|
||||
pub fn compute_next(&mut self) -> Result<EpochInfo, EpochError> {
|
||||
// unimplemented!()
|
||||
// TODO[1]: Implement this
|
||||
|
|
@ -199,7 +217,15 @@ impl EpochConfig {
|
|||
Ok(EpochInfo::with_id(&self.epoch_id.next()))
|
||||
}
|
||||
|
||||
/// Insert the given epoch and save it
|
||||
/// Insert a new epoch into the configuration and persist it.
|
||||
///
|
||||
/// The function creates the epoch’s directory, writes its metadata,
|
||||
/// updates the internal maps, and finally writes the updated
|
||||
/// configuration to disk.
|
||||
///
|
||||
/// # Returns
|
||||
/// * `Ok(())` – the epoch was added and the configuration was saved.
|
||||
/// * `Err(EpochError::EpochAlreadyExists(..))` if an epoch with the same ID already exists.
|
||||
pub fn insert_and_save(
|
||||
&mut self,
|
||||
new_epoch: EpochInfo,
|
||||
|
|
@ -222,7 +248,10 @@ impl EpochConfig {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
/// Loads into memory all elements to show them as log
|
||||
/// Load and display the metadata for a list of epoch IDs.
|
||||
///
|
||||
/// The function first ensures that each requested epoch’s metadata is
|
||||
/// loaded into memory, then prints a formatted log for each one.
|
||||
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 {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,106 @@
|
|||
//! Metadata management for individual epochs.
|
||||
//!
|
||||
//! The `EpochInfo` struct holds all information that the engine needs to
|
||||
//! reconstruct a particular epoch.
|
||||
//! It is persisted to `epoch/<epoch_id>/.epochinfo`. The file contains the epoch ID, the RNG
|
||||
//! seed that produced the world, any optional tags, and a human‑readable
|
||||
//! summary. World data itself is stored separately (e.g. in `world.json`).
|
||||
|
||||
use cli_table::Table;
|
||||
use derive_more::Display;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fs::create_dir_all;
|
||||
|
||||
use crate::{
|
||||
epoch_struct::{self, EpochId, SUB_NAME, SUBFOLDER_NAMING, TagList},
|
||||
epoch_traits::{ConfigWritable, Prettiable},
|
||||
error::EpochError,
|
||||
io_err_with_help,
|
||||
};
|
||||
|
||||
/// The metadata file stored inside each epoch directory
|
||||
/// (`epoch/<epoch_id>/.epochinfo`).
|
||||
///
|
||||
/// It contains only the information that is needed for the engine to
|
||||
/// 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, Display)]
|
||||
#[display(
|
||||
"Epoch ({epoch_id:>5}) | seed ({rng_seed:<10}) | tags ({tags:<10}) | summary ({summary:<20})"
|
||||
)]
|
||||
#[derive(Table)]
|
||||
pub struct EpochInfo {
|
||||
/// The ID of this epoch – should match the directory name.
|
||||
#[table(title = "ID")]
|
||||
pub epoch_id: EpochId,
|
||||
|
||||
/// 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.
|
||||
#[table(title = "Seed")]
|
||||
pub rng_seed: u64,
|
||||
|
||||
// /// List of event IDs that were accepted for this epoch.
|
||||
// /// The engine uses this to replay the world from the
|
||||
// /// parent epoch to the current one.
|
||||
// pub selected_events: Vec<u64>,
|
||||
/// Optional tags that help identify the epoch (e.g. `"Winter‑B"`).
|
||||
#[table(title = "Tags")]
|
||||
pub tags: TagList,
|
||||
|
||||
/// Human‑readable description or summary, useful for the `log` command.
|
||||
#[table(title = "Summary")]
|
||||
pub summary: String,
|
||||
}
|
||||
|
||||
impl Prettiable for EpochInfo {
|
||||
fn show_as_table(list: Vec<Self>)
|
||||
where
|
||||
Self: std::marker::Sized,
|
||||
{
|
||||
cli_table::print_stdout(list).unwrap();
|
||||
}
|
||||
|
||||
fn as_log(&self) -> String {
|
||||
format!("{}", self)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for EpochInfo {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
epoch_id: epoch_struct::EpochId::new(0),
|
||||
rng_seed: 0,
|
||||
tags: TagList::new(),
|
||||
summary: String::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl EpochInfo {
|
||||
/// Create all subfolders as needed
|
||||
///
|
||||
/// This command can be safely used even if the folder already exists
|
||||
pub fn create_subfolders(&self) -> Result<(), EpochError> {
|
||||
io_err_with_help!(create_dir_all(self.save_folder()), "Creating subfolders")
|
||||
}
|
||||
|
||||
/// Create an epoch with only an Id, please note that this function doesn't load the epoch at all
|
||||
pub(crate) fn with_id(epoch_id: &EpochId) -> Self {
|
||||
Self {
|
||||
epoch_id: *epoch_id,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ConfigWritable for EpochInfo {
|
||||
fn save_path(&self) -> String {
|
||||
format!("{}/{}/{}", SUBFOLDER_NAMING, self.epoch_id, SUB_NAME)
|
||||
}
|
||||
|
||||
fn save_folder(&self) -> String {
|
||||
format!("{}/{}/", SUBFOLDER_NAMING, self.epoch_id)
|
||||
}
|
||||
}
|
||||
|
|
@ -5,6 +5,11 @@
|
|||
//! common to many of the library’s element types.
|
||||
#![warn(clippy::missing_docs_in_private_items)]
|
||||
|
||||
use serde::Serialize;
|
||||
use std::{fs::File, io::Write};
|
||||
|
||||
use crate::{epoch_struct::SaveMode, error::EpochError};
|
||||
|
||||
/// Elements that can be compared with another instance to produce a diff.
|
||||
pub trait Diffable {}
|
||||
|
||||
|
|
@ -38,3 +43,41 @@ pub trait Prettiable {
|
|||
/// Convert the struct into a pretty log
|
||||
fn as_log(&self) -> String;
|
||||
}
|
||||
|
||||
/// Trait representing a serialisable / writable config
|
||||
pub trait ConfigWritable: Serialize {
|
||||
/// The full path indicating where to save the config
|
||||
fn save_path(&self) -> String;
|
||||
|
||||
/// The folder where to save the file to save the config
|
||||
fn save_folder(&self) -> String;
|
||||
|
||||
/// Have the config as JSON
|
||||
fn as_json(&self, action: String) -> Result<String, EpochError> {
|
||||
serde_json::to_string_pretty(self).map_err(|e| EpochError::Serde {
|
||||
source: e,
|
||||
file_name: action,
|
||||
help: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Save the config into it's nominal path
|
||||
///
|
||||
/// This command will NOT create all subdirectories
|
||||
fn save_with_context(
|
||||
&self,
|
||||
// Very unsure about this versus a macro
|
||||
action_description: &str,
|
||||
do_not_erase: &SaveMode,
|
||||
// advice: Option<String>,
|
||||
) -> Result<(), EpochError> {
|
||||
let mut f = match *do_not_erase {
|
||||
SaveMode::Erase => File::create(self.save_path()),
|
||||
SaveMode::DoNotErase => File::create_new(self.save_path()),
|
||||
}
|
||||
.map_err(|e| EpochError::ConfigCreation(self.save_path(), e))?;
|
||||
write!(f, "{}", self.as_json(action_description.to_owned())?)
|
||||
.map_err(EpochError::ConfigWrite)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue