diff --git a/Cargo.lock b/Cargo.lock index 56e1f13..b2e6278 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -161,6 +161,27 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75" +[[package]] +name = "derive_more" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "093242cf7570c207c83073cf82f79706fe7b8317e98620a47d5be7c3d8497678" +dependencies = [ + "derive_more-impl", +] + +[[package]] +name = "derive_more-impl" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bda628edc44c4bb645fbe0f758797143e4e07926f7ebf4e9bdfbd3d2ce621df3" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "unicode-xid", +] + [[package]] name = "errno" version = "0.3.14" @@ -206,6 +227,7 @@ name = "lib_efo" version = "0.1.0" dependencies = [ "clap", + "derive_more", "miette", "serde", "serde_json", @@ -478,6 +500,12 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + [[package]] name = "utf8parse" version = "0.2.2" diff --git a/bin_efo/src/commands.rs b/bin_efo/src/commands.rs index 507983a..a9861be 100644 --- a/bin_efo/src/commands.rs +++ b/bin_efo/src/commands.rs @@ -6,6 +6,7 @@ //! `efo::main.rs` can simply `use commands::*;` and dispatch based on the //! clap‑parsed enum. +#![warn(missing_docs, clippy::missing_docs_in_private_items)] + 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 677c6c8..96e191f 100644 --- a/bin_efo/src/commands/epoch.rs +++ b/bin_efo/src/commands/epoch.rs @@ -2,15 +2,16 @@ //! //! Handles all epoch‑related logic – logging, switching, computing the //! next epoch, and resetting future events. +#![warn(missing_docs, clippy::missing_docs_in_private_items)] +use crate::error::AppError; use lib_efo::{ epoch_struct::{ConfigWritable, EpochConfig}, error::EpochError, }; -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<(), AppError> { @@ -20,7 +21,7 @@ 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(args) => handle_next(args), + cli_epoch::EpochCmd::Next(args) => handle_next(args, &mut main_epoch), 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), @@ -28,37 +29,89 @@ pub fn handle_cmd(cmd: cli_epoch::EpochCmd) -> Result<(), AppError> { } } +/// Show the diff between two epochs fn handle_diff(args: cli_epoch::Diff) -> Result<(), AppError> { let _ = args; unimplemented!("Blocker: There is actually no way to diff the world yet") } +/// Show a log of all different epochs fn handle_log(_args: cli_epoch::Log) -> Result<(), AppError> { println!("Epoch log (most recent first):"); unimplemented!("Just needs for the epoch to implement lvels of displays trait: DisplayLevels"); } -/// Switch the current epoch for another +/// Switches the current epoch to the one specified by the user. +/// +/// This updates the in‑memory configuration, reloads the target epoch, +/// updates the epoch identifier, and persists the changes. +/// +/// # Arguments +/// * `args` – `cli_epoch::Switch` containing the target epoch identifier. +/// * `main_epoch` – mutable reference to the current `EpochConfig`. fn handle_switch(args: cli_epoch::Switch, main_epoch: &mut EpochConfig) -> Result<(), AppError> { let target = main_epoch.get(&args.target)?; main_epoch.try_load(&target)?; main_epoch.epoch_id = target; println!("Switched to epoch {:?}", target); - main_epoch.save( - "Saving modified epoch config".into(), - lib_efo::epoch_struct::SaveMode::Erase, + main_epoch.save_with_context( + "Saving modified epoch config", + &lib_efo::epoch_struct::SaveMode::Erase, )?; Ok(()) } -fn handle_next(args: cli_epoch::Next) -> Result<(), AppError> { - let _ = args; - println!("⚡ Next",); - unimplemented!("Missing logic to process a next event"); +/// Handle the `next` sub‑command. +/// +/// Advances the epoch to the next scheduled event. If the current +/// configuration contains any epochs with an identifier larger than +/// the current one, an error is returned – otherwise the next epoch +/// is computed. +/// +/// # Arguments +/// * `main_epoch` – mutable reference to the current `EpochConfig` +/// (the `cli_epoch::Next` argument is unused). +/// +/// # Returns +/// * `Ok(())` if the next epoch was successfully computed. +/// * `Err(AppError::Epoch(EpochError::FutureEpochExist))` if there are +/// no future epochs to advance to. +fn handle_next(_args: cli_epoch::Next, main_epoch: &mut EpochConfig) -> Result<(), AppError> { + let current_id = main_epoch.epoch_id; + + // Check that there are no future epochs + if main_epoch + .list_existing_epochs + .keys() + .any(|id| id > ¤t_id) + { + Err(AppError::Epoch(EpochError::FutureEpochExist)) + } else { + let new_epoch = main_epoch.compute_next()?; + // This epoch is not used or checked in this command, just directly inserted and saved + + // TODO: Finish + main_epoch + .insert_and_save(new_epoch, &lib_efo::epoch_struct::SaveMode::DoNotErase) + .unwrap(); + // TODO: Does main save or do we save, I feel like we should save + Ok(()) + } } -/// Reset all future events by deleting them +/// Handle the `reset` sub‑command. +/// +/// Deletes all epochs whose identifier is greater than the current one, +/// effectively rolling back to the present epoch. +/// +/// # Arguments +/// * `main_epoch` – mutable reference to the current `EpochConfig` +/// (the `cli_epoch::Reset` argument is unused). +/// +/// # Returns +/// * `Ok(())` if all future epochs were successfully removed. +/// * `Err(AppError)` if any deletion fails. fn handle_reset(args: cli_epoch::Reset, main_epoch: &mut EpochConfig) -> Result<(), AppError> { let _ = args; let current_id = main_epoch.epoch_id; @@ -74,7 +127,21 @@ fn handle_reset(args: cli_epoch::Reset, main_epoch: &mut EpochConfig) -> Result< Ok(()) } -/// Adds a tag to the current epoch +/// Handle the `tag` sub‑command. +/// +/// Adds a tag to the current epoch. The tag must not already exist +/// elsewhere in the configuration; otherwise an error is returned. +/// +/// # Arguments +/// * `args` – `cli_epoch::Tag` containing the tag to add. +/// * `main_epoch` – mutable reference to the current `EpochConfig`. +/// +/// # Returns +/// * `Ok(())` if the tag was successfully added. +/// * `Err(AppError::Epoch(EpochError::TagAlreadyExists))` if the tag +/// already exists in another epoch. +/// * `Err(AppError::Epoch(EpochError::Unknown))` if the epoch cannot +/// be found or saved. 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())?; @@ -88,22 +155,23 @@ fn handle_taging(args: cli_epoch::Tag, main_epoch: &mut EpochConfig) -> Result<( } // Modify the epoch to add the tag inside + #[allow(clippy::unwrap_used)] 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, + current_epoch_info.save_with_context( + "Saving modified epoch", + &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, + main_epoch.save_with_context( + "Saving modified main config", + &lib_efo::epoch_struct::SaveMode::Erase, )?; Ok(()) } else { @@ -113,7 +181,10 @@ fn handle_taging(args: cli_epoch::Tag, main_epoch: &mut EpochConfig) -> Result<( } } -/// Basic sanity check +/// Performs a basic sanity check. +/// +/// Currently unimplemented – the function will panic at runtime. +/// fn handle_fsck(args: cli_epoch::Fsck, main_epoch: &mut EpochConfig) -> Result<(), AppError> { let _ = main_epoch; let _ = args; diff --git a/bin_efo/src/commands/epoch/cli_epoch.rs b/bin_efo/src/commands/epoch/cli_epoch.rs index c27e836..1035258 100644 --- a/bin_efo/src/commands/epoch/cli_epoch.rs +++ b/bin_efo/src/commands/epoch/cli_epoch.rs @@ -1,7 +1,27 @@ +//! # `epoch` CLI module +//! +//! This module defines the command‑line interface for the `efo epoch` +//! sub‑command. +//! +//! ## Overview of commands +//! +//! * **`log`** – list epochs in a git‑log style. +//! * **`switch`** – switch to a specific epoch (by id, name or tag). +//! * **`next`** – compute the next epoch from the current one. +//! * **`reset`** – delete all future events after the current epoch. +//! * **`diff`** – show differences between two epochs. +//! * **`tag`** – add a tag to the current epoch. +//! * **`fsck`** – perform basic filesystem level maintenance. + +#![warn(missing_docs, clippy::missing_docs_in_private_items)] + use clap::{Args, Subcommand}; use lib_efo::epoch_struct::EpochIdentifier; -/// The outer clap entry that the binary will dispatch to +/// Top‑level sub‑command for the `efo epoch` command. +/// +/// Each variant represents a distinct epoch operation that can be +/// invoked from the command line. #[derive(Subcommand, Debug)] pub enum EpochCmd { /// List all epochs – a git‑log style view @@ -18,15 +38,19 @@ pub enum EpochCmd { /// Show the differences between two epochs Diff(Diff), - // Tag and next could be implemented as subcommands of epoch - // even if they barely belong here + + /// Add a tag to the current epoch Tag(Tag), /// Basic filesystem level maintenance Fsck(Fsck), } -/// `efo epoch log` +/// Displays a git‑log style list of epochs. +/// +/// # Arguments +/// * `limit` – (Optional) Limit the number of entries shown. +/// Default: `50`. #[derive(Args, Debug)] pub struct Log { /// (Optional) Limit the number of entries shown. @@ -34,7 +58,12 @@ pub struct Log { pub limit: usize, } -/// `efo epoch switch ` +/// Switches to the specified epoch. The target can be an integer, +/// a name, or a tag. +/// +/// # Arguments +/// * `target` – The epoch to switch to. +/// * `force` – If set, drops all pending work and forces the switch. #[derive(Args, Debug)] pub struct Switch { /// The epoch to switch to – can be an integer, a name, or a tag. @@ -46,15 +75,20 @@ pub struct Switch { pub force: bool, } -/// `efo epoch next` +/// Computes the next epoch from the current one. #[derive(Args, Debug)] pub struct Next; -/// `efo epoch reset` +/// Deletes all future events after the current epoch. #[derive(Args, Debug)] pub struct Reset; -/// `efo epoch diff ` +/// Shows the differences between two epochs. +/// +/// # Arguments +/// * `start` – The starting point to compute the differences. +/// * `end` – The end point to compute the differences; defaults to the +/// current epoch if omitted. #[derive(Args, Debug)] pub struct Diff { #[arg(required = true)] @@ -65,7 +99,10 @@ pub struct Diff { pub end: Option, } -/// `efo epoch tag "tag"` +/// Adds a tag to the current epoch. +/// +/// # Arguments +/// * `tag` – The tag to tag the current epoch with. #[derive(Args, Debug)] pub struct Tag { #[arg(required = true)] @@ -73,6 +110,6 @@ pub struct Tag { pub tag: String, } -/// `efo epoch fsck` +/// Performs basic filesystem level maintenance. #[derive(Debug, Args)] pub struct Fsck {} diff --git a/bin_efo/src/commands/error.rs b/bin_efo/src/commands/error.rs deleted file mode 100644 index d4ba9bd..0000000 --- a/bin_efo/src/commands/error.rs +++ /dev/null @@ -1,7 +0,0 @@ -//! 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; diff --git a/bin_efo/src/commands/init.rs b/bin_efo/src/commands/init.rs index 8e5527f..9cfa55d 100644 --- a/bin_efo/src/commands/init.rs +++ b/bin_efo/src/commands/init.rs @@ -1,3 +1,16 @@ +//! # `init` module +//! +//! Provides the implementation of the `init` sub‑command for the +//! command‑line interface. The sub‑command creates an empty +//! repository, writes the default configuration (`.epoch`), +//! and sets up the first epoch (epoch 0). +//! +//! The main public API consists of: +//! +//! * `InitCmd` – a struct containing the command‑line arguments. + +#![warn(missing_docs, clippy::missing_docs_in_private_items)] + use clap::Args; use lib_efo::epoch_struct::{ConfigWritable, EpochInfo}; use lib_efo::{epoch_struct::EpochConfig, error::EpochError}; @@ -6,13 +19,21 @@ use std::fs::read_dir; use crate::error::AppError; #[derive(Args, Debug)] + +/// Arguments for the `init` subcommand. +/// +/// The `--force` flag forces initialisation even when the target +/// directory already contains files. pub struct InitCmd { /// Force initialisation even if the directory isn't empty #[arg(long)] force: bool, } -/// Init an empty repository +/// Initialise an empty repository. +/// +/// Creates the default `EpochConfig`, verifies that the target directory +/// is empty, and writes the initial configuration and epoch data. pub fn init(args: &InitCmd) -> Result<(), AppError> { let epoch_config = EpochConfig::default(); let root = epoch_config.save_folder(); @@ -26,9 +47,9 @@ pub fn init(args: &InitCmd) -> Result<(), AppError> { } init_epoch(args)?; epoch_config - .save( - "Creatig initial config".into(), - lib_efo::epoch_struct::SaveMode::DoNotErase, + .save_with_context( + "Creatig initial config", + &lib_efo::epoch_struct::SaveMode::DoNotErase, ) .map_err(|_| EpochError::AlreadyInitialized { advice: Some( @@ -39,13 +60,16 @@ pub fn init(args: &InitCmd) -> Result<(), AppError> { Ok(()) } -/// Tries to init the epoch 0 +/// Helper that creates the initial epoch (epoch 0). +/// +/// This function is not part of the public API; it is kept internal +/// to `init`. It creates an empty `EpochInfo`, crea fn init_epoch(_args: &InitCmd) -> Result<(), AppError> { let empty = EpochInfo::default(); _ = empty.create_subfolders(); - empty.save( - "Creating empty epoch file 0".into(), - lib_efo::epoch_struct::SaveMode::DoNotErase, + empty.save_with_context( + "Creating empty epoch file 0", + &lib_efo::epoch_struct::SaveMode::DoNotErase, )?; Ok(()) } diff --git a/bin_efo/src/error.rs b/bin_efo/src/error.rs index 9820956..0199a3c 100644 --- a/bin_efo/src/error.rs +++ b/bin_efo/src/error.rs @@ -3,6 +3,8 @@ //! `AppError` aggregates all error kinds that may surface during a command //! execution: parsing, I/O, epoch logic, storage, and a catch‑all. +#![warn(missing_docs, clippy::missing_docs_in_private_items)] + use lib_efo::error::{EpochError, StorageError}; use miette::Diagnostic; use thiserror::Error; diff --git a/bin_efo/src/main.rs b/bin_efo/src/main.rs index d5e4391..4654c76 100644 --- a/bin_efo/src/main.rs +++ b/bin_efo/src/main.rs @@ -19,6 +19,8 @@ //! ```sh //! efo epoch switch 5 //! ``` + +#![warn(missing_docs, clippy::missing_docs_in_private_items)] use clap::{Parser, Subcommand}; use crate::commands::init::InitCmd; @@ -26,18 +28,28 @@ use crate::{commands::epoch::cli_epoch::EpochCmd, error::AppError}; mod commands; mod error; -/// Root parser – the “efo” program +/// The root command‑line parser for the `efo` binary. +/// +/// It uses `clap` to parse the top‑level sub‑commands (`init`, `epoch`, …) +/// and stores them in the `command` field. #[derive(Parser, Debug)] #[command(name = "efo")] #[command(about = "Epoch Forge – manage organisations over time")] struct Cli { #[command(subcommand)] + /// The top level command to be executed command: TopLevelCmd, } +/// Enumeration of the top‑level sub‑commands that `efo` accepts. +/// +/// Each variant corresponds to a single sub‑command and holds its own +/// argument structure. #[derive(Subcommand, Debug)] enum TopLevelCmd { + /// Initialise a new epoch folder. Init(InitCmd), + /// Advance or query the current epoch. #[command(subcommand)] Epoch(EpochCmd), // Event(commands::event::EventCmd), @@ -47,6 +59,11 @@ enum TopLevelCmd { // Link(commands::link::LinkCmd), } +/// Program entry point. +/// +/// Parses the command‑line arguments and dispatches to the selected +/// sub‑command. Errors returned by the sub‑command handlers are printed +/// to stdout and returned as a `miette::Result<()>`. fn main() -> miette::Result<()> { let cli = Cli::parse(); @@ -66,6 +83,19 @@ fn main() -> miette::Result<()> { Ok(()) } +/// Dispatches the parsed command to the appropriate handler. +/// +/// # Arguments +/// * `cli` – The parsed command‑line options. +/// +/// # Returns +/// * `Ok(())` on success. +/// * `Err(AppError)` if the chosen sub‑command handler fails. +/// +/// The function matches on the `TopLevelCmd` variant and calls the +/// corresponding handler in the `commands` module. Any error is +/// propagated to the caller, which in `main` will be printed to +/// stdout and returned as a `miette::Result<()>`. fn exec_dispatch(cli: Cli) -> Result<(), AppError> { match cli.command { TopLevelCmd::Init(cmd) => { diff --git a/lib_efo/Cargo.toml b/lib_efo/Cargo.toml index 9398e9c..734b55e 100644 --- a/lib_efo/Cargo.toml +++ b/lib_efo/Cargo.toml @@ -9,3 +9,4 @@ serde = {workspace = true} thiserror = {workspace = true} clap = {workspace = true} miette = {workspace = true} +derive_more = { version = "2.0.1", features = ["display"] } diff --git a/lib_efo/src/epoch_struct.rs b/lib_efo/src/epoch_struct.rs index b53e425..8432369 100644 --- a/lib_efo/src/epoch_struct.rs +++ b/lib_efo/src/epoch_struct.rs @@ -18,6 +18,7 @@ //! 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. +#![warn(missing_docs, clippy::missing_docs_in_private_items)] use clap::error::ErrorKind; use serde::{Deserialize, Serialize}; @@ -32,8 +33,12 @@ use std::{ use crate::{epoch_struct, error::EpochError, io_err_with_help}; +// TODO: Try to load from a config and have it inserted as a backup +/// The subfolder naming convention static SUBFOLDER_NAMING: &str = "epoch"; +/// The main name of the epoch static MAIN_NAME: &str = ".epoch"; +/// The subname of the epochinfo static SUB_NAME: &str = ".epochinfo"; /// The file written to *.epochconfig* that tells the CLI which @@ -155,6 +160,7 @@ impl EpochConfig { } } + /// Return the name of the subfolder used to save this structure fn save_subfolder(&self) -> String { format!("{}/", SUBFOLDER_NAMING) } @@ -174,6 +180,41 @@ impl EpochConfig { )?; Ok(()) } + + /// Compute the next epoch, by defering the work to the Epochinfo -> World + /// Return the id of the next (and now present) epoch + pub fn compute_next(&mut self) -> Result { + // unimplemented!() + // TODO: Implement this + print!("DEBUG LINE: COMPUTING NEXT EPOCH"); + // New fake epoch + Ok(EpochInfo::with_id(&self.epoch_id.next())) + } + + /// Insert the given epoch and save it + pub fn insert_and_save( + &mut self, + new_epoch: EpochInfo, + save_mode: &SaveMode, + ) -> Result<(), EpochError> { + if self.list_existing_epochs.contains_key(&new_epoch.epoch_id) { + return Err(EpochError::EpochAlreadyExists(new_epoch.epoch_id)); + } + + // TODO: Finish + new_epoch + .save_with_context("Saving new epoch without subfolders", save_mode) + .unwrap(); + new_epoch.create_subfolders().unwrap(); + new_epoch.create_subfolders().unwrap(); + new_epoch.create_subfolders().unwrap(); + new_epoch + .save_with_context("Saving new epoch", save_mode) + .unwrap(); + + // Add the epoch to the list of epochs + Ok(()) + } } /// Trait representing a serialisable / writable config @@ -194,19 +235,22 @@ pub trait ConfigWritable: Serialize { } /// Save the config into it's nominal path - fn save( + /// + /// This command will NOT create all subdirectories + fn save_with_context( &self, // Very unsure about this versus a macro - action_description: String, - do_not_erase: SaveMode, + action_description: &str, + do_not_erase: &SaveMode, // advice: Option, ) -> Result<(), EpochError> { - let mut f = match do_not_erase { + 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_description)?).map_err(EpochError::ConfigWrite)?; + write!(f, "{}", self.as_json(action_description.to_owned())?) + .map_err(EpochError::ConfigWrite)?; Ok(()) } } @@ -254,6 +298,8 @@ impl Default for EpochInfo { } } +/// Which save mode to use +#[allow(missing_docs)] pub enum SaveMode { DoNotErase, Erase, @@ -261,6 +307,8 @@ pub enum SaveMode { impl EpochInfo { /// Create all subfolders as needed + /// + /// This command can be safely used even if the folder already exists pub fn create_subfolders(&self) -> Result<(), EpochError> { io_err_with_help!(create_dir_all(self.save_folder()), "Creating subfolders") } @@ -301,6 +349,11 @@ impl EpochId { pub fn new(id: u64) -> Self { Self { id } } + + /// Return the next epochId + pub fn next(&self) -> Self { + Self { id: self.id + 1 } + } } impl std::ops::Deref for EpochId { diff --git a/lib_efo/src/error.rs b/lib_efo/src/error.rs index be6fc47..7f8ed38 100644 --- a/lib_efo/src/error.rs +++ b/lib_efo/src/error.rs @@ -1,9 +1,15 @@ //! 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`. +//! 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`. +//! +//! The public items below are all lightweight error types that can be +//! produced by the storage layer or the epoch handling subsystem. +#![warn(missing_docs, clippy::missing_docs_in_private_items)] + +use derive_more::Display; use std::{num::ParseIntError, path::PathBuf}; use thiserror::Error; @@ -12,6 +18,10 @@ use crate::epoch_struct::EpochId; use miette::Diagnostic; /// Errors that can be returned by the storage layer. +/// +/// The variants are intentionally small – each one carries all the +/// information required to surface a helpful message to the user. +// TODO: Remove or rethink these errors #[derive(Debug, Error, Diagnostic)] pub enum StorageError { /// Problems with serialisation / deserialisation. @@ -32,157 +42,207 @@ pub enum StorageError { } /// 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 +/// +/// 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). +// TODO: Split effectively user errors to avoid the usage of advice and such #[derive(Error, Debug, Diagnostic)] pub enum EpochError { - /// Problems with the `.epochconfig` file + /// Problems with the `.epochconfig` file. #[error("Failed to read epoch configuration")] + #[diagnostic(code(EpochError::ConfigRead))] ConfigRead(#[source] std::io::Error), + /// Failed to write the epoch configuration. #[error("Failed to write epoch configuration")] + #[diagnostic(code(EpochError::ConfigWrite))] ConfigWrite(#[source] std::io::Error), + /// Failed to create the epoch configuration. #[error("Failed to create the epoch configuration")] #[help("Make sure the path is writable")] + #[diagnostic(code(EpochError::ConfigCreation))] ConfigCreation(String, #[source] std::io::Error), + /// This directory is already an epoch folder and thus cannot be initialized. #[error("This directory is already an epoch folder and thus cannot be initialized")] #[diagnostic(code(EpochError::AlreadyInitialized))] AlreadyInitialized { #[help] + /// User given advice advice: Option, }, + /// This directory isn't empty and thus cannot be initialized. #[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 of the file causing problem name: Option, - + /// Trick used to have a cute line showing the following error message #[label("This file is present and forbid the command to execute properly")] show_label: Option<(usize, usize)>, }, - /// Problems while serialising / deserialising an `EpochInfo` + /// Problems while serialising / deserialising an `EpochInfo`. #[error("Failed to parse `.epochinfo` in epoch {0} ({1}): {2}")] + #[diagnostic(code(EpochError::EpochInfoParse))] EpochInfoParse(EpochId, PathBuf, #[source] serde_json::Error), + /// Failed to write `.epochinfo` in epoch {id} ({path}). #[error("Failed to write `.epochinfo` in epoch {id} ({path})")] #[diagnostic(code(EpochError::EpochInfoWrite))] EpochInfoWrite { + /// The id of the epoch id: EpochId, + /// The path of the epoch path: PathBuf, - + /// An optionnal help message #[help] help: Option, - + /// The source error #[source] src: Option, }, - /// The user supplied an epoch id or tag that does not exist - #[error("No epoch found for id/tag `{}`", .0)] + /// The user supplied an epoch id or tag that does not exist. + #[error("No epoch found for id/tag `{0}`")] + #[diagnostic(code(EpochError::EpochNotFound))] 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)] + /// The user attempted to resolve an epoch that is ambiguous. + #[error("Tag `{0}` resolves to either multiple epochs or invalid epoch")] + #[diagnostic(code(EpochError::AmbiguousTag))] AmbiguousTag(String), - /// The epoch folder for the target id is missing - #[error("Missing directory for epoch {} at `{}`", .0, .1.display())] + /// The epoch folder for the target id is missing. + #[error("Missing directory for epoch {0} at `{1}`")] + #[diagnostic(code(EpochError::EpochFolderMissing))] 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, + /// A future epoch exists, forbidding you to compute `next` and overriding them. + #[diagnostic(help("Use epoch reset if you want to erase all future epochs first"))] + #[error("Cannot compute `next` because future epoch exists")] + #[diagnostic(code(EpochError::FutureEpochExist))] + FutureEpochExist, - /// 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)] + /// A specific epoch exists, forbidding the further execution of the command. + #[diagnostic(help("Use epoch reset or manually delete the epoch {0}"))] + #[error("The epoch {0} exists forbidding the execution of the command")] + #[diagnostic(code(EpochError::EpochAlreadyExists))] + EpochAlreadyExists(EpochId), + + /// Attempt to switch to an epoch that has already been advanced past. + #[error("Cannot switch to epoch `{0}` – the world has already advanced beyond it")] + #[diagnostic(code(EpochError::SwitchPastEpoch))] 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)] + /// The supplied epoch id is out of bounds (negative, zero or too large). + #[error("Invalid epoch id `{0}` – must be a positive, non‑overflowing integer")] + #[diagnostic(code(EpochError::InvalidEpochId))] InvalidEpochId(EpochId), - /// A tag that the user tried to assign already exists - #[error("Tag `{}` already exists for epoch {}", .1, .0)] + /// A tag that the user tried to assign already exists. + #[error("Tag `{1}` already exists for epoch {0}")] + #[diagnostic(code(EpochError::InvalidEpochId))] 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 + /// The parent epoch referenced in an `EpochInfo` cannot be found. #[error("Parent epoch {} referenced by epoch {} does not exist", .0, .1)] + #[diagnostic(code(EpochError::ParentEpochMissing))] ParentEpochMissing(EpochId, EpochId), - /// Generic I/O errors that bubble up from other sub‑tasks + /// Generic I/O errors that bubble up from other sub‑tasks. #[error("I/O error")] #[diagnostic(code(EpochError::GenericIO))] Io { + /// The source error #[source] source: std::io::Error, - + /// An optionnal help message #[help] help: Option, + /// Where the error originated from + error_line: u32, }, - /// Serialization / deserialization errors that are not caught above + /// Serialization / deserialization errors that are not caught above. #[error("Serialization error from {file_name}")] #[diagnostic(code(EpochError::SerdeError))] Serde { + /// The source error #[source] source: serde_json::Error, - + /// The file that was being written file_name: String, - + /// An optionnal help message #[help] help: Option, }, - /// The epoch tree is in an incorrect state + /// The epoch tree is in an incorrect state. #[error("Invalid epoch tree at {0}")] + #[diagnostic(code(EpochError::TreeInvalid))] TreeInvalid(EpochId, String), - /// The main folder is not an epoch folder + /// The main folder is not an epoch folder. #[error("The given directory ({0:?}) is not an epoch folder")] + #[diagnostic(code(EpochError::MainFolderInvalid))] MainFolderInvalid(String), - /// Couldn't parse an EpochId + /// Couldn't parse an `EpochId`. #[error("The id ({0}) couldn't be converted to a valid EpochId")] - #[diagnostic(code(EpochError::ConversionIdImpossible))] + #[diagnostic(code(EpochError::ParsingEpochId))] ParsingEpochId(#[from] ParseIntError), - /// Any other error that didn't fit into the above categories + /// Any other error that didn't fit into the above categories. #[error("An unknown error occurred: {0}")] + #[diagnostic(code(EpochError::Unknown))] Unknown(String), - /// User error, meant to be very explicit over what happened and what to do + /// User error, meant to be very explicit over what happened and what to do. #[error("An user facing error")] - UserError(#[help] String), + #[diagnostic(code(EpochError::UserError))] + UserError(#[help] UserErrors), } +/// A small enum of explicit user‑facing error messages. +/// +/// The variants are deliberately simple; each one is rendered with a +/// clear message via `derive_more::Display`. +#[derive(Debug, Display, Diagnostic, Error)] +pub enum UserErrors { + /// The classic mistake + #[display("The user did a very bad thing")] + #[diagnostic(code(UserErrors::DSItF))] + DSItF, +} // macro_rules! err_with { // ($expr:expr, $err_ty:ty {$($field:ident : $value:expr),* $(,)?}) => {{ // $expr.map_err(|e| { $err_ty { $($field: $value),* } }) // }}; // } +/// Helper macro to convert a `std::io::Error` into an `EpochError::Io` +/// with an attached help message. +/// +/// ```rust +/// # use lib_efo::error::io_err_with_help; +/// let result: Result<(), std::io::Error> = std::fs::read_to_string("does_not_exist").map(|_| ()); +/// let err = io_err_with_help!(result, "Make sure the file exists"); +/// ``` +/// +/// The macro captures the current line number for debugging purposes. #[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(format!($($help),*)), + error_line: line!(), }) }}; } diff --git a/lib_efo/src/lib.rs b/lib_efo/src/lib.rs index 8a5d8e0..069ce41 100644 --- a/lib_efo/src/lib.rs +++ b/lib_efo/src/lib.rs @@ -17,6 +17,8 @@ //! be persisted easily. The `World` struct also offers a convenient //! `World::load()` / `World::save()` API that uses the default JSON file +#![warn(missing_docs, clippy::missing_docs_in_private_items)] + pub mod epoch_struct; #[macro_use] pub mod error; diff --git a/lib_efo/src/utils.rs b/lib_efo/src/utils.rs index c7963dd..d5c2794 100644 --- a/lib_efo/src/utils.rs +++ b/lib_efo/src/utils.rs @@ -4,6 +4,8 @@ //! //! +#![warn(missing_docs, clippy::missing_docs_in_private_items)] + use std::path::Path; use crate::error::EpochError;