Refactors EpochConfig

This commit is contained in:
Dandaedre 2025-11-29 00:50:30 +01:00
parent 48a9565893
commit 3d739e5b55
6 changed files with 385 additions and 316 deletions

79
Cargo.lock generated
View File

@ -155,12 +155,56 @@ version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a1d728cc89cf3aee9ff92b05e62b19ee65a02b5702cff7d5a377e32c6ae29d8d"
[[package]]
name = "cli-table"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "14da8d951cef7cc4f13ccc9b744d736963d57863c7e6fc33c070ea274546082c"
dependencies = [
"cli-table-derive",
"csv",
"termcolor",
"unicode-width 0.2.2",
]
[[package]]
name = "cli-table-derive"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c1b60bae2c3d45228dfb096046aa51ef6c300de70b658d7a13fcb0c4f832e"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "colorchoice"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75"
[[package]]
name = "csv"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "52cd9d68cf7efc6ddfaaee42e7288d3a99d613d4b50f76ce9827ae0c6e14f938"
dependencies = [
"csv-core",
"itoa",
"ryu",
"serde_core",
]
[[package]]
name = "csv-core"
version = "0.1.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "704a3c26996a80471189265814dbc2c257598b96b8a7feae2d31ace646bb9782"
dependencies = [
"memchr",
]
[[package]]
name = "derive_more"
version = "2.0.1"
@ -192,15 +236,6 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "fancy-table"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cca3bc2bf46d82914b5308d05b12053e79079429ae2b13267238718033ae1eb7"
dependencies = [
"smallvec",
]
[[package]]
name = "gimli"
version = "0.32.3"
@ -236,8 +271,8 @@ name = "lib_efo"
version = "0.1.0"
dependencies = [
"clap",
"cli-table",
"derive_more",
"fancy-table",
"miette",
"serde",
"serde_json",
@ -408,12 +443,6 @@ dependencies = [
"serde_core",
]
[[package]]
name = "smallvec"
version = "1.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"
[[package]]
name = "strsim"
version = "0.11.1"
@ -452,6 +481,15 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "termcolor"
version = "1.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755"
dependencies = [
"winapi-util",
]
[[package]]
name = "terminal_size"
version = "0.4.3"
@ -528,6 +566,15 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
[[package]]
name = "winapi-util"
version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "windows-link"
version = "0.2.1"

View File

@ -12,8 +12,8 @@
#![warn(missing_docs, clippy::missing_docs_in_private_items)]
use clap::Args;
use lib_efo::epoch_struct::{ConfigWritable, EpochInfo};
use lib_efo::{epoch_struct::EpochConfig, error::EpochError};
use lib_efo::epoch_struct::{ConfigWritable, EpochConfig, EpochInfo};
use lib_efo::error::EpochError;
use std::fs::read_dir;
use crate::error::AppError;

View File

@ -10,4 +10,4 @@ thiserror = {workspace = true}
clap = {workspace = true}
miette = {workspace = true}
derive_more = { version = "2.0.1", features = ["display"] }
fancy-table = "0.4.1"
cli-table = "0.5.0"

View File

@ -20,16 +20,17 @@
//! `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::io::Write;
use std::{
collections::HashMap,
fmt,
fs::{File, create_dir_all, read_to_string, remove_dir_all},
path::Path,
fs::{File, create_dir_all},
str::FromStr,
};
use std::{
io::Write,
ops::{Deref, DerefMut},
};
use crate::{epoch_struct, epoch_traits::Prettiable, error::EpochError, io_err_with_help};
@ -41,234 +42,8 @@ static MAIN_NAME: &str = ".epoch";
/// The subname of the epochinfo
static SUB_NAME: &str = ".epochinfo";
/// The file written to *.epochconfig* that tells the CLI which
/// epoch folder is the “current” one.
///
/// Only the minimal information needed for fast switches is stored:
/// * the numeric identifier of the selected epoch,
/// * a list of human‑readable tags,
/// * the absolute path to the epoch’s directory.
///
/// No world or event data lives here – it is purely a lightweight pointer.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EpochConfig {
/// The epoch ID that the binary should consider “current”.
pub epoch_id: EpochId,
/// Optional human‑friendly tags (e.g. `"winter‑B"`, `"post‑war"`).
pub tags: HashMap<String, EpochId>,
// TODO[6]: Can become important
// #[serde(skip)]
// /// Absolute path to `epoch/<epoch_id>/`.
// pub path: PathBuf,
/// A hashmap containing the name of all existing epochs, only loaded in memory if used
#[serde(skip)]
pub list_existing_epochs: HashMap<EpochId, Option<EpochInfo>>,
}
impl Default for EpochConfig {
/// Create an empty config, mainly for initialisation
fn default() -> Self {
EpochConfig {
epoch_id: EpochId::new(0),
tags: HashMap::new(),
list_existing_epochs: HashMap::new(),
}
}
}
impl EpochConfig {
/// Create a new config from an existig path
pub fn new_from_path(_path: Option<&Path>) -> Result<Self, EpochError> {
let path = Path::new(MAIN_NAME);
if path.is_file() {
// TODO[6]: write a trait for this
let config: EpochConfig = serde_json::from_str(&io_err_with_help!(
read_to_string(path),
"Reading config from path {:?}",
path
)?)
.map_err(|e| EpochError::Serde {
source: e,
file_name: path.to_string_lossy().to_string(),
help: None,
})?;
Ok(config.initialize()?)
} else {
Err(EpochError::MainFolderInvalid(
EpochConfig::default().save_folder(),
))
}
}
/// Initialize the epoch more in depth
fn initialize(mut self) -> Result<Self, EpochError> {
let path = EpochConfig::default().save_subfolder();
let path = io_err_with_help!(Path::new(&path).read_dir(), "Reading initial folder {path}")?;
// let mut valid_folders = HashMap::new();
for elt in path {
let elt = io_err_with_help!(elt, "Opening file in main config folder")?;
if io_err_with_help!(elt.file_type(), "Determining file type of {:?}", elt)?.is_dir() {
let id = elt.file_name().to_string_lossy().parse::<EpochId>();
// TODO: Logging
// println!("Initialized {:?}", id);
self.list_existing_epochs.insert(id.unwrap(), None);
}
}
Ok(self)
}
/// Loads the metadata for an epoch from disk into the in‑memory cache.
///
/// The epoch identified by `epoch_id` must exist in `list_existing_epochs`.
/// The JSON file on disk is read, deserialized into an `EpochInfo`, and
/// stored in the map. Any existing value for that epoch is overwritten.
///
/// # Returns
/// * `Ok(())` when the epoch was successfully read and cached.
/// * `Err(EpochError::EpochNotFound(..))` if the epoch is not present in the
/// internal map.
/// * `Err(EpochError::Serde { .. })` if the JSON file could not be parsed.
/// * `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 value = self
.list_existing_epochs
.get_mut(epoch_id)
.ok_or(EpochError::EpochNotFound(format!("{epoch_id}")))?;
// Create a mock epoch
let path = EpochInfo::with_id(epoch_id).save_path();
let read_to_string = io_err_with_help!(read_to_string(&path), "Reading {:?}", path);
// Try to load
let maybe_epoch: EpochInfo =
serde_json::from_str(&read_to_string?).map_err(|e| EpochError::Serde {
source: e,
file_name: path.to_string(),
help: None,
})?;
// Overwrite the value
*value = Some(maybe_epoch);
Ok(())
}
/// Retrieves the internal epoch ID for a given identifier.
///
/// The identifier can be either a *tag* string (`EpochIdentifier::Tag`) or an
/// explicit epoch ID (`EpochIdentifier::Id`).
/// * When a tag is supplied the function looks up the corresponding epoch ID in
/// the `tags` map.
/// * When an ID is supplied it verifies that an epoch with that ID exists in
/// `list_existing_epochs` and returns it.
///
/// # Returns
/// * `Ok(epoch_id)` when the identifier is successfully resolved.
/// * `Err(EpochError::AmbiguousTag(tag))` if a supplied tag does not exist.
/// * `Err(EpochError::EpochFolderMissing(id, path))` if an ID does not have an
/// associated epoch folder.
pub fn get(&self, id: &EpochIdentifier) -> Result<EpochId, EpochError> {
match id {
EpochIdentifier::Tag(s) => self
.tags
.get(s)
.copied()
.ok_or(EpochError::AmbiguousTag(s.to_string())),
EpochIdentifier::Id(epoch_id) => self
.list_existing_epochs
.contains_key(epoch_id)
.then_some(epoch_id)
.ok_or(EpochError::EpochFolderMissing(
*epoch_id,
EpochConfig::default().save_folder().into(),
))
.copied(),
}
}
/// Return the name of the subfolder used to save this structure
fn save_subfolder(&self) -> String {
format!("{}/", SUBFOLDER_NAMING)
}
/// Tries to delete an entire epoch folder by Id
// 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) {
println!(
"The given epoch {} doesn't exists and it's deletion was skipped",
id
)
}
io_err_with_help!(
remove_dir_all(EpochInfo::with_id(&id).save_folder()),
"Removing the epoch {}",
id
)?;
self.list_existing_epochs.remove(&id);
self.tags.retain(|_k, v| *v != id);
self.save_with_context("Saving after delete_id", &SaveMode::Erase)?;
Ok(())
}
/// Compute the next epoch, by defering the work to the Epochinfo -> World
/// Return the id of the next (and now present) epoch
pub fn compute_next(&mut self) -> Result<EpochInfo, EpochError> {
// unimplemented!()
// TODO[1]: Implement this
print!("DEBUG LINE: COMPUTING NEXT EPOCH");
// New fake epoch
Ok(EpochInfo::with_id(&self.epoch_id.next()))
}
/// Insert the given epoch and save it
pub fn insert_and_save(
&mut self,
new_epoch: EpochInfo,
save_mode: &SaveMode,
) -> Result<(), EpochError> {
if self.list_existing_epochs.contains_key(&new_epoch.epoch_id) {
return Err(EpochError::EpochAlreadyExists(new_epoch.epoch_id));
}
new_epoch.create_subfolders()?;
new_epoch.save_with_context("Saving new epoch", save_mode)?;
// Add the epoch to the list of epochs, not doing so will still have it added
// at the next iteration since the command always parse the files to determine it's state rater that the list
// not doing so would likely create errors if insert is used before another command
let new_id = new_epoch.epoch_id;
self.list_existing_epochs.insert(new_id, Some(new_epoch));
self.epoch_id = new_id;
self.save_with_context("Saving after insert_and_save", &SaveMode::Erase)?;
Ok(())
}
/// Loads into memory all elements to show them as log
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 {
self.try_load(id)?;
}
for id in list_ids {
if let Some(info) = self
.list_existing_epochs
.get(id)
.ok_or(EpochError::EpochNotFound(id.to_string()))?
{
items_to_log.push(info);
}
}
// items_to_log[0].as_log()
for item in items_to_log {
item.show_as_log();
}
// let table = FancyTable::create();!
Ok(())
}
}
pub mod epoch_config;
pub use epoch_config::EpochConfig;
/// Trait representing a serialisable / writable config
pub trait ConfigWritable: Serialize {
@ -316,14 +91,19 @@ pub trait ConfigWritable: Serialize {
/// 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:?} | summary {summary:?}")]
#[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.
@ -331,53 +111,52 @@ pub struct EpochInfo {
// /// parent epoch to the current one.
// pub selected_events: Vec<u64>,
/// Optional tags that help identify the epoch (e.g. `"Winter‑B"`).
pub tags: Vec<String>,
#[table(title = "Tags")]
pub tags: TagList,
/// Human‑readable description or summary, useful for the `log` command.
pub summary: Option<String>,
#[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
/// and to hide the internal representation.
#[derive(Debug, Clone, Serialize, Deserialize, Display)]
#[display("{inner:?}")]
pub struct TagList {
/// The inner vector of tags
inner: Vec<String>,
}
impl TagList {
/// Create a new empty tag list
fn new() -> Self {
Self { inner: Vec::new() }
}
}
impl Deref for TagList {
type Target = Vec<String>;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl DerefMut for TagList {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.inner
}
}
impl Prettiable for EpochInfo {
// fn show_as_table(list: &[Self])
// where
// Self: std::marker::Sized,
// {
// let table = fancy_table::FancyTable::create(fancy_table::FancyTableOpts {
// charset: fancy_table::charset::Charset::Modern,
// ..Default::default()
// })
// .add_title_with_align("log", fancy_table::TitleAlign::RightOffset(1))
// .add_column_named("ID", fancy_table::Layout::Slim)
// .add_column_named("RNG SEED", fancy_table::Layout::Fixed(16))
// .add_column_named_wrapping_with_align(
// "TAGS",
// fancy_table::Layout::Fixed(25),
// fancy_table::Align::Center,
// )
// .add_column_named_with_align(
// "SUMMARY",
// fancy_table::Layout::Expandable(150),
// fancy_table::Align::Right,
// )
// .hseparator(Some(fancy_table::Separator::Double))
// .padding(3)
// .width(102)
// .build();
// // table.render(
// let list: Vec<&[&str]> = list
// .iter()
// .map(|info| {
// [
// info.epoch_id.to_string().as_str(),
// info.rng_seed.to_string().as_str(),
// info.tags.join(",").as_str(),
// info.summary.unwrap_or("<None>".to_string()).as_str(),
// ]
// })
// .collect();
// // );
// }
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)
@ -389,8 +168,8 @@ impl Default for EpochInfo {
Self {
epoch_id: epoch_struct::EpochId::new(0),
rng_seed: 0,
tags: Vec::new(),
summary: None,
tags: TagList::new(),
summary: String::new(),
}
}
}
@ -420,10 +199,12 @@ impl EpochInfo {
}
/// Thin type to handle EpochIds
#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[derive(
Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Display,
)]
#[display("{id}")]
pub struct EpochId {
/// The underlying numeric value. A value of `0` is never used –
/// epoch IDs start at 1.
/// The underlying numeric value.
pub id: u64,
}
@ -435,12 +216,6 @@ impl FromStr for EpochId {
}
}
impl std::fmt::Display for EpochId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.id)
}
}
impl EpochId {
/// Creates a new `EpochId` from a numeric value.
pub fn new(id: u64) -> Self {
@ -461,15 +236,6 @@ impl std::ops::Deref for EpochId {
}
}
impl ConfigWritable for EpochConfig {
fn save_path(&self) -> String {
MAIN_NAME.to_string()
}
fn save_folder(&self) -> String {
".".to_string()
}
}
impl ConfigWritable for EpochInfo {
fn save_path(&self) -> String {
format!("{}/{}/{}", SUBFOLDER_NAMING, self.epoch_id, SUB_NAME)

View File

@ -0,0 +1,256 @@
//! Module containing all the EpochConfig functions
use std::{
collections::HashMap,
fs::{read_to_string, remove_dir_all},
path::Path,
};
use serde::{Deserialize, Serialize};
use crate::{
epoch_struct::{
ConfigWritable, EpochId, EpochIdentifier, EpochInfo, MAIN_NAME, SUBFOLDER_NAMING, SaveMode,
},
epoch_traits::Prettiable,
error::EpochError,
io_err_with_help,
};
/// The file written to *.epochconfig* that tells the CLI which
/// epoch folder is the “current” one.
///
/// Only the minimal information needed for fast switches is stored:
/// * the numeric identifier of the selected epoch,
/// * a list of human‑readable tags,
/// * the absolute path to the epoch’s directory.
///
/// No world or event data lives here – it is purely a lightweight pointer.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EpochConfig {
/// The epoch ID that the binary should consider “current”.
pub epoch_id: EpochId,
/// Optional human‑friendly tags (e.g. `"winter‑B"`, `"post‑war"`).
pub tags: HashMap<String, EpochId>,
// TODO[6]: Can become important
// #[serde(skip)]
// /// Absolute path to `epoch/<epoch_id>/`.
// pub path: PathBuf,
/// A hashmap containing the name of all existing epochs, only loaded in memory if used
#[serde(skip)]
pub list_existing_epochs: HashMap<EpochId, Option<EpochInfo>>,
}
impl Default for EpochConfig {
/// Create an empty config, mainly for initialisation
fn default() -> Self {
EpochConfig {
epoch_id: EpochId::new(0),
tags: HashMap::new(),
list_existing_epochs: HashMap::new(),
}
}
}
impl EpochConfig {
/// Create a new config from an existig path
pub fn new_from_path(_path: Option<&Path>) -> Result<Self, EpochError> {
let path = Path::new(MAIN_NAME);
if path.is_file() {
// TODO[6]: write a trait for this
let config: EpochConfig = serde_json::from_str(&io_err_with_help!(
read_to_string(path),
"Reading config from path {:?}",
path
)?)
.map_err(|e| EpochError::Serde {
source: e,
file_name: path.to_string_lossy().to_string(),
help: None,
})?;
Ok(config.initialize()?)
} else {
Err(EpochError::MainFolderInvalid(
EpochConfig::default().save_folder(),
))
}
}
/// Initialize the epoch more in depth
pub(crate) fn initialize(mut self) -> Result<Self, EpochError> {
let path = EpochConfig::default().save_subfolder();
let path = io_err_with_help!(Path::new(&path).read_dir(), "Reading initial folder {path}")?;
// let mut valid_folders = HashMap::new();
for elt in path {
let elt = io_err_with_help!(elt, "Opening file in main config folder")?;
if io_err_with_help!(elt.file_type(), "Determining file type of {:?}", elt)?.is_dir() {
let id = elt.file_name().to_string_lossy().parse::<EpochId>();
// TODO: Logging
// println!("Initialized {:?}", id);
self.list_existing_epochs.insert(id.unwrap(), None);
}
}
Ok(self)
}
/// Loads the metadata for an epoch from disk into the in‑memory cache.
///
/// The epoch identified by `epoch_id` must exist in `list_existing_epochs`.
/// The JSON file on disk is read, deserialized into an `EpochInfo`, and
/// stored in the map. Any existing value for that epoch is overwritten.
///
/// # Returns
/// * `Ok(())` when the epoch was successfully read and cached.
/// * `Err(EpochError::EpochNotFound(..))` if the epoch is not present in the
/// internal map.
/// * `Err(EpochError::Serde { .. })` if the JSON file could not be parsed.
/// * `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 value = self
.list_existing_epochs
.get_mut(epoch_id)
.ok_or(EpochError::EpochNotFound(format!("{epoch_id}")))?;
// Create a mock epoch
let path = EpochInfo::with_id(epoch_id).save_path();
let read_to_string = io_err_with_help!(read_to_string(&path), "Reading {:?}", path);
// Try to load
let maybe_epoch: EpochInfo =
serde_json::from_str(&read_to_string?).map_err(|e| EpochError::Serde {
source: e,
file_name: path.to_string(),
help: None,
})?;
// Overwrite the value
*value = Some(maybe_epoch);
Ok(())
}
/// Retrieves the internal epoch ID for a given identifier.
///
/// The identifier can be either a *tag* string (`EpochIdentifier::Tag`) or an
/// explicit epoch ID (`EpochIdentifier::Id`).
/// * When a tag is supplied the function looks up the corresponding epoch ID in
/// the `tags` map.
/// * When an ID is supplied it verifies that an epoch with that ID exists in
/// `list_existing_epochs` and returns it.
///
/// # Returns
/// * `Ok(epoch_id)` when the identifier is successfully resolved.
/// * `Err(EpochError::AmbiguousTag(tag))` if a supplied tag does not exist.
/// * `Err(EpochError::EpochFolderMissing(id, path))` if an ID does not have an
/// associated epoch folder.
pub fn get(&self, id: &EpochIdentifier) -> Result<EpochId, EpochError> {
match id {
EpochIdentifier::Tag(s) => self
.tags
.get(s)
.copied()
.ok_or(EpochError::AmbiguousTag(s.to_string())),
EpochIdentifier::Id(epoch_id) => self
.list_existing_epochs
.contains_key(epoch_id)
.then_some(epoch_id)
.ok_or(EpochError::EpochFolderMissing(
*epoch_id,
EpochConfig::default().save_folder().into(),
))
.copied(),
}
}
/// Return the name of the subfolder used to save this structure
pub(crate) fn save_subfolder(&self) -> String {
format!("{}/", SUBFOLDER_NAMING)
}
/// Tries to delete an entire epoch folder by Id
// 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) {
println!(
"The given epoch {} doesn't exists and it's deletion was skipped",
id
)
}
io_err_with_help!(
remove_dir_all(EpochInfo::with_id(&id).save_folder()),
"Removing the epoch {}",
id
)?;
self.list_existing_epochs.remove(&id);
self.tags.retain(|_k, v| *v != id);
self.save_with_context("Saving after delete_id", &SaveMode::Erase)?;
Ok(())
}
/// Compute the next epoch, by defering the work to the Epochinfo -> World
/// Return the id of the next (and now present) epoch
pub fn compute_next(&mut self) -> Result<EpochInfo, EpochError> {
// unimplemented!()
// TODO[1]: Implement this
print!("DEBUG LINE: COMPUTING NEXT EPOCH");
// New fake epoch
Ok(EpochInfo::with_id(&self.epoch_id.next()))
}
/// Insert the given epoch and save it
pub fn insert_and_save(
&mut self,
new_epoch: EpochInfo,
save_mode: &SaveMode,
) -> Result<(), EpochError> {
if self.list_existing_epochs.contains_key(&new_epoch.epoch_id) {
return Err(EpochError::EpochAlreadyExists(new_epoch.epoch_id));
}
new_epoch.create_subfolders()?;
new_epoch.save_with_context("Saving new epoch", save_mode)?;
// Add the epoch to the list of epochs, not doing so will still have it added
// at the next iteration since the command always parse the files to determine it's state rater that the list
// not doing so would likely create errors if insert is used before another command
let new_id = new_epoch.epoch_id;
self.list_existing_epochs.insert(new_id, Some(new_epoch));
self.epoch_id = new_id;
self.save_with_context("Saving after insert_and_save", &SaveMode::Erase)?;
Ok(())
}
/// Loads into memory all elements to show them as log
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 {
self.try_load(id)?;
}
for id in list_ids {
if let Some(info) = self
.list_existing_epochs
.get(id)
.ok_or(EpochError::EpochNotFound(id.to_string()))?
{
items_to_log.push(info);
}
}
// items_to_log[0].as_log()
for item in items_to_log {
item.show_as_log();
}
Ok(())
}
}
impl ConfigWritable for EpochConfig {
fn save_path(&self) -> String {
MAIN_NAME.to_string()
}
fn save_folder(&self) -> String {
".".to_string()
}
}

View File

@ -21,7 +21,7 @@ pub trait Nextable {}
pub trait Prettiable {
// TODO: Doc
/// Show many as a table
fn show_as_table(list: &[Self])
fn show_as_table(list: Vec<Self>)
where
Self: std::marker::Sized,
{