diff --git a/bin_efo/src/commands/epoch.rs b/bin_efo/src/commands/epoch.rs index 79787fb..5a7b1bf 100644 --- a/bin_efo/src/commands/epoch.rs +++ b/bin_efo/src/commands/epoch.rs @@ -3,7 +3,10 @@ //! Handles all epoch‑related logic – logging, switching, computing the //! next epoch, and resetting future events. -use lib_efo::epoch_struct::EpochConfig; +use lib_efo::{ + epoch_struct::{ConfigWritable, EpochConfig}, + error::EpochError, +}; use crate::error::AppError; @@ -11,15 +14,22 @@ pub mod cli_epoch; /// **Public entry point used by `efo::main`** – dispatches to the real /// handler that lives in `crate::world::EpochManager`. pub fn handle_cmd(cmd: cli_epoch::EpochCmd) -> Result<(), AppError> { - let _main_epoch = EpochConfig::new_from_path(None)?; + let mut main_epoch = EpochConfig::new_from_path(None)?; + // TODO: Remove this debug + println!("The main epoch is {:#?}", main_epoch); match cmd { cli_epoch::EpochCmd::Log(args) => handle_log(args), - cli_epoch::EpochCmd::Switch(args) => handle_switch(args), + cli_epoch::EpochCmd::Switch(args) => handle_switch(args, &mut main_epoch), cli_epoch::EpochCmd::Next(_) => handle_next(), cli_epoch::EpochCmd::Reset(_) => handle_reset(), + cli_epoch::EpochCmd::Diff(_) => handle_diff(), } } +fn handle_diff() -> Result<(), AppError> { + todo!() +} + fn handle_log(_args: cli_epoch::Log) -> Result<(), AppError> { // NOTE: `world.epoch_manager` already owns the schedule. println!("Epoch log (most recent first):"); @@ -30,10 +40,22 @@ fn handle_log(_args: cli_epoch::Log) -> Result<(), AppError> { Ok(()) } -fn handle_switch(args: cli_epoch::Switch) -> Result<(), AppError> { - // Resolve the target – we allow ID, name, or tag - - println!("Switched to epoch {:?}", args.target); +fn handle_switch(args: cli_epoch::Switch, main_epoch: &mut EpochConfig) -> Result<(), AppError> { + let target = match args.target { + cli_epoch::EpochIdentifier::Tag(ref s) => main_epoch + .tags + .get(s) + .copied() + .ok_or(EpochError::AmbiguousTag(s.to_string())), + cli_epoch::EpochIdentifier::Id(epoch_id) => main_epoch + .list_existing_epochs + .contains_key(&epoch_id.to_string()) + .then_some(epoch_id) + .ok_or(EpochError::EpochFolderMissing(epoch_id, ".".into())), + }?; + main_epoch.epoch_id = target; + println!("Switched to epoch {:?}", target); + main_epoch.save("Saving modified config".into())?; Ok(()) } diff --git a/bin_efo/src/commands/epoch/cli_epoch.rs b/bin_efo/src/commands/epoch/cli_epoch.rs index 3916c83..b90176b 100644 --- a/bin_efo/src/commands/epoch/cli_epoch.rs +++ b/bin_efo/src/commands/epoch/cli_epoch.rs @@ -9,17 +9,22 @@ use lib_efo::epoch_struct::EpochId; /// The outer clap entry that the binary will dispatch to #[derive(Subcommand, Debug)] pub enum EpochCmd { - /// List all epochs – a git‑log style view. + /// List all epochs – a git‑log style view Log(Log), - /// Switch to an epoch (by numeric ID, name, or tag). + /// Switch to an epoch (by numeric ID, name, or tag) Switch(Switch), - /// Compute the next epoch from the current one. + /// Compute the next epoch from the current one Next(Next), - /// Delete *all* future events after a `switch`. + /// Delete *all* future events after the current epoch Reset(Reset), + + /// Show the differences between two epochs + Diff(Diff), + // Tag and next could be implemented as subcommands of epoch + // even if they barely belong here } /// `efo epoch log` @@ -50,6 +55,17 @@ pub struct Next; #[derive(Args, Debug)] pub struct Reset; +/// `efo epoch diff ` +#[derive(Args, Debug)] +pub struct Diff { + #[arg(required = true)] + /// The starting point to compute the differences + pub start: EpochIdentifier, + + /// The end point to compute the differences, the current epoch by default + pub end: Option, +} + /// A flexible identifier for *any* epoch – the world may be /// addressed by a numeric ID or by a friendly tag (e.g. `"winter‑b"`). /// diff --git a/bin_efo/src/commands/init.rs b/bin_efo/src/commands/init.rs index 6a2f73d..c0693e3 100644 --- a/bin_efo/src/commands/init.rs +++ b/bin_efo/src/commands/init.rs @@ -3,7 +3,7 @@ use std::io::Write; use std::{fs::File, path::Path}; use clap::Args; -use lib_efo::epoch_struct::{EpochId, EpochInfo}; +use lib_efo::epoch_struct::{ConfigWritable, EpochId, EpochInfo}; use lib_efo::{epoch_struct::EpochConfig, error::EpochError}; use crate::error::AppError; @@ -25,12 +25,9 @@ pub fn init(args: &InitCmd) -> Result<(), AppError> { })?; } init_epoch(args)?; - let s = serde_json::to_string_pretty(&EpochConfig::empty()).map_err(|e| EpochError::Serde { - source: e, - file_name: "Creating config".to_owned(), - help: None, - })?; + let s = EpochConfig::empty().as_json("Creating config".into())?; let path = root.join(".epoch"); + // TODO: Just have a flag in save instad of this if let Ok(mut f) = File::create_new(path) { write!(f, "{}", s)?; Ok(()) @@ -48,16 +45,12 @@ pub fn init(args: &InitCmd) -> Result<(), AppError> { fn init_epoch(_args: &InitCmd) -> Result<(), AppError> { let path = Path::new(".").join("0"); create_dir(&path).map_err(|_| EpochError::FolderNotEmpty { - name: Some(path.to_str().unwrap_or_default().to_owned()), + name: Some(path.to_string_lossy().to_string()), show_label: Some((0, 0)), })?; - let json = - serde_json::to_string_pretty(&EpochInfo::empty()).map_err(|e| EpochError::Serde { - source: e, - file_name: "Creating epoch file".to_owned(), - help: None, - })?; + let json = EpochInfo::empty().as_json("Creating empty epoch file".into())?; + // TODO: Add a flag for creation only instead if let Ok(mut f) = File::create_new("0/.epochfile") { write!(f, "{}", json)?; Ok(()) diff --git a/lib_efo/src/epoch_struct.rs b/lib_efo/src/epoch_struct.rs index f28784b..92f5c82 100644 --- a/lib_efo/src/epoch_struct.rs +++ b/lib_efo/src/epoch_struct.rs @@ -20,7 +20,13 @@ //! `HEAD` pointer. use serde::{Deserialize, Serialize}; -use std::{collections::HashMap, fmt, fs::read_to_string, path::Path}; +use std::io::Write; +use std::{ + collections::HashMap, + fmt, + fs::{File, read_to_string}, + path::Path, +}; use crate::{epoch_struct, error::EpochError}; @@ -39,7 +45,7 @@ pub struct EpochConfig { pub epoch_id: EpochId, /// Optional human‑friendly tags (e.g. `"winter‑B"`, `"post‑war"`). - pub tags: HashMap, + pub tags: HashMap, // /// Absolute path to `epoch//`. // pub path: PathBuf, /// A hashmap containing the name of all existing epochs, only loaded in memory if used @@ -48,6 +54,7 @@ pub struct EpochConfig { } impl EpochConfig { + /// Create an empty config, mainly for initialisation pub fn empty() -> Self { EpochConfig { epoch_id: EpochId::new(0), @@ -55,20 +62,59 @@ impl EpochConfig { list_existing_epochs: HashMap::new(), } } + + /// Create a new config from an existig path pub fn new_from_path(_path: Option<&Path>) -> Result { - let join = Path::new(".").join(".epoch"); - if join.is_file() { + let path = Path::new(".").join(".epoch"); + if path.is_file() { let config: EpochConfig = - serde_json::from_str(&read_to_string(&join)?).map_err(|e| EpochError::Serde { + serde_json::from_str(&read_to_string(&path)?).map_err(|e| EpochError::Serde { source: e, - file_name: join.to_str().unwrap_or_default().to_owned(), + file_name: path.to_string_lossy().to_string(), help: None, })?; - Ok(config) + Ok(config.initialize()?) } else { Err(EpochError::MainFolderInvalid(".".into())) } } + + /// Initialize the epoch more in depth + fn initialize(mut self) -> Result { + let path = Path::new(".").read_dir()?; + // 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); + } + } + Ok(self) + } +} + +/// Trait representing a serialisable / writable config +pub trait ConfigWritable: Serialize { + /// Where to save the config + fn save_path(&self) -> String; + + /// Have the config as JSON + fn as_json(&self, action: String) -> Result { + 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 + fn save(&self, action: String) -> Result<(), EpochError> { + let mut f = File::create(self.save_path()) + .map_err(|e| EpochError::ConfigCreation(self.save_path(), e))?; + write!(f, "{}", self.as_json(action)?).map_err(EpochError::ConfigWrite)?; + Ok(()) + } } /// The metadata file stored inside each epoch directory @@ -142,3 +188,14 @@ impl std::ops::Deref for EpochId { &self.id } } + +impl ConfigWritable for EpochConfig { + fn save_path(&self) -> String { + ".epoch".to_string() + } +} +impl ConfigWritable for EpochInfo { + fn save_path(&self) -> String { + format!("{}/.epochinfo", self.epoch_id) + } +} diff --git a/lib_efo/src/error.rs b/lib_efo/src/error.rs index 14cf21b..533f9db 100644 --- a/lib_efo/src/error.rs +++ b/lib_efo/src/error.rs @@ -44,6 +44,10 @@ pub enum EpochError { #[error("Failed to write epoch configuration")] ConfigWrite(#[source] std::io::Error), + #[error("Failed to create the epoch configuration")] + #[help("Make sure the path is writable")] + ConfigCreation(String, #[source] std::io::Error), + #[error("This directory is already an epoch folder and thus cannot be initialized")] #[diagnostic(code(EpochError::AlreadyInitialized))] AlreadyInitialized {