Partial commit implementing some epoch mechanics

This commit is contained in:
Dandaedre 2025-11-27 16:46:40 +01:00
parent 80026b502b
commit fcd55b6e34
6 changed files with 151 additions and 106 deletions

View File

@ -50,7 +50,7 @@ fn handle_switch(args: cli_epoch::Switch, main_epoch: &mut EpochConfig) -> Resul
// .unwrap();
main_epoch
.try_load(&target)
.map_err(|_e| EpochError::EpochFolderMissing(target, ".".into()))?;
.map_err(|_e| EpochError::EpochFolderMissing(target, main_epoch.save_folder().into()))?;
main_epoch.epoch_id = target;
println!("Switched to epoch {:?}", target);
@ -63,11 +63,11 @@ fn handle_switch(args: cli_epoch::Switch, main_epoch: &mut EpochConfig) -> Resul
fn handle_next() -> Result<(), AppError> {
println!("⚡ Next",);
Ok(())
unimplemented!("Missing logic to process a next event");
}
/// Reset all future events by deleting them
fn handle_reset() -> Result<(), AppError> {
// After a `switch`, erase all future events
println!("✅ All future events deleted – back to epoch",);
Ok(())
unimplemented!("Blocked by non parsing of folders");
}

View File

@ -1,9 +1,7 @@
use std::fs::{create_dir, read_dir};
use std::path::Path;
use clap::Args;
use lib_efo::epoch_struct::{ConfigWritable, EpochId, EpochInfo};
use lib_efo::epoch_struct::{ConfigWritable, EpochInfo};
use lib_efo::{epoch_struct::EpochConfig, error::EpochError};
use std::fs::read_dir;
use crate::error::AppError;
@ -16,7 +14,9 @@ pub struct InitCmd {
/// Init an empty repository
pub fn init(args: &InitCmd) -> Result<(), AppError> {
let root = Path::new(".");
let epoch_config = EpochConfig::default();
let root = epoch_config.save_folder();
//TODO: This can be really deceiving when only .epoch is present
if read_dir(root)?.count() != 0 {
Err(EpochError::FolderNotEmpty {
@ -25,7 +25,7 @@ pub fn init(args: &InitCmd) -> Result<(), AppError> {
})?;
}
init_epoch(args)?;
EpochConfig::empty()
epoch_config
.save(
"Creatig initial config".into(),
lib_efo::epoch_struct::SaveMode::DoNotErase,
@ -41,23 +41,11 @@ pub fn init(args: &InitCmd) -> Result<(), AppError> {
/// Tries to init the epoch 0
fn init_epoch(_args: &InitCmd) -> Result<(), AppError> {
let path = Path::new(".").join("0");
create_dir(&path).map_err(|_| EpochError::FolderNotEmpty {
name: Some(path.to_string_lossy().to_string()),
show_label: Some((0, 0)),
})?;
// let json = EpochInfo::empty().as_json("Creating empty epoch file".into())?;
EpochInfo::empty().save(
"Creating empty epoch file".into(),
let empty = EpochInfo::default();
_ = empty.create_subfolders();
empty.save(
"Creating empty epoch file 0".into(),
lib_efo::epoch_struct::SaveMode::DoNotErase,
).map_err(|_| EpochError::EpochInfoWrite {
id: EpochId::new(0),
path,
help: Some(
"The .epochinfo was already present in the folder this is likely an error and shouldn't have happen".to_owned(),
),
src: None,
})?;
)?;
Ok(())
}

View File

@ -58,7 +58,7 @@ fn main() -> miette::Result<()> {
// AppError::Storage(storage_error) => todo!(),
// AppError::Other(_) => todo!(),
// }
// println!("The program didn't exit properly and returned the following error:");
println!("The program didn't exit properly and returned the following error:");
// println!("{}", e);
Err(e)?;
}

View File

@ -21,18 +21,22 @@
use clap::error::ErrorKind;
use serde::{Deserialize, Serialize};
use std::io::Write;
use std::str::FromStr;
use std::{
collections::HashMap,
fmt,
fs::{File, read_to_string},
fs::{File, create_dir_all, read_to_string},
io::Write,
path::Path,
str::FromStr,
};
use crate::{epoch_struct, error::EpochError};
use crate::{epoch_struct, error::EpochError, io_err_with_help};
/// The file written to *~/.epochconfig* that tells the CLI which
static SUBFOLDER_NAMING: &str = "epoch";
static MAIN_NAME: &str = ".epoch";
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:
@ -48,75 +52,100 @@ pub struct EpochConfig {
/// Optional human‑friendly tags (e.g. `"winter‑B"`, `"post‑war"`).
pub tags: HashMap<String, EpochId>,
// TODO: 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
// TODO: Only serialize epoch valid folders and map EpochId instead of Strings ?
#[serde(skip)]
pub list_existing_epochs: HashMap<String, Option<EpochInfo>>,
pub list_existing_epochs: HashMap<EpochId, Option<EpochInfo>>,
}
impl EpochConfig {
impl Default for EpochConfig {
/// Create an empty config, mainly for initialisation
pub fn empty() -> Self {
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(".").join(".epoch");
let path = Path::new(MAIN_NAME);
if path.is_file() {
// TODO: write a trait for this
let config: EpochConfig =
serde_json::from_str(&read_to_string(&path)?).map_err(|e| EpochError::Serde {
source: e,
file_name: path.to_string_lossy().to_string(),
help: None,
})?;
let config: EpochConfig = serde_json::from_str(&io_err_with_help!(
read_to_string(path),
format!("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(".".into()))
Err(EpochError::MainFolderInvalid(
EpochConfig::default().save_folder(),
))
}
}
/// Initialize the epoch more in depth
fn initialize(mut self) -> Result<Self, EpochError> {
let path = Path::new(".").read_dir()?;
let path = EpochConfig::default().save_subfolder();
let path = io_err_with_help!(
Path::new(&path).read_dir(),
format!("Reading initial folder {path}")
)?;
// let mut valid_folders = HashMap::new();
for elt in path {
let elt = elt?;
if elt.file_type()?.is_dir() {
self.list_existing_epochs
.insert(elt.file_name().to_string_lossy().into_owned(), None);
let elt = io_err_with_help!(elt, "Opening file in main config folder")?;
if io_err_with_help!(
elt.file_type(),
format!("Determining file type of {:?}", elt)
)?
.is_dir()
{
let id = elt.file_name().to_string_lossy().parse::<EpochId>();
println!("{:?}", id);
self.list_existing_epochs.insert(id.unwrap(), None);
}
}
Ok(self)
}
/// Try to load into memory the given epoch id
// TODO: CLEANSE THIS
// TODO: CLEANSE THIS
// TODO: CLEANSE THIS
pub fn try_load(&mut self, epoch_id: &EpochId) -> Result<(), EpochError> {
// TODO: Cleanse this abomination
let _ep = self
.list_existing_epochs
.contains_key(&epoch_id.to_string())
.contains_key(epoch_id)
.then_some(epoch_id)
.ok_or(EpochError::EpochFolderMissing(*epoch_id, ".".into()))
.ok_or(EpochError::EpochFolderMissing(
*epoch_id,
EpochConfig::default().save_path().into(),
))
.copied()?;
let path = Path::new(&epoch_id.to_string()).join(".epochinfo");
let read_to_string =
io_err_with_help!(read_to_string(&path), format!("Reading {:?}", path));
let maybe_epoch: EpochInfo =
serde_json::from_str(&read_to_string(&path)?).map_err(|e| EpochError::Serde {
serde_json::from_str(&read_to_string?).map_err(|e| EpochError::Serde {
source: e,
file_name: path.to_string_lossy().to_string(),
help: None,
})?;
let value = self
.list_existing_epochs
.get_mut(&epoch_id.to_string())
.unwrap();
let value = self.list_existing_epochs.get_mut(epoch_id).unwrap();
*value = Some(maybe_epoch);
Ok(())
}
@ -131,19 +160,29 @@ impl EpochConfig {
.ok_or(EpochError::AmbiguousTag(s.to_string())),
EpochIdentifier::Id(epoch_id) => self
.list_existing_epochs
.contains_key(&epoch_id.to_string())
.contains_key(epoch_id)
.then_some(epoch_id)
.ok_or(EpochError::EpochFolderMissing(*epoch_id, ".".into()))
.ok_or(EpochError::EpochFolderMissing(
*epoch_id,
EpochConfig::default().save_folder().into(),
))
.copied(),
}
}
fn save_subfolder(&self) -> String {
format!("{}/", SUBFOLDER_NAMING)
}
}
/// Trait representing a serialisable / writable config
pub trait ConfigWritable: Serialize {
/// Where to save the config
/// 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 {
@ -201,13 +240,8 @@ pub struct EpochInfo {
pub summary: Option<String>,
}
pub enum SaveMode {
DoNotErase,
Erase,
}
impl EpochInfo {
pub fn empty() -> Self {
impl Default for EpochInfo {
fn default() -> Self {
Self {
epoch_id: epoch_struct::EpochId::new(0),
parent_id: None,
@ -218,6 +252,18 @@ impl EpochInfo {
}
}
pub enum SaveMode {
DoNotErase,
Erase,
}
impl EpochInfo {
/// Create all subfolders as needed
pub fn create_subfolders(&self) -> Result<(), EpochError> {
io_err_with_help!(create_dir_all(self.save_folder()), "Creating subfolders")
}
}
/// Thin type to handle EpochIds
#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct EpochId {
@ -226,6 +272,14 @@ pub struct EpochId {
pub id: u64,
}
impl FromStr for EpochId {
type Err = EpochError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(EpochId { id: s.parse()? })
}
}
impl std::fmt::Display for EpochId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.id)
@ -249,12 +303,20 @@ impl std::ops::Deref for EpochId {
impl ConfigWritable for EpochConfig {
fn save_path(&self) -> String {
".epoch".to_string()
MAIN_NAME.to_string()
}
fn save_folder(&self) -> String {
".".to_string()
}
}
impl ConfigWritable for EpochInfo {
fn save_path(&self) -> String {
format!("{}/.epochinfo", self.epoch_id)
format!("{}/{}/{}", SUBFOLDER_NAMING, self.epoch_id, SUB_NAME)
}
fn save_folder(&self) -> String {
format!("{}/{}/", SUBFOLDER_NAMING, self.epoch_id)
}
}

View File

@ -4,7 +4,7 @@
//! They are lightweight, strongly‑typed and can be converted to the
//! top‑level `AppError` via `thiserror`.
use std::path::PathBuf;
use std::{num::ParseIntError, path::PathBuf};
use thiserror::Error;
@ -125,7 +125,14 @@ pub enum EpochError {
/// Generic I/O errors that bubble up from other sub‑tasks
#[error("I/O error")]
Io(#[source] std::io::Error),
#[diagnostic(code(EpochError::GenericIO))]
Io {
#[source]
source: std::io::Error,
#[help]
help: Option<String>,
},
/// Serialization / deserialization errors that are not caught above
#[error("Serialization error from {file_name}")]
@ -136,7 +143,7 @@ pub enum EpochError {
file_name: String,
#[diagnostic(help)]
#[help]
help: Option<String>,
},
@ -148,43 +155,30 @@ pub enum EpochError {
#[error("The given directory ({0:?}) is not an epoch folder")]
MainFolderInvalid(String),
/// Couldn't parse an EpochId
#[error("The id ({0}) couldn't be converted to a valid EpochId")]
#[diagnostic(code(EpochError::ConversionIdImpossible))]
ParsingEpochId(#[from] ParseIntError),
/// Any other error that didn't fit into the above categories
#[error("An unknown error occurred: {0}")]
Unknown(String),
}
impl From<std::io::Error> for EpochError {
fn from(e: std::io::Error) -> Self {
EpochError::Io(e)
}
// macro_rules! err_with {
// ($expr:expr, $err_ty:ty {$($field:ident : $value:expr),* $(,)?}) => {{
// $expr.map_err(|e| { $err_ty { $($field: $value),* } })
// }};
// }
#[macro_export]
macro_rules! io_err_with_help {
// $expr: the expression that produces the Result
// $help: string literal with the help message
($expr:expr, $help:expr) => {{
$expr.map_err(|e| EpochError::Io {
source: e,
help: Some($help.to_owned()),
})
}};
}
// impl From<serde_json::Error> for EpochError {
// fn from(e: serde_json::Error) -> Self {
// EpochError::Serde(e)
// }
// }
// /// Errors that can be produced by the epoch system.
// #[derive(Debug, Error)]
// #[allow(dead_code)]
// pub enum EpochError {
// /// The requested epoch ID does not exist in the schedule.
// #[error("Epoch #{id} does not exist")]
// NotFound { id: u64 },
// /// The provided tag or name could not be resolved to an epoch.
// #[error("No such tag or name: {name}")]
// UnknownNameOrTag { name: String },
// /// A `next` operation was attempted while future events were still pending.
// #[error("Cannot advance: future events still pending")]
// FutureEventsPresent,
// /// `reset` was called without a prior `switch`.
// #[error("Cannot reset: no switch performed yet")]
// NoSwitchPerformed,
// /// The transition requested by the user was not allowed.
// #[error("Invalid epoch transition: {msg}")]
// InvalidTransition { msg: String },
// }

View File

@ -18,6 +18,7 @@
//! `World::load()` / `World::save()` API that uses the default JSON file
pub mod epoch_struct;
#[macro_use]
pub mod error;
pub mod utils;