Some refactoring
Build Successful The build was successful
Gitea/epoch_forge/pipeline/head This commit looks good Details

This commit is contained in:
Dandaedre 2025-11-16 02:28:23 +01:00
parent ee53efd695
commit 0bec514226
6 changed files with 126 additions and 122 deletions

View File

@ -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 <epoch>`
#[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<Self, Self::Err> {
if let Ok(num) = s.parse::<u64>() {
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);

View File

@ -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 <epoch>`
#[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<Self, Self::Err> {
if let Ok(num) = s.parse::<u64>() {
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),
))
}
}
}

View File

@ -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;

View File

@ -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;

View File

@ -117,3 +117,27 @@ impl From<serde_json::Error> 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 },
// }