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 e0a76ba..d381520 100644 --- a/bin_efo/Cargo.toml +++ b/bin_efo/Cargo.toml @@ -8,3 +8,5 @@ lib_efo = { path = "../lib_efo" } serde = {workspace = true} clap = {workspace = true} thiserror = {workspace = true} +serde_json = {workspace = true} +miette = {workspace = true} diff --git a/bin_efo/src/commands/mod.rs b/bin_efo/src/commands.rs similarity index 96% rename from bin_efo/src/commands/mod.rs rename to bin_efo/src/commands.rs index 07c3b87..507983a 100644 --- a/bin_efo/src/commands/mod.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 a88d511..587f283 100644 --- a/bin_efo/src/commands/epoch.rs +++ b/bin_efo/src/commands/epoch.rs @@ -1,157 +1,113 @@ -// 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 lib_efo::{ + epoch_struct::{ConfigWritable, EpochConfig}, + error::EpochError, +}; -// 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) +use crate::error::AppError; -/// 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), +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 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, &mut main_epoch), + 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), + } } -/// `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, +fn handle_diff(args: cli_epoch::Diff) -> Result<(), AppError> { + let _ = args; + unimplemented!("Blocker: There is actually no way to diff the world yet") } -/// `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, +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"); } -/// `efo epoch next` -#[derive(Args, Debug)] -pub struct Next; +/// 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)?; + main_epoch.try_load(&target)?; + main_epoch.epoch_id = target; -/// `efo epoch reset` -#[derive(Args, Debug)] -pub struct Reset; + println!("Switched to epoch {:?}", target); + main_epoch.save( + "Saving modified epoch config".into(), + lib_efo::epoch_struct::SaveMode::Erase, + )?; + Ok(()) +} -// /// **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), -// } -// } +fn handle_next(args: cli_epoch::Next) -> Result<(), AppError> { + let _ = args; + println!("⚡ Next",); + unimplemented!("Missing logic to process a next event"); +} -// /// ---------- helpers ---------- +/// Reset all future events by deleting them +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)? + } -// 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(()) -// } + println!("All future events deleted – back to epoch {current_id}",); + 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)?; +/// 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())?; -// world.set_epoch(target_id); -// println!( -// "Switched to epoch #{} – {}", -// target_id, -// world.current_context().date -// ); -// Ok(()) -// } + // 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(), + )))?; + } -// 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(()) -// } + // 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 new file mode 100644 index 0000000..25b53a4 --- /dev/null +++ b/bin_efo/src/commands/epoch/cli_epoch.rs @@ -0,0 +1,71 @@ +use clap::{Args, Subcommand}; +use lib_efo::epoch_struct::EpochIdentifier; + +/// 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 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 + Tag(Tag), +} + +/// `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; + +/// `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, +} + +/// `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/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/commands/init.rs b/bin_efo/src/commands/init.rs new file mode 100644 index 0000000..8e5527f --- /dev/null +++ b/bin_efo/src/commands/init.rs @@ -0,0 +1,51 @@ +use clap::Args; +use lib_efo::epoch_struct::{ConfigWritable, EpochInfo}; +use lib_efo::{epoch_struct::EpochConfig, error::EpochError}; +use std::fs::read_dir; + +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 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 { + name: None, + show_label: None, + })?; + } + init_epoch(args)?; + epoch_config + .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 +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, + )?; + Ok(()) +} diff --git a/bin_efo/src/error.rs b/bin_efo/src/error.rs index 6974f51..9820956 100644 --- a/bin_efo/src/error.rs +++ b/bin_efo/src/error.rs @@ -3,29 +3,32 @@ //! `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 miette::Diagnostic; use thiserror::Error; -use crate::commands::error::EpochError; - /// 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 7caac44..d5e4391 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}; - +use crate::commands::init::InitCmd; +use crate::{commands::epoch::cli_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, @@ -74,26 +37,45 @@ struct Cli { #[derive(Subcommand, Debug)] enum TopLevelCmd { - /// Epoch‑related actions - + Init(InitCmd), #[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(); +fn main() -> miette::Result<()> { + 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 … - // } + 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); + Err(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!("") + } + } + Ok(()) +} 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 fa12405..131dd3a 100644 --- a/lib_efo/src/epoch_struct.rs +++ b/lib_efo/src/epoch_struct.rs @@ -19,10 +19,24 @@ //! files, just like a git repository tracks its commits and //! `HEAD` pointer. +use clap::error::ErrorKind; use serde::{Deserialize, Serialize}; -use std::{collections::HashMap, fmt}; +use std::{ + collections::HashMap, + fmt, + fs::{File, create_dir_all, read_to_string, remove_dir_all}, + io::Write, + path::Path, + str::FromStr, +}; -/// The file written to *~/.epochconfig* that tells the CLI which +use crate::{epoch_struct, error::EpochError, io_err_with_help}; + +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: @@ -37,9 +51,171 @@ pub struct EpochConfig { pub epoch_id: EpochId, /// Optional human‑friendly tags (e.g. `"winter‑B"`, `"post‑war"`). - pub tags: HashMap, + 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 + #[serde(skip)] + pub list_existing_epochs: HashMap>, +} + +impl Default for EpochConfig { + /// Create an empty config, mainly for initialisation + 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(MAIN_NAME); + + if path.is_file() { + // TODO: write a trait for this + 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( + EpochConfig::default().save_folder(), + )) + } + } + + /// Initialize the epoch more in depth + fn initialize(mut self) -> Result { + 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 = 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 + pub fn try_load(&mut self, epoch_id: &EpochId) -> Result<(), EpochError> { + // 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(), + help: None, + })?; + + // Overwrite the value + *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) + .then_some(epoch_id) + .ok_or(EpochError::EpochFolderMissing( + *epoch_id, + EpochConfig::default().save_folder().into(), + )) + .copied(), + } + } + + 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 +pub trait ConfigWritable: Serialize { + /// 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 { + source: e, + file_name: action, + help: None, + }) + } + + /// Save the config into it's nominal path + fn save( + &self, + // Very unsure about this versus a macro + action_description: 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_description)?).map_err(EpochError::ConfigWrite)?; + Ok(()) + } } /// The metadata file stored inside each epoch directory @@ -73,12 +249,54 @@ pub struct EpochInfo { pub summary: Option, } +impl Default for EpochInfo { + fn default() -> Self { + Self { + epoch_id: epoch_struct::EpochId::new(0), + parent_id: None, + rng_seed: 0, + tags: Vec::new(), + summary: None, + } + } +} + +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") + } + + /// 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 -#[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, } +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) @@ -86,6 +304,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 } } @@ -98,3 +317,62 @@ impl std::ops::Deref for EpochId { &self.id } } + +impl ConfigWritable for EpochConfig { + fn save_path(&self) -> String { + MAIN_NAME.to_string() + } + + fn save_folder(&self) -> String { + ".".to_string() + } +} +impl ConfigWritable for EpochInfo { + fn save_path(&self) -> String { + format!("{}/{}/{}", SUBFOLDER_NAMING, self.epoch_id, SUB_NAME) + } + + fn save_folder(&self) -> String { + format!("{}/{}/", SUBFOLDER_NAMING, 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), + )) + } + } +} diff --git a/lib_efo/src/error.rs b/lib_efo/src/error.rs index 7f34942..99914d7 100644 --- a/lib_efo/src/error.rs +++ b/lib_efo/src/error.rs @@ -4,14 +4,15 @@ //! 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; 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")] @@ -43,12 +44,45 @@ 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 { + #[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)] @@ -91,29 +125,60 @@ 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: {0}")] - Serde(#[source] serde_json::Error), + #[error("Serialization error from {file_name}")] + #[diagnostic(code(EpochError::SerdeError))] + Serde { + #[source] + source: serde_json::Error, + + file_name: String, + + #[help] + help: Option, + }, /// 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), + + /// 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),* } }) +// }}; +// } -impl From for EpochError { - fn from(e: serde_json::Error) -> Self { - EpochError::Serde(e) - } +#[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()), + }) + }}; } diff --git a/lib_efo/src/lib.rs b/lib_efo/src/lib.rs index 802ce5f..8a5d8e0 100644 --- a/lib_efo/src/lib.rs +++ b/lib_efo/src/lib.rs @@ -1,26 +1,27 @@ //! # `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; +#[macro_use] pub mod error; -// use async_trait::async_trait; +pub mod utils; + use std::io::Result as IoResult; /// Marker trait for anything that can be persisted via the `Store` abstraction. @@ -48,26 +49,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()), -// } -// } -// } -// -// - -mod epoch_struct; 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() {} +}