From 466ad9f98c65e087c34c6ff2c740fd00130cf54b Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sat, 15 Nov 2025 22:24:39 +0100 Subject: [PATCH 01/10] Structs for handling epoch --- bin_efo/src/commands/epoch.rs | 51 +++++++++++++++++++++++++++++++---- lib_efo/src/epoch_struct.rs | 5 +++- lib_efo/src/lib.rs | 4 +-- 3 files changed, 52 insertions(+), 8 deletions(-) diff --git a/bin_efo/src/commands/epoch.rs b/bin_efo/src/commands/epoch.rs index a88d511..b3aa6da 100644 --- a/bin_efo/src/commands/epoch.rs +++ b/bin_efo/src/commands/epoch.rs @@ -4,7 +4,11 @@ //! Handles all epoch‑related logic – logging, switching, computing the //! next epoch, and resetting future events. -use clap::{Args, Subcommand}; +use std::str::FromStr; + +use clap::{Args, Subcommand, error::ErrorKind}; +use lib_efo::epoch_struct::EpochId; +use serde::{Deserialize, Serialize}; // use crate::storage::JsonStore; // use crate::storage::StoreTrait; // abstraction for persistence @@ -39,10 +43,10 @@ pub struct Log { pub struct Switch { /// The epoch to switch to – can be an integer, a name, or a tag. #[arg(required = true)] - pub target: String, + pub target: EpochIdentifier, /// Optional confirmation flag (if you ever want to force‑switch) - #[arg(long, short, help = "Force‑switch even if the epoch has no tag")] + #[arg(long, short, help = "Force‑switch dropping all the pending work")] pub force: bool, } @@ -54,6 +58,45 @@ pub struct Next; #[derive(Args, Debug)] pub struct Reset; +/// A flexible identifier for *any* epoch – the world may be +/// addressed by a numeric ID or by a friendly tag (e.g. `"winter‑b"`). +/// +/// The enum is `untagged` so that serialising/deserialising does +/// **not** add a wrapper field, e.g. `{"Tag":"foo"}`. +/// Instead the JSON representation is exactly the inner value: +/// * `"42"` → `EpochIdentifier::Id(EpochId::new(42))` +/// * `"foo"` → `EpochIdentifier::Tag("foo".into())` +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Hash)] +#[serde(untagged)] // <‑‑ no “type” wrapper is written to JSON +pub enum EpochIdentifier { + /// A textual tag that maps to a numeric epoch ID in `EpochConfig::tags`. + Tag(String), + + /// The raw numeric identifier of the epoch. + Id(EpochId), +} + +impl FromStr for EpochIdentifier { + type Err = clap::Error; // any `std::error::Error` works + + /// Try to parse either a decimal number (-> `Id`) or any non‑empty + /// string (-> `Tag`). + /// + /// Errors are converted to a Clap error so that the CLI shows a + /// nice message. + fn from_str(s: &str) -> Result { + if let Ok(num) = s.parse::() { + Ok(EpochIdentifier::Id(EpochId::new(num))) + } else if !s.is_empty() { + Ok(EpochIdentifier::Tag(s.to_owned())) + } else { + Err(clap::Error::raw( + ErrorKind::InvalidValue, + format!("{} is not a valid epoch id or tag", s), + )) + } + } +} // /// **Public entry point used by `efo::main`** – dispatches to the real // /// handler that lives in `crate::world::EpochManager`. // pub fn handle_cmd(cmd: EpochCmd, world: &mut World) -> anyhow::Result<()> { @@ -126,8 +169,6 @@ pub struct Reset; // } // // -// use anyhow::Result; -// use crate::world::World; // pub fn handle_cmd(cmd: EpochCmd, world: &mut World) -> Result<()> { // match cmd { diff --git a/lib_efo/src/epoch_struct.rs b/lib_efo/src/epoch_struct.rs index fa12405..0f99137 100644 --- a/lib_efo/src/epoch_struct.rs +++ b/lib_efo/src/epoch_struct.rs @@ -74,8 +74,10 @@ pub struct EpochInfo { } /// Thin type to handle EpochIds -#[derive(Serialize, Deserialize, Clone, Copy, Debug)] +#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct EpochId { + /// The underlying numeric value. A value of `0` is never used – + /// epoch IDs start at 1. pub id: u64, } @@ -86,6 +88,7 @@ impl std::fmt::Display for EpochId { } impl EpochId { + /// Creates a new `EpochId` from a numeric value. pub fn new(id: u64) -> Self { Self { id } } diff --git a/lib_efo/src/lib.rs b/lib_efo/src/lib.rs index 802ce5f..e689d5a 100644 --- a/lib_efo/src/lib.rs +++ b/lib_efo/src/lib.rs @@ -19,7 +19,9 @@ //! `World::load()` / `World::save()` API that uses the default JSON file //! (`world.json` in the current directory). +pub mod epoch_struct; pub mod error; + // use async_trait::async_trait; use std::io::Result as IoResult; @@ -69,5 +71,3 @@ where // } // // - -mod epoch_struct; From ee53efd69559a1de05283cdb58106115b36f0c8b Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sat, 15 Nov 2025 23:04:33 +0100 Subject: [PATCH 02/10] Added base harness --- bin_efo/src/commands/epoch.rs | 134 +++++++++------------------------- bin_efo/src/error.rs | 4 +- bin_efo/src/main.rs | 64 ++++------------ 3 files changed, 48 insertions(+), 154 deletions(-) diff --git a/bin_efo/src/commands/epoch.rs b/bin_efo/src/commands/epoch.rs index b3aa6da..c0cd423 100644 --- a/bin_efo/src/commands/epoch.rs +++ b/bin_efo/src/commands/epoch.rs @@ -1,4 +1,3 @@ -// efo/src/commands/epoch.rs //! # `epoch` sub‑command //! //! Handles all epoch‑related logic – logging, switching, computing the @@ -7,13 +6,9 @@ use std::str::FromStr; use clap::{Args, Subcommand, error::ErrorKind}; -use lib_efo::epoch_struct::EpochId; +use lib_efo::{epoch_struct::EpochId, error::EpochError}; use serde::{Deserialize, Serialize}; -// use crate::storage::JsonStore; -// use crate::storage::StoreTrait; // abstraction for persistence -// use crate::world::World; // the domain model // concrete store (used only for the stub) - /// The outer clap entry that the binary will dispatch to #[derive(Subcommand, Debug)] pub enum EpochCmd { @@ -97,102 +92,41 @@ impl FromStr for EpochIdentifier { } } } -// /// **Public entry point used by `efo::main`** – dispatches to the real -// /// handler that lives in `crate::world::EpochManager`. -// pub fn handle_cmd(cmd: EpochCmd, world: &mut World) -> anyhow::Result<()> { -// match cmd { -// EpochCmd::Log(args) => handle_log(args, world), -// EpochCmd::Switch(args) => handle_switch(args, world), -// EpochCmd::Next(_) => handle_next(world), -// EpochCmd::Reset(_) => handle_reset(world), -// } -// } +/// **Public entry point used by `efo::main`** – dispatches to the real +/// handler that lives in `crate::world::EpochManager`. +pub fn handle_cmd(cmd: EpochCmd) -> Result<(), EpochError> { + match cmd { + EpochCmd::Log(args) => handle_log(args), + EpochCmd::Switch(args) => handle_switch(args), + EpochCmd::Next(_) => handle_next(), + EpochCmd::Reset(_) => handle_reset(), + } +} -// /// ---------- helpers ---------- +fn handle_log(_args: Log) -> Result<(), EpochError> { + // NOTE: `world.epoch_manager` already owns the schedule. + println!("Epoch log (most recent first):"); + // println!( + // "#{} {} [{}] {}", + // epoch.id, epoch.date, tags, epoch.summary + // ); + Ok(()) +} -// fn handle_log(_args: Log, world: &World) -> anyhow::Result<()> { -// // NOTE: `world.epoch_manager` already owns the schedule. -// println!("Epoch log (most recent first):"); -// for epoch in world.epoch_manager.schedule.iter().rev() { -// // a tiny human‑friendly representation -// let tags = epoch.tags.join(", "); -// println!( -// "#{} {} [{}] {}", -// epoch.id, epoch.date, tags, epoch.summary -// ); -// } -// Ok(()) -// } +fn handle_switch(args: Switch) -> Result<(), EpochError> { + // Resolve the target – we allow ID, name, or tag -// fn handle_switch(args: Switch, world: &mut World) -> anyhow::Result<()> { -// // Resolve the target – we allow ID, name, or tag -// let target_id = world.epoch_manager.resolve(&args.target, args.force)?; + println!("Switched to epoch {:?}", args.target); + Ok(()) +} -// world.set_epoch(target_id); -// println!( -// "Switched to epoch #{} – {}", -// target_id, -// world.current_context().date -// ); -// Ok(()) -// } +fn handle_next() -> Result<(), EpochError> { + println!("⚡ Next",); + Ok(()) +} -// fn handle_next(world: &mut World) -> anyhow::Result<()> { -// // 1️⃣ No future events? → OK -// // 2️⃣ Future events → error (branching TBD) -// if world -// .epoch_manager -// .schedule -// .iter() -// .any(|e| e.id > world.epoch_manager.current.id) -// { -// anyhow::bail!("❌ Cannot compute `next` – future events still pending"); -// } - -// world.epoch_manager.advance_to_next()?; -// println!( -// "⚡ Advanced to epoch #{} – {}", -// world.epoch_manager.current.id, -// world.current_context().date -// ); -// Ok(()) -// } - -// fn handle_reset(world: &mut World) -> anyhow::Result<()> { -// // After a `switch`, erase all future events -// world.clear_future_events()?; -// println!( -// "✅ All future events deleted – back to epoch #{}", -// world.epoch_manager.current.id -// ); -// Ok(()) -// } -// -// - -// pub fn handle_cmd(cmd: EpochCmd, world: &mut World) -> Result<()> { -// match cmd { -// EpochCmd::Log(_) => { -// for e in world.epoch_manager.schedule.iter().rev() { -// println!("#{} {} [{}] {}", e.id, e.date, e.tags.join(","), e.summary); -// } -// } -// EpochCmd::Switch(SwitchArgs { target, force }) => { -// let id = world.epoch_manager.resolve(&target, force)?; -// world.set_epoch(id); -// println!("🔀 Switched to epoch #{}", id); -// } -// EpochCmd::Next(_) => { -// if world.epoch_manager.has_future_events() { -// anyhow::bail!("Cannot run `next`: future events still pending"); -// } -// world.compute_next_epoch()?; -// println!("⚡ Advanced to epoch #{}", world.epoch_manager.current.id); -// } -// EpochCmd::Reset(_) => { -// world.clear_future_events()?; -// println!("🗑 All future events deleted – back at epoch #{}", world.epoch_manager.current.id); -// } -// } -// Ok(()) -// } +fn handle_reset() -> Result<(), EpochError> { + // After a `switch`, erase all future events + println!("✅ All future events deleted – back to epoch",); + Ok(()) +} diff --git a/bin_efo/src/error.rs b/bin_efo/src/error.rs index 6974f51..8379b04 100644 --- a/bin_efo/src/error.rs +++ b/bin_efo/src/error.rs @@ -3,11 +3,9 @@ //! `AppError` aggregates all error kinds that may surface during a command //! execution: parsing, I/O, epoch logic, storage, and a catch‑all. -use lib_efo::error::StorageError; +use lib_efo::error::{EpochError, StorageError}; use thiserror::Error; -use crate::commands::error::EpochError; - /// All errors that can bubble up to the CLI. #[derive(Debug, Error)] #[allow(dead_code)] diff --git a/bin_efo/src/main.rs b/bin_efo/src/main.rs index 7caac44..03ec881 100644 --- a/bin_efo/src/main.rs +++ b/bin_efo/src/main.rs @@ -17,56 +17,19 @@ //! //! ## Usage //! ```sh -//! efo org add --name "The Iron Horde" --leader "Gorun" -//! efo epoch --advance 5 -//! efo link add --type alliance --org "Iron Horde" --town "Durn" +//! efo epoch switch 5 //! ``` -// use clap::{Parser, Subcommand}; - -// mod cli; use clap::{Parser, Subcommand}; use crate::{commands::epoch::EpochCmd, error::AppError}; mod commands; mod error; -// use commands::EpochCmd; - -// use commands::*; - -// #[derive(Parser)] -// #[command(name = "efo")] -// #[command(about = "Epoch Forge – manage organisations over time")] -// struct Opts { -// #[command(subcommand)] -// cmd: Subcommands, -// } - -// #[derive(Subcommand)] -// enum Subcommands { -// Epoch(commands::epoch::EpochCmd), -// Event(commands::event::EventCmd), -// Org(commands::org::OrgCmd), -// Chr(commands::chr::ChrCmd), -// Town(commands::town::TownCmd), -// Link(commands::link::LinkCmd), -// } - -// fn main() { -// let opts = Opts::parse(); -// match opts.cmd { -// Subcommands::Epoch(c) => c.handle(), -// Subcommands::Event(c) => c.handle(), -// Subcommands::Org(c) => c.handle(), -// Subcommands::Chr(c) => c.handle(), -// Subcommands::Town(c) => c.handle(), -// Subcommands::Link(c) => c.handle(), -// } -// } /// Root parser – the “efo” program #[derive(Parser, Debug)] #[command(name = "efo")] +#[command(about = "Epoch Forge – manage organisations over time")] struct Cli { #[command(subcommand)] command: TopLevelCmd, @@ -78,22 +41,21 @@ enum TopLevelCmd { #[command(subcommand)] Epoch(EpochCmd), - // … other sub‑commands (org, event, etc.) + // Event(commands::event::EventCmd), + // Org(commands::org::OrgCmd), + // Chr(commands::chr::ChrCmd), + // Town(commands::town::TownCmd), + // Link(commands::link::LinkCmd), } fn main() -> Result<(), AppError> { - // let cli = Cli::parse(); + let cli = Cli::parse(); - // // Load the world (you’ll probably want a proper store here) - // let store = crate::storage::JsonStore::new(PathBuf::from("./data")); - // let mut world = store.load_world(); // async‑aware - - // match cli.command { - // TopLevelCmd::Epoch(cmd) => { - // commands::epoch::handle_cmd(cmd, &mut world)?; - // store.persist_world(&world).await?; // write back if anything changed - // } // … other top‑level cases … - // } + match cli.command { + TopLevelCmd::Epoch(cmd) => { + commands::epoch::handle_cmd(cmd)?; + } + } Ok(()) } From 0bec514226e42b5a7aad7b536f6e60152c586b91 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sun, 16 Nov 2025 02:28:23 +0100 Subject: [PATCH 03/10] Some refactoring --- bin_efo/src/{commands/mod.rs => commands.rs} | 0 bin_efo/src/commands/epoch.rs | 104 ++----------------- bin_efo/src/commands/epoch/cli_epoch.rs | 91 ++++++++++++++++ bin_efo/src/commands/error.rs | 27 +---- bin_efo/src/main.rs | 2 +- lib_efo/src/error.rs | 24 +++++ 6 files changed, 126 insertions(+), 122 deletions(-) rename bin_efo/src/{commands/mod.rs => commands.rs} (100%) create mode 100644 bin_efo/src/commands/epoch/cli_epoch.rs diff --git a/bin_efo/src/commands/mod.rs b/bin_efo/src/commands.rs similarity index 100% rename from bin_efo/src/commands/mod.rs rename to bin_efo/src/commands.rs diff --git a/bin_efo/src/commands/epoch.rs b/bin_efo/src/commands/epoch.rs index c0cd423..3572e56 100644 --- a/bin_efo/src/commands/epoch.rs +++ b/bin_efo/src/commands/epoch.rs @@ -3,107 +3,21 @@ //! Handles all epoch‑related logic – logging, switching, computing the //! next epoch, and resetting future events. -use std::str::FromStr; +use lib_efo::error::EpochError; -use clap::{Args, Subcommand, error::ErrorKind}; -use lib_efo::{epoch_struct::EpochId, error::EpochError}; -use serde::{Deserialize, Serialize}; - -/// The outer clap entry that the binary will dispatch to -#[derive(Subcommand, Debug)] -pub enum EpochCmd { - /// List all epochs – a git‑log style view. - Log(Log), - - /// Switch to an epoch (by numeric ID, name, or tag). - Switch(Switch), - - /// Compute the next epoch from the current one. - Next(Next), - - /// Delete *all* future events after a `switch`. - Reset(Reset), -} - -/// `efo epoch log` -#[derive(Args, Debug)] -pub struct Log { - /// (Optional) Limit the number of entries shown. - #[arg(short, long, default_value = "50")] - pub limit: usize, -} - -/// `efo epoch switch ` -#[derive(Args, Debug)] -pub struct Switch { - /// The epoch to switch to – can be an integer, a name, or a tag. - #[arg(required = true)] - pub target: EpochIdentifier, - - /// Optional confirmation flag (if you ever want to force‑switch) - #[arg(long, short, help = "Force‑switch dropping all the pending work")] - pub force: bool, -} - -/// `efo epoch next` -#[derive(Args, Debug)] -pub struct Next; - -/// `efo epoch reset` -#[derive(Args, Debug)] -pub struct Reset; - -/// A flexible identifier for *any* epoch – the world may be -/// addressed by a numeric ID or by a friendly tag (e.g. `"winter‑b"`). -/// -/// The enum is `untagged` so that serialising/deserialising does -/// **not** add a wrapper field, e.g. `{"Tag":"foo"}`. -/// Instead the JSON representation is exactly the inner value: -/// * `"42"` → `EpochIdentifier::Id(EpochId::new(42))` -/// * `"foo"` → `EpochIdentifier::Tag("foo".into())` -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Hash)] -#[serde(untagged)] // <‑‑ no “type” wrapper is written to JSON -pub enum EpochIdentifier { - /// A textual tag that maps to a numeric epoch ID in `EpochConfig::tags`. - Tag(String), - - /// The raw numeric identifier of the epoch. - Id(EpochId), -} - -impl FromStr for EpochIdentifier { - type Err = clap::Error; // any `std::error::Error` works - - /// Try to parse either a decimal number (-> `Id`) or any non‑empty - /// string (-> `Tag`). - /// - /// Errors are converted to a Clap error so that the CLI shows a - /// nice message. - fn from_str(s: &str) -> Result { - if let Ok(num) = s.parse::() { - Ok(EpochIdentifier::Id(EpochId::new(num))) - } else if !s.is_empty() { - Ok(EpochIdentifier::Tag(s.to_owned())) - } else { - Err(clap::Error::raw( - ErrorKind::InvalidValue, - format!("{} is not a valid epoch id or tag", s), - )) - } - } -} +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: EpochCmd) -> Result<(), EpochError> { +pub fn handle_cmd(cmd: cli_epoch::EpochCmd) -> Result<(), EpochError> { match cmd { - EpochCmd::Log(args) => handle_log(args), - EpochCmd::Switch(args) => handle_switch(args), - EpochCmd::Next(_) => handle_next(), - EpochCmd::Reset(_) => handle_reset(), + cli_epoch::EpochCmd::Log(args) => handle_log(args), + cli_epoch::EpochCmd::Switch(args) => handle_switch(args), + cli_epoch::EpochCmd::Next(_) => handle_next(), + cli_epoch::EpochCmd::Reset(_) => handle_reset(), } } -fn handle_log(_args: Log) -> Result<(), EpochError> { +fn handle_log(_args: cli_epoch::Log) -> Result<(), EpochError> { // NOTE: `world.epoch_manager` already owns the schedule. println!("Epoch log (most recent first):"); // println!( @@ -113,7 +27,7 @@ fn handle_log(_args: Log) -> Result<(), EpochError> { Ok(()) } -fn handle_switch(args: Switch) -> Result<(), EpochError> { +fn handle_switch(args: cli_epoch::Switch) -> Result<(), EpochError> { // Resolve the target – we allow ID, name, or tag println!("Switched to epoch {:?}", args.target); diff --git a/bin_efo/src/commands/epoch/cli_epoch.rs b/bin_efo/src/commands/epoch/cli_epoch.rs new file mode 100644 index 0000000..3916c83 --- /dev/null +++ b/bin_efo/src/commands/epoch/cli_epoch.rs @@ -0,0 +1,91 @@ +use clap::{Args, Subcommand, error::ErrorKind}; +use serde::Deserialize; +use serde::Serialize; + +use std::str::FromStr; + +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. + Log(Log), + + /// Switch to an epoch (by numeric ID, name, or tag). + Switch(Switch), + + /// Compute the next epoch from the current one. + Next(Next), + + /// Delete *all* future events after a `switch`. + Reset(Reset), +} + +/// `efo epoch log` +#[derive(Args, Debug)] +pub struct Log { + /// (Optional) Limit the number of entries shown. + #[arg(short, long, default_value = "50")] + pub limit: usize, +} + +/// `efo epoch switch ` +#[derive(Args, Debug)] +pub struct Switch { + /// The epoch to switch to – can be an integer, a name, or a tag. + #[arg(required = true)] + pub target: EpochIdentifier, + + /// Optional confirmation flag (if you ever want to force‑switch) + #[arg(long, short, help = "Force‑switch dropping all the pending work")] + pub force: bool, +} + +/// `efo epoch next` +#[derive(Args, Debug)] +pub struct Next; + +/// `efo epoch reset` +#[derive(Args, Debug)] +pub struct Reset; + +/// A flexible identifier for *any* epoch – the world may be +/// addressed by a numeric ID or by a friendly tag (e.g. `"winter‑b"`). +/// +/// The enum is `untagged` so that serialising/deserialising does +/// **not** add a wrapper field, e.g. `{"Tag":"foo"}`. +/// Instead the JSON representation is exactly the inner value: +/// * `"42"` → `EpochIdentifier::Id(EpochId::new(42))` +/// * `"foo"` → `EpochIdentifier::Tag("foo".into())` +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Hash)] +#[serde(untagged)] // <‑‑ no “type” wrapper is written to JSON +pub enum EpochIdentifier { + /// A textual tag that maps to a numeric epoch ID in `EpochConfig::tags`. + Tag(String), + + /// The raw numeric identifier of the epoch. + Id(EpochId), +} + +impl FromStr for EpochIdentifier { + type Err = clap::Error; // any `std::error::Error` works + + /// Try to parse either a decimal number (-> `Id`) or any non‑empty + /// string (-> `Tag`). + /// + /// Errors are converted to a Clap error so that the CLI shows a + /// nice message. + fn from_str(s: &str) -> Result { + if let Ok(num) = s.parse::() { + Ok(EpochIdentifier::Id(EpochId::new(num))) + } else if !s.is_empty() { + Ok(EpochIdentifier::Tag(s.to_owned())) + } else { + Err(clap::Error::raw( + ErrorKind::InvalidValue, + format!("{} is not a valid epoch id or tag", s), + )) + } + } +} diff --git a/bin_efo/src/commands/error.rs b/bin_efo/src/commands/error.rs index 9ae09c2..d4ba9bd 100644 --- a/bin_efo/src/commands/error.rs +++ b/bin_efo/src/commands/error.rs @@ -4,29 +4,4 @@ //! the underlying `EpochManager`. They are lightweight, strongly‑typed //! and can be converted into a top‑level error with `thiserror`. -use thiserror::Error; - -/// 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 }, -} +// use thiserror::Error; diff --git a/bin_efo/src/main.rs b/bin_efo/src/main.rs index 03ec881..8790bc3 100644 --- a/bin_efo/src/main.rs +++ b/bin_efo/src/main.rs @@ -21,7 +21,7 @@ //! ``` use clap::{Parser, Subcommand}; -use crate::{commands::epoch::EpochCmd, error::AppError}; +use crate::{commands::epoch::cli_epoch::EpochCmd, error::AppError}; mod commands; mod error; diff --git a/lib_efo/src/error.rs b/lib_efo/src/error.rs index 7f34942..86fe905 100644 --- a/lib_efo/src/error.rs +++ b/lib_efo/src/error.rs @@ -117,3 +117,27 @@ impl From for EpochError { 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 }, +// } From f75f430c14cd9fb1698e60504b3e9cf000bbe333 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 26 Nov 2025 16:18:13 +0100 Subject: [PATCH 04/10] Heavy draft of the epoch/init --- bin_efo/Cargo.toml | 1 + bin_efo/src/commands.rs | 1 + bin_efo/src/commands/epoch.rs | 15 +++++++----- bin_efo/src/commands/init.rs | 41 +++++++++++++++++++++++++++++++ bin_efo/src/main.rs | 33 +++++++++++++++++++------ lib_efo/src/epoch_struct.rs | 33 ++++++++++++++++++++++++- lib_efo/src/error.rs | 21 ++++++++++------ lib_efo/src/lib.rs | 45 +++++++++-------------------------- lib_efo/src/utils.rs | 35 +++++++++++++++++++++++++++ testepo/.gitignore | 1 + 10 files changed, 171 insertions(+), 55 deletions(-) create mode 100644 bin_efo/src/commands/init.rs create mode 100644 lib_efo/src/utils.rs create mode 100644 testepo/.gitignore diff --git a/bin_efo/Cargo.toml b/bin_efo/Cargo.toml index e0a76ba..0f2170d 100644 --- a/bin_efo/Cargo.toml +++ b/bin_efo/Cargo.toml @@ -8,3 +8,4 @@ lib_efo = { path = "../lib_efo" } serde = {workspace = true} clap = {workspace = true} thiserror = {workspace = true} +serde_json = "1.0.145" diff --git a/bin_efo/src/commands.rs b/bin_efo/src/commands.rs index 07c3b87..507983a 100644 --- a/bin_efo/src/commands.rs +++ b/bin_efo/src/commands.rs @@ -8,3 +8,4 @@ pub mod epoch; pub mod error; +pub mod init; diff --git a/bin_efo/src/commands/epoch.rs b/bin_efo/src/commands/epoch.rs index 3572e56..0b37a45 100644 --- a/bin_efo/src/commands/epoch.rs +++ b/bin_efo/src/commands/epoch.rs @@ -3,12 +3,15 @@ //! Handles all epoch‑related logic – logging, switching, computing the //! next epoch, and resetting future events. -use lib_efo::error::EpochError; +use lib_efo::epoch_struct::EpochConfig; + +use crate::error::AppError; 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<(), EpochError> { +pub fn handle_cmd(cmd: cli_epoch::EpochCmd) -> Result<(), AppError> { + let main_epoch = EpochConfig::new_from_path(None)?; match cmd { cli_epoch::EpochCmd::Log(args) => handle_log(args), cli_epoch::EpochCmd::Switch(args) => handle_switch(args), @@ -17,7 +20,7 @@ pub fn handle_cmd(cmd: cli_epoch::EpochCmd) -> Result<(), EpochError> { } } -fn handle_log(_args: cli_epoch::Log) -> Result<(), EpochError> { +fn handle_log(_args: cli_epoch::Log) -> Result<(), AppError> { // NOTE: `world.epoch_manager` already owns the schedule. println!("Epoch log (most recent first):"); // println!( @@ -27,19 +30,19 @@ fn handle_log(_args: cli_epoch::Log) -> Result<(), EpochError> { Ok(()) } -fn handle_switch(args: cli_epoch::Switch) -> Result<(), EpochError> { +fn handle_switch(args: cli_epoch::Switch) -> Result<(), AppError> { // Resolve the target – we allow ID, name, or tag println!("Switched to epoch {:?}", args.target); Ok(()) } -fn handle_next() -> Result<(), EpochError> { +fn handle_next() -> Result<(), AppError> { println!("⚡ Next",); Ok(()) } -fn handle_reset() -> Result<(), EpochError> { +fn handle_reset() -> Result<(), AppError> { // After a `switch`, erase all future events println!("✅ All future events deleted – back to epoch",); Ok(()) diff --git a/bin_efo/src/commands/init.rs b/bin_efo/src/commands/init.rs new file mode 100644 index 0000000..a712e50 --- /dev/null +++ b/bin_efo/src/commands/init.rs @@ -0,0 +1,41 @@ +use std::fs::{create_dir, read_dir}; +use std::io::Write; +use std::{fs::File, path::Path}; + +use clap::Args; +use lib_efo::{epoch_struct::EpochConfig, error::EpochError}; + +use crate::error::AppError; + +#[derive(Args, Debug)] +pub struct InitCmd { + /// Force initialisation even if the directory isn't empty + #[arg(long)] + force: bool, +} + +/// Init an empty repository +pub fn init(args: InitCmd) -> Result<(), AppError> { + let root = Path::new("."); + if !(read_dir(root)?.count() == 0 || args.force) { + Err(EpochError::AlreadyInitialized)? + } + let s = serde_json::to_string_pretty(&EpochConfig::empty()) + .map_err(|e| EpochError::Serde(e, "Creating config".to_owned(), ".".to_owned()))?; + let path = root.join(".epoch"); + if let Ok(mut f) = File::create_new(path) { + write!(f, "{}", s)?; + println!("{:?}", args); + Ok(()) + } else { + Err(EpochError::AlreadyInitialized)? + } +} + +/// Tries to init the epoch 0 +fn init_epoch(args: InitCmd) -> Result<(), AppError> { + let path = Path::new(".").join("0"); + create_dir(path)?; + + Ok(()) +} diff --git a/bin_efo/src/main.rs b/bin_efo/src/main.rs index 8790bc3..3ff5605 100644 --- a/bin_efo/src/main.rs +++ b/bin_efo/src/main.rs @@ -21,8 +21,8 @@ //! ``` use clap::{Parser, Subcommand}; +use crate::commands::init::InitCmd; use crate::{commands::epoch::cli_epoch::EpochCmd, error::AppError}; - mod commands; mod error; @@ -37,8 +37,7 @@ struct Cli { #[derive(Subcommand, Debug)] enum TopLevelCmd { - /// Epoch‑related actions - + Init(InitCmd), #[command(subcommand)] Epoch(EpochCmd), // Event(commands::event::EventCmd), @@ -51,11 +50,31 @@ enum TopLevelCmd { fn main() -> Result<(), AppError> { let cli = Cli::parse(); - match cli.command { - TopLevelCmd::Epoch(cmd) => { - commands::epoch::handle_cmd(cmd)?; - } + if let Err(e) = exec_dispatch(cli) { + // match e{ + // AppError::Clap(error) => todo!(), + // AppError::Io(error) => todo!(), + // AppError::Epoch(epoch_error) => todo!(), + // AppError::Storage(storage_error) => todo!(), + // AppError::Other(_) => todo!(), + // } + println!("The program didn't exit properly and returned the following error:"); + println!("{}", e); } Ok(()) } + +fn exec_dispatch(cli: Cli) -> Result<(), AppError> { + match cli.command { + TopLevelCmd::Init(cmd) => { + commands::init::init(cmd)?; + println!("The folder was initialized as an epoch folder") + } + TopLevelCmd::Epoch(cmd) => { + commands::epoch::handle_cmd(cmd)?; + println!("Epoch nicely executed") + } + } + Ok(()) +} diff --git a/lib_efo/src/epoch_struct.rs b/lib_efo/src/epoch_struct.rs index 0f99137..5d48145 100644 --- a/lib_efo/src/epoch_struct.rs +++ b/lib_efo/src/epoch_struct.rs @@ -20,7 +20,9 @@ //! `HEAD` pointer. use serde::{Deserialize, Serialize}; -use std::{collections::HashMap, fmt}; +use std::{collections::HashMap, fmt, fs::read_to_string, path::Path}; + +use crate::error::EpochError; /// The file written to *~/.epochconfig* that tells the CLI which /// epoch folder is the “current” one. @@ -40,6 +42,35 @@ pub struct EpochConfig { 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 + #[serde(skip)] + pub list_existing_epochs: HashMap>, +} + +impl EpochConfig { + pub fn empty() -> Self { + EpochConfig { + epoch_id: EpochId::new(0), + tags: HashMap::new(), + list_existing_epochs: HashMap::new(), + } + } + pub fn new_from_path(_path: Option<&Path>) -> Result { + let join = Path::new(".").join(".epoch"); + if join.is_file() { + let config: EpochConfig = + serde_json::from_str(&read_to_string(&join)?).map_err(|e| { + EpochError::Serde( + e, + "Config".into(), + join.to_str().unwrap_or_default().to_owned(), + ) + })?; + Ok(config) + } else { + Err(EpochError::MainFolderInvalid(".".into())) + } + } } /// The metadata file stored inside each epoch directory diff --git a/lib_efo/src/error.rs b/lib_efo/src/error.rs index 86fe905..e3ea976 100644 --- a/lib_efo/src/error.rs +++ b/lib_efo/src/error.rs @@ -43,6 +43,9 @@ pub enum EpochError { #[error("Failed to write epoch configuration")] ConfigWrite(#[source] std::io::Error), + #[error("This directory is already an epoch folder and thus cannot be initialized")] + AlreadyInitialized, + /// Problems while serialising / deserialising an `EpochInfo` #[error("Failed to parse `.epochinfo` in epoch {0} ({1}): {2}")] EpochInfoParse(EpochId, PathBuf, #[source] serde_json::Error), @@ -94,13 +97,17 @@ pub enum EpochError { Io(#[source] std::io::Error), /// Serialization / deserialization errors that are not caught above - #[error("Serialization error: {0}")] - Serde(#[source] serde_json::Error), + #[error("Serialization error: {1}:{2} {0}")] + Serde(serde_json::Error, String, String), /// The epoch tree is in an incorrect state #[error("Invalid epoch tree at {0}")] TreeInvalid(EpochId, String), + /// The main folder is not an epoch folder + #[error("The given directory ({0:?}) is not an epoch folder")] + MainFolderInvalid(String), + /// Any other error that didn't fit into the above categories #[error("An unknown error occurred: {0}")] Unknown(String), @@ -112,11 +119,11 @@ impl From for EpochError { } } -impl From for EpochError { - fn from(e: serde_json::Error) -> Self { - EpochError::Serde(e) - } -} +// impl From 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)] diff --git a/lib_efo/src/lib.rs b/lib_efo/src/lib.rs index e689d5a..6a12f41 100644 --- a/lib_efo/src/lib.rs +++ b/lib_efo/src/lib.rs @@ -1,28 +1,26 @@ //! # `lib_efo` //! -//! The **engine** that drives *Epoch Forge*. It contains a pure, dependency‑free -//! representation of a fantasy world and all the logic needed to manipulate it. +//! The **engine** that drives *Epoch Forge*. It contains a pure, representation of a fantasy world and all the logic needed to manipulate it. //! //! The crate is split into the following domains, each exposed as a public module: -//! - `world` – holds the global state (`World`) and a lightweight snapshot (`Context`). -//! - `epoch` – manages the passage of time and epoch switching. -//! - `event` – CRUD and evaluation of events that affect the world. -//! - `org` – organisations, guilds, factions and their history. -//! - `character` – individual characters, traits and lineage. -//! - `town` – towns, cities, trade hubs and their populations. -//! - `link` – relations such as wars, alliances, roads, commerce. -//! - `storage` – generic persistence layer (`Store`) with JSON/YAML back‑ends. -//! - `util` – small helpers, ID generation, error types, etc. +//! - TODO: `world` – holds the global state (`World`) and a lightweight snapshot (`Context`). +//! - TODO: `epoch` – manages the passage of time and epoch switching. +//! - TODO: `event` – CRUD and evaluation of events that affect the world. +//! - TODO: `org` – organisations, guilds, factions and their history. +//! - TODO: `character` – individual characters, traits and lineage. +//! - TODO: `town` – towns, cities, trade hubs and their populations. +//! - TODO: `link` – relations such as wars, alliances, roads, commerce. +//! - TODO: `storage` – generic persistence layer (`Store`) with JSON/YAML back‑ends. +//! - TODO: `util` – small helpers, ID generation, error types, etc. //! //! All public types implement `serde::Serialize / Deserialize` so that they can //! be persisted easily. The `World` struct also offers a convenient //! `World::load()` / `World::save()` API that uses the default JSON file -//! (`world.json` in the current directory). pub mod epoch_struct; pub mod error; +pub mod utils; -// use async_trait::async_trait; use std::io::Result as IoResult; /// Marker trait for anything that can be persisted via the `Store` abstraction. @@ -50,24 +48,3 @@ where /// List all ids known to this store. fn list_ids(&self) -> IoResult>; } - -// /// A convenience wrapper that stores the *entire* `World` -// /// as a single JSON document. It also exposes a `ContextStore` -// /// if you want to keep a snapshot of a specific epoch -// /// for quick read‑only queries. -// pub trait WorldStore: Store { -// /// Persist the current world state. -// fn persist_world(&self, world: &crate::World) -> IoResult<()> { -// self.write("world", world).await -// } - -// /// Load the world, or create a new one if nothing exists. -// fn load_world(&self) -> IoResult { -// match self.read("world").await? { -// Some(w) => Ok(w), -// None => Ok(crate::World::new()), -// } -// } -// } -// -// diff --git a/lib_efo/src/utils.rs b/lib_efo/src/utils.rs new file mode 100644 index 0000000..c7963dd --- /dev/null +++ b/lib_efo/src/utils.rs @@ -0,0 +1,35 @@ +//! Utilities asserting that the data being worked on is sound and well formatted. +//! +//! This module provides simple helpers that validate file system paths. +//! +//! + +use std::path::Path; + +use crate::error::EpochError; + +/// Check whether `path` points to a valid Epoch directory. +/// +/// A *valid* directory is one that satisfies the expectations of the `epoch` format. +#[deprecated] +pub fn is_a_epoch_directory(path: &Path) -> Result<(), EpochError> { + let dir = path.read_dir().map_err(|_e| { + EpochError::MainFolderInvalid(path.to_str().unwrap_or_default().to_owned()) + })?; + for e in dir.flatten() { + println!("{:?}", e.file_name()); + } + Ok(()) +} + +/// Validate that the configuration file at `path` is well‑formed. +pub fn is_config_well_formated(_path: &Path) -> Result<(), EpochError> { + Ok(()) +} + +#[cfg(test)] +mod test { + #![allow(dead_code)] + fn test_directory() {} + fn test_config() {} +} diff --git a/testepo/.gitignore b/testepo/.gitignore new file mode 100644 index 0000000..e3eeed8 --- /dev/null +++ b/testepo/.gitignore @@ -0,0 +1 @@ +testepo* From d1e9435ea6cae3cd8765ff8acb601e10ca5253ea Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 26 Nov 2025 18:40:38 +0100 Subject: [PATCH 05/10] some bad git hgappened --- .gitignore | 1 + Cargo.lock | 574 ++++++++++++++++++++++++++++++++++ Cargo.toml | 2 + bin_efo/Cargo.toml | 3 +- bin_efo/src/commands/epoch.rs | 2 +- bin_efo/src/commands/init.rs | 53 +++- bin_efo/src/error.rs | 9 +- bin_efo/src/main.rs | 9 +- lib_efo/Cargo.toml | 3 +- lib_efo/src/epoch_struct.rs | 24 +- lib_efo/src/error.rs | 50 ++- testepo/.gitignore | 1 - 12 files changed, 697 insertions(+), 34 deletions(-) create mode 100644 Cargo.lock delete mode 100644 testepo/.gitignore diff --git a/.gitignore b/.gitignore index e7180de..fe7b57a 100644 --- a/.gitignore +++ b/.gitignore @@ -26,3 +26,4 @@ Cargo.lock # already existing elements were commented out #/target +testepo diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..56e1f13 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,574 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "addr2line" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b5d307320b3181d6d7954e663bd7c774a838b8220fe0593c86d9fb09f498b4b" +dependencies = [ + "gimli", +] + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "anstream" +version = "0.6.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43d5b281e737544384e969a5ccad3f1cdd24b48086a0fc1b2a5262a26b8f4f4a" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5192cca8006f1fd4f7237516f40fa183bb07f8fbdfedaa0036de5ea9b0b45e78" + +[[package]] +name = "anstyle-parse" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7644824f0aa2c7b9384579234ef10eb7efb6a0deb83f9630a49594dd9c15c2" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "backtrace" +version = "0.3.76" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb531853791a215d7c62a30daf0dde835f381ab5de4589cfe7c649d2cbe92bd6" +dependencies = [ + "addr2line", + "cfg-if", + "libc", + "miniz_oxide", + "object", + "rustc-demangle", + "windows-link", +] + +[[package]] +name = "backtrace-ext" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "537beee3be4a18fb023b570f80e3ae28003db9167a751266b259926e25539d50" +dependencies = [ + "backtrace", +] + +[[package]] +name = "bin_efo" +version = "0.1.0" +dependencies = [ + "clap", + "lib_efo", + "miette", + "serde", + "serde_json", + "thiserror", +] + +[[package]] +name = "bitflags" +version = "2.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812e12b5285cc515a9c72a5c1d3b6d46a19dac5acfef5265968c166106e31dd3" + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "clap" +version = "4.5.51" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c26d721170e0295f191a69bd9a1f93efcdb0aff38684b61ab5750468972e5f5" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.5.51" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75835f0c7bf681bfd05abe44e965760fea999a5286c6eb2d59883634fd02011a" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.5.49" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a0b5487afeab2deb2ff4e03a807ad1a03ac532ff5a2cee5d86884440c7f7671" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "clap_lex" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1d728cc89cf3aee9ff92b05e62b19ee65a02b5702cff7d5a377e32c6ae29d8d" + +[[package]] +name = "colorchoice" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "gimli" +version = "0.32.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e629b9b98ef3dd8afe6ca2bd0f89306cec16d43d907889945bc5d6687f2f13c7" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "is_ci" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7655c9839580ee829dfacba1d1278c2b7883e50a277ff7541299489d6bdfdc45" + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itoa" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" + +[[package]] +name = "lib_efo" +version = "0.1.0" +dependencies = [ + "clap", + "miette", + "serde", + "serde_json", + "thiserror", +] + +[[package]] +name = "libc" +version = "0.2.177" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2874a2af47a2325c2001a6e6fad9b16a53b802102b528163885171cf92b15976" + +[[package]] +name = "linux-raw-sys" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039" + +[[package]] +name = "memchr" +version = "2.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273" + +[[package]] +name = "miette" +version = "7.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f98efec8807c63c752b5bd61f862c165c115b0a35685bdcfd9238c7aeb592b7" +dependencies = [ + "backtrace", + "backtrace-ext", + "cfg-if", + "miette-derive", + "owo-colors", + "supports-color", + "supports-hyperlinks", + "supports-unicode", + "terminal_size", + "textwrap", + "unicode-width 0.1.14", +] + +[[package]] +name = "miette-derive" +version = "7.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db5b29714e950dbb20d5e6f74f9dcec4edbcc1067bb7f8ed198c097b8c1a818b" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", +] + +[[package]] +name = "object" +version = "0.37.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff76201f031d8863c38aa7f905eca4f53abbfa15f609db4277d44cd8938f33fe" +dependencies = [ + "memchr", +] + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "owo-colors" +version = "4.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c6901729fa79e91a0913333229e9ca5dc725089d1c363b2f4b4760709dc4a52" + +[[package]] +name = "proc-macro2" +version = "1.0.103" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ee95bc4ef87b8d5ba32e8b7714ccc834865276eab0aed5c9958d00ec45f49e8" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.42" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a338cc41d27e6cc6dce6cefc13a0729dfbb81c262b1f519331575dd80ef3067f" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "rustc-demangle" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56f7d92ca342cea22a06f2121d944b4fd82af56988c270852495420f961d4ace" + +[[package]] +name = "rustix" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd15f8a2c5551a84d56efdc1cd049089e409ac19a3072d5037a17fd70719ff3e" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "ryu" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f" + +[[package]] +name = "serde" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.145" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "402a6f66d8c709116cf22f558eab210f5a50187f702eb4d7e5ef38d9a7f1c79c" +dependencies = [ + "itoa", + "memchr", + "ryu", + "serde", + "serde_core", +] + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "supports-color" +version = "3.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c64fc7232dd8d2e4ac5ce4ef302b1d81e0b80d055b9d77c7c4f51f6aa4c867d6" +dependencies = [ + "is_ci", +] + +[[package]] +name = "supports-hyperlinks" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "804f44ed3c63152de6a9f90acbea1a110441de43006ea51bcce8f436196a288b" + +[[package]] +name = "supports-unicode" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7401a30af6cb5818bb64852270bb722533397edcfc7344954a38f420819ece2" + +[[package]] +name = "syn" +version = "2.0.110" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a99801b5bd34ede4cf3fc688c5919368fea4e4814a4664359503e6015b280aea" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "terminal_size" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60b8cb979cb11c32ce1603f8137b22262a9d131aaa5c37b5678025f22b8becd0" +dependencies = [ + "rustix", + "windows-sys 0.60.2", +] + +[[package]] +name = "textwrap" +version = "0.16.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c13547615a44dc9c452a8a534638acdf07120d4b6847c8178705da06306a3057" +dependencies = [ + "unicode-linebreak", + "unicode-width 0.2.2", +] + +[[package]] +name = "thiserror" +version = "2.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f63587ca0f12b72a0600bcba1d40081f830876000bb46dd2337a3051618f4fc8" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ff15c8ecd7de3849db632e14d18d2571fa09dfc5ed93479bc4485c7a517c913" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "unicode-ident" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9312f7c4f6ff9069b165498234ce8be658059c6728633667c526e27dc2cf1df5" + +[[package]] +name = "unicode-linebreak" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b09c83c3c29d37506a3e260c08c03743a6bb66a9cd432c6934ab501a190571f" + +[[package]] +name = "unicode-width" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" + +[[package]] +name = "unicode-width" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.53.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" +dependencies = [ + "windows-link", + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" + +[[package]] +name = "windows_i686_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" + +[[package]] +name = "windows_i686_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" diff --git a/Cargo.toml b/Cargo.toml index e04d41c..12fd715 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,3 +6,5 @@ members = ["bin_efo", "lib_efo"] serde = { version = "1.0.228", features = ["derive"] } clap = { version = "4.5.51", features = ["derive"] } thiserror = "2.0.17" +serde_json = "1.0.145" +miette = { version = "7.6.0", features = ["fancy"] } diff --git a/bin_efo/Cargo.toml b/bin_efo/Cargo.toml index 0f2170d..d381520 100644 --- a/bin_efo/Cargo.toml +++ b/bin_efo/Cargo.toml @@ -8,4 +8,5 @@ lib_efo = { path = "../lib_efo" } serde = {workspace = true} clap = {workspace = true} thiserror = {workspace = true} -serde_json = "1.0.145" +serde_json = {workspace = true} +miette = {workspace = true} diff --git a/bin_efo/src/commands/epoch.rs b/bin_efo/src/commands/epoch.rs index 0b37a45..79787fb 100644 --- a/bin_efo/src/commands/epoch.rs +++ b/bin_efo/src/commands/epoch.rs @@ -11,7 +11,7 @@ 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 _main_epoch = EpochConfig::new_from_path(None)?; match cmd { cli_epoch::EpochCmd::Log(args) => handle_log(args), cli_epoch::EpochCmd::Switch(args) => handle_switch(args), diff --git a/bin_efo/src/commands/init.rs b/bin_efo/src/commands/init.rs index a712e50..6a2f73d 100644 --- a/bin_efo/src/commands/init.rs +++ b/bin_efo/src/commands/init.rs @@ -3,6 +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::EpochConfig, error::EpochError}; use crate::error::AppError; @@ -15,27 +16,59 @@ pub struct InitCmd { } /// Init an empty repository -pub fn init(args: InitCmd) -> Result<(), AppError> { +pub fn init(args: &InitCmd) -> Result<(), AppError> { let root = Path::new("."); - if !(read_dir(root)?.count() == 0 || args.force) { - Err(EpochError::AlreadyInitialized)? + if read_dir(root)?.count() != 0 { + Err(EpochError::FolderNotEmpty { + name: None, + show_label: None, + })?; } - let s = serde_json::to_string_pretty(&EpochConfig::empty()) - .map_err(|e| EpochError::Serde(e, "Creating config".to_owned(), ".".to_owned()))?; + 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 path = root.join(".epoch"); if let Ok(mut f) = File::create_new(path) { write!(f, "{}", s)?; - println!("{:?}", args); Ok(()) } else { - Err(EpochError::AlreadyInitialized)? + Err(EpochError::AlreadyInitialized { + advice: Some( + "You must remove the .epoch configuration file manually or pick another folder" + .to_string(), + ), + })? } } /// Tries to init the epoch 0 -fn init_epoch(args: InitCmd) -> Result<(), AppError> { +fn init_epoch(_args: &InitCmd) -> Result<(), AppError> { let path = Path::new(".").join("0"); - create_dir(path)?; + create_dir(&path).map_err(|_| EpochError::FolderNotEmpty { + name: Some(path.to_str().unwrap_or_default().to_owned()), + show_label: Some((0, 0)), + })?; - Ok(()) + 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, + })?; + if let Ok(mut f) = File::create_new("0/.epochfile") { + write!(f, "{}", json)?; + Ok(()) + } else { + 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, + })? + } } diff --git a/bin_efo/src/error.rs b/bin_efo/src/error.rs index 8379b04..9820956 100644 --- a/bin_efo/src/error.rs +++ b/bin_efo/src/error.rs @@ -4,26 +4,31 @@ //! execution: parsing, I/O, epoch logic, storage, and a catch‑all. use lib_efo::error::{EpochError, StorageError}; +use miette::Diagnostic; use thiserror::Error; /// All errors that can bubble up to the CLI. -#[derive(Debug, Error)] +#[derive(Debug, Error, Diagnostic)] #[allow(dead_code)] pub enum AppError { /// Generic “invalid command / missing flag” – emitted by clap. #[error("Command‑line error: {0}")] + // #[diagnostic(transparent)] Clap(#[from] clap::Error), /// Errors that happen when reading / writing the JSON file. #[error("I/O error: {0}")] + // #[diagnostic(transparent)] Io(#[from] std::io::Error), /// Domain‑specific problems (see `EpochError`). - #[error("Epoch error: {0}")] + #[error("Epoch error:")] + #[diagnostic(transparent)] Epoch(#[from] EpochError), /// Storage‑layer (e.g. DB) errors. #[error("Storage error: {0}")] + // #[diagnostic(transparent)] Storage(#[from] StorageError), /// Anything else we didn’t anticipate. diff --git a/bin_efo/src/main.rs b/bin_efo/src/main.rs index 3ff5605..84f415e 100644 --- a/bin_efo/src/main.rs +++ b/bin_efo/src/main.rs @@ -47,7 +47,7 @@ enum TopLevelCmd { // Link(commands::link::LinkCmd), } -fn main() -> Result<(), AppError> { +fn main() -> miette::Result<()> { let cli = Cli::parse(); if let Err(e) = exec_dispatch(cli) { @@ -58,8 +58,9 @@ fn main() -> Result<(), AppError> { // AppError::Storage(storage_error) => todo!(), // AppError::Other(_) => todo!(), // } - println!("The program didn't exit properly and returned the following error:"); - println!("{}", e); + // println!("The program didn't exit properly and returned the following error:"); + // println!("{}", e); + Err(e)?; } Ok(()) @@ -68,7 +69,7 @@ fn main() -> Result<(), AppError> { fn exec_dispatch(cli: Cli) -> Result<(), AppError> { match cli.command { TopLevelCmd::Init(cmd) => { - commands::init::init(cmd)?; + commands::init::init(&cmd)?; println!("The folder was initialized as an epoch folder") } TopLevelCmd::Epoch(cmd) => { diff --git a/lib_efo/Cargo.toml b/lib_efo/Cargo.toml index 29c59f7..9398e9c 100644 --- a/lib_efo/Cargo.toml +++ b/lib_efo/Cargo.toml @@ -4,7 +4,8 @@ version = "0.1.0" edition = "2024" [dependencies] -serde_json = "1.0.145" +serde_json = {workspace = true} serde = {workspace = true} thiserror = {workspace = true} clap = {workspace = true} +miette = {workspace = true} diff --git a/lib_efo/src/epoch_struct.rs b/lib_efo/src/epoch_struct.rs index 5d48145..f28784b 100644 --- a/lib_efo/src/epoch_struct.rs +++ b/lib_efo/src/epoch_struct.rs @@ -22,7 +22,7 @@ use serde::{Deserialize, Serialize}; use std::{collections::HashMap, fmt, fs::read_to_string, path::Path}; -use crate::error::EpochError; +use crate::{epoch_struct, error::EpochError}; /// The file written to *~/.epochconfig* that tells the CLI which /// epoch folder is the “current” one. @@ -59,12 +59,10 @@ impl EpochConfig { let join = Path::new(".").join(".epoch"); if join.is_file() { let config: EpochConfig = - serde_json::from_str(&read_to_string(&join)?).map_err(|e| { - EpochError::Serde( - e, - "Config".into(), - join.to_str().unwrap_or_default().to_owned(), - ) + serde_json::from_str(&read_to_string(&join)?).map_err(|e| EpochError::Serde { + source: e, + file_name: join.to_str().unwrap_or_default().to_owned(), + help: None, })?; Ok(config) } else { @@ -104,6 +102,18 @@ pub struct EpochInfo { pub summary: Option, } +impl EpochInfo { + pub fn empty() -> Self { + Self { + epoch_id: epoch_struct::EpochId::new(0), + parent_id: None, + rng_seed: 0, + tags: Vec::new(), + summary: None, + } + } +} + /// Thin type to handle EpochIds #[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct EpochId { diff --git a/lib_efo/src/error.rs b/lib_efo/src/error.rs index e3ea976..14cf21b 100644 --- a/lib_efo/src/error.rs +++ b/lib_efo/src/error.rs @@ -9,9 +9,10 @@ use std::path::PathBuf; use thiserror::Error; use crate::epoch_struct::EpochId; +use miette::Diagnostic; /// Errors that can be returned by the storage layer. -#[derive(Debug, Error)] +#[derive(Debug, Error, Diagnostic)] pub enum StorageError { /// Problems with serialisation / deserialisation. #[error("Data error: {0}")] @@ -34,7 +35,7 @@ pub enum StorageError { /// The enum is deliberately *small* – each variant is self‑contained /// and carries the information you need to surface a friendly message /// to the user (and to the test‑suite). -#[derive(Error, Debug)] +#[derive(Error, Debug, Diagnostic)] pub enum EpochError { /// Problems with the `.epochconfig` file #[error("Failed to read epoch configuration")] @@ -44,14 +45,40 @@ pub enum EpochError { ConfigWrite(#[source] std::io::Error), #[error("This directory is already an epoch folder and thus cannot be initialized")] - AlreadyInitialized, + #[diagnostic(code(EpochError::AlreadyInitialized))] + AlreadyInitialized { + #[help] + advice: Option, + }, + + #[error("This directory isn't empty and thus cannot be initialized")] + #[diagnostic(code(EpochError::FolderNotEmpty))] + #[diagnostic(help("Empty the folder or remove its content first"))] + // #[diagnostic(label((1,1)))] + FolderNotEmpty { + #[source_code] + name: Option, + + #[label("This file is present and forbid the command to execute properly")] + show_label: Option<(usize, usize)>, + }, /// Problems while serialising / deserialising an `EpochInfo` #[error("Failed to parse `.epochinfo` in epoch {0} ({1}): {2}")] EpochInfoParse(EpochId, PathBuf, #[source] serde_json::Error), - #[error("Failed to write `.epochinfo` in epoch {0} ({1}): {2}")] - EpochInfoWrite(EpochId, PathBuf, #[source] std::io::Error), + #[error("Failed to write `.epochinfo` in epoch {id} ({path})")] + #[diagnostic(code(EpochError::EpochInfoWrite))] + EpochInfoWrite { + id: EpochId, + path: PathBuf, + + #[help] + help: Option, + + #[source] + src: Option, + }, /// The user supplied an epoch id or tag that does not exist #[error("No epoch found for id/tag `{}`", .0)] @@ -97,8 +124,17 @@ pub enum EpochError { Io(#[source] std::io::Error), /// Serialization / deserialization errors that are not caught above - #[error("Serialization error: {1}:{2} {0}")] - Serde(serde_json::Error, String, String), + #[error("Serialization error from {file_name}")] + #[diagnostic(code(EpochError::SerdeError))] + Serde { + #[source] + source: serde_json::Error, + + file_name: String, + + #[diagnostic(help)] + help: Option, + }, /// The epoch tree is in an incorrect state #[error("Invalid epoch tree at {0}")] diff --git a/testepo/.gitignore b/testepo/.gitignore deleted file mode 100644 index e3eeed8..0000000 --- a/testepo/.gitignore +++ /dev/null @@ -1 +0,0 @@ -testepo* From 3db8139b5f7a5e4dca6efa6ca4883fa90a7cc3f6 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Thu, 27 Nov 2025 00:25:13 +0100 Subject: [PATCH 06/10] Adds some more epoch functions --- bin_efo/src/commands/epoch.rs | 36 ++++++++++--- bin_efo/src/commands/epoch/cli_epoch.rs | 24 +++++++-- bin_efo/src/commands/init.rs | 19 +++---- lib_efo/src/epoch_struct.rs | 71 ++++++++++++++++++++++--- lib_efo/src/error.rs | 4 ++ 5 files changed, 123 insertions(+), 31 deletions(-) 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 { From 80026b502b1b02efec758bfc10810b6b683f8aec Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Thu, 27 Nov 2025 01:33:25 +0100 Subject: [PATCH 07/10] Adds some more epoch plumbing --- bin_efo/src/commands/epoch.rs | 30 +++---- bin_efo/src/commands/epoch/cli_epoch.rs | 49 +---------- bin_efo/src/commands/init.rs | 38 ++++----- bin_efo/src/main.rs | 2 +- lib_efo/src/epoch_struct.rs | 104 +++++++++++++++++++++++- 5 files changed, 137 insertions(+), 86 deletions(-) diff --git a/bin_efo/src/commands/epoch.rs b/bin_efo/src/commands/epoch.rs index 5a7b1bf..d8a90d2 100644 --- a/bin_efo/src/commands/epoch.rs +++ b/bin_efo/src/commands/epoch.rs @@ -27,11 +27,12 @@ pub fn handle_cmd(cmd: cli_epoch::EpochCmd) -> Result<(), AppError> { } fn handle_diff() -> Result<(), AppError> { + // Blocker: There is actually no way to diff the world yet todo!() } fn handle_log(_args: cli_epoch::Log) -> Result<(), AppError> { - // NOTE: `world.epoch_manager` already owns the schedule. + // Just needs for the epoch to implement lvels of displays trait: DisplayLevels println!("Epoch log (most recent first):"); // println!( // "#{} {} [{}] {}", @@ -41,21 +42,22 @@ fn handle_log(_args: cli_epoch::Log) -> Result<(), AppError> { } 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())), - }?; + let target = main_epoch.get(&args.target)?; + // TODO: Check if the epoch is valid + // let b = main_epoch + // .list_existing_epochs + // .get(&target.to_string()) + // .unwrap(); + main_epoch + .try_load(&target) + .map_err(|_e| EpochError::EpochFolderMissing(target, ".".into()))?; + main_epoch.epoch_id = target; println!("Switched to epoch {:?}", target); - main_epoch.save("Saving modified config".into())?; + main_epoch.save( + "Saving modified config".into(), + lib_efo::epoch_struct::SaveMode::Erase, + )?; Ok(()) } diff --git a/bin_efo/src/commands/epoch/cli_epoch.rs b/bin_efo/src/commands/epoch/cli_epoch.rs index b90176b..c5773d3 100644 --- a/bin_efo/src/commands/epoch/cli_epoch.rs +++ b/bin_efo/src/commands/epoch/cli_epoch.rs @@ -1,10 +1,5 @@ -use clap::{Args, Subcommand, error::ErrorKind}; -use serde::Deserialize; -use serde::Serialize; - -use std::str::FromStr; - -use lib_efo::epoch_struct::EpochId; +use clap::{Args, Subcommand}; +use lib_efo::epoch_struct::EpochIdentifier; /// The outer clap entry that the binary will dispatch to #[derive(Subcommand, Debug)] @@ -65,43 +60,3 @@ pub struct Diff { /// 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"`). -/// -/// The enum is `untagged` so that serialising/deserialising does -/// **not** add a wrapper field, e.g. `{"Tag":"foo"}`. -/// Instead the JSON representation is exactly the inner value: -/// * `"42"` → `EpochIdentifier::Id(EpochId::new(42))` -/// * `"foo"` → `EpochIdentifier::Tag("foo".into())` -#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Hash)] -#[serde(untagged)] // <‑‑ no “type” wrapper is written to JSON -pub enum EpochIdentifier { - /// A textual tag that maps to a numeric epoch ID in `EpochConfig::tags`. - Tag(String), - - /// The raw numeric identifier of the epoch. - Id(EpochId), -} - -impl FromStr for EpochIdentifier { - type Err = clap::Error; // any `std::error::Error` works - - /// Try to parse either a decimal number (-> `Id`) or any non‑empty - /// string (-> `Tag`). - /// - /// Errors are converted to a Clap error so that the CLI shows a - /// nice message. - fn from_str(s: &str) -> Result { - if let Ok(num) = s.parse::() { - Ok(EpochIdentifier::Id(EpochId::new(num))) - } else if !s.is_empty() { - Ok(EpochIdentifier::Tag(s.to_owned())) - } else { - Err(clap::Error::raw( - ErrorKind::InvalidValue, - format!("{} is not a valid epoch id or tag", s), - )) - } - } -} diff --git a/bin_efo/src/commands/init.rs b/bin_efo/src/commands/init.rs index c0693e3..b92aa0a 100644 --- a/bin_efo/src/commands/init.rs +++ b/bin_efo/src/commands/init.rs @@ -1,6 +1,5 @@ use std::fs::{create_dir, read_dir}; -use std::io::Write; -use std::{fs::File, path::Path}; +use std::path::Path; use clap::Args; use lib_efo::epoch_struct::{ConfigWritable, EpochId, EpochInfo}; @@ -18,6 +17,7 @@ pub struct InitCmd { /// Init an empty repository pub fn init(args: &InitCmd) -> Result<(), AppError> { let root = Path::new("."); + //TODO: This can be really deceiving when only .epoch is present if read_dir(root)?.count() != 0 { Err(EpochError::FolderNotEmpty { name: None, @@ -25,20 +25,18 @@ pub fn init(args: &InitCmd) -> Result<(), AppError> { })?; } init_epoch(args)?; - 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(()) - } else { - Err(EpochError::AlreadyInitialized { + EpochConfig::empty() + .save( + "Creatig initial config".into(), + lib_efo::epoch_struct::SaveMode::DoNotErase, + ) + .map_err(|_| EpochError::AlreadyInitialized { advice: Some( "You must remove the .epoch configuration file manually or pick another folder" .to_string(), ), - })? - } + })?; + Ok(()) } /// Tries to init the epoch 0 @@ -49,19 +47,17 @@ fn init_epoch(_args: &InitCmd) -> Result<(), AppError> { show_label: Some((0, 0)), })?; - 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(()) - } else { - Err(EpochError::EpochInfoWrite { + // let json = EpochInfo::empty().as_json("Creating empty epoch file".into())?; + EpochInfo::empty().save( + "Creating empty epoch file".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(()) } diff --git a/bin_efo/src/main.rs b/bin_efo/src/main.rs index 84f415e..7c6f9c2 100644 --- a/bin_efo/src/main.rs +++ b/bin_efo/src/main.rs @@ -74,7 +74,7 @@ fn exec_dispatch(cli: Cli) -> Result<(), AppError> { } TopLevelCmd::Epoch(cmd) => { commands::epoch::handle_cmd(cmd)?; - println!("Epoch nicely executed") + // println!("") } } Ok(()) diff --git a/lib_efo/src/epoch_struct.rs b/lib_efo/src/epoch_struct.rs index 92f5c82..1cedb07 100644 --- a/lib_efo/src/epoch_struct.rs +++ b/lib_efo/src/epoch_struct.rs @@ -19,8 +19,10 @@ //! files, just like a git repository tracks its commits and //! `HEAD` pointer. +use clap::error::ErrorKind; use serde::{Deserialize, Serialize}; use std::io::Write; +use std::str::FromStr; use std::{ collections::HashMap, fmt, @@ -49,6 +51,7 @@ pub struct EpochConfig { // /// Absolute path to `epoch//`. // 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>, } @@ -67,6 +70,7 @@ impl EpochConfig { pub fn new_from_path(_path: Option<&Path>) -> Result { let path = Path::new(".").join(".epoch"); 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, @@ -92,6 +96,47 @@ impl EpochConfig { } Ok(self) } + + /// Try to load into memory the given epoch id + 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()) + .then_some(epoch_id) + .ok_or(EpochError::EpochFolderMissing(*epoch_id, ".".into())) + .copied()?; + let path = Path::new(&epoch_id.to_string()).join(".epochinfo"); + let maybe_epoch: EpochInfo = + 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 value = self + .list_existing_epochs + .get_mut(&epoch_id.to_string()) + .unwrap(); + *value = Some(maybe_epoch); + Ok(()) + } + + /// Get an identifier or returns None + pub fn get(&self, id: &EpochIdentifier) -> Result { + 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.to_string()) + .then_some(epoch_id) + .ok_or(EpochError::EpochFolderMissing(*epoch_id, ".".into())) + .copied(), + } + } } /// Trait representing a serialisable / writable config @@ -109,9 +154,17 @@ pub trait ConfigWritable: Serialize { } /// 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))?; + fn save( + &self, + action: String, + do_not_erase: SaveMode, + // advice: Option, + ) -> 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)?).map_err(EpochError::ConfigWrite)?; Ok(()) } @@ -148,6 +201,11 @@ pub struct EpochInfo { pub summary: Option, } +pub enum SaveMode { + DoNotErase, + Erase, +} + impl EpochInfo { pub fn empty() -> Self { Self { @@ -199,3 +257,43 @@ impl ConfigWritable for EpochInfo { format!("{}/.epochinfo", 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"`). +/// +/// The enum is `untagged` so that serialising/deserialising does +/// **not** add a wrapper field, e.g. `{"Tag":"foo"}`. +/// Instead the JSON representation is exactly the inner value: +/// * `"42"` → `EpochIdentifier::Id(EpochId::new(42))` +/// * `"foo"` → `EpochIdentifier::Tag("foo".into())` +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Hash)] +#[serde(untagged)] // <‑‑ no “type” wrapper is written to JSON +pub enum EpochIdentifier { + /// A textual tag that maps to a numeric epoch ID in `EpochConfig::tags`. + Tag(String), + + /// The raw numeric identifier of the epoch. + Id(EpochId), +} + +impl FromStr for EpochIdentifier { + type Err = clap::Error; // any `std::error::Error` works + + /// Try to parse either a decimal number (-> `Id`) or any non‑empty + /// string (-> `Tag`). + /// + /// Errors are converted to a Clap error so that the CLI shows a + /// nice message. + fn from_str(s: &str) -> Result { + if let Ok(num) = s.parse::() { + Ok(EpochIdentifier::Id(EpochId::new(num))) + } else if !s.is_empty() { + Ok(EpochIdentifier::Tag(s.to_owned())) + } else { + Err(clap::Error::raw( + ErrorKind::InvalidValue, + format!("{} is not a valid epoch id or tag", s), + )) + } + } +} From fcd55b6e341fa1635088286c2dfe56f13801dd0e Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Thu, 27 Nov 2025 16:46:40 +0100 Subject: [PATCH 08/10] Partial commit implementing some epoch mechanics --- bin_efo/src/commands/epoch.rs | 8 +- bin_efo/src/commands/init.rs | 34 +++----- bin_efo/src/main.rs | 2 +- lib_efo/src/epoch_struct.rs | 144 ++++++++++++++++++++++++---------- lib_efo/src/error.rs | 68 ++++++++-------- lib_efo/src/lib.rs | 1 + 6 files changed, 151 insertions(+), 106 deletions(-) diff --git a/bin_efo/src/commands/epoch.rs b/bin_efo/src/commands/epoch.rs index d8a90d2..d1c27be 100644 --- a/bin_efo/src/commands/epoch.rs +++ b/bin_efo/src/commands/epoch.rs @@ -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"); } diff --git a/bin_efo/src/commands/init.rs b/bin_efo/src/commands/init.rs index b92aa0a..8e5527f 100644 --- a/bin_efo/src/commands/init.rs +++ b/bin_efo/src/commands/init.rs @@ -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(()) } diff --git a/bin_efo/src/main.rs b/bin_efo/src/main.rs index 7c6f9c2..d5e4391 100644 --- a/bin_efo/src/main.rs +++ b/bin_efo/src/main.rs @@ -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)?; } diff --git a/lib_efo/src/epoch_struct.rs b/lib_efo/src/epoch_struct.rs index 1cedb07..c92a78a 100644 --- a/lib_efo/src/epoch_struct.rs +++ b/lib_efo/src/epoch_struct.rs @@ -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, + // TODO: Can become important + // #[serde(skip)] // /// Absolute path to `epoch//`. // 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>, + pub list_existing_epochs: HashMap>, } -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 { - 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 { - 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::(); + 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 { serde_json::to_string_pretty(self).map_err(|e| EpochError::Serde { @@ -201,13 +240,8 @@ pub struct EpochInfo { pub summary: Option, } -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 { + 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) } } diff --git a/lib_efo/src/error.rs b/lib_efo/src/error.rs index 533f9db..99914d7 100644 --- a/lib_efo/src/error.rs +++ b/lib_efo/src/error.rs @@ -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, + }, /// 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, }, @@ -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 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 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 }, -// } diff --git a/lib_efo/src/lib.rs b/lib_efo/src/lib.rs index 6a12f41..8a5d8e0 100644 --- a/lib_efo/src/lib.rs +++ b/lib_efo/src/lib.rs @@ -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; From 4cd3d4de98d66fc8ee0ed7492dcc840444b6a2ce Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Thu, 27 Nov 2025 17:31:34 +0100 Subject: [PATCH 09/10] Epoch first draft finished --- bin_efo/src/commands/epoch.rs | 57 +++++++++++++++++------------------ lib_efo/src/epoch_struct.rs | 50 +++++++++++++++++++----------- 2 files changed, 60 insertions(+), 47 deletions(-) diff --git a/bin_efo/src/commands/epoch.rs b/bin_efo/src/commands/epoch.rs index d1c27be..8a9aaf8 100644 --- a/bin_efo/src/commands/epoch.rs +++ b/bin_efo/src/commands/epoch.rs @@ -3,10 +3,7 @@ //! Handles all epoch‑related logic – logging, switching, computing the //! next epoch, and resetting future events. -use lib_efo::{ - epoch_struct::{ConfigWritable, EpochConfig}, - error::EpochError, -}; +use lib_efo::epoch_struct::{ConfigWritable, EpochConfig}; use crate::error::AppError; @@ -20,54 +17,54 @@ pub fn handle_cmd(cmd: cli_epoch::EpochCmd) -> Result<(), AppError> { match cmd { cli_epoch::EpochCmd::Log(args) => handle_log(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(), + cli_epoch::EpochCmd::Next(args) => handle_next(args), + cli_epoch::EpochCmd::Reset(args) => handle_reset(args, &mut main_epoch), + cli_epoch::EpochCmd::Diff(args) => handle_diff(args), } } -fn handle_diff() -> Result<(), AppError> { - // Blocker: There is actually no way to diff the world yet - todo!() +fn handle_diff(args: cli_epoch::Diff) -> Result<(), AppError> { + let _ = args; + unimplemented!("Blocker: There is actually no way to diff the world yet") } fn handle_log(_args: cli_epoch::Log) -> Result<(), AppError> { - // Just needs for the epoch to implement lvels of displays trait: DisplayLevels println!("Epoch log (most recent first):"); - // println!( - // "#{} {} [{}] {}", - // epoch.id, epoch.date, tags, epoch.summary - // ); - Ok(()) + unimplemented!("Just needs for the epoch to implement lvels of displays trait: DisplayLevels"); } +/// Switch the current epoch for another fn handle_switch(args: cli_epoch::Switch, main_epoch: &mut EpochConfig) -> Result<(), AppError> { let target = main_epoch.get(&args.target)?; - // TODO: Check if the epoch is valid - // let b = main_epoch - // .list_existing_epochs - // .get(&target.to_string()) - // .unwrap(); - main_epoch - .try_load(&target) - .map_err(|_e| EpochError::EpochFolderMissing(target, main_epoch.save_folder().into()))?; - + main_epoch.try_load(&target)?; main_epoch.epoch_id = target; + println!("Switched to epoch {:?}", target); main_epoch.save( - "Saving modified config".into(), + "Saving modified epoch config".into(), lib_efo::epoch_struct::SaveMode::Erase, )?; Ok(()) } -fn handle_next() -> Result<(), AppError> { +fn handle_next(args: cli_epoch::Next) -> Result<(), AppError> { + let _ = args; println!("⚡ Next",); unimplemented!("Missing logic to process a next event"); } /// Reset all future events by deleting them -fn handle_reset() -> Result<(), AppError> { - println!("✅ All future events deleted – back to epoch",); - unimplemented!("Blocked by non parsing of folders"); +fn handle_reset(args: cli_epoch::Reset, main_epoch: &mut EpochConfig) -> Result<(), AppError> { + let _ = args; + let current_id = main_epoch.epoch_id; + for id in main_epoch + .list_existing_epochs + .keys() + .filter(|&k| k > ¤t_id) + { + main_epoch.delete_id(*id)? + } + + println!("All future events deleted – back to epoch {current_id}",); + Ok(()) } diff --git a/lib_efo/src/epoch_struct.rs b/lib_efo/src/epoch_struct.rs index c92a78a..4c6b70f 100644 --- a/lib_efo/src/epoch_struct.rs +++ b/lib_efo/src/epoch_struct.rs @@ -24,7 +24,7 @@ use serde::{Deserialize, Serialize}; use std::{ collections::HashMap, fmt, - fs::{File, create_dir_all, read_to_string}, + fs::{File, create_dir_all, read_to_string, remove_dir_all}, io::Write, path::Path, str::FromStr, @@ -121,31 +121,24 @@ impl EpochConfig { } /// 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) - .then_some(epoch_id) - .ok_or(EpochError::EpochFolderMissing( - *epoch_id, - EpochConfig::default().save_path().into(), - )) - .copied()?; - let path = Path::new(&epoch_id.to_string()).join(".epochinfo"); + // Preload the epoch + let value = self.list_existing_epochs.get_mut(epoch_id).unwrap(); + + // 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), format!("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_lossy().to_string(), + file_name: path.to_string(), help: None, })?; - let value = self.list_existing_epochs.get_mut(epoch_id).unwrap(); + + // Overwrite the value *value = Some(maybe_epoch); Ok(()) } @@ -173,6 +166,21 @@ impl EpochConfig { fn save_subfolder(&self) -> String { format!("{}/", SUBFOLDER_NAMING) } + + /// Tries to delete an entire epoch folder by Id + pub fn delete_id(&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()), + format!("Removing the epoch {}", id) + )?; + Ok(()) + } } /// Trait representing a serialisable / writable config @@ -262,6 +270,14 @@ impl EpochInfo { 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 From 3e309291e855fbf5e872c4b283d35ce7befdfa7c Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Thu, 27 Nov 2025 18:00:24 +0100 Subject: [PATCH 10/10] Adds a basic tagging system --- bin_efo/src/commands/epoch.rs | 45 ++++++++++++++++++++++++- bin_efo/src/commands/epoch/cli_epoch.rs | 9 +++++ lib_efo/src/epoch_struct.rs | 5 +-- 3 files changed, 56 insertions(+), 3 deletions(-) diff --git a/bin_efo/src/commands/epoch.rs b/bin_efo/src/commands/epoch.rs index 8a9aaf8..587f283 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::{ConfigWritable, EpochConfig}; +use lib_efo::{ + epoch_struct::{ConfigWritable, EpochConfig}, + error::EpochError, +}; use crate::error::AppError; @@ -20,6 +23,7 @@ pub fn handle_cmd(cmd: cli_epoch::EpochCmd) -> Result<(), AppError> { cli_epoch::EpochCmd::Next(args) => handle_next(args), cli_epoch::EpochCmd::Reset(args) => handle_reset(args, &mut main_epoch), cli_epoch::EpochCmd::Diff(args) => handle_diff(args), + cli_epoch::EpochCmd::Tag(args) => handle_taging(args, &mut main_epoch), } } @@ -68,3 +72,42 @@ fn handle_reset(args: cli_epoch::Reset, main_epoch: &mut EpochConfig) -> Result< println!("All future events deleted – back to epoch {current_id}",); Ok(()) } + +/// Adds a tag to the current epoch +fn handle_taging(args: cli_epoch::Tag, main_epoch: &mut EpochConfig) -> Result<(), AppError> { + // Load into memory the current epoch + main_epoch.try_load(&main_epoch.epoch_id.clone())?; + + // Check if the tag doens't exists + if main_epoch.tags.contains_key(&args.tag) { + Err(AppError::Epoch(EpochError::TagAlreadyExists( + main_epoch.epoch_id, + args.tag.clone(), + )))?; + } + + // Modify the epoch to add the tag inside + if let Some(current_epoch_info) = main_epoch + .list_existing_epochs + .get_mut(&main_epoch.epoch_id) + .unwrap() + { + current_epoch_info.tags.push(args.tag.clone()); + current_epoch_info.save( + "Saving modified epoch".to_owned(), + lib_efo::epoch_struct::SaveMode::Erase, + )?; + main_epoch + .tags + .insert(args.tag.clone(), main_epoch.epoch_id); + main_epoch.save( + "Saving modified main config".into(), + lib_efo::epoch_struct::SaveMode::Erase, + )?; + Ok(()) + } else { + Err(AppError::Epoch(lib_efo::error::EpochError::Unknown( + format!("Couldn't add the tag {}", args.tag), + ))) + } +} diff --git a/bin_efo/src/commands/epoch/cli_epoch.rs b/bin_efo/src/commands/epoch/cli_epoch.rs index c5773d3..25b53a4 100644 --- a/bin_efo/src/commands/epoch/cli_epoch.rs +++ b/bin_efo/src/commands/epoch/cli_epoch.rs @@ -20,6 +20,7 @@ pub enum EpochCmd { Diff(Diff), // Tag and next could be implemented as subcommands of epoch // even if they barely belong here + Tag(Tag), } /// `efo epoch log` @@ -60,3 +61,11 @@ pub struct Diff { /// The end point to compute the differences, the current epoch by default pub end: Option, } + +/// `efo epoch tag "tag"` +#[derive(Args, Debug)] +pub struct Tag { + #[arg(required = true)] + /// The tag to tag the current epoch with + pub tag: String, +} diff --git a/lib_efo/src/epoch_struct.rs b/lib_efo/src/epoch_struct.rs index 4c6b70f..131dd3a 100644 --- a/lib_efo/src/epoch_struct.rs +++ b/lib_efo/src/epoch_struct.rs @@ -203,7 +203,8 @@ pub trait ConfigWritable: Serialize { /// Save the config into it's nominal path fn save( &self, - action: String, + // Very unsure about this versus a macro + action_description: String, do_not_erase: SaveMode, // advice: Option, ) -> Result<(), EpochError> { @@ -212,7 +213,7 @@ pub trait ConfigWritable: Serialize { SaveMode::DoNotErase => File::create_new(self.save_path()), } .map_err(|e| EpochError::ConfigCreation(self.save_path(), e))?; - write!(f, "{}", self.as_json(action)?).map_err(EpochError::ConfigWrite)?; + write!(f, "{}", self.as_json(action_description)?).map_err(EpochError::ConfigWrite)?; Ok(()) } }