Heavy draft of the epoch/init
Build Successful The build was successful
Gitea/epoch_forge/pipeline/head This commit looks good Details

This commit is contained in:
Dandaedre 2025-11-26 16:18:13 +01:00
parent 0bec514226
commit f75f430c14
10 changed files with 171 additions and 55 deletions

View File

@ -8,3 +8,4 @@ lib_efo = { path = "../lib_efo" }
serde = {workspace = true}
clap = {workspace = true}
thiserror = {workspace = true}
serde_json = "1.0.145"

View File

@ -8,3 +8,4 @@
pub mod epoch;
pub mod error;
pub mod init;

View File

@ -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(())

View File

@ -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(())
}

View File

@ -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(())
}

View File

@ -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<String, u64>,
// /// Absolute path to `epoch/<epoch_id>/`.
// pub path: PathBuf,
/// A hashmap containing the name of all existing epochs, only loaded in memory if used
#[serde(skip)]
pub list_existing_epochs: HashMap<String, Option<EpochInfo>>,
}
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<Self, EpochError> {
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

View File

@ -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<std::io::Error> for EpochError {
}
}
impl From<serde_json::Error> for EpochError {
fn from(e: serde_json::Error) -> Self {
EpochError::Serde(e)
}
}
// impl From<serde_json::Error> for EpochError {
// fn from(e: serde_json::Error) -> Self {
// EpochError::Serde(e)
// }
// }
// /// Errors that can be produced by the epoch system.
// #[derive(Debug, Error)]
// #[allow(dead_code)]

View File

@ -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<T>`) 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<T>`) 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<T>` abstraction.
@ -50,24 +48,3 @@ where
/// List all ids known to this store.
fn list_ids(&self) -> IoResult<Vec<String>>;
}
// /// 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<crate::World> {
// /// 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<crate::World> {
// match self.read("world").await? {
// Some(w) => Ok(w),
// None => Ok(crate::World::new()),
// }
// }
// }
//
//

35
lib_efo/src/utils.rs Normal file
View File

@ -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() {}
}

1
testepo/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
testepo*