diff --git a/Cargo.toml b/Cargo.toml index 63180ca..e04d41c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,26 +1,8 @@ -[package] -name = "epoch_forge" -version = "0.1.0" -edition = "2024" - -[dependencies] - -[[bin]] -name = "efo" -path = "bin_efo/src/main.rs" - [workspace] resolver = "3" -members = ["bin_efo", "cli_common", "lib_efo"] - -# [workspace.package] -# version = "1.2.3" -# authors = ["Nice Folks"] -# description = "A short description of my package" -# documentation = "https://example.com/bar" - -# [workspace.dependencies] -# cc = "1.0.73" -# rand = "0.8.5" -# regex = { version = "1.6.0", default-features = false, features = ["std"] } +members = ["bin_efo", "lib_efo"] +[workspace.dependencies] +serde = { version = "1.0.228", features = ["derive"] } +clap = { version = "4.5.51", features = ["derive"] } +thiserror = "2.0.17" diff --git a/bin_efo/Cargo.toml b/bin_efo/Cargo.toml index 0ec51f8..e0a76ba 100644 --- a/bin_efo/Cargo.toml +++ b/bin_efo/Cargo.toml @@ -4,5 +4,7 @@ version = "0.1.0" edition = "2024" [dependencies] -cli_common = { path = "../cli_common" } lib_efo = { path = "../lib_efo" } +serde = {workspace = true} +clap = {workspace = true} +thiserror = {workspace = true} diff --git a/bin_efo/src/commands/epoch.rs b/bin_efo/src/commands/epoch.rs new file mode 100644 index 0000000..a88d511 --- /dev/null +++ b/bin_efo/src/commands/epoch.rs @@ -0,0 +1,157 @@ +// efo/src/commands/epoch.rs +//! # `epoch` sub‑command +//! +//! Handles all epoch‑related logic – logging, switching, computing the +//! next epoch, and resetting future events. + +use clap::{Args, Subcommand}; + +// 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 { + /// 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: String, + + /// Optional confirmation flag (if you ever want to force‑switch) + #[arg(long, short, help = "Force‑switch even if the epoch has no tag")] + pub force: bool, +} + +/// `efo epoch next` +#[derive(Args, Debug)] +pub struct Next; + +/// `efo epoch reset` +#[derive(Args, Debug)] +pub struct Reset; + +// /// **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), +// } +// } + +// /// ---------- helpers ---------- + +// 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, 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)?; + +// world.set_epoch(target_id); +// println!( +// "Switched to epoch #{} – {}", +// target_id, +// world.current_context().date +// ); +// 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(()) +// } +// +// +// use anyhow::Result; +// use crate::world::World; + +// 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(()) +// } diff --git a/bin_efo/src/commands/error.rs b/bin_efo/src/commands/error.rs new file mode 100644 index 0000000..9ae09c2 --- /dev/null +++ b/bin_efo/src/commands/error.rs @@ -0,0 +1,32 @@ +//! Error types that can arise while manipulating epochs. +//! +//! These errors are returned by the `epoch` sub‑command handlers and +//! 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 }, +} diff --git a/bin_efo/src/commands/mod.rs b/bin_efo/src/commands/mod.rs new file mode 100644 index 0000000..07c3b87 --- /dev/null +++ b/bin_efo/src/commands/mod.rs @@ -0,0 +1,10 @@ +//! # `commands` module +//! +//! This module is the entry point for all CLI sub‑commands of the `efo` binary. +//! Each sub‑command (e.g. `epoch`, `org`, `event`, `town`, `link`) lives in its +//! own file inside this directory and is re‑exported here so that the main +//! `efo::main.rs` can simply `use commands::*;` and dispatch based on the +//! clap‑parsed enum. + +pub mod epoch; +pub mod error; diff --git a/bin_efo/src/error.rs b/bin_efo/src/error.rs new file mode 100644 index 0000000..6974f51 --- /dev/null +++ b/bin_efo/src/error.rs @@ -0,0 +1,34 @@ +//! General error type that the CLI propagates. +//! +//! `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 thiserror::Error; + +use crate::commands::error::EpochError; + +/// All errors that can bubble up to the CLI. +#[derive(Debug, Error)] +#[allow(dead_code)] +pub enum AppError { + /// Generic “invalid command / missing flag” – emitted by clap. + #[error("Command‑line error: {0}")] + Clap(#[from] clap::Error), + + /// Errors that happen when reading / writing the JSON file. + #[error("I/O error: {0}")] + Io(#[from] std::io::Error), + + /// Domain‑specific problems (see `EpochError`). + #[error("Epoch error: {0}")] + Epoch(#[from] EpochError), + + /// Storage‑layer (e.g. DB) errors. + #[error("Storage error: {0}")] + Storage(#[from] StorageError), + + /// Anything else we didn’t anticipate. + #[error("Unknown error: {0}")] + Other(String), +} diff --git a/bin_efo/src/main.rs b/bin_efo/src/main.rs index eca8049..7caac44 100644 --- a/bin_efo/src/main.rs +++ b/bin_efo/src/main.rs @@ -24,7 +24,13 @@ // use clap::{Parser, Subcommand}; // mod cli; -// mod commands; +use clap::{Parser, Subcommand}; + +use crate::{commands::epoch::EpochCmd, error::AppError}; + +mod commands; +mod error; +// use commands::EpochCmd; // use commands::*; @@ -58,6 +64,36 @@ // } // } -fn main() { - println!("Hello, world!"); +/// Root parser – the “efo” program +#[derive(Parser, Debug)] +#[command(name = "efo")] +struct Cli { + #[command(subcommand)] + command: TopLevelCmd, +} + +#[derive(Subcommand, Debug)] +enum TopLevelCmd { + /// Epoch‑related actions + + #[command(subcommand)] + Epoch(EpochCmd), + // … other sub‑commands (org, event, etc.) +} + +fn main() -> Result<(), AppError> { + // 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 … + // } + + Ok(()) } diff --git a/cli_common/Cargo.toml b/cli_common/Cargo.toml deleted file mode 100644 index 00feba1..0000000 --- a/cli_common/Cargo.toml +++ /dev/null @@ -1,6 +0,0 @@ -[package] -name = "cli_common" -version = "0.1.0" -edition = "2024" - -[dependencies] diff --git a/cli_common/src/lib.rs b/cli_common/src/lib.rs deleted file mode 100644 index b93cf3f..0000000 --- a/cli_common/src/lib.rs +++ /dev/null @@ -1,14 +0,0 @@ -pub fn add(left: u64, right: u64) -> u64 { - left + right -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn it_works() { - let result = add(2, 2); - assert_eq!(result, 4); - } -} diff --git a/lib_efo/Cargo.toml b/lib_efo/Cargo.toml index e79ecc2..29c59f7 100644 --- a/lib_efo/Cargo.toml +++ b/lib_efo/Cargo.toml @@ -4,3 +4,7 @@ version = "0.1.0" edition = "2024" [dependencies] +serde_json = "1.0.145" +serde = {workspace = true} +thiserror = {workspace = true} +clap = {workspace = true} diff --git a/lib_efo/src/epoch_struct.rs b/lib_efo/src/epoch_struct.rs new file mode 100644 index 0000000..fa12405 --- /dev/null +++ b/lib_efo/src/epoch_struct.rs @@ -0,0 +1,100 @@ +//! # Epoch configuration and state +//! +//! The *epoch* system is deliberately split into two tiny, serialisable +//! structures so that the binary can quickly read/write its “current +//! position” without pulling the whole world into memory. +//! +//! * `EpochConfig` – lives in `.epochconfig`. It only remembers +//! which epoch folder should be considered “current” and a few +//! convenience fields (tags, path). It never holds any event or +//! world data. +//! +//! * `EpochInfo` – stored inside `epoch//.epochinfo`. +//! This file contains the *metadata* for that particular epoch +//! (seed, selected events, parent link, etc.). Again, it does **not** +//! hold the full world; that is handled elsewhere in the engine. +//! +//! Keeping these two structs tiny means that switching epochs, logging, +//! or resetting can be done by reading/writing a handful of JSON/YAML +//! files, just like a git repository tracks its commits and +//! `HEAD` pointer. + +use serde::{Deserialize, Serialize}; +use std::{collections::HashMap, fmt}; + +/// The file written to *~/.epochconfig* that tells the CLI which +/// epoch folder is the “current” one. +/// +/// Only the minimal information needed for fast switches is stored: +/// * the numeric identifier of the selected epoch, +/// * a list of human‑readable tags, +/// * the absolute path to the epoch’s directory. +/// +/// No world or event data lives here – it is purely a lightweight pointer. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct EpochConfig { + /// The epoch ID that the binary should consider “current”. + pub epoch_id: EpochId, + + /// Optional human‑friendly tags (e.g. `"winter‑B"`, `"post‑war"`). + pub tags: HashMap, + // /// Absolute path to `epoch//`. + // pub path: PathBuf, +} + +/// The metadata file stored inside each epoch directory +/// (`epoch//.epochinfo`). +/// +/// It contains only the information that is needed for the engine to +/// reconstruct the state *of that particular epoch* (seed, selected +/// events, parent link, etc.). The full world data is kept in +/// separate storage (e.g. `world.json`). +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct EpochInfo { + /// The ID of this epoch – should match the directory name. + pub epoch_id: EpochId, + + /// The ID of the parent (previous) epoch, if not a root. + pub parent_id: Option, + + /// RNG seed that was used to generate randomised data for + /// this epoch. Keeping it in the file guarantees repeatable + /// behaviour when replaying the same epoch. + pub rng_seed: u64, + + // /// List of event IDs that were accepted for this epoch. + // /// The engine uses this to replay the world from the + // /// parent epoch to the current one. + // pub selected_events: Vec, + /// Optional tags that help identify the epoch (e.g. `"Winter‑B"`). + pub tags: Vec, + + /// Human‑readable description or summary, useful for the `log` command. + pub summary: Option, +} + +/// Thin type to handle EpochIds +#[derive(Serialize, Deserialize, Clone, Copy, Debug)] +pub struct EpochId { + pub id: u64, +} + +impl std::fmt::Display for EpochId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.id) + } +} + +impl EpochId { + pub fn new(id: u64) -> Self { + Self { id } + } +} + +impl std::ops::Deref for EpochId { + type Target = u64; + + fn deref(&self) -> &Self::Target { + &self.id + } +} diff --git a/lib_efo/src/error.rs b/lib_efo/src/error.rs new file mode 100644 index 0000000..7f34942 --- /dev/null +++ b/lib_efo/src/error.rs @@ -0,0 +1,119 @@ +//! Error types that arise when interacting with the storage layer. +//! +//! These are the only errors emitted by the `Storage` abstraction. +//! They are lightweight, strongly‑typed and can be converted to the +//! top‑level `AppError` via `thiserror`. + +use std::path::PathBuf; + +use thiserror::Error; + +use crate::epoch_struct::EpochId; + +/// Errors that can be returned by the storage layer. +#[derive(Debug, Error)] +pub enum StorageError { + /// Problems with serialisation / deserialisation. + #[error("Data error: {0}")] + Serialisation(#[from] serde_json::Error), + + /// Database connection failed for the provided reason. + #[error("Database connection failed: {0}")] + Connection(String), + + /// An error occurred while executing a database query. + #[error("Query error: {0}")] + Query(String), + + /// The requested record could not be found. + #[error("Record not found")] + NotFound, +} + +/// All errors that can occur while working with epochs. +/// 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)] +pub enum EpochError { + /// Problems with the `.epochconfig` file + #[error("Failed to read epoch configuration")] + ConfigRead(#[source] std::io::Error), + + #[error("Failed to write epoch configuration")] + ConfigWrite(#[source] std::io::Error), + + /// 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), + + /// The user supplied an epoch id or tag that does not exist + #[error("No epoch found for id/tag `{}`", .0)] + EpochNotFound(String), + + /// The user attempted to resolve an epoch that is *ambiguous* – e.g. two + /// tags with the same name or a tag that points to a non‑existent id + #[error("Tag `{}` resolves to either multiple epochs or invalid epoch", .0)] + AmbiguousTag(String), + + /// The epoch folder for the target id is missing + #[error("Missing directory for epoch {} at `{}`", .0, .1.display())] + EpochFolderMissing(EpochId, PathBuf), + + /// There are *future* events left in the current epoch, so you cannot compute `next` + #[error("Cannot compute `next` because there are pending future events")] + FutureEventsExist, + + /// Attempt to switch to an epoch that has already been *advanced* past + /// the current world state (e.g. you are at epoch 5 but try to switch + /// to epoch 7 while epoch 6 is still in the past) + #[error("Cannot switch to epoch `{}` – the world has already advanced beyond it", .0)] + SwitchPastEpoch(EpochId), + + /// The supplied epoch id is out of bounds (negative, zero or too large) + #[error("Invalid epoch id `{}` – must be a positive, non‑overflowing integer", .0)] + InvalidEpochId(EpochId), + + /// A tag that the user tried to assign already exists + #[error("Tag `{}` already exists for epoch {}", .1, .0)] + TagAlreadyExists(EpochId, String), + + // /// An attempt to delete or reset events failed because the world + // /// was in an inconsistent state (e.g. `reset` called before any `switch`) + // #[error("Reset failed: no epoch has been switched to yet")] + // ResetBeforeSwitch, + /// The parent epoch referenced in an `EpochInfo` cannot be found + #[error("Parent epoch {} referenced by epoch {} does not exist", .0, .1)] + ParentEpochMissing(EpochId, EpochId), + + /// Generic I/O errors that bubble up from other sub‑tasks + #[error("I/O error")] + Io(#[source] std::io::Error), + + /// Serialization / deserialization errors that are not caught above + #[error("Serialization error: {0}")] + Serde(#[source] serde_json::Error), + + /// The epoch tree is in an incorrect state + #[error("Invalid epoch tree at {0}")] + TreeInvalid(EpochId, String), + + /// 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) + } +} + +impl From for EpochError { + fn from(e: serde_json::Error) -> Self { + EpochError::Serde(e) + } +} diff --git a/lib_efo/src/lib.rs b/lib_efo/src/lib.rs index 9cf4fae..6addecf 100644 --- a/lib_efo/src/lib.rs +++ b/lib_efo/src/lib.rs @@ -30,37 +30,57 @@ //! //! // persist it //! world.save().expect("save world"); -//! ```// -// pub mod character; -// pub mod epoch; -// pub mod event; -// pub mod link; -// pub mod org; -// pub mod storage; -// pub mod town; -// pub mod util; -// pub mod world; +//! ``` -// pub use character::{Character, CharacterManager}; -// pub use epoch::{Epoch, EpochManager}; -// pub use event::{Event, EventManager}; -// pub use link::{Link, LinkKind, LinkManager}; -// pub use org::{Org, OrgManager}; -// pub use storage::{JsonStore, Store, YamlStore}; -// pub use town::{Town, TownManager}; -// pub use world::{Context, World}; +pub mod error; +// use async_trait::async_trait; +use std::io::Result as IoResult; -pub fn add(left: u64, right: u64) -> u64 { - left + right +/// Marker trait for anything that can be persisted via the `Store` abstraction. +/// +/// It is a thin wrapper around `serde::Serialize` and `serde::de::DeserializeOwned` so that the +/// compiler can infer that the type is both serialisable *and* deserialisable. +pub trait Persistable: serde::Serialize + serde::de::DeserializeOwned {} +impl Persistable for T where T: serde::Serialize + serde::de::DeserializeOwned + 'static {} + +/// The generic store. All domain entities that need persistence should use this trait. +/// It can be backed by a file, a DB, an HTTP API, … as long as it knows how to read/write the type `T`. +pub trait Store +where + T: Persistable, +{ + /// Read a value identified by `id`. + fn read(&self, id: &str) -> IoResult>; + + /// Write (or overwrite) a value identified by `id`. + fn write(&self, id: &str, value: &T) -> IoResult<()>; + + /// Delete the value identified by `id`. + fn delete(&self, id: &str) -> IoResult<()>; + + /// List all ids known to this store. + fn list_ids(&self) -> IoResult>; } -#[cfg(test)] -mod tests { - use super::*; +// /// 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 +// } - #[test] - fn it_works() { - let result = add(2, 2); - assert_eq!(result, 4); - } -} +// /// 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()), +// } +// } +// } +// +// + +mod epoch_struct;