diff --git a/.gitignore b/.gitignore index fe7b57a..61afd58 100644 --- a/.gitignore +++ b/.gitignore @@ -26,4 +26,7 @@ Cargo.lock # already existing elements were commented out #/target -testepo +testepo* +naming.json +config.toml +tarpaulin-report.html diff --git a/.run_status.toml b/.run_status.toml new file mode 100644 index 0000000..553a8af --- /dev/null +++ b/.run_status.toml @@ -0,0 +1,8 @@ +[last_run_clean] +run_status = "Success" +lines_parsed = 83 +coverage = 51.17 + +[last_run_clean.run_duration] +secs = 24 +nanos = 975426411 diff --git a/.rust-toolchain.toml b/.rust-toolchain.toml new file mode 100644 index 0000000..f19782d --- /dev/null +++ b/.rust-toolchain.toml @@ -0,0 +1,2 @@ +[toolchain] +channel = "1.92.0" diff --git a/Cargo.lock b/Cargo.lock index 56e1f13..1d8352a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -17,6 +17,15 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" +[[package]] +name = "aho-corasick" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" +dependencies = [ + "memchr", +] + [[package]] name = "anstream" version = "0.6.21" @@ -96,7 +105,12 @@ name = "bin_efo" version = "0.1.0" dependencies = [ "clap", + "colored", + "derive_more", + "env_logger", + "insta", "lib_efo", + "log", "miette", "serde", "serde_json", @@ -109,6 +123,12 @@ version = "2.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "812e12b5285cc515a9c72a5c1d3b6d46a19dac5acfef5265968c166106e31dd3" +[[package]] +name = "bumpalo" +version = "3.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46c5e41b57b8bba42a04676d81cb89e9ee8e859a1a66f80a5a72e1cb76b34d43" + [[package]] name = "cfg-if" version = "1.0.4" @@ -117,9 +137,9 @@ checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" [[package]] name = "clap" -version = "4.5.51" +version = "4.5.53" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c26d721170e0295f191a69bd9a1f93efcdb0aff38684b61ab5750468972e5f5" +checksum = "c9e340e012a1bf4935f5282ed1436d1489548e8f72308207ea5df0e23d2d03f8" dependencies = [ "clap_builder", "clap_derive", @@ -127,9 +147,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.51" +version = "4.5.53" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75835f0c7bf681bfd05abe44e965760fea999a5286c6eb2d59883634fd02011a" +checksum = "d76b5d13eaa18c901fd2f7fca939fefe3a0727a953561fefdf3b2922b8569d00" dependencies = [ "anstream", "anstyle", @@ -155,12 +175,138 @@ version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a1d728cc89cf3aee9ff92b05e62b19ee65a02b5702cff7d5a377e32c6ae29d8d" +[[package]] +name = "cli-table" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14da8d951cef7cc4f13ccc9b744d736963d57863c7e6fc33c070ea274546082c" +dependencies = [ + "cli-table-derive", + "csv", + "termcolor", + "unicode-width 0.2.2", +] + +[[package]] +name = "cli-table-derive" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c1b60bae2c3d45228dfb096046aa51ef6c300de70b658d7a13fcb0c4f832e" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "colorchoice" version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75" +[[package]] +name = "colored" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fde0e0ec90c9dfb3b4b1a0891a7dcd0e2bffde2f7efed5fe7c9bb00e5bfb915e" +dependencies = [ + "windows-sys 0.59.0", +] + +[[package]] +name = "console" +version = "0.15.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "054ccb5b10f9f2cbf51eb355ca1d05c2d279ce1804688d0db74b4733a5aeafd8" +dependencies = [ + "encode_unicode", + "libc", + "once_cell", + "windows-sys 0.59.0", +] + +[[package]] +name = "convert_case" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "633458d4ef8c78b72454de2d54fd6ab2e60f9e02be22f3c6104cdc8a4e0fceb9" +dependencies = [ + "unicode-segmentation", +] + +[[package]] +name = "csv" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52cd9d68cf7efc6ddfaaee42e7288d3a99d613d4b50f76ce9827ae0c6e14f938" +dependencies = [ + "csv-core", + "itoa", + "ryu", + "serde_core", +] + +[[package]] +name = "csv-core" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "704a3c26996a80471189265814dbc2c257598b96b8a7feae2d31ace646bb9782" +dependencies = [ + "memchr", +] + +[[package]] +name = "derive_more" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10b768e943bed7bf2cab53df09f4bc34bfd217cdb57d971e769874c9a6710618" +dependencies = [ + "derive_more-impl", +] + +[[package]] +name = "derive_more-impl" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d286bfdaf75e988b4a78e013ecd79c581e06399ab53fbacd2d916c2f904f30b" +dependencies = [ + "convert_case", + "proc-macro2", + "quote", + "rustc_version", + "syn", + "unicode-xid", +] + +[[package]] +name = "encode_unicode" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" + +[[package]] +name = "env_filter" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bf3c259d255ca70051b30e2e95b5446cdb8949ac4cd22c0d7fd634d89f568e2" +dependencies = [ + "log", + "regex", +] + +[[package]] +name = "env_logger" +version = "0.11.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c863f0904021b108aa8b2f55046443e6b1ebde8fd4a15c399893aae4fa069f" +dependencies = [ + "anstream", + "anstyle", + "env_filter", + "jiff", + "log", +] + [[package]] name = "errno" version = "0.3.14" @@ -171,6 +317,18 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi", + "wasip2", +] + [[package]] name = "gimli" version = "0.32.3" @@ -183,6 +341,17 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "insta" +version = "1.44.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5c943d4415edd8153251b6f197de5eb1640e56d84e8d9159bea190421c73698" +dependencies = [ + "console", + "once_cell", + "similar", +] + [[package]] name = "is_ci" version = "1.2.0" @@ -201,22 +370,65 @@ version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" +[[package]] +name = "jiff" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49cce2b81f2098e7e3efc35bc2e0a6b7abec9d34128283d7a26fa8f32a6dbb35" +dependencies = [ + "jiff-static", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", +] + +[[package]] +name = "jiff-static" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "980af8b43c3ad5d8d349ace167ec8170839f753a42d233ba19e08afe1850fa69" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "js-sys" +version = "0.3.83" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "464a3709c7f55f1f721e5389aa6ea4e3bc6aba669353300af094b29ffbdde1d8" +dependencies = [ + "once_cell", + "wasm-bindgen", +] + [[package]] name = "lib_efo" version = "0.1.0" dependencies = [ "clap", + "cli-table", + "colored", + "derive_more", + "env_logger", + "insta", + "log", "miette", + "once_cell", + "rand", "serde", "serde_json", "thiserror", + "uuid", ] [[package]] name = "libc" -version = "0.2.177" +version = "0.2.178" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2874a2af47a2325c2001a6e6fad9b16a53b802102b528163885171cf92b15976" +checksum = "37c93d8daa9d8a012fd8ab92f088405fb202ea0b6ab73ee2482ae66af4f42091" [[package]] name = "linux-raw-sys" @@ -224,6 +436,12 @@ version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039" +[[package]] +name = "log" +version = "0.4.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" + [[package]] name = "memchr" version = "2.7.6" @@ -278,6 +496,12 @@ dependencies = [ "memchr", ] +[[package]] +name = "once_cell" +version = "1.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" + [[package]] name = "once_cell_polyfill" version = "1.70.2" @@ -290,6 +514,30 @@ version = "4.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c6901729fa79e91a0913333229e9ca5dc725089d1c363b2f4b4760709dc4a52" +[[package]] +name = "portable-atomic" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f84267b20a16ea918e43c6a88433c2d54fa145c92a811b5b047ccbe153674483" + +[[package]] +name = "portable-atomic-util" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8a2f0d8d040d7848a709caf78912debcc3f33ee4b3cac47d73d1e1069e83507" +dependencies = [ + "portable-atomic", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + [[package]] name = "proc-macro2" version = "1.0.103" @@ -308,12 +556,85 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "rand" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1" +dependencies = [ + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "99d9a13982dcf210057a8a78572b2217b667c3beacbf3a0d8b454f6f82837d38" +dependencies = [ + "getrandom", +] + +[[package]] +name = "regex" +version = "1.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "843bc0191f75f3e22651ae5f1e72939ab2f72a4bc30fa80a066bd66edefc24d4" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5276caf25ac86c8d810222b3dbb938e512c55c6831a10f3e6ed1c93b84041f1c" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a2d987857b319362043e95f5353c0535c1f58eec5336fdfcf626430af7def58" + [[package]] name = "rustc-demangle" version = "0.1.26" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "56f7d92ca342cea22a06f2121d944b4fd82af56988c270852495420f961d4ace" +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + [[package]] name = "rustix" version = "1.1.2" @@ -327,12 +648,24 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "rustversion" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" + [[package]] name = "ryu" version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f" +[[package]] +name = "semver" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2" + [[package]] name = "serde" version = "1.0.228" @@ -376,6 +709,12 @@ dependencies = [ "serde_core", ] +[[package]] +name = "similar" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa" + [[package]] name = "strsim" version = "0.11.1" @@ -405,15 +744,24 @@ checksum = "b7401a30af6cb5818bb64852270bb722533397edcfc7344954a38f420819ece2" [[package]] name = "syn" -version = "2.0.110" +version = "2.0.111" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a99801b5bd34ede4cf3fc688c5919368fea4e4814a4664359503e6015b280aea" +checksum = "390cc9a294ab71bdb1aa2e99d13be9c753cd2d7bd6560c77118597410c4d2e87" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] +[[package]] +name = "termcolor" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" +dependencies = [ + "winapi-util", +] + [[package]] name = "terminal_size" version = "0.4.3" @@ -466,6 +814,12 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3b09c83c3c29d37506a3e260c08c03743a6bb66a9cd432c6934ab501a190571f" +[[package]] +name = "unicode-segmentation" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6ccf251212114b54433ec949fd6a7841275f9ada20dddd2f29e9ceea4501493" + [[package]] name = "unicode-width" version = "0.1.14" @@ -478,25 +832,115 @@ 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" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" +[[package]] +name = "uuid" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2e054861b4bd027cd373e18e8d8d8e6548085000e41290d95ce0c373a654b4a" +dependencies = [ + "getrandom", + "js-sys", + "serde_core", + "wasm-bindgen", +] + +[[package]] +name = "wasip2" +version = "1.0.1+wasi-0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d759f433fa64a2d763d1340820e46e111a7a5ab75f993d1852d70b03dbb80fd" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48cb0d2638f8baedbc542ed444afc0644a29166f1595371af4fecf8ce1e7eeb3" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cefb59d5cd5f92d9dcf80e4683949f15ca4b511f4ac0a6e14d4e1ac60c6ecd40" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cbc538057e648b67f72a982e708d485b2efa771e1ac05fec311f9f63e5800db4" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + [[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.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets 0.52.6", +] + [[package]] name = "windows-sys" version = "0.60.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" dependencies = [ - "windows-targets", + "windows-targets 0.53.5", ] [[package]] @@ -508,6 +952,22 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm 0.52.6", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + [[package]] name = "windows-targets" version = "0.53.5" @@ -515,60 +975,134 @@ 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", + "windows_aarch64_gnullvm 0.53.1", + "windows_aarch64_msvc 0.53.1", + "windows_i686_gnu 0.53.1", + "windows_i686_gnullvm 0.53.1", + "windows_i686_msvc 0.53.1", + "windows_x86_64_gnu 0.53.1", + "windows_x86_64_gnullvm 0.53.1", + "windows_x86_64_msvc 0.53.1", ] +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + [[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.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + [[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.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + [[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.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + [[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.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + [[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.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + [[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.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + [[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.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + [[package]] name = "windows_x86_64_msvc" version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" + +[[package]] +name = "wit-bindgen" +version = "0.46.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59" + +[[package]] +name = "zerocopy" +version = "0.8.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd74ec98b9250adb3ca554bdde269adf631549f51d8a8f8f0a10b50f1cb298c3" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8a8d209fdf45cf5138cbb5a506f6b52522a25afccc534d1475dad8e31105c6a" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] diff --git a/Cargo.toml b/Cargo.toml index 12fd715..79701f1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,7 @@ [workspace] resolver = "3" members = ["bin_efo", "lib_efo"] +version = "0.1" [workspace.dependencies] serde = { version = "1.0.228", features = ["derive"] } @@ -8,3 +9,8 @@ clap = { version = "4.5.51", features = ["derive"] } thiserror = "2.0.17" serde_json = "1.0.145" miette = { version = "7.6.0", features = ["fancy"] } +env_logger = "0.11.8" +log = "0.4.28" +derive_more = { version = "2.0.1", features = ["display", "add"] } +colored = "3.0.0" +insta = "1.44.3" diff --git a/Jenkinsfile b/Jenkinsfile index f9e155d..6d40fcd 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -17,6 +17,13 @@ pipeline { } } + stage('Update') { + steps { + sh "rustup update" + // sh "rustup show" + } + } + /* =============== END USER CONFIG ================== */ @@ -29,7 +36,7 @@ pipeline { } else if (env.BRANCH_NAME == 'origin/master' || env.BRANCH_NAME == 'master') { sh 'cargo test' } else { - echo "Unknown branch: ${env.BRANCH_NAME} — skipping build." + echo "Unknown branch: ${env.BRANCH_NAME} - skipping build." } } } @@ -39,11 +46,11 @@ pipeline { post { success { publishChecks conclusion: 'SUCCESS', name: 'Build Successful', summary: 'The build was successful', text: 'The build was sucessful', title: 'Build Successful' - echo '✅Site Deployed!' + echo '✅ Build Deployed!' } failure { publishChecks conclusion: 'FAILURE', name: 'Build Failed', summary: 'The build failed', text: 'The build was a failure', title: 'Build failed' - echo '❌Site Failed to Deploy' + echo '❌Build Failed to Deploy' } unstable{ publishChecks conclusion: 'ACTION_REQUIRED', name: 'Build Unstable', summary: 'Unstable build', text: 'Unstable build', title: 'Build Unstable' diff --git a/LICENSE b/LICENSE index c17e26f..d5ef671 100644 --- a/LICENSE +++ b/LICENSE @@ -6,10 +6,10 @@ treat the Software as is, without restriction, subject to the following condition: • The Software may not be used, directly or indirectly, for training, - fine‑tuning, or otherwise feeding into any artificial‑intelligence + fine-tuning, or otherwise feeding into any artificial-intelligence model or system. This includes, but is not limited to, usage as a - training dataset for machine‑learning or deep‑learning models, - model‑optimization, reinforcement‑learning, or any AI‑based analytics + training dataset for machine-learning or deep-learning models, + model-optimization, reinforcement-learning, or any AI-based analytics pipeline. • The Software may not be “scraped,” extracted, or otherwise harvested @@ -24,8 +24,8 @@ condition: All other rights granted under the MIT license remain in force, namely: - • The Software may be used for any non‑AI purpose, including commercial - or non‑commercial use, modification, distribution, private or public + • The Software may be used for any non-AI purpose, including commercial + or non-commercial use, modification, distribution, private or public deployment, and so on. • The Software is provided “as is,” without warranty of any kind, diff --git a/README.md b/README.md index 5c963ba..8bf7e8d 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,10 @@ # 📦 Epoch Forge (`epoch_forge`) +![code coverage](badges/coverage.svg) ![version](badges/version.svg) ![code coverage](badges/test.svg) -> **A Rust‑powered CLI for managing fantasy organisations across time.** -> *Think of it as a living, breathing world‑state engine that lets you “rewind”, “fast‑forward”, and **alter** the history of guilds, towns, wars, and characters.* +> **A Rust-powered CLI for managing fantasy organisations across time.** +> *Think of it as a living, breathing world-state engine that lets you “rewind”, “fast-forward”, and **alter** the history of guilds, towns, wars, and characters.* -> 🚀 *Fast, type‑safe, and fully testable.* +> 🚀 *Fast, type-safe, and fully testable.* ## ✨ Quick start @@ -40,19 +41,19 @@ cat world.json | Feature | What it gives you | Where it lives | |---------|------------------|----------------| | **Epoch management** | Switch, advance, or rewind the timeline | `core::epoch` | -| **Event handling** | Add/remove world‑shaping events (storms, festivals, wars) | `core::event` | +| **Event handling** | Add/remove world-shaping events (storms, festivals, wars) | `core::event` | | **Organisation CRUD** | Guilds, factions, corporations | `core::org` | | **Character CRUD** | Heroes, villains, NPCs | `core::character` | | **Town CRUD** | Villages, cities, trade hubs | `core::town` | | **Link network** | Alliances, wars, roads, trade routes | `core::link` | -| **Persistence** | JSON/YAML stores, pluggable back‑ends | `core::storage` | -| **CLI** | `efo` binary with sub‑commands | `efo` crate | +| **Persistence** | JSON/YAML stores, pluggable back-ends | `core::storage` | +| **CLI** | `efo` binary with sub-commands | `efo` crate | | **Tests** | Unit & integration coverage | `tests/` | ### 📃 Quick reference table -| Sub‑command | Usage | What it changes | +| Sub-command | Usage | What it changes | |-------------|-------|-----------------| | `epoch` | `efo epoch --init`
`efo epoch --advance N`
`efo epoch --target ID` | Creates a world; moves time forward or back. | | `event` | `efo event add ...`
`efo event remove ...` | Adds or removes an event. | diff --git a/badges/coverage.svg b/badges/coverage.svg new file mode 100644 index 0000000..8819e8f --- /dev/null +++ b/badges/coverage.svg @@ -0,0 +1 @@ +test-coverage: 51%test-coverage51% \ No newline at end of file diff --git a/badges/test.svg b/badges/test.svg new file mode 100644 index 0000000..382bf2f --- /dev/null +++ b/badges/test.svg @@ -0,0 +1 @@ +test: passingtestpassing \ No newline at end of file diff --git a/badges/version.svg b/badges/version.svg new file mode 100644 index 0000000..c835340 --- /dev/null +++ b/badges/version.svg @@ -0,0 +1 @@ +version: 0.1version0.1 \ No newline at end of file diff --git a/bin_efo/Cargo.toml b/bin_efo/Cargo.toml index d381520..1accc67 100644 --- a/bin_efo/Cargo.toml +++ b/bin_efo/Cargo.toml @@ -10,3 +10,10 @@ clap = {workspace = true} thiserror = {workspace = true} serde_json = {workspace = true} miette = {workspace = true} +env_logger = {workspace = true} +log = {workspace = true} +derive_more = {workspace = true} +colored = {workspace = true} + +[dev-dependencies] +insta = {workspace = true} diff --git a/bin_efo/src/commands.rs b/bin_efo/src/commands.rs index 507983a..2786614 100644 --- a/bin_efo/src/commands.rs +++ b/bin_efo/src/commands.rs @@ -1,11 +1,19 @@ //! # `commands` module //! -//! This module is the entry point for all CLI sub‑commands of the `efo` binary. -//! Each sub‑command (e.g. `epoch`, `org`, `event`, `town`, `link`) lives in its -//! own file inside this directory and is re‑exported here so that the main +//! This module is the entry point for all CLI sub-commands of the `efo` binary. +//! Each sub-command (e.g. `epoch`, `org`, `event`, `town`, `link`) lives in its +//! own file inside this directory and is re-exported here so that the main //! `efo::main.rs` can simply `use commands::*;` and dispatch based on the -//! clap‑parsed enum. +//! clap-parsed enum. +#![warn(missing_docs, clippy::missing_docs_in_private_items)] + +pub mod chr; pub mod epoch; -pub mod error; +pub mod generate; pub mod init; +pub mod show; +// pub mod diff; +// pub mod utils; +// pub mod event; +// pub mod town; diff --git a/bin_efo/src/commands/chr.rs b/bin_efo/src/commands/chr.rs new file mode 100644 index 0000000..d34e841 --- /dev/null +++ b/bin_efo/src/commands/chr.rs @@ -0,0 +1,474 @@ +//! Module handling the creation of characters + +use lib_efo::entity::{EffectApplication, EffectBounds, EntityDuration, EntityIdentifier}; +use lib_efo::epoch::epoch_traits::{ConfigWritable, Diffable}; +use lib_efo::naming::NAMING; +use lib_efo::stats::{Position, Symbols}; + +use clap::{Args, Subcommand}; +use lib_efo::Displayable; +use lib_efo::utils::RngLevel; +use lib_efo::{ + entity::Entity, + epoch::EpochConfig, + error::EpochError, + stats::{EntityType, StatPair}, +}; +use log::info; + +use crate::error::AppError; +use crate::success::display_success; + +/// Commands that operate on an entity. +/// +/// Each variant represents a different operation that can be performed on an +/// entity. The variant holds the arguments that are common to all operations. +#[derive(Subcommand, Debug)] +pub enum EntitySubCommands { + /// Add an entity + Add(EntityArgs), + /// Delete an entity + Del(EntityArgs), + /// Edit an existing entity + Edit(EntityArgs), + /// Find an entity by its identifier + Find(EntityArgs), + /// Show the details of an entity + Show(EntityArgs), + /// Show differences between two entities + Diff(EntityArgs), +} + +/// Arguments required for any entity operation. +/// +/// All fields are required. The `rng` field determines how unspecified stat +/// values are handled when an entity is created or edited. +#[derive(Args, Debug)] +pub struct EntityArgs { + /// The identifier either a name or a @tag + pub identifier: Option, + + // /// A name to change to + // #[arg(long, group = "identifier")] + // pub new_name: Option, + /// Applies a delta to stats instead of setting the values + #[arg(long, short, action = clap::ArgAction::SetTrue, default_value_t = false)] + pub delta: bool, + + /// Non specified stat Repartition + #[arg(value_enum, long, default_value_t = RngLevel::Zero)] + pub rng: RngLevel, + + /// Adds at a specific position + #[arg(long, group = "position")] + pub pos_exact: Option, + + /// Adds at a specific position + #[arg(long, group = "position")] + pub pos: Option, + + /// The duration of the entity + #[arg(long)] + pub duration: Option, + + /// The bounds of the effect of the entity + #[arg(long)] + pub bounds: Option, + + /// How is the effect of the entity applied + #[arg(long)] + pub effect: Option, + + /// All stats pairs involved + pub stats: Vec, +} + +/// Handles an entity subcommand. +/// +/// This function loads the main epoch configuration, then dispatches the +/// provided subcommand to the appropriate handler. It returns an +/// `AppError` if any operation fails. +/// +/// # Arguments +/// * `entity_sub_commands` - The subcommand chosen by the user. +/// * `e_type` - The type of entity to operate on. +/// +/// # Returns +/// A `Result` indicating success (`Ok(())`) or the encountered `AppError`. +pub fn handle_entity_commands( + entity_sub_commands: &EntitySubCommands, + e_type: &EntityType, +) -> Result<(), AppError> { + let mut main_epoch = EpochConfig::new_from_path(None)?; + match entity_sub_commands { + EntitySubCommands::Add(entity_args) => { + handle_create_entity(entity_args, e_type, &mut main_epoch) + } + EntitySubCommands::Del(entity_args) => { + handle_delete_entity(entity_args, e_type, &mut main_epoch) + } + EntitySubCommands::Edit(entity_args) => { + handle_edit_entity(entity_args, e_type, &mut main_epoch) + } + EntitySubCommands::Find(entity_args) => { + handle_find_entity(entity_args, e_type, &mut main_epoch) + } + EntitySubCommands::Show(entity_args) => { + handle_show_entity(entity_args, e_type, &mut main_epoch) + } + EntitySubCommands::Diff(entity_args) => { + handle_diff_entity(entity_args, e_type, &mut main_epoch) + } + }?; + Ok(()) +} + +/// Function handler for the create subcommand +fn handle_create_entity( + entity_args: &EntityArgs, + e_type: &EntityType, + main_epoch: &mut EpochConfig, +) -> Result<(), EpochError> { + let epoch_info = main_epoch.try_load_current_as_mut()?; + let vec_entities: &mut Vec = vec_entities_mut(e_type, epoch_info); + + let mut entity = Entity::create_rng(e_type, &entity_args.rng)?; + update_stats(entity_args, &mut entity); + // Specifying a name means the name needs to be changed + // Specifying an id however means nothing and should be ignored + + update_defaults(entity_args, &mut entity); + + info!("Created character: {:#?}", entity); + entity.print_full(); + let message = &crate::success::SuccessMessages::CreatedEntity( + entity.name.clone(), + entity.entity_type.to_shortest(), + entity.id.to_string(), + ); + vec_entities.push(entity); + + // No need to change main epoch that didn't change a serialized field + epoch_info.save_with_context("Created entity", &lib_efo::epoch::SaveMode::Erase)?; + display_success(message); + + Ok(()) +} + +/// Function handler for the delete subcommand +fn handle_delete_entity( + entity_args: &EntityArgs, + e_type: &EntityType, + main_epoch: &mut EpochConfig, +) -> Result<(), EpochError> { + let epoch_info = main_epoch.try_load_current_as_mut()?; + + let vec_entities: &mut Vec = vec_entities_mut(e_type, epoch_info); + let index = vec_entities + .iter() + .position(|e| find_by_args(e, entity_args)) + .ok_or(EpochError::EntityNotFound( + e_type.clone(), + entity_args.identifier.clone(), + ))?; + + let entity = vec_entities.swap_remove(index); + + epoch_info.save_with_context("Deleted entity", &lib_efo::epoch::SaveMode::Erase)?; + display_success(&crate::success::SuccessMessages::DeletedEntity( + entity.name, + entity.entity_type.to_shortest(), + entity.id.to_string(), + )); + Ok(()) +} + +/// Function handler for the diff subcommand +fn handle_diff_entity( + entity_args: &EntityArgs, + e_type: &EntityType, + main_epoch: &mut EpochConfig, +) -> Result<(), EpochError> { + // Load the epochs to diff + let id = main_epoch.epoch_id; + let id2 = main_epoch.epoch_id.add_to_epoch(-1); + main_epoch.try_load(&id)?; + main_epoch.try_load(&id2)?; + + let epoch_current = unsafe { main_epoch.try_load_id(id) }?; + let epoch_past = unsafe { main_epoch.try_load_id(id2) }?; + let current_entity = find_entity(entity_args, e_type, epoch_current)?; + let past_entity = find_entity(entity_args, e_type, epoch_past)?; + + let diff = current_entity.delta(past_entity); + display_success(&crate::success::SuccessMessages::DiffBetweenEpoch(id, id2)); + diff.print_full(); + + Ok(()) +} + +/// Function handler for the show subcommand +// TODO: Add filters else this will become very clustered +fn handle_show_entity( + entity_args: &EntityArgs, + e_type: &EntityType, + main_epoch: &mut EpochConfig, +) -> Result<(), EpochError> { + let epoch_info = main_epoch.try_load_current()?; + if entity_args.identifier.is_none() { + for entity in vec_entities(e_type, epoch_info) { + entity.print_oneline(); + } + } else { + let entity = find_entity(entity_args, e_type, epoch_info)?; + entity.print_full(); + } + Ok(()) +} + +/// Function handler for the find subcommand +fn handle_find_entity( + entity_args: &EntityArgs, + e_type: &EntityType, + main_epoch: &mut EpochConfig, +) -> Result<(), EpochError> { + handle_show_entity(entity_args, e_type, main_epoch) +} + +/// Function handler for the edit subcommand +fn handle_edit_entity( + entity_args: &EntityArgs, + e_type: &EntityType, + main_epoch: &mut EpochConfig, +) -> Result<(), EpochError> { + let epoch_info = main_epoch.try_load_current_as_mut()?; + let vec_entities = vec_entities_mut(e_type, epoch_info); + let entity = vec_entities + .iter_mut() + .find(|e| find_by_args(e, entity_args)) + .ok_or(EpochError::EntityNotFound( + e_type.clone(), + entity_args.identifier.clone(), + ))?; + + for stat in &entity_args.stats { + entity.change_stat(stat.clone()); + } + if let Some(duration) = &entity_args.duration { + entity.modify_duration(duration.clone()); + } + // // Only update the name if an id was given + // if entity_args.id.is_some() + // && let Some(name) = &entity_args.name + // { + // entity.name = name.clone(); + // } + if let Some(effect) = &entity_args.effect { + entity.modify_effect_application(effect.clone()); + } + if let Some(bounds) = &entity_args.bounds { + entity.modify_effect_bounds(bounds.clone()); + } + + entity.print_full(); + let message = &crate::success::SuccessMessages::EditedEntity( + entity.name.clone(), + entity.entity_type.to_shortest(), + entity.id.to_string(), + ); + epoch_info.save_with_context("Deleted entity", &lib_efo::epoch::SaveMode::Erase)?; + + display_success(message); + Ok(()) +} + +/// Update the given stats with the given argumenbts +/// Note that this function will not change name & id due to the usage variance between caller +fn update_stats(entity_args: &EntityArgs, e: &mut Entity) { + if entity_args.delta { + for stat in &entity_args.stats { + e.delta_stat(stat.clone()); + } + } else { + for stat in &entity_args.stats { + e.change_stat(stat.clone()); + } + } +} + +/// Looks up an entity inside the given `epoch_info` according to the +/// supplied arguments. +/// +/// The function returns a reference to the matching entity or an +/// `EpochError::EntityNotFound` if no entity matches. +/// +/// # Arguments +/// * `entity_args` - The arguments that identify the entity. +/// * `e_type` - The type of entity to look for. +/// * `epoch_info` - The epoch that contains all entities. +/// +/// # Returns +/// * `Ok(&Entity)` - The entity that matches the arguments. +/// * `Err(EpochError::EntityNotFound)` - No matching entity was found. +fn find_entity<'a>( + entity_args: &'a EntityArgs, + e_type: &'a EntityType, + epoch_info: &'a lib_efo::epoch::EpochInfo, +) -> Result<&'a Entity, EpochError> { + vec_entities(e_type, epoch_info) + .iter() + .find(|&e| find_by_args(e, entity_args)) + .ok_or(EpochError::EntityNotFound( + e_type.clone(), + entity_args.identifier.clone(), + )) +} + +/// Returns a slice over the entities of the requested type from the given `EpochInfo`. +/// +/// The function matches the supplied `e_type` to the appropriate collection +/// inside `epoch_info`. For unimplemented entity types the call will panic +/// because of the `todo!()` placeholder. +/// +/// # Arguments +/// * `e_type` - The type of entities to retrieve. +/// * `epoch_info` - The epoch information containing the collections. +/// +/// # Returns +/// A reference to the vector containing the requested entities. +/// The lifetime of the returned slice is tied to that of `epoch_info`. +#[inline] +fn vec_entities<'a>( + e_type: &'a EntityType, + epoch_info: &'a lib_efo::epoch::EpochInfo, +) -> &'a Vec { + match e_type { + EntityType::Character => &epoch_info.characters, + EntityType::Player => todo!(), + EntityType::Town => &epoch_info.towns, + EntityType::Monster => todo!(), + EntityType::Blocker => todo!(), + EntityType::Event => &epoch_info.events, + } +} + +#[inline] +/// Returns a mutable slice over the entities of the requested type from the given +/// `EpochInfo`. +/// +/// Like `vec_entities`, this function selects the appropriate collection +/// based on `e_type`. Unimplemented variants will panic due to the `todo!()`. +/// +/// # Arguments +/// * `e_type` - The type of entities to retrieve. +/// * `epoch_info` - The epoch information containing the collections. +/// +/// # Returns +/// A mutable reference to the vector containing the requested entities. +/// The lifetime of the returned slice is tied to that of `epoch_info`. +fn vec_entities_mut<'a>( + e_type: &'a EntityType, + epoch_info: &'a mut lib_efo::epoch::EpochInfo, +) -> &'a mut Vec { + match e_type { + EntityType::Character => &mut epoch_info.characters, + EntityType::Player => todo!(), + EntityType::Town => &mut epoch_info.towns, + EntityType::Monster => todo!(), + EntityType::Blocker => todo!(), + EntityType::Event => &mut epoch_info.events, + } +} + +/// Helper function finding by name, note that a lot more helpers could be done to find by other criterias +fn find_by_args(entity: &Entity, entity_args: &EntityArgs) -> bool { + match entity_args.identifier { + Some(EntityIdentifier::Name(ref name)) => entity.name.starts_with(name), + Some(EntityIdentifier::Id(ref id)) => entity.id.hyphenated().to_string().starts_with(id), + None => false, + } +} + +/// Find an entity matching a tag +#[allow(dead_code)] +fn find_by_id<'a>(entities: &'a [Entity], id: &'a String) -> Option<&'a Entity> { + entities + .iter() + .find(|e| e.id.hyphenated().to_string().starts_with(id)) +} + +/// Find an entity matching a name +#[allow(dead_code)] +fn find_by_name<'a>(entities: &'a [Entity], id: &'a String) -> Option<&'a Entity> { + entities.iter().find(|e| e.name.starts_with(id)) +} + +/// Update the default values of the entity with sensible defaults +fn update_defaults(entity_args: &EntityArgs, e: &mut Entity) { + let entity_type = &e.entity_type; + + let (duration, effect, bounds, name) = match entity_type { + EntityType::Character => ( + lib_efo::entity::EntityDuration::Permanent, + lib_efo::entity::EffectApplication::WhenPresent, + EffectBounds { min: 20, max: 110 }, + NAMING.generate_character_name(), + ), + EntityType::Player => ( + lib_efo::entity::EntityDuration::Permanent, + lib_efo::entity::EffectApplication::WhenPresent, + EffectBounds { min: 0, max: 120 }, + NAMING.generate_exotic_character_name(), + ), + EntityType::Town => ( + lib_efo::entity::EntityDuration::Permanent, + lib_efo::entity::EffectApplication::WhenPresent, + EffectBounds { min: 20, max: 60 }, + NAMING.generate_town_name(), + ), + EntityType::Monster => ( + lib_efo::entity::EntityDuration::Permanent, + lib_efo::entity::EffectApplication::WhenPresent, + EffectBounds { min: 20, max: 80 }, + NAMING.generate_calamity_name(), + ), + EntityType::Blocker => ( + lib_efo::entity::EntityDuration::Permanent, + lib_efo::entity::EffectApplication::WhenPresent, + EffectBounds { min: 0, max: 120 }, + NAMING.generate_blocker_name(), + ), + EntityType::Event => ( + lib_efo::entity::EntityDuration::Duration(1), + lib_efo::entity::EffectApplication::PermanentEffectToApply, + EffectBounds { min: 10, max: 80 }, + NAMING.random_event_name(), + ), + }; + // This is the sensible default for all creatures & characters + if let Some(duration) = &entity_args.duration { + e.modify_duration(duration.clone()); + } else { + e.modify_duration(duration); + } + + if let Some(EntityIdentifier::Name(name)) = &entity_args.identifier { + e.name = name.clone() + } else { + e.name = name + } + + // This is the sensible default for all creatures & characters + if let Some(effect) = &entity_args.effect { + e.modify_effect_application(effect.clone()); + } else { + e.modify_effect_application(effect); + } + + // This is the sensible default for characters + if let Some(bounds) = &entity_args.bounds { + e.modify_effect_bounds(bounds.clone()); + } else { + e.modify_effect_bounds(bounds); + } +} diff --git a/bin_efo/src/commands/epoch.rs b/bin_efo/src/commands/epoch.rs index 587f283..b426aea 100644 --- a/bin_efo/src/commands/epoch.rs +++ b/bin_efo/src/commands/epoch.rs @@ -1,80 +1,230 @@ -//! # `epoch` sub‑command +//! # `epoch` sub-command //! -//! Handles all epoch‑related logic – logging, switching, computing the +//! 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, + success::{SuccessMessages, display_success}, +}; use lib_efo::{ - epoch_struct::{ConfigWritable, EpochConfig}, + epoch::{EpochConfig, EpochId, epoch_traits::ConfigWritable}, error::EpochError, }; - -use crate::error::AppError; +use log::{debug, info}; pub mod cli_epoch; -/// **Public entry point used by `efo::main`** – dispatches to the real + +/// **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> { +/// +/// # Arguments +/// * `cmd` - The command to execute. This is an enum that represents +/// one of the possible sub-commands for the `epoch` feature. +/// +/// # Returns +/// * `Ok(())` on success. +/// * `Err(AppError)` if any step of the command handling fails. +/// +/// # Examples +/// ```no_run +/// // Create a command to switch to epoch 3. +/// let cmd = cli_epoch::EpochCmd::Switch(cli_epoch::Switch { target: 3 }); +/// // Execute the command. +/// let result = handle_cmd(cmd); +/// assert!(result.is_ok()); +/// ``` +/// +/// The function never panics under normal operation. All errors are +/// reported via the returned `Result`. +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); + // // TODO[2]: Remove this debug + debug!("The main epoch befor any action is {:#?}", main_epoch); match cmd { - cli_epoch::EpochCmd::Log(args) => handle_log(args), + cli_epoch::EpochCmd::Log(args) => handle_log(args, &mut main_epoch), 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), - } + cli_epoch::EpochCmd::Fsck(args) => handle_fsck(args, &mut main_epoch), + cli_epoch::EpochCmd::Summary(args) => handle_summary(args, &mut main_epoch), + }?; + + info!("The main epoch after all actions is {:#?}", main_epoch); + Ok(()) } -fn handle_diff(args: cli_epoch::Diff) -> Result<(), AppError> { +/// Edits the summary for the current epoch. +/// +/// The function loads the epoch that is currently active in +/// `main_epoch`, then replaces its `summary` field with the value +/// supplied in `args.summary`. The epoch map in `main_epoch` is +/// modified in place. +/// +/// This helper is internal to the `epoch` sub-command and is not part +/// of the public API. +fn handle_summary(args: &cli_epoch::Summary, main_epoch: &mut EpochConfig) -> Result<(), AppError> { + let epoch_id = main_epoch.epoch_id; + main_epoch.try_load(&epoch_id)?; + #[allow(clippy::unwrap_used)] // The epoch_id must exists at this point + if let Some(epoch) = main_epoch + .list_existing_epochs + .get_mut(&epoch_id) + .ok_or(EpochError::EpochHashingImpossible(file!(), line!()))? + { + epoch.summary = args.summary.clone(); + epoch.save_with_context("Saving new summary", &lib_efo::epoch::SaveMode::Erase)?; + display_success(&SuccessMessages::ChangedSummary( + epoch_id, + args.summary.clone(), + )); + } + + Ok(()) +} + +/// Show a diff between two epochs. +/// +/// Currently unimplemented. The function is a placeholder until a +/// world-level diff algorithm is available. +/// +/// This helper is internal to the `epoch` sub-command and is not part +/// of the public API. +fn handle_diff(args: &cli_epoch::Diff) -> Result<(), AppError> { let _ = args; unimplemented!("Blocker: There is actually no way to diff the world yet") } -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"); -} +/// Show a log of all epochs up to the current one. +/// +/// The function collects the identifiers of all epochs that are +/// less than or equal to the currently active epoch (`main_epoch.epoch_id`), +/// sorts them, and then asks the configuration to log the elements +/// up to the supplied limit. The log is written by the +/// underlying `EpochConfig::log_elements` implementation. +/// +/// This helper is internal to the `epoch` sub-command. +fn handle_log(args: &cli_epoch::Log, main_epoch: &mut EpochConfig) -> Result<(), AppError> { + let limit = args.limit; + let start_id = &main_epoch.epoch_id; -/// 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; - - println!("Switched to epoch {:?}", target); - main_epoch.save( - "Saving modified epoch config".into(), - lib_efo::epoch_struct::SaveMode::Erase, - )?; + let mut list_id: Vec = main_epoch + .list_existing_epochs + .iter() + .filter(|(id, _)| id <= &start_id) + .map(|(id, _)| *id) + .collect(); + list_id.sort(); + main_epoch.log_elements(&list_id[..std::cmp::min(list_id.len(), limit)])?; Ok(()) } -fn handle_next(args: cli_epoch::Next) -> Result<(), AppError> { - let _ = args; - println!("⚡ Next",); - unimplemented!("Missing logic to process a next event"); +/// Switches the current epoch to the one specified by the user. +/// +/// The function loads the target epoch, updates the epoch identifier +/// in the configuration, and persists the change. It also prints a +/// success message via `display_success`. +/// +/// This helper is internal to the `epoch` sub-command. +fn handle_switch(args: &cli_epoch::Switch, main_epoch: &mut EpochConfig) -> Result<(), AppError> { + let target = main_epoch.get_epoch_id(&args.target)?; + main_epoch.try_load(&target)?; + main_epoch.epoch_id = target; + + main_epoch.save_with_context( + "Saving modified epoch config", + &lib_efo::epoch::SaveMode::Erase, + )?; + display_success(&SuccessMessages::EpochSwitchSuccess(target)); + Ok(()) } -/// Reset all future events by deleting them -fn handle_reset(args: cli_epoch::Reset, main_epoch: &mut EpochConfig) -> Result<(), AppError> { +/// 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()?; + let new_id = new_epoch.epoch_id; + + // Insert new epoch + main_epoch.insert_and_save(new_epoch, &lib_efo::epoch::SaveMode::DoNotErase)?; + display_success(&SuccessMessages::EpochNextSuccess(current_id, new_id)); + Ok(()) + } +} + +/// 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; + // for id in main_epoch for id in main_epoch .list_existing_epochs .keys() .filter(|&k| k > ¤t_id) + .copied() + // Middle step necessary for borrowing purposes + .collect::>() { - main_epoch.delete_id(*id)? + main_epoch.delete_id(id)? } - println!("All future events deleted – back to epoch {current_id}",); + display_success(&SuccessMessages::DeletedAllFutureEvents(current_id)); Ok(()) } -/// Adds a tag to the current epoch -fn handle_taging(args: cli_epoch::Tag, main_epoch: &mut EpochConfig) -> Result<(), AppError> { +/// 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())?; @@ -87,22 +237,21 @@ 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() + .ok_or(EpochError::EpochHashingImpossible(file!(), line!()))? { 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::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::SaveMode::Erase, )?; Ok(()) } else { @@ -111,3 +260,18 @@ fn handle_taging(args: cli_epoch::Tag, main_epoch: &mut EpochConfig) -> Result<( ))) } } + +/// Perform a filesystem consistency check on the epoch data. +/// +/// The function invokes the internal consistency-check logic of +/// `EpochConfig`. It is intended for use from the `fsck` sub-command +/// and does **not** modify the current epoch. Any problems that +/// are detected are reported through the returned `Result`; the +/// command may also print a diagnostic message to the user. +/// +/// This helper is internal to the `epoch` sub-command. +fn handle_fsck(args: &cli_epoch::Fsck, main_epoch: &mut EpochConfig) -> Result<(), AppError> { + let _ = main_epoch; + let _ = args; + unimplemented!() +} diff --git a/bin_efo/src/commands/epoch/cli_epoch.rs b/bin_efo/src/commands/epoch/cli_epoch.rs index 25b53a4..bb7aa2f 100644 --- a/bin_efo/src/commands/epoch/cli_epoch.rs +++ b/bin_efo/src/commands/epoch/cli_epoch.rs @@ -1,10 +1,30 @@ -use clap::{Args, Subcommand}; -use lib_efo::epoch_struct::EpochIdentifier; +//! # `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. -/// The outer clap entry that the binary will dispatch to +#![warn(missing_docs, clippy::missing_docs_in_private_items)] + +use clap::{Args, Subcommand}; +use lib_efo::epoch::EpochIdentifier; + +/// 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 + /// List all epochs - a git-log style view Log(Log), /// Switch to an epoch (by numeric ID, name, or tag) @@ -18,12 +38,22 @@ 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), + + /// Edits the summary for the current epoch + Summary(Summary), } -/// `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. @@ -31,27 +61,37 @@ 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. + /// 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")] + /// 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` +/// 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)] @@ -59,13 +99,29 @@ pub struct Diff { pub start: EpochIdentifier, /// The end point to compute the differences, the current epoch by default + // TODO: Change this epochId by another better object 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)] - /// The tag to tag the current epoch with + #[allow(clippy::missing_docs_in_private_items)] pub tag: String, } + +/// Performs basic filesystem level maintenance. +#[derive(Debug, Args)] +pub struct Fsck {} + +/// Edits the current's epoch summary. +#[derive(Debug, Args)] +pub struct Summary { + #[arg(required = true)] + #[allow(clippy::missing_docs_in_private_items)] + pub summary: String, +} 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/generate.rs b/bin_efo/src/commands/generate.rs new file mode 100644 index 0000000..dc37aee --- /dev/null +++ b/bin_efo/src/commands/generate.rs @@ -0,0 +1,136 @@ +//! # Generation Sub-command +//! +//! This module implements the `gen` sub-command used to quickly produce +//! sample data for the various generators in *lib_efo*. The command has no +//! side-effects beyond printing the generated data; it is intended for +//! interactive use or for embedding in scripts. +//! +//! ## Available sub-commands +//! +//! * `character` - Generate character names (long or short). +//! * `event` - Generate event ideas. +//! * `town` - Generate town names. +//! * `exotic` - Generate exotic character names. +//! +//! Each sub-command accepts a set of common options (see [`Qty`]) that +//! control how many items are produced and how they are displayed. +//! + +use clap::{Args, Subcommand}; +use lib_efo::{Displayable, error::EpochError, naming::NAMING}; + +use crate::error::AppError; +/// The types of examples to generate. +/// +/// Each variant maps directly to a public sub-command of the `gen` tool. +#[derive(Subcommand, Debug)] +pub enum GenCmd { + /// Generate a character + Character(Qty), + /// Events + Event(Qty), + /// Town + Town(Qty), + /// Exotic name + Exotic(Qty), +} + +#[derive(Args, Debug)] +/// Common arguments for the generation subcommands. +/// +/// The fields are deliberately named to match the command-line flags +/// produced by `clap`. The struct is used by all sub-commands to +/// keep the CLI surface area minimal. +pub struct Qty { + /// Amount of entities to generate. + #[arg(short, long, default_value_t = 1)] + number: usize, + /// Full print. + /// + /// If set to `false` the generator will produce a *short* representation + #[arg(long, action = clap::ArgAction::SetFalse, default_value_t = true)] + short: bool, + /// Generate only a name, no underlying structure. + /// + /// When this flag is present the generator prints only the name string + /// rather than any additional data or formatting. + #[arg(long="name", action = clap::ArgAction::SetTrue, default_value_t = false)] + name_only: bool, +} + +/// Handles the subcommand for generating various kinds of entities. +/// +/// Depending on the selected variant of [`GenCmd`], it delegates to the +/// corresponding private handler function. +/// +/// # Arguments +/// * `cmd` - The parsed subcommand arguments. +/// +/// # Errors +/// Returns an [`AppError`] if any of the underlying handlers fail. +pub fn gen_handler(cmd: &GenCmd) -> Result<(), AppError> { + match cmd { + GenCmd::Character(args) => handle_chr(args)?, + GenCmd::Event(args) => handle_event(args)?, + GenCmd::Town(args) => handle_town(args)?, + GenCmd::Exotic(args) => handle_exotic(args)?, + } + Ok(()) +} + +/// Prints exotic name +fn handle_exotic(args: &Qty) -> Result<(), EpochError> { + for _ in 0..args.number { + let name = NAMING.generate_exotic_character_name(); + if args.name_only { + println!("{}", name); + } else { + unimplemented!("DEPENS ON : CHARACTER CREATION") + } + } + Ok(()) +} + +/// Prints town +fn handle_town(args: &Qty) -> Result<(), EpochError> { + for _ in 0..args.number { + let name = NAMING.generate_town_name(); + if args.name_only { + println!("{}", name); + } else { + unimplemented!("DEPENS ON : TOWN CREATION") + } + } + Ok(()) +} + +/// Print events +fn handle_event(args: &Qty) -> Result<(), EpochError> { + for _ in 0..args.number { + let event = NAMING.random_event_idea()?; + if args.name_only { + println!("{}", event.name); + } else { + println!("{}", event.oneline_display()); + } + } + Ok(()) +} + +/// Print a character name +fn handle_chr(args: &Qty) -> Result<(), EpochError> { + for _ in 0..args.number { + let name = if args.short { + NAMING.generate_long_character_name() + } else { + NAMING.generate_character_name() + }; + + if args.name_only { + println!("{}", name); + } else { + unimplemented!("DEPENS ON : CHARACTER CREATION") + } + } + Ok(()) +} diff --git a/bin_efo/src/commands/init.rs b/bin_efo/src/commands/init.rs index 8e5527f..f6bea46 100644 --- a/bin_efo/src/commands/init.rs +++ b/bin_efo/src/commands/init.rs @@ -1,23 +1,49 @@ +//! # `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}; +use lib_efo::{ + epoch::{EpochConfig, EpochInfo, epoch_traits::ConfigWritable}, + error::EpochError, +}; use std::fs::read_dir; -use crate::error::AppError; +use crate::{ + error::AppError, + success::{SuccessMessages, display_success}, +}; #[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. +//TODO[5]: Upholster the logic behind force and empty detection 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, @@ -26,9 +52,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::SaveMode::DoNotErase, ) .map_err(|_| EpochError::AlreadyInitialized { advice: Some( @@ -36,16 +62,21 @@ pub fn init(args: &InitCmd) -> Result<(), AppError> { .to_string(), ), })?; + + display_success(&SuccessMessages::FolderInitializedSuccessfully(".")); 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::SaveMode::DoNotErase, )?; Ok(()) } diff --git a/bin_efo/src/commands/show.rs b/bin_efo/src/commands/show.rs new file mode 100644 index 0000000..5058021 --- /dev/null +++ b/bin_efo/src/commands/show.rs @@ -0,0 +1,51 @@ +//! The show commands +//! Used to display structures with various degree of verbosity + +use clap::Subcommand; +use lib_efo::{Displayable, entity::Entity, naming::NAMING}; + +use crate::error::AppError; +#[derive(Subcommand, Debug)] +/// Show command +pub enum ShowCmd { + /// Show an event + Event, + /// Show an event + Character, + /// Show an event + Town, +} + +// #[derive(Args)] +// struct Specifics { +// name: String, +// } + +/// Handle all show cmds +pub fn handle_show_cmd(cmd: &ShowCmd) -> Result<(), AppError> { + let _ = cmd; + let mut e = Entity::default(); + e.name = NAMING.generate_long_character_name(); + println!("Original Struct: \n{e:#?}"); + println!("\n\n\nONELINES"); + println!("{}", e.oneline_display()); + println!("{}", e.oneline_display()); + println!("{}", e.oneline_display()); + println!("{}", e.oneline_display()); + println!("{}", e.oneline_display()); + println!("{}", e.oneline_display()); + println!("{}", e.oneline_display()); + println!("\n\n\n SHORT"); + e.print_short(); + + println!("\n\n\n LONG"); + e.print_full(); + println!("\n\n\n TREE"); + println!("{}", e.to_pretty_tree()); + + Ok(()) +} + +// Show event +// Show diff (char/town) +// Show .... diff --git a/bin_efo/src/error.rs b/bin_efo/src/error.rs index 9820956..cf2e886 100644 --- a/bin_efo/src/error.rs +++ b/bin_efo/src/error.rs @@ -1,7 +1,9 @@ //! General error type that the CLI propagates. //! //! `AppError` aggregates all error kinds that may surface during a command -//! execution: parsing, I/O, epoch logic, storage, and a catch‑all. +//! 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; @@ -11,8 +13,8 @@ use thiserror::Error; #[derive(Debug, Error, Diagnostic)] #[allow(dead_code)] pub enum AppError { - /// Generic “invalid command / missing flag” – emitted by clap. - #[error("Command‑line error: {0}")] + /// Generic “invalid command / missing flag” - emitted by clap. + #[error("Command-line error: {0}")] // #[diagnostic(transparent)] Clap(#[from] clap::Error), @@ -21,17 +23,17 @@ pub enum AppError { // #[diagnostic(transparent)] Io(#[from] std::io::Error), - /// Domain‑specific problems (see `EpochError`). + /// Domain-specific problems (see `EpochError`). #[error("Epoch error:")] #[diagnostic(transparent)] Epoch(#[from] EpochError), - /// Storage‑layer (e.g. DB) errors. + /// Storage-layer (e.g. DB) errors. #[error("Storage error: {0}")] // #[diagnostic(transparent)] Storage(#[from] StorageError), - /// Anything else we didn’t anticipate. + /// Anything else we didn't anticipate. #[error("Unknown error: {0}")] Other(String), } diff --git a/bin_efo/src/main.rs b/bin_efo/src/main.rs index d5e4391..f656027 100644 --- a/bin_efo/src/main.rs +++ b/bin_efo/src/main.rs @@ -1,16 +1,16 @@ //! # `efo` //! -//! The **command‑line interface** for `epoch_forge`. It exposes a single -//! binary `efo` that supports the following sub‑commands: +//! The **command-line interface** for `epoch_forge`. It exposes a single +//! binary `efo` that supports the following sub-commands: //! -//! - `epoch` – switch / advance time -//! - `event` – add / remove events -//! - `org` – add / remove organisations -//! - `chr` – add / remove characters -//! - `town` – add / remove towns -//! - `link` – add / remove links (alliances, wars, roads, etc.) +//! - `epoch` - switch / advance time +//! - `event` - add / remove events +//! - `org` - add / remove organisations +//! - `chr` - add / remove characters +//! - `town` - add / remove towns +//! - `link` - add / remove links (alliances, wars, roads, etc.) //! -//! Each sub‑command is implemented in its own module under `commands/`. +//! Each sub-command is implemented in its own module under `commands/`. //! The `main.rs` file simply parses arguments with `clap` and dispatches //! to the appropriate handler. The handlers share a common `World` //! instance that they load from / persist to disk. @@ -19,63 +19,106 @@ //! ```sh //! efo epoch switch 5 //! ``` -use clap::{Parser, Subcommand}; -use crate::commands::init::InitCmd; -use crate::{commands::epoch::cli_epoch::EpochCmd, error::AppError}; +#![warn(missing_docs, clippy::missing_docs_in_private_items)] +#![deny(clippy::unwrap_used)] + +use std::fmt::Debug; + +use clap::{ArgAction, Parser, Subcommand}; + +use crate::{ + commands::{ + chr::EntitySubCommands, epoch::cli_epoch::EpochCmd, generate::GenCmd, init::InitCmd, + show::ShowCmd, + }, + error::AppError, +}; mod commands; mod error; +mod success; -/// 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")] +#[command(about = "Epoch Forge - manage organisations over time")] struct Cli { + /// The level of verbosity + #[arg(short, long, action = ArgAction::Count, global = true)] + verbose: u8, + #[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), + /// Display some elements + #[command(subcommand)] + Show(ShowCmd), + /// Handle characters + #[command(subcommand)] + Chr(EntitySubCommands), + // Event(commands::event::EventCmd), // Org(commands::org::OrgCmd), - // Chr(commands::chr::ChrCmd), // Town(commands::town::TownCmd), // Link(commands::link::LinkCmd), + /// Generate random structures and display them + #[command(subcommand)] + Gen(GenCmd), } +/// Program entry point. +/// +/// Parses the command-line arguments and dispatches to the selected +/// sub-command. Errors returned by the sub-command handlers are shown +/// in stdout and returned as a `miette::Result<()>`. fn main() -> miette::Result<()> { + env_logger::init(); + let cli = Cli::parse(); 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(()) } +/// 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 shown to +/// stdout and returned as a `miette::Result<()>`. 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!("") + TopLevelCmd::Init(cmd) => commands::init::init(&cmd), + TopLevelCmd::Epoch(cmd) => commands::epoch::handle_cmd(&cmd), + TopLevelCmd::Show(cmd) => commands::show::handle_show_cmd(&cmd), + TopLevelCmd::Gen(cmd) => commands::generate::gen_handler(&cmd), + TopLevelCmd::Chr(cmd) => { + commands::chr::handle_entity_commands(&cmd, &lib_efo::stats::EntityType::Character) } } - Ok(()) } diff --git a/bin_efo/src/success.rs b/bin_efo/src/success.rs new file mode 100644 index 0000000..702b1af --- /dev/null +++ b/bin_efo/src/success.rs @@ -0,0 +1,40 @@ +//! List of all success messages possible + +use colored::*; +use derive_more::Display; +use lib_efo::epoch::EpochId; + +#[derive(Display, Clone, Debug)] +#[allow(missing_docs, clippy::missing_docs_in_private_items)] +pub enum SuccessMessages { + #[display("Switched to epoch {_0}")] + EpochSwitchSuccess(lib_efo::epoch::EpochId), + + #[display("All future events deleted - back to epoch {_0}")] + DeletedAllFutureEvents(lib_efo::epoch::EpochId), + + #[display("The folder was initialized as an epoch folder")] + FolderInitializedSuccessfully(&'static str), + + #[display("Changed the summary of epoch {_0} with: '{_1}'")] + ChangedSummary(EpochId, String), + + #[display("Successfully computed the new epoch. The current epoch is now {_1} (was {_0})")] + EpochNextSuccess(EpochId, EpochId), + + #[display("Successfully deleted the entity {_0} ({_1} 󰻾[{_2}])")] + DeletedEntity(String, String, String), + + #[display("Successfully created the entity {_0} ({_1} 󰻾[{_2}])")] + CreatedEntity(String, String, String), + + #[display("Successfully edited the entity {_0} ({_1} 󰻾[{_2}])")] + EditedEntity(String, String, String), + #[display("Showing delta between Epoch ({_0} & {_1})")] + DiffBetweenEpoch(lib_efo::epoch::EpochId, lib_efo::epoch::EpochId), +} + +/// Display the success message to stdout +pub fn display_success(message: &SuccessMessages) { + println!("{}", message.to_string().cyan()) +} diff --git a/lib_efo/Cargo.toml b/lib_efo/Cargo.toml index 9398e9c..e96c4e6 100644 --- a/lib_efo/Cargo.toml +++ b/lib_efo/Cargo.toml @@ -9,3 +9,15 @@ serde = {workspace = true} thiserror = {workspace = true} clap = {workspace = true} miette = {workspace = true} +env_logger = {workspace = true} +log = {workspace = true} +derive_more = {workspace = true} +cli-table = "0.5.0" +uuid = { version = "1.18.1", features = ["serde", "v4"] } +colored = {workspace = true} +rand = "0.9.2" +once_cell = "1.21.3" + +[dev-dependencies] +insta = {workspace = true} + diff --git a/lib_efo/naming.json b/lib_efo/naming.json new file mode 100644 index 0000000..4089c8b --- /dev/null +++ b/lib_efo/naming.json @@ -0,0 +1,1594 @@ +{ + "first_names": [ + "Aeron", + "Brienne", + "Cedric", + "Darya", + "Eldon", + "Fiora", + "Galen", + "Hela", + "Ivor", + "Juno", + "Aldric", + "Briar", + "Caelum", + "Dorin", + "Elysia", + "Fendrel", + "Gryphon", + "Hector", + "Iseult", + "Kael", + "Lysander", + "Morgath", + "Nyx", + "Odin", + "Riven", + "Sylvan", + "Thorne", + "Valen", + "Wraith", + "Xander", + "Yara", + "Zarek", + "Artemis", + "Baldric", + "Corvin", + "Draven", + "Eira", + "Fenris", + "Gale", + "Helios", + "Ivy", + "Jasper", + "Kara", + "Luna", + "Mira", + "Nimrod", + "Onyx", + "Peregrine", + "Quinn", + "Aegon", + "Brek", + "Calandra", + "Darrion", + "Eryndor", + "Fenn", + "Galax", + "Hestia", + "Ilarion", + "Jareth", + "Kassandra", + "Lyris", + "Maelor", + "Nyssa", + "Oren", + "Phaedra", + "Quillon", + "Rhea", + "Soren", + "Thalia", + "Uther", + "Vesper", + "Wulfric", + "Xara", + "Yoren", + "Zorath", + "Aerith", + "Baldrick", + "Cress", + "Dazai", + "Elara", + "Fira" + ], + "last_names": [ + "Ashwood", + "Blackthorn", + "Cinderglow", + "Dunwynn", + "Everfield", + "Frosthelm", + "Goldleaf", + "Holloway", + "Iverson", + "Jasper", + "Ravencrest", + "Stormblade", + "Nightshade", + "Wraithborne", + "Dreadmoor", + "Ironhart", + "Bloodstone", + "Stonegate", + "Gloomreach", + "Sablewick", + "Rookhaven", + "Ironcrest", + "Bleakmoor", + "Thornshield", + "Wyrmwood", + "Darkwater", + "Stormbreaker", + "Ebonhart", + "Bloodbane", + "Eclipseborne", + "Firethorn", + "Silvershade", + "Blackfrost", + "Sorrowblade", + "Stonehelm", + "Gravelock", + "Voidwalker", + "Nightfall", + "Ashenfall", + "Ashenridge", + "Duskfall", + "Thornhaven", + "Gloombreaker", + "Riftwalker", + "Althmar", + "Brimstone", + "Cinderfall", + "Duskbane", + "Emberforge", + "Frostbane", + "Grimsbane", + "Ironbark", + "Jaggedspire", + "Keldrith", + "Lament", + "Mistveil", + "Nightglow", + "Oathbreaker", + "Palegrave", + "Quicksilver", + "Riftshard", + "Shadowforge", + "Thornbane", + "Umbral", + "Vengeance", + "Wraithbane", + "Xylander", + "Yester", + "Zephyr", + "Blackfire", + "Bloodthorn", + "Crimsonveil", + "Dreadspire", + "Eboncrest", + "Firebrand", + "Grimshard", + "Ironheart", + "Javelin", + "Krait", + "Luminous", + "Marrowbone", + "Nocturne", + "Obsidian", + "Pyre", + "Quagmire", + "Reaver", + "Sableheart", + "Tidebreaker" + ], + "mystical_adjectives": [ + "The Sky Devourer", + "World Asunder", + "Otherworldly Tormentor", + "The Abyssal Maw", + "The Nightfall Harbinger", + "Storm of the Void", + "Echoes of the Unmaking", + "The Star-Cutter", + "Realm-Sunderer", + "The Veil-Shredder", + "Giant of the Shadowed Depths", + "The Whispering Oblivion", + "Crown of the Endless Night", + "The Loom-Breaker", + "The Sun-Wither", + "Harbinger of the Broken Veil", + "The Gloom-Harvest", + "Of the Otherworldly Pleasure", + "The Cataclysmic Resonance", + "The Tempest of Erasure", + "The Crimson Eclipse", + "The Null-Seeker", + "The Rift-Harvester", + "The Desolation King", + "The Silent Oblivion", + "The Shattered Covenant", + "The Veiled Devourer", + "The Plague of Eternity", + "The Storm-Wreathed Titan", + "The Echo-Demon", + "The Loom-of-Night", + "The Shard-Weaver", + "The Ember-Wraith", + "The Void-Warden", + "The Twilight Serpent", + "The Obsidian Herald", + "The Celestial Bane", + "The Maw of Forgotten Stars", + "The Grief-Harbinger", + "The Fractured Eclipse", + "The Devourer of Dawn", + "The Rift-Born Leviathan", + "The Wailing Abyss", + "The Pulse of Ruin", + "The Starless Nightfall", + "The Maw-Of-Eons", + "The Shadow-Eater", + "The Echo-of-Despair", + "The Void-Cutter" + ], + "blocker_prefixes": [ + "Abysmal", + "Aetheric", + "Ashen", + "Avaricious", + "Black", + "Bleak", + "Blood", + "Brackish", + "Cursed", + "Cryptic", + "Darkened", + "Dread", + "Dusk", + "Ebon", + "Eerie", + "Enchanted", + "Eternal", + "Fallen", + "Feral", + "Foreboding", + "Gloom", + "Grim", + "Hollow", + "Iron", + "Lurking", + "Mournful", + "Obsidian", + "Onyx", + "Pale", + "Phantom", + "Plague", + "Pyre", + "Ragged", + "Riven", + "Rust", + "Shadow", + "Sorrow", + "Spectral", + "Thorn", + "Twilight", + "Wraith", + "Wretched" + ], + "blocker_suffixes": [ + "Bane", + "Blight", + "Bloom", + "Burst", + "Call", + "Crown", + "Creek", + "Dawn", + "Depth", + "Fall", + "Forge", + "Forge", + "Gloom", + "Heart", + "Hollow", + "Ice", + "Knell", + "Lament", + "Mire", + "Night", + "Pit", + "Reach", + "Rift", + "Scream", + "Shard", + "Shade", + "Shroud", + "Soul", + "Spine", + "Spire", + "Stream", + "Storm", + "Surge", + "Tide", + "Thorn", + "Veil", + "Veil", + "Void", + "Waste", + "Wound", + "Wrath", + "Yonder" + ], + "town_prefixes": [ + "Ash", + "Bright", + "Cedar", + "Deep", + "Elder", + "Frost", + "Glen", + "High", + "Iron", + "Jade", + "Ashen", + "Blood", + "Cobalt", + "Dusk", + "Ebon", + "Gloom", + "Ironforge", + "Keen", + "Mourn", + "Raven", + "Storm", + "Void", + "Wraith", + "Night", + "Silvers", + "Black", + "Crimson", + "Fire", + "Grim", + "Briar", + "Obsidian", + "Shade", + "Thorn", + "Sable", + "Rift", + "Dread", + "Sorrow", + "Bleak", + "Eclipse", + "Eternity", + "Glint", + "Gleam", + "Hollow", + "Lament", + "Mire", + "Molt", + "Nocturne", + "Onyx", + "Pale", + "Rook", + "Shimmer", + "Stonem", + "Stone", + "Stonehold", + "Stonekeep", + "Stoneforge", + "Stormfall", + "Stormgate", + "Stormhold", + "Stormreach", + "Stormspire", + "Stormwind", + "Throne", + "Twilight", + "Valiant", + "Valest", + "Valer", + "Vex", + "Vile", + "Warden" + ], + "town_suffixes": [ + "brook", + "dale", + "field", + "haven", + "keep", + "moor", + "port", + "reach", + "stone", + "vale", + "forge", + "shard", + "hollow", + "cove", + "hall", + "watch", + "spire", + "glade", + "cliff", + "glen", + "tower", + "fort", + "hold", + "bastion", + "crypt", + "crossing", + "crown", + "ridge", + "fell", + "breach", + "briar", + "bloom", + "field", + "river", + "canyon", + "fen", + "crag", + "gate", + "bridge", + "watchtower", + "watcher", + "mire", + "waste", + "breach", + "fall", + "crone", + "shadow", + "veil", + "blight", + "soul", + "night", + "storm", + "fire", + "ice", + "iron", + "dark", + "glimmer", + "glare", + "scar", + "scarred", + "spire", + "peak", + "ridge", + "hall", + "hold", + "spire", + "vale", + "vale", + "haven", + "hollow", + "breach", + "crust" + ], + "character_adjectives": [ + "the Blind", + "the Magnificent", + "the Cunning", + "the Swift", + "the Stoic", + "the Fearless", + "the Enigmatic", + "the Shadow", + "the Light", + "the Wanderer", + "the Unbroken", + "the Relentless", + "the Ruthless", + "the Merciless", + "the Devourer", + "the Ancient", + "the Fallen", + "the Immortal", + "the Vengeful", + "the Stormborn", + "the Silent", + "the Bloodied", + "the Corrupt", + "the Darkened", + "the Ember", + "the Crimson", + "the Iron", + "the Sable", + "the Radiant", + "the Tempest", + "the Gloom", + "the Warlord", + "the Titan", + "the Behemoth", + "the Leviathan", + "the Doombringer", + "the Wraith", + "the Sundered", + "the Gloomstalker", + "the Blight", + "the Harbinger", + "the Abyssal", + "the Scourge", + "the Dread", + "the Fury", + "the Specter", + "the Maw", + "the Protector", + "the Guardian", + "the Champion", + "the Savior", + "the Reaper", + "the Harvester", + "the Seeker", + "the Whisperer", + "the Tempest-born", + "the Iron-clad", + "the Moonlit", + "the Sun-scarred", + "the Bone-choked", + "the Frost-kissed", + "the Ashen", + "the Shattered", + "the Echo-bound", + "the Vile", + "the Harsh", + "the Unseen", + "the Unyielding", + "of the North", + "of the South", + "of the East", + "of the West", + "of the Dark", + "of the Light", + "of the Forgotten", + "of the Broken", + "of the Eternal", + "of the Shadowlands", + "of the Burning", + "of the Frozen", + "of the Storm", + "of the Depths", + "of the Maw", + "of the Ashen Sea", + "of the Crimson Dawn" + ], + "character_prefixes": [ + "Sir", + "Lady", + "Mighty", + "Elder", + "Grand", + "Humble", + "Radiant", + "Lord", + "High", + "Royal", + "Ancient", + "Warden", + "Seer", + "Master" + ], + "exotic_prefixes": [ + "Ar", + "Bel", + "Zel", + "Kyn", + "Nai", + "Vyr", + "Sera", + "Jor", + "Lun", + "Yara", + "Esh", + "Mor", + "Kael", + "Tar", + "Lyr", + "Dra", + "Qin", + "Thal", + "Oryn", + "Sil", + "Vex", + "Gor", + "Rin", + "Zan" + ], + "exotic_infixes": [ + "en", + "ae", + "or", + "is", + "sen", + "kar", + "ju", + "ja", + "ur", + "ai", + "ir", + "an", + "el", + "ël", + "æl", + "ær", + "łu", + "đj", + "äl", + "in", + "eu", + "ai", + "aï", + "io", + "ea", + "oa", + "ui", + "oi", + "øl", + "ou", + "ea", + "'", + "au" + ], + "exotic_suffixes": [ + "ion", + "ara", + "eth", + "on", + "yr", + "ith", + "dor", + "zen", + "mar", + "fen", + "is", + "al", + "or", + "ex", + "an", + "ul", + "ik", + "en", + "ar", + "ur" + ], + "exotic_syllables": [ + "ra", + "el", + "ka", + "la", + "ma", + "za", + "sha", + "na", + "ta", + "li", + "vi", + "da", + "shi", + "ri", + "lo", + "xi", + "po", + "ke", + "do", + "zo" + ], + "event_ideas": [ + { + "name": "storm_flood", + "description": "A sudden storm floods the river, threatening the local farms.", + "stats": [ + { "stat": "Population", "value": -5 }, + { "stat": "Food", "value": -12 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 10, "max": 70 }, + "strength": 20 + }, + { + "name": "earthquake", + "description": "A massive quake ripples across the region.", + "stats": [ + { "stat": "Transportation", "value": -9 }, + { "stat": "Sprawl", "value": -5 }, + { "stat": "Health", "value": -3 }, + { "stat": "Industry", "value": -2 }, + { "stat": "Population", "value": -10 }, + { "stat": "Happiness", "value": -8 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 10, "max": 110 }, + "strength": 80 + }, + + { + "name": "region_blood_monsoon", + "description": "A crimson rain falls over the region, poisoning crops and water sources.", + "stats": [ + { "stat": "Food", "value": -18 }, + { "stat": "Health", "value": -12 }, + { "stat": "Population", "value": -7 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 10, "max": 110 }, + "strength": 70 + }, + + { + "name": "town_haunted_market", + "description": "Spectral merchants appear, selling cryptic ware from a bygone era.", + "stats": [ + { "stat": "Trade", "value": 9 }, + { "stat": "Science", "value": 9 }, + { "stat": "Food", "value": 13 }, + { "stat": "Crime", "value": 7 }, + { "stat": "Threat", "value": 11 } + ], + "duration": { "Duration": 3 }, + "application": "WhenPresent", + "effect_bounds": { "min": 10, "max": 80 }, + "strength": 60 + }, + + { + "name": "region_darkening_sun", + "description": "The sky is shrouded in an unnatural pallid dusk, lowering morale and crop yields.", + "stats": [ + { "stat": "Happiness", "value": -14 }, + { "stat": "Food", "value": -10 }, + { "stat": "Culture", "value": -5 } + ], + "duration": { "Duration": 6 }, + "application": "WhenPresent", + "effect_bounds": { "min": 20, "max": 90 }, + "strength": 75 + }, + + { + "name": "town_giant_earthworm", + "description": "A colossal earthworm burrows beneath the town, destabilizing foundations and causing tremors.", + "stats": [ + { "stat": "Food", "value": -5 }, + { "stat": "Industry", "value": -2 }, + { "stat": "Happiness", "value": -12 }, + { "stat": "Fortification", "value": -8 }, + { "stat": "Population", "value": -4 } + ], + "duration": { "Duration": 4 }, + "application": "WhenPresent", + "effect_bounds": { "min": 30, "max": 70 }, + "strength": 65 + }, + { + "name": "region_arcane_surge", + "description": "An uncontrollable surge of raw sangressence tears through reality, causing unpredictable effects.", + "stats": [ + { "stat": "Science", "value": 12 }, + { "stat": "Education", "value": 8 }, + { "stat": "Population", "value": -6 } + ], + "duration": { "Duration": 6 }, + "application": "WhenPresent", + "effect_bounds": { "min": 30, "max": 70 }, + "strength": 80 + }, + { + "name": "town_mushroom_meteor", + "description": "A meteor of colossal fungi explodes over a town, releasing spores that induce vivid hallucinations.", + "stats": [ + { "stat": "Health", "value": -10 }, + { "stat": "Crime", "value": 6 }, + { "stat": "Population", "value": -3 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 20, "max": 90 }, + "strength": 60 + }, + { + "name": "region_infernal_flood", + "description": "Molten rivers run through the region, boiling over cities and devouring forests.", + "stats": [ + { "stat": "Transportation", "value": -4 }, + { "stat": "Sprawl", "value": -5 }, + { "stat": "Happiness", "value": -19 }, + { "stat": "Food", "value": -15 }, + { "stat": "Population", "value": -12 } + ], + "duration": { "Duration": 5 }, + "application": "WhenPresent", + "effect_bounds": { "min": 20, "max": 90 }, + "strength": 70 + }, + { + "name": "region_sand_vortex", + "description": "A vortex of shifting sands sweeps the region, burying entire nations under dunes.", + "stats": [ + { "stat": "Bureaucracy", "value": -14 }, + { "stat": "Transportation", "value": -14 }, + { "stat": "Sprawl", "value": -14 }, + { "stat": "Population", "value": -16 }, + { "stat": "Trade", "value": -10 } + ], + "duration": { "Duration": 5 }, + "application": "WhenPresent", + "effect_bounds": { "min": 20, "max": 90 }, + "strength": 65 + }, + { + "name": "region_wind_of_gods", + "description": "A relentless gale from the gods tears through the region, scattering armies and wrecking supply lines.", + "stats": [ + { "stat": "Transportation", "value": -12 }, + { "stat": "Army", "value": -9 }, + { "stat": "Population", "value": -3 } + ], + "duration": { "Duration": 8 }, + "application": "WhenPresent", + "effect_bounds": { "min": 20, "max": 90 }, + "strength": 75 + }, + { + "name": "region_ancient_sunrise", + "description": "The sun rises in a crimson glow, amplifying the power of all dark cults and spreading fear.", + "stats": [ + { "stat": "Crime", "value": 9 }, + { "stat": "Happiness", "value": -8 }, + { "stat": "Influence", "value": -5 } + ], + "duration": { "Duration": 7 }, + "application": "WhenPresent", + "effect_bounds": { "min": 20, "max": 90 }, + "strength": 70 + }, + { + "name": "town_forest_of_eyes", + "description": "A forest that watches every step, slowly siphoning the life force from any who walk through.", + "stats": [ + { "stat": "Health", "value": -10 }, + { "stat": "Crime", "value": 7 }, + { "stat": "Happiness", "value": 7 }, + { "stat": "Population", "value": -14 } + ], + "duration": { "Duration": 8 }, + "application": "WhenPresent", + "effect_bounds": { "min": 20, "max": 90 }, + "strength": 80 + }, + { + "name": "city_corruption_scandal", + "description": "A high-ranking magistrate is discovered embezzling city funds, sparking public outrage and a demand for accountability.", + "stats": [ + { "stat": "Food", "value": -4 }, + { "stat": "Industry", "value": -3 }, + { "stat": "Science", "value": -3 }, + { "stat": "Trade", "value": -8 }, + { "stat": "Bureaucracy", "value": -7 }, + { "stat": "Crime", "value": 7 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 22, "max": 86 }, + "strength": 78 + }, + { + "name": "city_tax_reform", + "description": "The council implements a sweeping tax overhaul that raises revenue but triggers protests among merchants.", + "stats": [ + { "stat": "Food", "value": 9 }, + { "stat": "Industry", "value": 10 }, + { "stat": "Science", "value": 7 }, + { "stat": "Trade", "value": 13 }, + { "stat": "Happiness", "value": -4 }, + { "stat": "Crime", "value": 5 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 25, "max": 92 }, + "strength": 94 + }, + { + "name": "city_watch_mutiny", + "description": "The city guard, disgruntled by unpaid wages, mutinies turns bandits.", + "stats": [ + { "stat": "Strength", "value": -6 }, + { "stat": "Crime", "value": 8 }, + { "stat": "Population", "value": -2 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 18, "max": 80 }, + "strength": 66 + }, + { + "name": "city_water_contamination", + "description": "Tainted water leaks into the municipal supply, causing a sudden spike in illnesses.", + "stats": [ + { "stat": "Health", "value": -14 }, + { "stat": "Population", "value": -5 }, + { "stat": "Bureaucracy", "value": -3 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 21, "max": 88 }, + "strength": 87 + }, + { + "name": "city_bureaucratic_bureaucracy", + "description": "A new procedural reform overhauls city administration, halting projects for months and stalling economic growth.", + "stats": [ + { "stat": "Bureaucracy", "value": 14 }, + { "stat": "Sprawl", "value": -9 }, + { "stat": "Health", "value": -7 }, + { "stat": "Food", "value": 3 }, + { "stat": "Industry", "value": 2 }, + { "stat": "Science", "value": 3 }, + { "stat": "Trade", "value": 4 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 23, "max": 90 }, + "strength": 82 + }, + { + "name": "city_guild_suppression", + "description": "The council cracks down on the city's merchant guilds, confiscating goods and driving merchants underground.", + "stats": [ + { "stat": "Trade", "value": -11 }, + { "stat": "Crime", "value": 6 }, + { "stat": "Population", "value": -3 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 19, "max": 83 }, + "strength": 68 + }, + { + "name": "city_civic_riot", + "description": "An assembly of disgruntled workers erupts into a violent riot, tearing through market stalls and public buildings.", + "stats": [ + { "stat": "Trade", "value": -12 }, + { "stat": "Happiness", "value": -9 }, + { "stat": "Crime", "value": 10 } + ], + "duration": { "Duration": 2 }, + "application": "WhenPresent", + "effect_bounds": { "min": 25, "max": 95 }, + "strength": 78 + }, + { + "name": "city_public_health_crisis", + "description": "A mysterious disease spreads through the city's crowded streets, overwhelming the local infirmaries.", + "stats": [ + { "stat": "Health", "value": -3 }, + { "stat": "Population", "value": -3 }, + { "stat": "Happiness", "value": -2 } + ], + "duration": { "Duration": 6 }, + "application": "Recurring", + "effect_bounds": { "min": 20, "max": 95 }, + "strength": 71 + }, + { + "name": "city_transport_infrastructure_fail", + "description": "The city's main aqueduct collapses, cutting off water supply to half the districts.", + "stats": [ + { "stat": "Transportation", "value": -15 }, + { "stat": "Population", "value": -4 }, + { "stat": "Bureaucracy", "value": -2 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 20, "max": 90 }, + "strength": 70 + }, + { + "name": "city_festival_corruption", + "description": "During a grand city festival, officials accept bribes to award contracts, compromising civic integrity.", + "stats": [ + { "stat": "Bureaucracy", "value": -8 }, + { "stat": "Crime", "value": 4 }, + { "stat": "Happiness", "value": -3 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 20, "max": 90 }, + "strength": 70 + }, + { + "name": "city_gold_exodus", + "description": "A sudden discovery of gold in the hinterlands draws merchants away, leaving local markets starved of currency.", + "stats": [ + { "stat": "Food", "value": -4 }, + { "stat": "Industry", "value": -4 }, + { "stat": "Trade", "value": -8 }, + { "stat": "Population", "value": -2 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 20, "max": 90 }, + "strength": 70 + }, + { + "name": "regional_drought", + "description": "An extended dry spell cripples crop yields, driving up food prices and crippling the agrarian economy.", + "stats": [ + { "stat": "Food", "value": -15 }, + { "stat": "Trade", "value": -13 }, + { "stat": "Happiness", "value": -5 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 20, "max": 90 }, + "strength": 70 + }, + { + "name": "city_tariff_levy", + "description": "The city council imposes a high tariff on imported goods to boost local industry, sparking backlash from merchants.", + "stats": [ + { "stat": "Trade", "value": -10 }, + { "stat": "Food", "value": -4 }, + { "stat": "Industry", "value": -6 }, + { "stat": "Science", "value": -3 }, + { "stat": "Crime", "value": 15 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 20, "max": 90 }, + "strength": 70 + }, + { + "name": "market_hoarding", + "description": "A powerful merchant cartel hoards staple goods, manipulating prices to inflate profits at the cost of ordinary citizens.", + "stats": [ + { "stat": "Food", "value": -7 }, + { "stat": "Industry", "value": -6 }, + { "stat": "Trade", "value": -7 }, + { "stat": "Population", "value": -3 } + ], + "duration": { "Duration": 7 }, + "application": "WhenPresent", + "effect_bounds": { "min": 20, "max": 90 }, + "strength": 70 + }, + + { + "name": "industrial_explosion", + "description": "A catastrophic blast at the main ironworks destroys equipment and halts production for months.", + "stats": [ + { "stat": "Industry", "value": -19 }, + { "stat": "Food", "value": -3 }, + { "stat": "Trade", "value": -7 }, + { "stat": "Population", "value": -4 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 20, "max": 90 }, + "strength": 70 + }, + { + "name": "foreign_investment_boom", + "description": "A foreign dynasty invests heavily in local mining, sparking a surge in jobs and wealth but also widening inequality.", + "stats": [ + { "stat": "Industry", "value": 12 }, + { "stat": "Science", "value": 3 }, + { "stat": "Trade", "value": 8 }, + { "stat": "Crime", "value": 5 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 20, "max": 90 }, + "strength": 70 + }, + { + "name": "tax_evasion_scheme", + "description": "A sophisticated tax evasion network siphons off a large portion of city revenue, forcing austerity measures.", + "stats": [ + { "stat": "Food", "value": -8 }, + { "stat": "Industry", "value": -7 }, + { "stat": "Trade", "value": -9 }, + { "stat": "Crime", "value": 15 }, + { "stat": "Bureaucracy", "value": -6 }, + { "stat": "Population", "value": -2 } + ], + "duration": { "Duration": 6 }, + "application": "WhenPresent", + "effect_bounds": { "min": 25, "max": 95 }, + "strength": 81 + }, + { + "name": "currency_devaluation", + "description": "The city's coinage is devalued by a sudden policy shift, causing imported goods to skyrocket in price.", + "stats": [ + { "stat": "Food", "value": -8 }, + { "stat": "Industry", "value": -3 }, + { "stat": "Trade", "value": -9 }, + { "stat": "Health", "value": -4 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 23, "max": 95 }, + "strength": 76 + }, + { + "name": "artisan_fair_success", + "description": "A grand artisan fair attracts wealthy patrons, boosting local crafts and increasing export revenues.", + "stats": [ + { "stat": "Industry", "value": 8 }, + { "stat": "Industry", "value": 9 }, + { "stat": "Trade", "value": 9 }, + { "stat": "Population", "value": 2 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 23, "max": 95 }, + "strength": 77 + }, + { + "name": "resource_piracy", + "description": "Sea-borne raiders seize a shipment of precious stones destined for the city, flooding the market with counterfeit goods.", + "stats": [ + { "stat": "Trade", "value": -12 }, + { "stat": "Food", "value": -7 }, + { "stat": "Industry", "value": -6 }, + { "stat": "Threat", "value": 3 }, + { "stat": "Crime", "value": 14 } + ], + "duration": { "Duration": 4 }, + "application": "WhenPresent", + "effect_bounds": { "min": 25, "max": 95 }, + "strength": 80 + }, + { + "name": "steel_furnace_overheat", + "description": "A critical failure in the city's primary steel furnace sparks an uncontrollable fire, destroying production lines.", + "stats": [ + { "stat": "Industry", "value": -17 }, + { "stat": "Trade", "value": -9 }, + { "stat": "Happiness", "value": -2 }, + { "stat": "Population", "value": -3 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 24, "max": 95 }, + "strength": 77 + }, + { + "name": "artisan_tech_innovation", + "description": "A guild of master craftsmen invents a new forging technique that doubles output and lowers raw material usage.", + "stats": [ + { "stat": "Industry", "value": 14 }, + { "stat": "Industry", "value": 13 }, + { "stat": "Science", "value": 15 }, + { "stat": "Trade", "value": 9 }, + { "stat": "Crime", "value": 3 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 26, "max": 95 }, + "strength": 83 + }, + { + "name": "coal_mine_sabotage", + "description": "Covert saboteurs collapse a major coal shaft, halting fuel supply to all local factories for weeks.", + "stats": [ + { "stat": "Industry", "value": -15 }, + { "stat": "Crime", "value": 6 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 23, "max": 95 }, + "strength": 75 + }, + { + "name": "foreign_factory_purchase", + "description": "A foreign conglomerate purchases the city's largest textile mill, imposing new quotas that reduce local employment.", + "stats": [ + { "stat": "Industry", "value": -9 }, + { "stat": "Population", "value": -4 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 22, "max": 95 }, + "strength": 73 + }, + { + "name": "blacksmiths_rebel", + "description": "Skilled blacksmiths organize a strike demanding better wages, halting the production of critical weapons.", + "stats": [ + { "stat": "Industry", "value": -10 }, + { "stat": "Strength", "value": -5 }, + { "stat": "Crime", "value": 4 } + ], + "duration": { "Duration": 6 }, + "application": "WhenPresent", + "effect_bounds": { "min": 22, "max": 95 }, + "strength": 74 + }, + { + "name": "machine_revolution", + "description": "The introduction of automated presses in the leather works cuts labor costs but renders many artisans obsolete.", + "stats": [ + { "stat": "Industry", "value": 11 }, + { "stat": "Population", "value": -5 }, + { "stat": "Crime", "value": 3 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 22, "max": 95 }, + "strength": 74 + }, + { + "name": "bottleneck_transportation", + "description": "The city's main mean of transportation is seized by gangsters, disrupting the flow of raw materials to factories.", + "stats": [ + { "stat": "Transportation", "value": -8 }, + { "stat": "Industry", "value": -6 }, + { "stat": "Crime", "value": 7 } + ], + "duration": { "Duration": 3 }, + "application": "WhenPresent", + "effect_bounds": { "min": 23, "max": 95 }, + "strength": 75 + }, + { + "name": "export_tariff_relief", + "description": "An unexpected removal of export tariffs on metal goods opens new markets, boosting production rates.", + "stats": [ + { "stat": "Industry", "value": 12 }, + { "stat": "Trade", "value": 9 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 23, "max": 95 }, + "strength": 75 + }, + { + "name": "smelter_piracy", + "description": "A band of raiders captures a shipment of precious ores destined for the city, flooding the market with cheap counterfeit.", + "stats": [ + { "stat": "Industry", "value": -11 }, + { "stat": "Trade", "value": -7 }, + { "stat": "Crime", "value": 10 } + ], + "duration": { "Duration": 4 }, + "application": "WhenPresent", + "effect_bounds": { "min": 23, "max": 95 }, + "strength": 77 + }, + { + "name": "frontline_betrayal", + "description": "A key vanguard commander secretly defects, scattering a significant portion of the army and boosting enemy threat.", + "stats": [ + { "stat": "Strength", "value": -6 }, + { "stat": "Threat", "value": 11 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 22, "max": 95 }, + "strength": 74 + }, + { + "name": "naval_battle_victory", + "description": "The city's navy defeats a hostile threat, securing coastal trade routes and striking a blow to the enemy's threat level.", + "stats": [ + { "stat": "Strength", "value": 12 }, + { "stat": "Threat", "value": -9 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 23, "max": 95 }, + "strength": 75 + }, + { + "name": "disease_in_soldiers", + "description": "A virulent pestilence breaks out among the ranks, lowering army numbers and damaging overall health.", + "stats": [ + { "stat": "Army", "value": -14 }, + { "stat": "Health", "value": -10 }, + { "stat": "Strength", "value": -5 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 23, "max": 95 }, + "strength": 77 + }, + { + "name": "recruitment_panic", + "description": "A surge of conscripts floods the army, but poor training causes a sharp drop in combat effectiveness.", + "stats": [ + { "stat": "Army", "value": 8 }, + { "stat": "Strength", "value": -9 }, + { "stat": "Threat", "value": 3 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 23, "max": 95 }, + "strength": 75 + }, + { + "name": "training_expedition", + "description": "A focused military academy expedition hones the troops' skills, raising overall strength at the cost of a temporary manpower drain.", + "stats": [ + { "stat": "Strength", "value": 11 }, + { "stat": "Army", "value": -6 }, + { "stat": "Threat", "value": -5 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 23, "max": 95 }, + "strength": 75 + }, + { + "name": "spy_operation_success", + "description": "A covert spy network uncovers threats around, reducing the threat level and providing a tactical advantage.", + "stats": [ + { "stat": "Threat", "value": -10 }, + { "stat": "Influence", "value": 3 }, + { "stat": "Strength", "value": 4 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 23, "max": 95 }, + "strength": 75 + }, + { + "name": "war_taxes_harsh", + "description": "The council imposes severe war taxes to fund the army, inflating military budgets but cracking public happiness.", + "stats": [ + { "stat": "Strength", "value": 9 }, + { "stat": "Happiness", "value": -8 }, + { "stat": "Food", "value": -3 }, + { "stat": "Industry", "value": -3 }, + { "stat": "Science", "value": -3 }, + { "stat": "Trade", "value": -3 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 23, "max": 95 }, + "strength": 75 + }, + { + "name": "battlefield_innovation", + "description": "A revolutionary tactic is adopted on the front lines, dramatically boosting army strength and lowering enemy threat.", + "stats": [ + { "stat": "Strength", "value": 13 }, + { "stat": "Threat", "value": -8 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 23, "max": 95 }, + "strength": 75 + }, + { + "name": "trade_agreement", + "description": "The city brokered a favorable trade pact with a neighboring realm, opening new markets for local goods.", + "stats": [ + { "stat": "Trade", "value": 12 }, + { "stat": "Food", "value": 3 }, + { "stat": "Industry", "value": 3 }, + { "stat": "Science", "value": 3 }, + { "stat": "Trade", "value": 3 }, + { "stat": "Population", "value": 3 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 23, "max": 95 }, + "strength": 76 + }, + { + "name": "peace_council", + "description": "A diplomatic summit ends a long-standing border conflict, reducing threat levels and fostering cultural exchange.", + "stats": [ + { "stat": "Trade", "value": 10 }, + { "stat": "Culture", "value": 7 }, + { "stat": "Happiness", "value": 5 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 22, "max": 95 }, + "strength": 76 + }, + { + "name": "bounty_hunt_success", + "description": "A coordinated hunt eliminates a notorious calamity, restoring safety to nearby villages.", + "stats": [ + { "stat": "Crime", "value": -12 }, + { "stat": "Threat", "value": -8 }, + { "stat": "Happiness", "value": 4 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 23, "max": 95 }, + "strength": 75 + }, + { + "name": "technological_breakthrough", + "description": "Inventors in the city unveiled new technologies with huge applications in the industrial field.", + "stats": [ + { "stat": "Science", "value": 15 }, + { "stat": "Industry", "value": 6 }, + { "stat": "Food", "value": 3 }, + { "stat": "Trade", "value": 3 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 21, "max": 95 }, + "strength": 78 + }, + { + "name": "festival_of_luxury", + "description": "A grand festival draws wealthy merchants and foreign dignitaries, boosting tourism and local pride.", + "stats": [ + { "stat": "Tourism", "value": 13 }, + { "stat": "Science", "value": 3 }, + { "stat": "Trade", "value": 3 }, + { "stat": "Culture", "value": 3 }, + { "stat": "Influence", "value": 3 }, + { "stat": "Happiness", "value": 6 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 22, "max": 95 }, + "strength": 77 + }, + { + "name": "military_training_expedition", + "description": "An intensive training expedition sharpens the army's tactics, increasing overall strength without cost.", + "stats": [ + { "stat": "Strength", "value": 12 }, + { "stat": "Army", "value": 3 }, + { "stat": "Threat", "value": -5 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 21, "max": 95 }, + "strength": 77 + }, + { + "name": "health_initiative", + "description": "A citywide vaccination campaign eradicates a deadly plague, dramatically improving public health.", + "stats": [ + { "stat": "Health", "value": 16 }, + { "stat": "Population", "value": 4 }, + { "stat": "Happiness", "value": 5 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 23, "max": 95 }, + "strength": 79 + }, + { + "name": "artisan_summit", + "description": "A gathering of master artisans leads to the sharing of techniques that double production efficiency.", + "stats": [ + { "stat": "Industry", "value": 14 }, + { "stat": "Science", "value": 8 }, + { "stat": "Trade", "value": 3 }, + { "stat": "Population", "value": 2 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 21, "max": 95 }, + "strength": 77 + }, + { + "name": "infrastructure_repair", + "description": "A massive repair drive restores crumbling roads and bridges, slashing travel time and boosting trade.", + "stats": [ + { "stat": "Sprawl", "value": 10 }, + { "stat": "Transportation", "value": 9 }, + { "stat": "Health", "value": 7 }, + { "stat": "Industry", "value": 7 }, + { "stat": "Trade", "value": 7 }, + { "stat": "Food", "value": 5 }, + { "stat": "Trade", "value": 4 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 24, "max": 95 }, + "strength": 79 + }, + { + "name": "cultural_exposition", + "description": "The city hosts an international exposition, showcasing its heritage and attracting scholars and tourists alike.", + "stats": [ + { "stat": "Culture", "value": 12 }, + { "stat": "Tourism", "value": 10 }, + { "stat": "Happiness", "value": 4 }, + { "stat": "Influence", "value": 4 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 23, "max": 95 }, + "strength": 78 + }, + { + "name": "great_earthquake", + "description": "A massive quake rips through the city, shattering buildings, collapsing bridges, and killing thousands.", + "stats": [ + { "stat": "Health", "value": -19 }, + { "stat": "Population", "value": -18 }, + { "stat": "Happiness", "value": -15 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 26, "max": 95 }, + "strength": 81 + }, + { + "name": "plague_of_scorpion", + "description": "A deadly disease spreads through the populace, turning citizens into venom-infused monsters.", + "stats": [ + { "stat": "Health", "value": -14 }, + { "stat": "Population", "value": -10 }, + { "stat": "Crime", "value": 8 } + ], + "duration": { "Duration": 14 }, + "application": "WhenPresent", + "effect_bounds": { "min": 23, "max": 95 }, + "strength": 79 + }, + { + "name": "oil_fire_in_barnyard", + "description": "An oil storage depot explodes, sending a wave of fire over the city that reduces the army's morale and strength.", + "stats": [ + { "stat": "Industry", "value": -9 }, + { "stat": "Happiness", "value": -4 }, + { "stat": "Threat", "value": 10 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 22, "max": 95 }, + "strength": 73 + }, + { + "name": "fire_of_sacred_temple", + "description": "The city's most revered temple is consumed by a supernatural inferno, spilling holy ash into the streets and igniting widespread panic.", + "stats": [ + { "stat": "Culture", "value": -15 }, + { "stat": "Threat", "value": 12 }, + { "stat": "Happiness", "value": -6 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 24, "max": 95 }, + "strength": 77 + }, + { + "name": "cursed_great_flood", + "description": "An unseasonal deluge swallows the city, flooding every district, destroying crops, and causing widespread disease.", + "stats": [ + { "stat": "Food", "value": -13 }, + { "stat": "Industry", "value": -6 }, + { "stat": "Trade", "value": -8 }, + { "stat": "Threat", "value": 13 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 25, "max": 95 }, + "strength": 81 + }, + { + "name": "massive_barricade_breach", + "description": "A minor calamity overpowers the city's fortifications, unleashing a wave of slaughter and chaos.", + "stats": [ + { "stat": "Fortification", "value": -19 }, + { "stat": "Threat", "value": 19 }, + { "stat": "Happiness", "value": -12 } + ], + "duration": { "Duration": 1 }, + "application": "PermanentEffectToApply", + "effect_bounds": { "min": 24, "max": 95 }, + "strength": 81 + }, + { + "name": "invasion_of_the_undead", + "description": "A horde of reanimated civilians under the influence of a calamity attack citizens and military alike.", + "stats": [ + { "stat": "Threat", "value": 14 }, + { "stat": "Crime", "value": -10 }, + { "stat": "Population", "value": -12 } + ], + "duration": { "Duration": 5 }, + "application": "WhenPresent", + "effect_bounds": { "min": 23, "max": 95 }, + "strength": 78 + } + ] +} diff --git a/lib_efo/src/entity.rs b/lib_efo/src/entity.rs new file mode 100644 index 0000000..f99eddd --- /dev/null +++ b/lib_efo/src/entity.rs @@ -0,0 +1,152 @@ +//! # Entity System +//! +//! The `Entity` type represents any object that can participate in the game world. +//! It encapsulates runtime statistics, temporary bonuses, and metadata, +//! along with information about its lifetime and the nature of its effects. +//! +//! The design intentionally groups behaviour into two primary components, +//! `OverallStats` and `MetaStats`. The `entity_type` field is a placeholder +//! for future trait-based dispatch - the enum will eventually be replaced +//! by a type-safe system. For the moment it provides a quick lookup for +//! logic that distinguishes creatures, items, terrain, etc. +//! + +use clap::ValueEnum; +use derive_more::{Add, Display, Sub}; +use serde::{Deserialize, Serialize}; +use uuid::Uuid; + +use crate::stats::{EntityType, MetaStats, OverallStats}; +pub mod implementations; + +/// An entity that can be present in the game world. +/// +/// Entities are mutable only through the entity system's public API. +/// Their fields are private to prevent accidental state corruption. +#[derive(Serialize, Deserialize, Debug, Clone, Default)] +pub struct Entity { + /// The name of the entity + pub name: String, + + /// The global identifier for the entity + pub id: Uuid, + + /// Runtime statistics that determine the entity's behaviour. + /// + /// These values are updated by the game loop and reflect the + /// entity's current state (e.g., health, speed, attack). + stats: OverallStats, + + /// Temporary statistics that include bonuses from events, + /// leaders, or other temporary modifiers. + /// + /// `temp_stats` is recalculated each turn and does not persist + /// beyond the entity's lifetime. + #[serde(skip)] + temp_stats: Option, + + /// Non-statistical metadata such as name, rarity, and faction. + /// + /// This information is not directly part of the entity's combat + /// calculations but is useful for UI and logic. + metadata: MetaStats, + + /// The categorical type of the entity. + /// + /// Currently an enum that distinguishes creatures, items, + /// terrain, etc. It will be phased out in favor of a trait-based + /// system for greater type safety. + pub entity_type: EntityType, + + /// The lifetime of the entity within the game world. + /// + /// The game loop checks this value during each tick to decide + /// whether to keep or remove the entity. + duration: EntityDuration, + + /// Describes the effect applied by the entity. + /// + /// This determines when the effect is applied and whether it + /// persists after the entity is removed. + effect_nature: EffectApplication, + + /// Limits that clamp any stat changes caused by the entity's effect. + effect_bounds: EffectBounds, +} + +/// Limits for the maximum and minimum value that an effect may +/// modify a statistic. The bounds are applied after the effect has +/// been calculated to keep stats within a sane range. +/// +/// `min` and `max` are inclusive. +#[derive(Debug, Serialize, Deserialize, Clone, Default, Add, Sub)] +#[allow(missing_docs)] +pub struct EffectBounds { + pub min: usize, + pub max: usize, +} + +/// How the entity's effect is applied over time. +#[derive(Debug, Serialize, Deserialize, Clone, Default, ValueEnum)] +pub enum EffectApplication { + /// Repeatedly applied every turn while the entity is present. + /// Use with caution, as this can produce catastrophic results + /// (e.g., an ever-erupting terrain). + Recurring, + + /// Modifies the attached entity's stats only while present. + /// Removed when the entity is removed. Common for leaders, + /// temporary events, or terrain. + WhenPresent, + + /// Permanently modifies stats; the change persists after + /// the event ends. + #[default] + PermanentEffectToApply, + + /// Indicates that a permanent effect has already been applied. + /// Useful for bookkeeping when a long-lasting event applies + /// its effect only once. + PermanentEffectApplied, +} + +/// Represents how long an entity remains active in the world. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default)] +pub enum EntityDuration { + /// The entity persists until it is explicitly destroyed. + Permanent, + + /// The entity remains for a fixed number of turns. + /// The counter is decremented each tick and the entity becomes + /// `Done` once it reaches zero. + Duration(usize), + + /// The entity's lifecycle has finished and it should no longer + /// be updated. This variant is typically used for one-off + /// events or buffs that expire after their final turn. + #[default] + Done, +} + +/// An identifier that can be supplied on the command line. +/// +/// The enum is deliberately small so it can be used as a Clap argument type. +/// It accepts **either** +/// * a plain name (e.g. `"bob"`), or +/// * a UUID that is prefixed with an `@` (e.g. `"@3f4c6b7e-d4d1-4b3f-a7a4-0d5c6b8e1f9b"`). +/// +/// The two variants are kept separate so that downstream code can decide +/// whether it should treat the value as a human-readable name or a +/// machine-identifiable UUID. +#[derive(Debug, Clone, PartialEq, Eq, Display)] +pub enum EntityIdentifier { + /// A human-readable name. + Name(String), + /// A UUID that was supplied with a leading `@`. The `@` is stripped + /// when the enum is constructed - only the raw UUID string is stored. + Id(String), +} + +#[allow(clippy::unwrap_used)] +#[cfg(test)] +mod test; diff --git a/lib_efo/src/entity/implementations.rs b/lib_efo/src/entity/implementations.rs new file mode 100644 index 0000000..c87d3fd --- /dev/null +++ b/lib_efo/src/entity/implementations.rs @@ -0,0 +1,418 @@ +//! Implementation of all needed traits for the Entity struct +mod from_impl; +use cli_table::format::{Border, HorizontalLine, Separator, VerticalLine}; +use cli_table::{Style, WithTitle}; +use colored::*; +use rand::distr::Distribution; +use uuid::Uuid; // [3] - colored-rs examples + +use crate::Displayable; +use crate::entity::{EffectApplication, EffectBounds, Entity, EntityDuration}; +use crate::epoch::epoch_traits::Diffable; +use crate::error::EpochError; +use crate::stats::{EntityType, GenericStat, MetaStats, OverallStats, Position, StatPair, Symbols}; +use crate::utils::RngLevel; + +// ---------- Implementation ---------- +impl Displayable for Entity { + // Detailed multi-line view (used e.g. in logs) + fn print_full(&self) { + println!("{}", self.to_pretty_tree(),); + if let Ok(c) = self.stats_to_table() { + println!("{c}"); + } + } + + /// One-liner used for auto-generation of Vec displays + fn oneline_display(&self) -> String { + let capital = self + .metadata + .capital + .as_ref() + .map(|c| format!(" 󰻾[{:>2}] ", c).green()) + .unwrap_or_default(); + + let governor = self + .metadata + .governor + .as_ref() + .map(|g| format!(" 󰻾[{:>2}]", g).red()) + .unwrap_or_default(); + + let prestige = if *self.metadata.prestige > 0 { + format!(" {:2}{}", self.metadata.prestige, "📈".yellow()) + } else { + String::new() + }; + + // ---- build the two lines ---- + let line1 = format!( + "├──┬─ {} {:23} {} ──────> {} {}", + self.id.to_string().split_at(7).0.blue(), + self.name.green(), + self.entity_type.to_symbol(), + self.metadata.position.to_symbol(), + self.duration.to_symbol().yellow(), + ); + + let (junction, line3) = if !capital.is_empty() | !governor.is_empty() { + ("├", format!("│ └─ {}{}\n", capital, governor,)) + } else { + ("└", "".to_string()) + }; + let line2 = format!( + "│ {}─ Faction: {} │ Effect: {} {}, Stats: {}{}", + junction, + self.metadata.faction.to_symbol(), + self.effect_nature.to_symbol(), + self.effect_bounds.to_symbol(), + self.stats.to_symbol(), + prestige, + ); + + format!("{}\n{}\n{}│", line1, line2, line3) + } +} + +impl Entity { + // Display the entity's statistics in a pretty table. + /// + /// The table contains both the permanent and temporary statistics of the + /// entity. The table is formatted with a custom border and separator + /// using the `cli_table` crate. + /// + /// # Returns + /// A `Result` containing the table display on success, or an `EpochError` if the + /// conversion to a table string fails. + pub fn full_stats_to_table(&self) -> Result { + let items = if let Some(t) = &self.temp_stats { + vec![&self.stats, t] + } else { + vec![&self.stats] + }; + self.stat_to_table(items) + } + + /// Display the entity's statistics in a pretty table (same format as + /// `full_stats_to_table`). + /// + /// This method is provided for backward compatibility and forwards all + /// work to `full_stats_to_table`. + /// + /// # Returns + /// A `Result` containing the table display on success, or an `EpochError` if the + /// conversion to a table string fails. + pub fn stats_to_table(&self) -> Result { + let items = if let Some(t) = &self.temp_stats { + vec![t] + } else { + vec![&self.stats] + }; + self.stat_to_table(items) + } + + /// Display the entity's statistics in a pretty table (same format as + /// `full_stats_to_table`). + /// + /// This method is provided for backward compatibility and forwards all + /// work to `full_stats_to_table`. + /// + /// # Returns + /// A `Result` containing the table display on success, or an `EpochError` if the + /// conversion to a table string fails. + /// + fn stat_to_table( + &self, + items: Vec<&OverallStats>, + ) -> Result { + items + .with_title() + .bold(true) + .border( + Border::builder() + .top(HorizontalLine::new('┌', '┐', '┬', '─')) + .bottom(HorizontalLine::new('└', '┘', '┴', '─')) + .left(VerticalLine::new('│')) + .right(VerticalLine::new('│')) + .build(), + ) + .separator( + Separator::builder() + .column(Some(VerticalLine::new('│'))) + .row(Some(HorizontalLine::new('├', '┤', '┼', '─'))) + .build(), + ) + // .foreground_color(Some(cli_table::Color::Blue)) // Border Color + .display() + .map_err(|_e| EpochError::TableStringConversionError { + name: self.name.clone(), + id: self.id, + }) + } + + /// Pretty-print the entity as a coloured tree. + /// + /// The output is a `String` that visualises the entity's metadata, type, + /// duration, effect bounds, and any links. Colours are applied using + /// `colored::Colorize`. + /// + /// # Returns + /// A `String` containing the formatted tree. + pub fn to_pretty_tree(&self) -> String { + // Helper that prefixes a line with the correct amount of vertical bars. + fn indent(level: usize, line: &str) -> String { + let bars = "│ ".repeat(level); + format!(" {}{}", bars, line) + } + + let mut out = String::new(); + + // ── Top line: + out.push_str(&format!( + "[{} {} 󰻾[{}]]\n", + self.entity_type.to_symbol().blue().bold(), + self.name.cyan().bold(), + self.id.to_string().blue().bold() + )); + + // ── Metadata section + out.push_str(&indent(0, &format!("├─ {}\n", "metadata".green()))); + if self.metadata.capital.is_some() { + out.push_str(&indent( + 1, + &format!( + "├─ {}: {:?}\n", + "capital".bright_green(), + self.metadata.capital + ), + )); + } + if *self.metadata.prestige > 0 { + out.push_str(&indent( + 1, + &format!( + "├─ {}: {}\n", + "prestige".bright_green(), + self.metadata.prestige + ), + )); + } + out.push_str(&indent( + 1, + &format!( + "└─ {}: {}\n", + "position".bright_green(), + self.metadata.position.to_symbol() + ), + )); + + // ── Optional links + if !self.metadata.links.is_empty() { + out.push_str(&indent(0, &format!("├─ {}\n", "links".green()))); + for (i, link) in self.metadata.links.iter().enumerate() { + let last = i == self.metadata.links.len() - 1; + let symbol = if last { "└─" } else { "├─" }; + out.push_str(&indent( + 1, + &format!("{} 󰻾[{}]\n", symbol, link.to_string().yellow()), + )); + } + } + // ── Other top-level fields + out.push_str(&indent( + 0, + &format!( + "├─ {}: {}\n", + "duration".green(), + self.duration.to_symbol().yellow() + ), + )); + out.push_str(&indent( + 0, + &format!("├─ {}: {:?}\n", "effect_nature".green(), self.effect_nature), + )); + out.push_str(&indent( + 0, + &format!( + "└─ {}: {}", + "effect_bounds".green(), + self.effect_bounds.to_symbol() + ), + )); + + out + } + + /// Create an entity using a specific RNG level. + /// + /// The entity is initialised with random statistics, a random position, + /// and a random prestige value derived from the supplied `RngLevel`. + /// + /// # Arguments + /// * `e_type` - The type of entity to create. + /// * `rng` - The RNG level to use when generating random values. + /// + /// # Returns + /// * `Ok(Self)` - The newly created entity. + /// * `Err(EpochError)` - Propagated from any randomisation failure. + /// + pub fn create_rng(e_type: &EntityType, rng: &RngLevel) -> Result { + let mut r = rand::rng(); + Ok(Self { + id: Uuid::new_v4(), + stats: OverallStats::create_rng(rng, &mut r)?, + temp_stats: None, + metadata: MetaStats { + prestige: GenericStat(rng.to_rng()?.sample(&mut r) as isize), + position: Position::create_rng(&mut r)?, + ..Default::default() + }, + entity_type: e_type.clone(), + ..Default::default() + }) + } + + /// Change one of the entity's statistics. + /// + /// The stat identified by `pair` is replaced with the new value specified in + /// the `StatPair`. This is a direct overwrite and does not apply any delta. + /// + /// # Arguments + /// * `pair` - The stat pair containing the key and new value. + /// + pub fn change_stat(&mut self, pair: StatPair) { + overwrite_stat(&mut self.stats, pair); + } + + /// Apply a delta to all of the entity's statistics. + /// + /// The delta specified by `pair` is added to each of the statistics in + /// `self.stats`. Positive values increase the stat, negative values + /// decrease it. + /// + /// # Arguments + /// * `pair` - The stat pair representing the change to apply. + pub fn delta_stat(&mut self, pair: StatPair) { + add_to_stat(&mut self.stats, pair); + } + + /// Replace the entity's duration. + /// + /// The method simply overwrites the current `duration` field with the + /// supplied value. It is primarily intended for use when an entity + /// is instantiated from external data that already contains a duration value. + pub fn modify_duration(&mut self, duration: EntityDuration) { + self.duration = duration + } + + /// Set the way the entity's effects are applied. + /// + /// The field `effect_nature` determines how the entity's abilities or + /// status effects interact with the world. + /// This method overwrites the existing value with the supplied `EffectApplication`. + pub fn modify_effect_application(&mut self, effect: EffectApplication) { + self.effect_nature = effect + } + + /// Update the bounds that govern the entity's effects. + /// + /// `effect_bounds` controls the maximum/minimum strength, duration or + /// other limits that can be applied to the entity's effects. This + /// method simply replaces the current bounds with the supplied + /// `EffectBounds`. + pub fn modify_effect_bounds(&mut self, effect: EffectBounds) { + self.effect_bounds = effect + } +} + +/// Replace a statistic in `stats` with the value from `pair`. +/// +/// This function performs a direct overwrite: the existing value is +/// discarded and the new value from `pair` is written in its place. +fn overwrite_stat(stats: &mut OverallStats, pair: StatPair) { + let affected_stat = stats.get_field_mut(&pair.stat); + *affected_stat = pair.value; +} + +/// Add a delta to a statistic in `stats`. +/// +/// The delta in `pair.value` is added to the current statistic value +/// using `saturating_add`, so that the result never overflows the +/// underlying integer type. +fn add_to_stat(stats: &mut OverallStats, pair: StatPair) { + let affected_stat = stats.get_field_mut(&pair.stat); + let current_value = *affected_stat; + *affected_stat = GenericStat(current_value.saturating_add(*pair.value)); +} + +/// Compare a field on `self` with the same field on `other`. +/// If they are equal → `None`, otherwise → the value from `other`. +macro_rules! diff_fields { + // Two arguments: the two objects you want to compare + ($self:ident, $other:ident, $( $field:ident ),* $(,)?) => { + $( + let $field = if $self.$field == $other.$field { + None + } else { + $other.$field.clone() + }; + )* + }; +} +impl Diffable for Entity { + fn delta(&self, other: &Self) -> Self { + let name = if self.name == other.name { + self.name.clone() + } else { + format!("{}->{}", self.name, other.name) + }; + Self { + name, + stats: self.stats.clone() - other.stats.clone(), + temp_stats: self.temp_stats.delta(&other.temp_stats), + metadata: self.metadata.delta(&other.metadata), + entity_type: other.entity_type.clone(), + duration: other.duration.clone(), + effect_nature: other.effect_nature.clone(), + effect_bounds: other.effect_bounds.clone(), + id: Uuid::new_v4(), + } + } +} + +impl Diffable for Option { + fn delta(&self, other: &Self) -> Self { + match (self, other) { + (None, None) => None, + (None, Some(a)) => Some(a.clone()), + (Some(a), None) => Some(a.clone()), + (Some(a), Some(b)) => Some(a.clone() - b.clone()), + } + } +} + +impl Diffable for MetaStats { + fn delta(&self, other: &Self) -> Self { + diff_fields!(self, other, capital, governor); + Self { + position: self.position.clone() - other.position.clone(), + capital, + governor, + faction: { + match (self.faction.as_ref(), other.faction.as_ref()) { + (None, None) => None, + (None, Some(b)) => Some(*b), + (Some(a), None) => Some(*a), + (Some(_), Some(b)) => Some(*b), + } + }, + links: self + .links + .clone() + .into_iter() + .filter(|t1| other.links.iter().any(|t2| t1 == t2)) + .collect(), + prestige: self.prestige - other.prestige, + } + } +} diff --git a/lib_efo/src/entity/implementations/from_impl.rs b/lib_efo/src/entity/implementations/from_impl.rs new file mode 100644 index 0000000..b30bc5b --- /dev/null +++ b/lib_efo/src/entity/implementations/from_impl.rs @@ -0,0 +1,132 @@ +//! Mostly from implementation for entities + +use crate::{ + entity::{EffectBounds, EntityDuration, EntityIdentifier}, + error::EpochError, +}; + +use std::{ops::Range, str::FromStr}; + +/// Simple error type used by `FromStr`. +/// clap only needs the error to implement `Display`, so a `String` is fine. +impl FromStr for EntityDuration { + type Err = EpochError; + + fn from_str(s: &str) -> Result { + // Normalise the string: trim and lowercase. + let raw = s.trim().to_ascii_lowercase(); + + match raw.as_str() { + "permanent" | "perm" => Ok(EntityDuration::Permanent), + "done" => Ok(EntityDuration::Done), + + // Handle the `duration:NNN` form. + _ if raw.starts_with("duration:") => { + let num_part = &raw["duration:".len()..]; + match num_part.parse::() { + Ok(v) => Ok(EntityDuration::Duration(v)), + Err(_) => Err(EpochError::ParsingDuration( + "Invalid duration value", + num_part.to_string(), + )), + } + } + + // Allow a bare number (e.g. `10` → Duration(10)). + _ if raw.chars().all(|c| c.is_ascii_digit()) => match raw.parse::() { + Ok(v) => Ok(EntityDuration::Duration(v)), + Err(_) => Err(EpochError::ParsingDuration("Could not parse number", raw)), + }, + + // Anything else is an error. + _ => Err(EpochError::ParsingDuration("Invalid EntityDuration", raw)), + } + } +} + +impl FromStr for EffectBounds { + type Err = EpochError; + + /// Parse an `EffectBounds` from a string. + /// + /// Acceptable forms: + /// * `min:max` - colon-separated values + /// * `min-max` - dash-separated values + /// + /// Errors are reported with `EpochError::ParsingDurationError`. + fn from_str(s: &str) -> Result { + // Normalise the string: trim whitespace. + let raw = s.trim(); + + // Helper to parse a pair of numbers from a delimiter separated string. + fn parse_pair(raw: &str, delim: char) -> Result<(usize, usize), EpochError> { + let parts: Vec<&str> = raw.split(delim).collect(); + if parts.len() != 2 { + return Err(EpochError::ParsingBounds( + "Invalid EffectBounds format", + raw.to_string(), + )); + } + let min = parts[0].trim().parse::().map_err(|_| { + EpochError::ParsingBounds("Could not parse number", raw.to_string()) + })?; + let max = parts[1].trim().parse::().map_err(|_| { + EpochError::ParsingBounds("Could not parse number", raw.to_string()) + })?; + Ok((min, max)) + } + + // 1. Try colon-separated (`min:max`). + if raw.find(':').is_some() { + let (min, max) = parse_pair(raw, ':')?; + return Ok(EffectBounds { min, max }); + } + + // 2. Try dash-separated (`min-max`). + if raw.find('-').is_some() { + let (min, max) = parse_pair(raw, '-')?; + return Ok(EffectBounds { min, max }); + } + + // 3. Anything else is an error. + Err(EpochError::ParsingBounds( + "Invalid EffectBounds", + raw.to_string(), + )) + } +} + +impl FromStr for EntityIdentifier { + type Err = EpochError; + + /// Parse a string into an `EntityIdentifier`. + /// + /// * If the string starts with `@`, the remainder is parsed as a UUID + /// (using the `uuid` crate). The `@` is **not** stored. + /// * Otherwise the string is treated as a name. + fn from_str(s: &str) -> Result { + match s.strip_prefix('@') { + Some(uuid) if !uuid.is_empty() => Ok(EntityIdentifier::Id(uuid.to_string())), + Some(_) => Err(EpochError::EmptyIdentifier), + None => Ok(EntityIdentifier::Name(s.to_string())), + } + } +} + +impl From<(usize, usize)> for EffectBounds { + fn from(value: (usize, usize)) -> Self { + Self { + min: value.0, + max: value.1, + } + } +} + +impl From> for EffectBounds { + fn from(value: Range) -> Self { + Self { + min: value.start, + max: value.end, + } + } +} diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_delta_stat_positive.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_delta_stat_positive.snap new file mode 100644 index 0000000..c0df3e1 --- /dev/null +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_delta_stat_positive.snap @@ -0,0 +1,91 @@ +--- +source: lib_efo/src/entity/test.rs +expression: "format!(\"{:#?}\", e)" +--- +Entity { + name: "", + id: 00000000-0000-0000-0000-000000000000, + stats: OverallStats { + demographics: GenericStat( + 0, + ), + population: GenericStat( + 0, + ), + growth_rate: GenericStat( + 0, + ), + crime: GenericStat( + 0, + ), + happiness: GenericStat( + 0, + ), + economy: GenericStat( + 0, + ), + food: GenericStat( + 0, + ), + industry: GenericStat( + 0, + ), + science: GenericStat( + 0, + ), + trade: GenericStat( + 0, + ), + military: GenericStat( + 0, + ), + army: GenericStat( + 0, + ), + strength: GenericStat( + 0, + ), + fortification: GenericStat( + 0, + ), + threat: GenericStat( + 0, + ), + infrastructure: GenericStat( + 0, + ), + bureaucracy: GenericStat( + 0, + ), + transportation: GenericStat( + 0, + ), + sprawl: GenericStat( + 0, + ), + health: GenericStat( + 4, + ), + }, + temp_stats: None, + metadata: MetaStats { + position: Position( + 0, + 0, + ), + capital: None, + governor: None, + faction: None, + links: [], + prestige: GenericStat( + 0, + ), + }, + entity_type: Event, + duration: Done, + effect_nature: PermanentEffectToApply, + effect_bounds: EffectBounds { + min: 0, + max: 0, + }, +} diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta-2.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta-2.snap new file mode 100644 index 0000000..58a59f3 --- /dev/null +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta-2.snap @@ -0,0 +1,169 @@ +--- +source: lib_efo/src/entity/test.rs +expression: "format!(\"{:#?}{}\", delta2, delta2.full_stats_to_table().unwrap())" +--- +Entity { + name: "Bob", + id: 00000000-0000-0000-0000-000000000000, + stats: OverallStats { + demographics: GenericStat( + 0, + ), + population: GenericStat( + 0, + ), + growth_rate: GenericStat( + 0, + ), + crime: GenericStat( + 0, + ), + happiness: GenericStat( + 0, + ), + economy: GenericStat( + 0, + ), + food: GenericStat( + 0, + ), + industry: GenericStat( + 0, + ), + science: GenericStat( + 0, + ), + trade: GenericStat( + 0, + ), + military: GenericStat( + 0, + ), + army: GenericStat( + 0, + ), + strength: GenericStat( + 0, + ), + fortification: GenericStat( + 0, + ), + threat: GenericStat( + 0, + ), + infrastructure: GenericStat( + 0, + ), + bureaucracy: GenericStat( + 0, + ), + transportation: GenericStat( + 0, + ), + sprawl: GenericStat( + 0, + ), + health: GenericStat( + 0, + ), + }, + temp_stats: Some( + OverallStats { + demographics: GenericStat( + 0, + ), + population: GenericStat( + 0, + ), + growth_rate: GenericStat( + 0, + ), + crime: GenericStat( + 0, + ), + happiness: GenericStat( + 0, + ), + economy: GenericStat( + 0, + ), + food: GenericStat( + 0, + ), + industry: GenericStat( + 0, + ), + science: GenericStat( + 0, + ), + trade: GenericStat( + 0, + ), + military: GenericStat( + 0, + ), + army: GenericStat( + 0, + ), + strength: GenericStat( + 0, + ), + fortification: GenericStat( + 0, + ), + threat: GenericStat( + 0, + ), + infrastructure: GenericStat( + 0, + ), + bureaucracy: GenericStat( + 0, + ), + transportation: GenericStat( + 0, + ), + sprawl: GenericStat( + 0, + ), + health: GenericStat( + 0, + ), + }, + ), + metadata: MetaStats { + position: Position( + 0, + 0, + ), + capital: None, + governor: None, + faction: Some( + FactionId( + 5, + ), + ), + links: [ + TownId( + 6, + ), + ], + prestige: GenericStat( + 0, + ), + }, + entity_type: Town, + duration: Permanent, + effect_nature: Recurring, + effect_bounds: EffectBounds { + min: 0, + max: 3, + }, +}┌─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┐ +│ DEM │ POP │ GRW │ CRM │ HPY │ ECO │ FOD │ IND │ SCI │ TRD │ MIL │ ARM │ STR │ FRT │ THR │ IFR │ BUR │ TRP │ SPR │ HLT │ +├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤ +│ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ +├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤ +│ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ +└─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┘ + diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta-3.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta-3.snap new file mode 100644 index 0000000..548c7f5 --- /dev/null +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta-3.snap @@ -0,0 +1,173 @@ +--- +source: lib_efo/src/entity/test.rs +expression: "format!(\"{:#?}{}\", delta3, delta3.full_stats_to_table().unwrap())" +--- +Entity { + name: "Bob->Alice", + id: 00000000-0000-0000-0000-000000000000, + stats: OverallStats { + demographics: GenericStat( + 42, + ), + population: GenericStat( + 42, + ), + growth_rate: GenericStat( + 42, + ), + crime: GenericStat( + 42, + ), + happiness: GenericStat( + 42, + ), + economy: GenericStat( + 42, + ), + food: GenericStat( + 42, + ), + industry: GenericStat( + 42, + ), + science: GenericStat( + 42, + ), + trade: GenericStat( + 42, + ), + military: GenericStat( + 42, + ), + army: GenericStat( + 42, + ), + strength: GenericStat( + 42, + ), + fortification: GenericStat( + 42, + ), + threat: GenericStat( + 42, + ), + infrastructure: GenericStat( + 42, + ), + bureaucracy: GenericStat( + 42, + ), + transportation: GenericStat( + 42, + ), + sprawl: GenericStat( + 42, + ), + health: GenericStat( + 42, + ), + }, + temp_stats: Some( + OverallStats { + demographics: GenericStat( + 5, + ), + population: GenericStat( + 6, + ), + growth_rate: GenericStat( + 7, + ), + crime: GenericStat( + 8, + ), + happiness: GenericStat( + 9, + ), + economy: GenericStat( + 10, + ), + food: GenericStat( + 11, + ), + industry: GenericStat( + 12, + ), + science: GenericStat( + 13, + ), + trade: GenericStat( + 14, + ), + military: GenericStat( + 15, + ), + army: GenericStat( + 16, + ), + strength: GenericStat( + 17, + ), + fortification: GenericStat( + 18, + ), + threat: GenericStat( + 19, + ), + infrastructure: GenericStat( + 20, + ), + bureaucracy: GenericStat( + 21, + ), + transportation: GenericStat( + 22, + ), + sprawl: GenericStat( + 23, + ), + health: GenericStat( + 24, + ), + }, + ), + metadata: MetaStats { + position: Position( + -11, + -662, + ), + capital: Some( + TownId( + 5000, + ), + ), + governor: Some( + CharacterId( + 2000, + ), + ), + faction: Some( + FactionId( + 44, + ), + ), + links: [], + prestige: GenericStat( + 2, + ), + }, + entity_type: Monster, + duration: Permanent, + effect_nature: Recurring, + effect_bounds: EffectBounds { + min: 0, + max: 33, + }, +}┌─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┐ +│ DEM │ POP │ GRW │ CRM │ HPY │ ECO │ FOD │ IND │ SCI │ TRD │ MIL │ ARM │ STR │ FRT │ THR │ IFR │ BUR │ TRP │ SPR │ HLT │ +├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤ +│ 42  │ 42  │ 42  │ 42  │ 42  │ 42  │ 42  │ 42  │ 42  │ 42  │ 42  │ 42  │ 42  │ 42  │ 42  │ 42  │ 42  │ 42  │ 42  │ 42  │ +├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤ +│ 5  │ 6  │ 7  │ 8  │ 9  │ 10  │ 11  │ 12  │ 13  │ 14  │ 15  │ 16  │ 17  │ 18  │ 19  │ 20  │ 21  │ 22  │ 23  │ 24  │ +└─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┘ + diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta.snap new file mode 100644 index 0000000..bfc612a --- /dev/null +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_entity_delta.snap @@ -0,0 +1,173 @@ +--- +source: lib_efo/src/entity/test.rs +expression: "format!(\"{:#?}{}\", &delta, delta.full_stats_to_table().unwrap())" +--- +Entity { + name: "Alice->Bob", + id: 00000000-0000-0000-0000-000000000000, + stats: OverallStats { + demographics: GenericStat( + -42, + ), + population: GenericStat( + -42, + ), + growth_rate: GenericStat( + -42, + ), + crime: GenericStat( + -42, + ), + happiness: GenericStat( + -42, + ), + economy: GenericStat( + -42, + ), + food: GenericStat( + -42, + ), + industry: GenericStat( + -42, + ), + science: GenericStat( + -42, + ), + trade: GenericStat( + -42, + ), + military: GenericStat( + -42, + ), + army: GenericStat( + -42, + ), + strength: GenericStat( + -42, + ), + fortification: GenericStat( + -42, + ), + threat: GenericStat( + -42, + ), + infrastructure: GenericStat( + -42, + ), + bureaucracy: GenericStat( + -42, + ), + transportation: GenericStat( + -42, + ), + sprawl: GenericStat( + -42, + ), + health: GenericStat( + -42, + ), + }, + temp_stats: Some( + OverallStats { + demographics: GenericStat( + 5, + ), + population: GenericStat( + 6, + ), + growth_rate: GenericStat( + 7, + ), + crime: GenericStat( + 8, + ), + happiness: GenericStat( + 9, + ), + economy: GenericStat( + 10, + ), + food: GenericStat( + 11, + ), + industry: GenericStat( + 12, + ), + science: GenericStat( + 13, + ), + trade: GenericStat( + 14, + ), + military: GenericStat( + 15, + ), + army: GenericStat( + 16, + ), + strength: GenericStat( + 17, + ), + fortification: GenericStat( + 18, + ), + threat: GenericStat( + 19, + ), + infrastructure: GenericStat( + 20, + ), + bureaucracy: GenericStat( + 21, + ), + transportation: GenericStat( + 22, + ), + sprawl: GenericStat( + 23, + ), + health: GenericStat( + 24, + ), + }, + ), + metadata: MetaStats { + position: Position( + 11, + 662, + ), + capital: Some( + TownId( + 3000, + ), + ), + governor: Some( + CharacterId( + 1500, + ), + ), + faction: Some( + FactionId( + 5, + ), + ), + links: [], + prestige: GenericStat( + -2, + ), + }, + entity_type: Town, + duration: Permanent, + effect_nature: Recurring, + effect_bounds: EffectBounds { + min: 0, + max: 3, + }, +}┌─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┐ +│ DEM │ POP │ GRW │ CRM │ HPY │ ECO │ FOD │ IND │ SCI │ TRD │ MIL │ ARM │ STR │ FRT │ THR │ IFR │ BUR │ TRP │ SPR │ HLT │ +├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤ +│ -42 │ -42 │ -42 │ -42 │ -42 │ -42 │ -42 │ -42 │ -42 │ -42 │ -42 │ -42 │ -42 │ -42 │ -42 │ -42 │ -42 │ -42 │ -42 │ -42 │ +├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤ +│ 5  │ 6  │ 7  │ 8  │ 9  │ 10  │ 11  │ 12  │ 13  │ 14  │ 15  │ 16  │ 17  │ 18  │ 19  │ 20  │ 21  │ 22  │ 23  │ 24  │ +└─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┘ + diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_oneline_display-2.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_oneline_display-2.snap new file mode 100644 index 0000000..f9b9836 --- /dev/null +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_oneline_display-2.snap @@ -0,0 +1,14 @@ +--- +source: lib_efo/src/entity/test.rs +expression: e.to_pretty_tree() +--- +[ Hero 󰻾[0c000000-0000-0000-0000-000000000000]] + ├─ metadata + │ ├─ capital: Some(TownId(50)) + │ ├─ prestige: 3 + │ └─ position: ( 2, 4)⚓ + ├─ links + │ └─ 󰻾[3] + ├─ duration: ⧗10 + ├─ effect_nature: Recurring + └─ effect_bounds: (1 ⭾ 5) diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_oneline_display.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_oneline_display.snap new file mode 100644 index 0000000..3f3d182 --- /dev/null +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_oneline_display.snap @@ -0,0 +1,8 @@ +--- +source: lib_efo/src/entity/test.rs +expression: e.oneline_display() +--- +├──┬─ 0c00000 Hero  ──────> ( 2, 4)⚓ ⧗10 +│ ├─ Faction: 2 │ Effect: ⟳ (1 ⭾ 5), Stats: 0 0💰 0 0󰡢 3📈 +│ └─  󰻾[50]  󰻾[11] +│ diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_stats_no_temp-2.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_stats_no_temp-2.snap new file mode 100644 index 0000000..18dc09e --- /dev/null +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_stats_no_temp-2.snap @@ -0,0 +1,10 @@ +--- +source: lib_efo/src/entity/test.rs +expression: "format!(\"{}\", table)" +--- +┌─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┐ +│ DEM │ POP │ GRW │ CRM │ HPY │ ECO │ FOD │ IND │ SCI │ TRD │ MIL │ ARM │ STR │ FRT │ THR │ IFR │ BUR │ TRP │ SPR │ HLT │ +├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤ +│ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ +└─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┘ + diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_stats_no_temp.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_stats_no_temp.snap new file mode 100644 index 0000000..18dc09e --- /dev/null +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_stats_no_temp.snap @@ -0,0 +1,10 @@ +--- +source: lib_efo/src/entity/test.rs +expression: "format!(\"{}\", table)" +--- +┌─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┐ +│ DEM │ POP │ GRW │ CRM │ HPY │ ECO │ FOD │ IND │ SCI │ TRD │ MIL │ ARM │ STR │ FRT │ THR │ IFR │ BUR │ TRP │ SPR │ HLT │ +├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤ +│ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ +└─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┘ + diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_stats_with_temp-2.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_stats_with_temp-2.snap new file mode 100644 index 0000000..18dc09e --- /dev/null +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_stats_with_temp-2.snap @@ -0,0 +1,10 @@ +--- +source: lib_efo/src/entity/test.rs +expression: "format!(\"{}\", table)" +--- +┌─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┐ +│ DEM │ POP │ GRW │ CRM │ HPY │ ECO │ FOD │ IND │ SCI │ TRD │ MIL │ ARM │ STR │ FRT │ THR │ IFR │ BUR │ TRP │ SPR │ HLT │ +├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤ +│ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ +└─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┘ + diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_stats_with_temp.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_stats_with_temp.snap new file mode 100644 index 0000000..e2c91d6 --- /dev/null +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_full_stats_with_temp.snap @@ -0,0 +1,12 @@ +--- +source: lib_efo/src/entity/test.rs +expression: "format!(\"{}\", table)" +--- +┌─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┐ +│ DEM │ POP │ GRW │ CRM │ HPY │ ECO │ FOD │ IND │ SCI │ TRD │ MIL │ ARM │ STR │ FRT │ THR │ IFR │ BUR │ TRP │ SPR │ HLT │ +├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤ +│ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ +├─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┼─────┤ +│ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ 0  │ +└─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┘ + diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta-2.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta-2.snap new file mode 100644 index 0000000..3beae88 --- /dev/null +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta-2.snap @@ -0,0 +1,25 @@ +--- +source: lib_efo/src/entity/test.rs +expression: "format!(\"{:#?}\", delta2)" +--- +MetaStats { + position: Position( + 0, + 0, + ), + capital: None, + governor: None, + faction: Some( + FactionId( + 33, + ), + ), + links: [ + TownId( + 55, + ), + ], + prestige: GenericStat( + 0, + ), +} diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta-3.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta-3.snap new file mode 100644 index 0000000..63e30c0 --- /dev/null +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta-3.snap @@ -0,0 +1,25 @@ +--- +source: lib_efo/src/entity/test.rs +expression: "format!(\"{:#?}\", delta3)" +--- +MetaStats { + position: Position( + 0, + 0, + ), + capital: None, + governor: None, + faction: Some( + FactionId( + 33, + ), + ), + links: [ + TownId( + 55, + ), + ], + prestige: GenericStat( + 0, + ), +} diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta.snap new file mode 100644 index 0000000..6d39112 --- /dev/null +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_meta_stats_delta.snap @@ -0,0 +1,29 @@ +--- +source: lib_efo/src/entity/test.rs +expression: "format!(\"{:#?}\", delta)" +--- +MetaStats { + position: Position( + -43, + -544, + ), + capital: Some( + TownId( + 1500, + ), + ), + governor: Some( + CharacterId( + 400, + ), + ), + faction: Some( + FactionId( + 33, + ), + ), + links: [], + prestige: GenericStat( + 2, + ), +} diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_minimal_oneline_display-2.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_minimal_oneline_display-2.snap new file mode 100644 index 0000000..c7e7d4e --- /dev/null +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_minimal_oneline_display-2.snap @@ -0,0 +1,10 @@ +--- +source: lib_efo/src/entity/test.rs +expression: e.to_pretty_tree() +--- +[ 󰻾[00000000-0000-0000-0000-000000000000]] + ├─ metadata + │ └─ position: ( 0, 0)⚓ + ├─ duration: ✔ + ├─ effect_nature: PermanentEffectToApply + └─ effect_bounds: (0 ⭾ 0) diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_minimal_oneline_display.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_minimal_oneline_display.snap new file mode 100644 index 0000000..bf6a2cb --- /dev/null +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_minimal_oneline_display.snap @@ -0,0 +1,7 @@ +--- +source: lib_efo/src/entity/test.rs +expression: e.oneline_display() +--- +├──┬─ 0000000  ──────> ( 0, 0)⚓ ✔ +│ └─ Faction: Ø │ Effect: ☈ (0 ⭾ 0), Stats: 0 0💰 0 0󰡢 +│ diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_modify_duration.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_modify_duration.snap new file mode 100644 index 0000000..61f463d --- /dev/null +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_modify_duration.snap @@ -0,0 +1,93 @@ +--- +source: lib_efo/src/entity/test.rs +expression: "format!(\"{:#?}\", e)" +--- +Entity { + name: "", + id: 00000000-0000-0000-0000-000000000000, + stats: OverallStats { + demographics: GenericStat( + 0, + ), + population: GenericStat( + 0, + ), + growth_rate: GenericStat( + 0, + ), + crime: GenericStat( + 0, + ), + happiness: GenericStat( + 0, + ), + economy: GenericStat( + 0, + ), + food: GenericStat( + 0, + ), + industry: GenericStat( + 0, + ), + science: GenericStat( + 0, + ), + trade: GenericStat( + 0, + ), + military: GenericStat( + 0, + ), + army: GenericStat( + 0, + ), + strength: GenericStat( + 0, + ), + fortification: GenericStat( + 0, + ), + threat: GenericStat( + 0, + ), + infrastructure: GenericStat( + 0, + ), + bureaucracy: GenericStat( + 0, + ), + transportation: GenericStat( + 0, + ), + sprawl: GenericStat( + 0, + ), + health: GenericStat( + 0, + ), + }, + temp_stats: None, + metadata: MetaStats { + position: Position( + 0, + 0, + ), + capital: None, + governor: None, + faction: None, + links: [], + prestige: GenericStat( + 0, + ), + }, + entity_type: Event, + duration: Duration( + 33, + ), + effect_nature: PermanentEffectToApply, + effect_bounds: EffectBounds { + min: 0, + max: 0, + }, +} diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_modify_effect_application.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_modify_effect_application.snap new file mode 100644 index 0000000..3fffbfd --- /dev/null +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_modify_effect_application.snap @@ -0,0 +1,91 @@ +--- +source: lib_efo/src/entity/test.rs +expression: "format!(\"{:#?}\", e)" +--- +Entity { + name: "", + id: 00000000-0000-0000-0000-000000000000, + stats: OverallStats { + demographics: GenericStat( + 0, + ), + population: GenericStat( + 0, + ), + growth_rate: GenericStat( + 0, + ), + crime: GenericStat( + 0, + ), + happiness: GenericStat( + 0, + ), + economy: GenericStat( + 0, + ), + food: GenericStat( + 0, + ), + industry: GenericStat( + 0, + ), + science: GenericStat( + 0, + ), + trade: GenericStat( + 0, + ), + military: GenericStat( + 0, + ), + army: GenericStat( + 0, + ), + strength: GenericStat( + 0, + ), + fortification: GenericStat( + 0, + ), + threat: GenericStat( + 0, + ), + infrastructure: GenericStat( + 0, + ), + bureaucracy: GenericStat( + 0, + ), + transportation: GenericStat( + 0, + ), + sprawl: GenericStat( + 0, + ), + health: GenericStat( + 0, + ), + }, + temp_stats: None, + metadata: MetaStats { + position: Position( + 0, + 0, + ), + capital: None, + governor: None, + faction: None, + links: [], + prestige: GenericStat( + 0, + ), + }, + entity_type: Event, + duration: Done, + effect_nature: PermanentEffectApplied, + effect_bounds: EffectBounds { + min: 0, + max: 0, + }, +} diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_modify_effect_bounds.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_modify_effect_bounds.snap new file mode 100644 index 0000000..7ce3de6 --- /dev/null +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_modify_effect_bounds.snap @@ -0,0 +1,91 @@ +--- +source: lib_efo/src/entity/test.rs +expression: "format!(\"{:#?}\", e)" +--- +Entity { + name: "", + id: 00000000-0000-0000-0000-000000000000, + stats: OverallStats { + demographics: GenericStat( + 0, + ), + population: GenericStat( + 0, + ), + growth_rate: GenericStat( + 0, + ), + crime: GenericStat( + 0, + ), + happiness: GenericStat( + 0, + ), + economy: GenericStat( + 0, + ), + food: GenericStat( + 0, + ), + industry: GenericStat( + 0, + ), + science: GenericStat( + 0, + ), + trade: GenericStat( + 0, + ), + military: GenericStat( + 0, + ), + army: GenericStat( + 0, + ), + strength: GenericStat( + 0, + ), + fortification: GenericStat( + 0, + ), + threat: GenericStat( + 0, + ), + infrastructure: GenericStat( + 0, + ), + bureaucracy: GenericStat( + 0, + ), + transportation: GenericStat( + 0, + ), + sprawl: GenericStat( + 0, + ), + health: GenericStat( + 0, + ), + }, + temp_stats: None, + metadata: MetaStats { + position: Position( + 0, + 0, + ), + capital: None, + governor: None, + faction: None, + links: [], + prestige: GenericStat( + 0, + ), + }, + entity_type: Event, + duration: Done, + effect_nature: PermanentEffectToApply, + effect_bounds: EffectBounds { + min: 33, + max: 33, + }, +} diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_option_stats_delta-2.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_option_stats_delta-2.snap new file mode 100644 index 0000000..0979c2d --- /dev/null +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_option_stats_delta-2.snap @@ -0,0 +1,68 @@ +--- +source: lib_efo/src/entity/test.rs +expression: "format!(\"{:#?}\", delta2)" +--- +Some( + OverallStats { + demographics: GenericStat( + 23, + ), + population: GenericStat( + 24, + ), + growth_rate: GenericStat( + 25, + ), + crime: GenericStat( + 26, + ), + happiness: GenericStat( + 27, + ), + economy: GenericStat( + 28, + ), + food: GenericStat( + 29, + ), + industry: GenericStat( + 30, + ), + science: GenericStat( + 31, + ), + trade: GenericStat( + 32, + ), + military: GenericStat( + 33, + ), + army: GenericStat( + 34, + ), + strength: GenericStat( + 35, + ), + fortification: GenericStat( + 36, + ), + threat: GenericStat( + 37, + ), + infrastructure: GenericStat( + 38, + ), + bureaucracy: GenericStat( + 39, + ), + transportation: GenericStat( + 40, + ), + sprawl: GenericStat( + 41, + ), + health: GenericStat( + 42, + ), + }, +) diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_option_stats_delta-3.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_option_stats_delta-3.snap new file mode 100644 index 0000000..81d4653 --- /dev/null +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_option_stats_delta-3.snap @@ -0,0 +1,68 @@ +--- +source: lib_efo/src/entity/test.rs +expression: "format!(\"{:#?}\", delta3)" +--- +Some( + OverallStats { + demographics: GenericStat( + 33, + ), + population: GenericStat( + 34, + ), + growth_rate: GenericStat( + 35, + ), + crime: GenericStat( + 36, + ), + happiness: GenericStat( + 37, + ), + economy: GenericStat( + 38, + ), + food: GenericStat( + 39, + ), + industry: GenericStat( + 40, + ), + science: GenericStat( + 41, + ), + trade: GenericStat( + 42, + ), + military: GenericStat( + 43, + ), + army: GenericStat( + 44, + ), + strength: GenericStat( + 45, + ), + fortification: GenericStat( + 46, + ), + threat: GenericStat( + 47, + ), + infrastructure: GenericStat( + 48, + ), + bureaucracy: GenericStat( + 49, + ), + transportation: GenericStat( + 50, + ), + sprawl: GenericStat( + 51, + ), + health: GenericStat( + 52, + ), + }, +) diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_option_stats_delta-4.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_option_stats_delta-4.snap new file mode 100644 index 0000000..7e98cf8 --- /dev/null +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_option_stats_delta-4.snap @@ -0,0 +1,5 @@ +--- +source: lib_efo/src/entity/test.rs +expression: "format!(\"{:#?}\", delta4)" +--- +None diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_option_stats_delta.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_option_stats_delta.snap new file mode 100644 index 0000000..0f89743 --- /dev/null +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_option_stats_delta.snap @@ -0,0 +1,68 @@ +--- +source: lib_efo/src/entity/test.rs +expression: "format!(\"{:#?}\", delta)" +--- +Some( + OverallStats { + demographics: GenericStat( + 10, + ), + population: GenericStat( + 10, + ), + growth_rate: GenericStat( + 10, + ), + crime: GenericStat( + 10, + ), + happiness: GenericStat( + 10, + ), + economy: GenericStat( + 10, + ), + food: GenericStat( + 10, + ), + industry: GenericStat( + 10, + ), + science: GenericStat( + 10, + ), + trade: GenericStat( + 10, + ), + military: GenericStat( + 10, + ), + army: GenericStat( + 10, + ), + strength: GenericStat( + 10, + ), + fortification: GenericStat( + 10, + ), + threat: GenericStat( + 10, + ), + infrastructure: GenericStat( + 10, + ), + bureaucracy: GenericStat( + 10, + ), + transportation: GenericStat( + 10, + ), + sprawl: GenericStat( + 10, + ), + health: GenericStat( + 10, + ), + }, +) diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_overwrite_stat.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_overwrite_stat.snap new file mode 100644 index 0000000..c088bce --- /dev/null +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_overwrite_stat.snap @@ -0,0 +1,66 @@ +--- +source: lib_efo/src/entity/test.rs +expression: "format!(\"{:#?}\", entity.stats)" +--- +OverallStats { + demographics: GenericStat( + 1, + ), + population: GenericStat( + 33, + ), + growth_rate: GenericStat( + 3, + ), + crime: GenericStat( + 4, + ), + happiness: GenericStat( + 5, + ), + economy: GenericStat( + 6, + ), + food: GenericStat( + 7, + ), + industry: GenericStat( + 8, + ), + science: GenericStat( + 9, + ), + trade: GenericStat( + 10, + ), + military: GenericStat( + 11, + ), + army: GenericStat( + 12, + ), + strength: GenericStat( + 13, + ), + fortification: GenericStat( + 14, + ), + threat: GenericStat( + 15, + ), + infrastructure: GenericStat( + 16, + ), + bureaucracy: GenericStat( + 17, + ), + transportation: GenericStat( + 18, + ), + sprawl: GenericStat( + 19, + ), + health: GenericStat( + 20, + ), +} diff --git a/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_print_full_output.snap b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_print_full_output.snap new file mode 100644 index 0000000..67966a5 --- /dev/null +++ b/lib_efo/src/entity/snapshots/lib_efo__entity__test__snapshot_print_full_output.snap @@ -0,0 +1,5 @@ +--- +source: lib_efo/src/entity/test.rs +expression: output +--- + diff --git a/lib_efo/src/entity/test.rs b/lib_efo/src/entity/test.rs new file mode 100644 index 0000000..22fc8bd --- /dev/null +++ b/lib_efo/src/entity/test.rs @@ -0,0 +1,541 @@ +// tests/mod.rs - or put this inside your crate's tests module +#![allow(unused_imports)] + +use std::str::FromStr; + +use crate::entity::{EffectApplication, EffectBounds, Entity, EntityDuration, EntityIdentifier}; +use crate::epoch::epoch_traits::Diffable; +use crate::error::EpochError; +use crate::stats::{self, EntityType, MetaStats, Position, StatPair, TownId}; +use std::io::Write; + +use super::*; +use crate::Displayable; +use insta::assert_snapshot; +use uuid::Uuid; + +#[test] +fn entity_duration_parses_permanent_and_done() { + assert_eq!( + EntityDuration::from_str("permanent").unwrap(), + EntityDuration::Permanent + ); + assert_eq!( + EntityDuration::from_str("PERMANENT").unwrap(), + EntityDuration::Permanent + ); + assert_eq!( + EntityDuration::from_str("perm").unwrap(), + EntityDuration::Permanent + ); + assert_eq!( + EntityDuration::from_str("done").unwrap(), + EntityDuration::Done + ); +} + +#[test] +fn entity_duration_parses_numeric_forms() { + // bare number + assert_eq!( + EntityDuration::from_str("5").unwrap(), + EntityDuration::Duration(5) + ); + // with leading zeros + assert_eq!( + EntityDuration::from_str("0005").unwrap(), + EntityDuration::Duration(5) + ); + // duration: prefix + assert_eq!( + EntityDuration::from_str("duration:10").unwrap(), + EntityDuration::Duration(10) + ); + // case-insensitive prefix + assert_eq!( + EntityDuration::from_str("DurAtIoN:20").unwrap(), + EntityDuration::Duration(20) + ); + // zero value + assert_eq!( + EntityDuration::from_str("duration:0").unwrap(), + EntityDuration::Duration(0) + ); +} + +#[test] +fn entity_duration_parses_with_surrounding_whitespace() { + assert_eq!( + EntityDuration::from_str(" 7 ").unwrap(), + EntityDuration::Duration(7) + ); + assert_eq!( + EntityDuration::from_str(" PERMANENT ").unwrap(), + EntityDuration::Permanent + ); +} + +#[test] +fn entity_duration_returns_error_on_invalid_inputs() { + // non-numeric bare string + let err = EntityDuration::from_str("10a").unwrap_err(); + match err { + EpochError::ParsingDuration(msg, val) => { + assert!(!msg.is_empty()); + assert_eq!(val, "10a"); + } + _ => panic!("Expected ParsingDuration error"), + } + + // malformed duration: form + let err = EntityDuration::from_str("duration:invalid").unwrap_err(); + match err { + EpochError::ParsingDuration(msg, val) => { + assert!(!msg.is_empty()); + assert_eq!(val, "invalid"); + } + _ => panic!("Expected ParsingDuration error"), + } + + // trailing spaces after the duration prefix - the numeric parser fails + let err = EntityDuration::from_str("duration: 5").unwrap_err(); + match err { + EpochError::ParsingDuration(msg, val) => { + assert_eq!(msg, "Invalid duration value"); + assert_eq!(val, " 5"); + } + _ => panic!("Expected ParsingDuration error"), + } + + // empty string + let err = EntityDuration::from_str("").unwrap_err(); + match err { + EpochError::ParsingDuration(msg, val) => { + assert!(!msg.is_empty()); + assert_eq!(val, ""); + } + _ => panic!("Expected ParsingDuration error"), + } +} + +#[test] +fn effect_bounds_parses_colon_and_dash_separated_values() { + // colon + let eb = EffectBounds::from_str("1:5").unwrap(); + assert_eq!(eb.min, 1); + assert_eq!(eb.max, 5); + + // dash + let eb = EffectBounds::from_str("2-10").unwrap(); + assert_eq!(eb.min, 2); + assert_eq!(eb.max, 10); +} + +#[test] +fn effect_bounds_parses_with_whitespace_and_leading_zeros() { + let eb = EffectBounds::from_str(" 01 : 05 ").unwrap(); + assert_eq!(eb.min, 1); + assert_eq!(eb.max, 5); +} + +#[test] +fn effect_bounds_returns_error_on_invalid_inputs() { + // too many parts + let err = EffectBounds::from_str("1:5:7").unwrap_err(); + match err { + EpochError::ParsingBounds(msg, val) => { + assert_eq!(msg, "Invalid EffectBounds format"); + assert_eq!(val, "1:5:7"); + } + _ => panic!("Expected ParsingBounds error"), + } + + // missing one side + let err = EffectBounds::from_str("1:").unwrap_err(); + match err { + EpochError::ParsingBounds(msg, val) => { + assert_eq!(msg, "Could not parse number"); + assert_eq!(val, "1:"); + } + _ => panic!("Expected ParsingBounds error"), + } + + // non-numeric part + let err = EffectBounds::from_str("a:5").unwrap_err(); + match err { + EpochError::ParsingBounds(msg, val) => { + assert_eq!(msg, "Could not parse number"); + assert_eq!(val, "a:5"); + } + _ => panic!("Expected ParsingBounds error"), + } + + // no delimiter + let err = EffectBounds::from_str("5").unwrap_err(); + match err { + EpochError::ParsingBounds(msg, val) => { + assert_eq!(msg, "Invalid EffectBounds"); + assert_eq!(val, "5"); + } + _ => panic!("Expected ParsingBounds error"), + } +} + +#[test] +fn entity_identifier_parses_id_and_name() { + // id + let id = EntityIdentifier::from_str("@1234-5678-9012-3456-7890").unwrap(); + match id { + EntityIdentifier::Id(uuid) => assert_eq!(uuid, "1234-5678-9012-3456-7890"), + _ => panic!("Expected Id variant"), + } + + // name + let name = EntityIdentifier::from_str("my_entity").unwrap(); + match name { + EntityIdentifier::Name(n) => assert_eq!(n, "my_entity"), + _ => panic!("Expected Name variant"), + } + + // empty name is still a valid Name + let empty = EntityIdentifier::from_str("").unwrap(); + match empty { + EntityIdentifier::Name(n) => assert_eq!(n, ""), + _ => panic!("Expected Name variant"), + } +} + +#[test] +fn entity_identifier_errors_on_invalid_id() { + // prefix with nothing after @ + let err = EntityIdentifier::from_str("@").unwrap_err(); + match err { + EpochError::EmptyIdentifier => {} + _ => panic!("Expected EmptyIdentifier error"), + } + + // // prefix followed by whitespace only + // let err = EntityIdentifier::from_str("@ ").unwrap_err(); + // match err { + // EpochError::EmptyIdentifier => {} + // _ => panic!("Expected EmptyIdentifier error"), + // } +} + +fn init_snapshot_env() { + colored::control::set_override(false); +} + +fn full_entity() -> Entity { + Entity { + id: Uuid::from_u128_le(12), + name: "Hero".into(), + entity_type: EntityType::Character, + metadata: MetaStats { + capital: Some(stats::TownId(50)), + governor: Some(stats::CharacterId(11)), + prestige: stats::GenericStat(3), + position: Position::from((2, 4)), + faction: Some(crate::stats::FactionId(2)), + links: vec![TownId(3)], + }, + duration: EntityDuration::Duration(10), + effect_nature: EffectApplication::Recurring, + effect_bounds: EffectBounds::from((1, 5)), + stats: stats::OverallStats::default(), + temp_stats: Some(stats::OverallStats::default()), + } +} + +#[test] +fn effect_bound_testing() { + let EffectBounds { min, max } = EffectBounds::from(0..1); + let EffectBounds { + min: min2, + max: max2, + } = EffectBounds::from((0, 1)); + assert_eq!(min, min2); + assert_eq!(max, max2); +} + +#[test] +fn snapshot_full_oneline_display() { + init_snapshot_env(); + let e = full_entity(); + assert_snapshot!(e.oneline_display()); + assert_snapshot!(e.to_pretty_tree()); +} + +#[test] +fn snapshot_minimal_oneline_display() { + init_snapshot_env(); + let e = Entity::default(); + assert_snapshot!(e.oneline_display()); + assert_snapshot!(e.to_pretty_tree()); +} + +#[test] +fn snapshot_print_full_output() { + init_snapshot_env(); + + let e = full_entity(); + + // Capture stdout into a buffer + let buffer = Vec::new(); + { + // let stdout = std::io::stdout(); + // let mut handle = stdout.lock(); + + // // Temporarily swap the real stdout for our buffer. + // let original = std::mem::replace(&mut handle, &mut buffer); + // Run the method we want to snapshot. + e.print_full(); + // Restore the original stdout. + // std::mem::replace(&mut handle, original); + } + + // Convert buffer → UTF-8 string and snapshot it. + let output = String::from_utf8_lossy(&buffer); + assert_snapshot!(output); +} + +#[test] +fn snapshot_full_stats_no_temp() { + init_snapshot_env(); + + let mut e = full_entity(); + e.temp_stats = None; + let table = e.full_stats_to_table().expect("table generation failed"); + assert_snapshot!(format!("{}", table)); + let table = e.stats_to_table().expect("table generation failed"); + assert_snapshot!(format!("{}", table)); +} + +#[test] +fn snapshot_full_stats_with_temp() { + init_snapshot_env(); + + let mut e = full_entity(); + e.temp_stats = Some(OverallStats::default()); + let table = e.full_stats_to_table().expect("table generation failed"); + assert_snapshot!(format!("{}", table)); + let table = e.stats_to_table().expect("table generation failed"); + assert_snapshot!(format!("{}", table)); +} + +/// ------------------------------------------------------------------ +/// 1. Helpers - `overwrite_stat` & `add_to_stat` +/// ------------------------------------------------------------------ +#[test] +fn snapshot_overwrite_stat() { + init_snapshot_env(); + + let mut entity = Entity::default(); + let stats = OverallStats::linear(0); + entity.stats = stats; + entity.change_stat(StatPair { + stat: stats::ListStats::Population, + value: stats::GenericStat(33), + }); + + assert_snapshot!(format!("{:#?}", entity.stats)); +} + +// #[test] +// fn snapshot_add_to_stat_saturating_add() { +// init_snapshot_env(); + +// let mut stats = stats_from_values(u32::MAX as i32 - 1, 20, 30); +// let pair = pair("health", 5); + +// add_to_stat(&mut stats, pair); + +// // The saturated addition should clamp to `u32::MAX`. +// assert_snapshot!(format!("{}\n", stats)); +// } + +/// ------------------------------------------------------------------ +/// 2. `Diffable` - `Entity::delta` +/// ------------------------------------------------------------------ +#[test] +fn snapshot_entity_delta() { + init_snapshot_env(); + + // Build two slightly different entities + let e1 = Entity { + id: uuid::Uuid::nil(), + name: "Alice".into(), + stats: OverallStats::linear(2), + temp_stats: None, + metadata: MetaStats { + position: Position::from((44, 666)), + capital: Some(stats::TownId(5000)), + governor: Some(stats::CharacterId(2000)), + faction: Some(stats::FactionId(44)), + links: vec![TownId(33)], + prestige: stats::GenericStat(3), + }, + entity_type: EntityType::Monster, + duration: EntityDuration::Permanent, + effect_nature: EffectApplication::Recurring, + effect_bounds: EffectBounds::from(0..33), + }; + + let e2 = Entity { + id: uuid::Uuid::nil(), + name: "Bob".into(), + stats: OverallStats::linear(44), + temp_stats: Some(OverallStats::linear(4)), + metadata: MetaStats { + position: Position::from_str("33,4").unwrap(), + capital: Some(stats::TownId(3000)), + governor: Some(stats::CharacterId(1500)), + faction: Some(stats::FactionId(5)), + links: vec![TownId(6)], + prestige: stats::GenericStat(5), + }, + entity_type: EntityType::Town, + duration: EntityDuration::Permanent, + effect_nature: EffectApplication::Recurring, + effect_bounds: EffectBounds::from(0..3), + }; + + // Compute the delta + let mut delta = e1.delta(&e2); + let mut delta2 = e2.delta(&e2); + let mut delta3 = e2.delta(&e1); + delta.id = Uuid::nil(); + delta2.id = Uuid::nil(); + delta3.id = Uuid::nil(); + assert_snapshot!(format!( + "{:#?}{}", + &delta, + delta.full_stats_to_table().unwrap() + )); + assert_snapshot!(format!( + "{:#?}{}", + delta2, + delta2.full_stats_to_table().unwrap() + )); + assert_snapshot!(format!( + "{:#?}{}", + delta3, + delta3.full_stats_to_table().unwrap() + )); +} + +#[test] +fn snapshot_option_stats_delta() { + init_snapshot_env(); + + let a = OverallStats::linear(32); + let b = OverallStats::linear(22); + + let opt_a = Some(a.clone()); + let opt_b = Some(b.clone()); + + // `delta` is commutative for the purpose of the snapshot + let delta = opt_a.delta(&opt_b); + let delta2 = None.delta(&opt_b); + let delta3 = opt_a.delta(&None); + let delta4 = None::.delta(&None); + + assert_snapshot!(format!("{:#?}", delta)); + assert_snapshot!(format!("{:#?}", delta2)); + assert_snapshot!(format!("{:#?}", delta3)); + assert_snapshot!(format!("{:#?}", delta4)); +} + +#[test] +fn snapshot_meta_stats_delta() { + init_snapshot_env(); + + let meta1 = MetaStats { + position: Position::from((1, 11)), + capital: Some(stats::TownId(1000)), + governor: Some(stats::CharacterId(500)), + faction: Some(stats::FactionId(1)), + links: vec![TownId(22)], + prestige: stats::GenericStat(3), + }; + + let meta2 = MetaStats { + position: Position::from((44, 555)), + capital: Some(stats::TownId(1500)), + governor: Some(stats::CharacterId(400)), + faction: Some(stats::FactionId(33)), + links: vec![TownId::from(55)], + prestige: stats::GenericStat(1), + }; + let meta3 = MetaStats { + position: Position::from((44, 555)), + capital: None, + governor: Some(stats::CharacterId(400)), + faction: Some(stats::FactionId(33)), + links: vec![TownId::from(55)], + prestige: stats::GenericStat(1), + }; + + let delta = meta1.delta(&meta2); + let delta2 = meta2.delta(&meta3); + let delta3 = meta3.delta(&meta3); + + assert_snapshot!(format!("{:#?}", delta)); + assert_snapshot!(format!("{:#?}", delta2)); + assert_snapshot!(format!("{:#?}", delta3)); +} + +#[test] +fn snapshot_delta_stat_positive() { + init_snapshot_env(); + + let mut e = Entity::default(); + e.delta_stat(StatPair::from_str("health:4").unwrap()); + e.id = Uuid::nil(); + + assert_snapshot!(format!("{:#?}", e)); +} + +#[test] +fn snapshot_modify_duration() { + init_snapshot_env(); + + let mut e = Entity::default(); + e.modify_duration(EntityDuration::Duration(33)); + e.id = Uuid::nil(); + + assert_snapshot!(format!("{:#?}", e)); +} + +#[test] +fn snapshot_modify_effect_application() { + init_snapshot_env(); + + let mut e = Entity::default(); + e.modify_effect_application(EffectApplication::PermanentEffectApplied); + e.id = Uuid::nil(); + + assert_snapshot!(format!("{:#?}", e)); +} + +#[test] +fn snapshot_modify_effect_bounds() { + init_snapshot_env(); + + let mut e = Entity::default(); + e.modify_effect_bounds(EffectBounds::from(33..33)); + e.id = Uuid::nil(); + + assert_snapshot!(format!("{:#?}", e)); +} + +#[test] +fn test_rng() { + Entity::create_rng(&EntityType::Character, &crate::utils::RngLevel::Zero).unwrap(); + Entity::create_rng(&EntityType::Player, &crate::utils::RngLevel::Low).unwrap(); + Entity::create_rng(&EntityType::Town, &crate::utils::RngLevel::Med).unwrap(); + Entity::create_rng(&EntityType::Monster, &crate::utils::RngLevel::High).unwrap(); + Entity::create_rng(&EntityType::Blocker, &crate::utils::RngLevel::Legendary).unwrap(); + Entity::create_rng(&EntityType::Event, &crate::utils::RngLevel::Mixed).unwrap(); + Entity::create_rng(&EntityType::Event, &crate::utils::RngLevel::Flawed).unwrap(); +} diff --git a/lib_efo/src/epoch.rs b/lib_efo/src/epoch.rs new file mode 100644 index 0000000..d18f433 --- /dev/null +++ b/lib_efo/src/epoch.rs @@ -0,0 +1,167 @@ +//! # Epoch configuration and state +//! +//! The *epoch* system is deliberately split into two tiny, serialisable +//! structures so that the binary can quickly read/write its “current +//! position” without pulling the whole world into memory. +//! +//! * `EpochConfig` - lives in `.epochconfig`. It only remembers +//! which epoch folder should be considered “current” and a few +//! convenience fields (tags, path). It never holds any event or +//! world data. +//! +//! * `EpochInfo` - stored inside `epoch//.epochinfo`. +//! This file contains the *metadata* for that particular epoch +//! (seed, selected events, parent link, etc.). Again, it does **not** +//! hold the full world; that is handled elsewhere in the engine. +//! +//! Keeping these two structs tiny means that switching epochs, logging, +//! or resetting can be done by reading/writing a handful of JSON/YAML +//! files, just like a git repository tracks its commits and +//! `HEAD` pointer. +#![warn(missing_docs, clippy::missing_docs_in_private_items)] +use clap::error::ErrorKind; +use derive_more::Display; +use serde::{Deserialize, Serialize}; +use std::{ + ops::{Deref, DerefMut}, + str::FromStr, +}; + +use crate::error::EpochError; +pub mod epoch_config; +pub use epoch_config::EpochConfig; + +pub mod epoch_info; +pub use epoch_info::EpochInfo; +pub mod epoch_traits; + +// TODO[5]: 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"; + +/// A lightweight wrapper around a list of tags. +/// +/// The wrapper exists mainly to give the collection a semantic type +/// and to hide the internal representation. +#[derive(Debug, Clone, Serialize, Deserialize, Display)] +#[display("{inner:?}")] +pub struct TagList { + /// The inner vector of tags + inner: Vec, +} + +impl TagList { + /// Create a new empty tag list + fn new() -> Self { + Self { inner: Vec::new() } + } +} + +impl Deref for TagList { + type Target = Vec; + + fn deref(&self) -> &Self::Target { + &self.inner + } +} +impl DerefMut for TagList { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.inner + } +} + +/// Which save mode to use +#[allow(missing_docs)] +pub enum SaveMode { + DoNotErase, + Erase, +} + +/// Thin type to handle EpochIds +#[derive( + Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Display, +)] +#[display("{id}")] +pub struct EpochId { + /// The underlying numeric value. + pub id: u64, +} + +impl FromStr for EpochId { + type Err = EpochError; + + fn from_str(s: &str) -> Result { + Ok(EpochId { id: s.parse()? }) + } +} + +impl EpochId { + /// Creates a new `EpochId` from a numeric value. + pub fn new(id: u64) -> Self { + Self { id } + } + + /// Return the next epochId + pub fn next(&self) -> Self { + Self { id: self.id + 1 } + } + + /// Return a new epoch Id derived from this one + pub fn add_to_epoch(&self, other: i64) -> Self { + Self { + id: self.id.saturating_add_signed(other), + } + } +} + +impl std::ops::Deref for EpochId { + type Target = u64; + + fn deref(&self) -> &Self::Target { + &self.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/epoch/epoch_config.rs b/lib_efo/src/epoch/epoch_config.rs new file mode 100644 index 0000000..8ffe7ab --- /dev/null +++ b/lib_efo/src/epoch/epoch_config.rs @@ -0,0 +1,415 @@ +//! Management of the *current-epoch* configuration. +//! +//! The configuration is stored in a file named `.epoch` and contains only +//! the lightweight information needed for the CLI to switch between epochs +//! quickly: +//! * the numeric ID of the current epoch, +//! * a map of human-friendly tags to epoch IDs, +//! * a map of known epoch IDs to unloaded metadata (`EpochInfo`). +//! +//! The world data and all event logs belong to the individual epoch +//! directories and are **not** part of this file. + +use crate::{ + entity::Entity, + epoch::{ + EpochId, EpochIdentifier, EpochInfo, MAIN_NAME, SUBFOLDER_NAMING, SaveMode, + epoch_traits::ConfigWritable, + }, +}; +use std::{ + collections::HashMap, + fs::{read_to_string, remove_dir_all}, + path::Path, +}; + +use log::{info, warn}; +use serde::{Deserialize, Serialize}; +use uuid::Uuid; + +use crate::{epoch::epoch_traits::Prettiable, error::EpochError}; + +/// The file written to *.epochconfig* that tells the CLI which +/// epoch folder is the “current” one. +/// +/// Only the minimal information needed for fast switches is stored: +/// * the numeric identifier of the selected epoch, +/// * a list of human-readable tags, +/// * the absolute path to the epoch's directory. +/// +/// No world or event data lives here - it is purely a lightweight pointer. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct EpochConfig { + /// The epoch ID that the binary should consider “current”. + pub epoch_id: EpochId, + + /// Optional human-friendly tags (e.g. `"winter-B"`, `"post-war"`). + pub tags: HashMap, + // TODO[6]: 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[6]: write a trait for this + let config: EpochConfig = serde_json::from_str(&io_err_with_help!( + read_to_string(path), + "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 structure in depth. + /// + /// Scans the default configuration folder for sub-directories that are + /// interpreted as epoch identifiers, logs each discovered epoch and + /// registers it in the in-memory cache. + /// + /// This function may return an error if the configuration folder cannot + /// be read or if any directory name cannot be parsed as an `EpochId`. + pub(crate) fn initialize(mut self) -> Result { + let path = EpochConfig::default().save_subfolder(); + let path = io_err_with_help!(Path::new(&path).read_dir(), "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(), "Determining file type of {:?}", elt)?.is_dir() { + let id = elt.file_name().to_string_lossy().parse::()?; + info!("Initialized {:?}", id); + self.list_existing_epochs.insert(id, None); + } + } + Ok(self) + } + + /// Loads the metadata for an epoch from disk into the in-memory cache. + /// + /// The epoch identified by `epoch_id` must exist in `list_existing_epochs`. + /// The JSON file on disk is read, deserialized into an `EpochInfo`, and + /// stored in the map. Any existing value for that epoch is overwritten. + /// + /// # Returns + /// * `Ok(())` when the epoch was successfully read and cached. + /// * `Err(EpochError::EpochNotFound(..))` if the epoch is not present in the + /// internal map. + /// * `Err(EpochError::Serde { .. })` if the JSON file could not be parsed. + /// * `Err(EpochError::Io { .. })` if the file could not be read. + pub fn try_load(&mut self, epoch_id: &EpochId) -> Result<(), EpochError> { + // Preload the epoch + let value = self + .list_existing_epochs + .get_mut(epoch_id) + .ok_or(EpochError::EpochNotFound(format!("{epoch_id}")))?; + + // 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), "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(()) + } + + /// Load the currently active epoch. + /// + /// This helper first ensures that the current epoch's metadata is cached + /// by delegating to `try_load`, then returns a reference to it. + /// + /// # Returns + /// * `Ok(&EpochInfo)` - Reference to the cached epoch. + /// * Propagates any error from `try_load`. + pub fn try_load_current(&mut self) -> Result<&EpochInfo, EpochError> { + self.try_load(&self.epoch_id.clone())?; + unsafe { self.try_load_id(self.epoch_id) } + } + + /// Load an epoch by its identifier. + /// + /// The caller must guarantee that the epoch has already been loaded into + /// the cache (e.g. by calling `try_load`). This function is marked `unsafe` + /// because it performs a raw reference conversion without performing that + /// check. + /// + /// # Safety + /// Calling this function when the requested epoch has not yet been + /// loaded results in undefined behaviour. + /// + /// # Arguments + /// * `epoch_id` - Identifier of the epoch to load. + /// + /// # Returns + /// * `Ok(&EpochInfo)` - Reference to the cached epoch. + /// * `Err(EpochError::EpochHashingImpossible(..))` - The identifier is + /// unknown. + /// * `Err(EpochError::LoadingEpochId(..))` - The epoch data is not yet + /// present in the cache. + pub unsafe fn try_load_id(&self, epoch_id: EpochId) -> Result<&EpochInfo, EpochError> { + let current = self + .list_existing_epochs + .get(&epoch_id) + .ok_or(EpochError::EpochHashingImpossible(file!(), line!()))? + .as_ref() + .ok_or(EpochError::LoadingEpochId(self.epoch_id))?; + Ok(current) + } + + /// Load the currently active epoch mutably. + /// + /// This is a convenience wrapper that forwards to `try_load_id_as_mut` + /// for the current epoch. + /// + /// # Returns + /// * `Ok(&mut EpochInfo)` - Mutable reference to the cached epoch. + /// * Propagates any error from the underlying load routine. + pub fn try_load_current_as_mut(&mut self) -> Result<&mut EpochInfo, EpochError> { + self.try_load_id_as_mut(self.epoch_id) + } + + /// Load an epoch's metadata mutably. + /// + /// The function guarantees that the epoch data is present in the cache + /// by first invoking `try_load` on the current epoch ID. It then + /// retrieves a mutable reference to the requested epoch. + /// + /// # Arguments + /// * `epoch_id` - Identifier of the epoch to load. + /// + /// # Returns + /// * `Ok(&mut EpochInfo)` - Mutable reference to the cached epoch. + /// * `Err(EpochError::EpochHashingImpossible(..))` - The identifier is + /// unknown. + /// * `Err(EpochError::LoadingEpochId(..))` - The epoch data is not yet + /// present in the cache. + /// + /// # Notes + /// The call to `try_load` may incur a small performance penalty because + /// it ensures that the epoch metadata is read from disk even when the + /// caller already knows the epoch is cached. This function is *not* `unsafe`; + /// it performs all safety checks internally. + fn try_load_id_as_mut(&mut self, epoch_id: EpochId) -> Result<&mut EpochInfo, EpochError> { + self.try_load(&self.epoch_id.clone())?; + let current = self + .list_existing_epochs + .get_mut(&epoch_id) + .ok_or(EpochError::EpochHashingImpossible(file!(), line!()))? + .as_mut() + .ok_or(EpochError::LoadingEpochId(self.epoch_id))?; + Ok(current) + } + + /// Retrieves the internal epoch ID for a given identifier. + /// + /// The identifier can be either a *tag* string (`EpochIdentifier::Tag`) or an + /// explicit epoch ID (`EpochIdentifier::Id`). + /// * When a tag is supplied the function looks up the corresponding epoch ID in + /// the `tags` map. + /// * When an ID is supplied it verifies that an epoch with that ID exists in + /// `list_existing_epochs` and returns it. + /// + /// # Returns + /// * `Ok(epoch_id)` when the identifier is successfully resolved. + /// * `Err(EpochError::AmbiguousTag(tag))` if a supplied tag does not exist. + /// * `Err(EpochError::EpochFolderMissing(id, path))` if an ID does not have an + /// associated epoch folder. + pub fn get_epoch_id(&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(), + } + } + + /// Return the name of the subfolder used to save this structure + pub(crate) fn save_subfolder(&self) -> String { + format!("{}/", SUBFOLDER_NAMING) + } + + /// Delete an entire epoch folder by its ID. + /// + /// The function removes the directory, deletes all references to the + /// epoch from `list_existing_epochs` and `tags`, and then writes the + /// updated configuration to disk. + // TODO[9]: Create a delete_ids taking an iterator for added performance on huge deletions + pub fn delete_id(&mut self, id: EpochId) -> Result<(), EpochError> { + if !self.list_existing_epochs.contains_key(&id) { + warn!( + "The given epoch {} doesn't exists and it's deletion was skipped", + id + ) + } else { + io_err_with_help!( + remove_dir_all(EpochInfo::with_id(&id).save_folder()), + "Removing the epoch {}", + id + )?; + self.list_existing_epochs.remove(&id); + self.tags.retain(|_k, v| *v != id); + self.save_with_context("Saving after delete_id", &SaveMode::Erase)?; + } + Ok(()) + } + + /// Compute the next epoch. + /// + /// Currently this function is a placeholder that creates a new epoch + /// with the ID immediately following the current one. The actual logic + /// is deferred to the `EpochInfo -> World` subsystem. + pub fn compute_next(&mut self) -> Result { + // unimplemented!() + // TODO[1]: Implement this + warn!("DEBUG LINE: COMPUTING NEXT EPOCH"); + // New fake epoch + let mut new_epoch = self.try_load_current()?.clone(); + new_epoch.epoch_id = self.epoch_id.next(); + Ok(new_epoch) + } + + /// Insert a new epoch into the configuration and persist it. + /// + /// The function creates the epoch's directory, writes its metadata, + /// updates the internal maps, and finally writes the updated + /// configuration to disk. + /// + /// # Returns + /// * `Ok(())` - the epoch was added and the configuration was saved. + /// * `Err(EpochError::EpochAlreadyExists(..))` if an epoch with the same ID already exists. + 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)); + } + + new_epoch.create_subfolders()?; + new_epoch.save_with_context("Saving new epoch", save_mode)?; + + // Add the epoch to the list of epochs, not doing so will still have it added + // at the next iteration since the command always parse the files to determine it's state rater that the list + // not doing so would likely create errors if insert is used before another command + let new_id = new_epoch.epoch_id; + self.list_existing_epochs.insert(new_id, Some(new_epoch)); + self.epoch_id = new_id; + self.save_with_context("Saving after insert_and_save", &SaveMode::Erase)?; + Ok(()) + } + + /// Load and display the metadata for a list of epoch IDs. + /// + /// The function first ensures that each requested epoch's metadata is + /// loaded into memory, then displays a formatted log for each one. + pub fn log_elements(&mut self, list_ids: &[EpochId]) -> Result<(), EpochError> { + let mut items_to_log = Vec::with_capacity(list_ids.len()); + // Tries to load all ids into memory + for id in list_ids { + self.try_load(id)?; + } + // Makes a vector with all elements from the list of ids + for id in list_ids { + if let Some(info) = self + .list_existing_epochs + .get(id) + .ok_or(EpochError::EpochNotFound(id.to_string()))? + { + items_to_log.push(info); + } + } + EpochInfo::show_as_table(items_to_log); + Ok(()) + } + + /// Find an entity by its UUID. + /// + /// This function searches the currently loaded epoch for an entity whose + /// `id` matches the supplied `Uuid`. It looks in both the `events`, `towns` + /// and `characters` collections of the epoch. + /// + /// # Safety + /// The caller must guarantee that the epoch identified by `self.epoch_id` + /// has already been loaded into memory (for example by calling + /// `try_load` first). The function performs an unchecked reference + /// conversion via `try_load_id`; invoking it when the epoch is not + /// cached results in **undefined behaviour**. + /// + /// # Arguments + /// * `id` - The `Uuid` of the entity to locate. + /// + /// # Returns + /// * `Ok(&Entity)` - Reference to the entity if it is present in the + /// current epoch. + /// * `Err(EpochError::EntityNotFoundById(id))` - No entity with the + /// supplied UUID exists in the epoch. + /// + unsafe fn find_entity(&self, id: Uuid) -> Result<&Entity, EpochError> { + let epoch_info = unsafe { self.try_load_id(self.epoch_id) }?; + let predicate = |entity: &&Entity| entity.id == id; + epoch_info + .events + .iter() + .find(predicate) + .or(epoch_info.characters.iter().find(predicate)) + .or(epoch_info.towns.iter().find(predicate)) + .ok_or(EpochError::EntityNotFoundById(id)) + } +} + +impl ConfigWritable for EpochConfig { + fn save_path(&self) -> String { + MAIN_NAME.to_string() + } + + fn save_folder(&self) -> String { + ".".to_string() + } +} diff --git a/lib_efo/src/epoch/epoch_info.rs b/lib_efo/src/epoch/epoch_info.rs new file mode 100644 index 0000000..cdbe376 --- /dev/null +++ b/lib_efo/src/epoch/epoch_info.rs @@ -0,0 +1,109 @@ +//! Metadata management for individual epochs. +//! +//! The `EpochInfo` struct holds all information that the engine needs to +//! reconstruct a particular epoch. +//! It is persisted to `epoch//.epochinfo`. The file contains the epoch ID, the RNG +//! seed that produced the world, any optional tags, and a human-readable +//! summary. World data itself is stored separately (e.g. in `world.json`). + +use cli_table::Table; +use derive_more::Display; +use serde::{Deserialize, Serialize}; +use std::fs::create_dir_all; + +use crate::{ + entity::Entity, + epoch::{ + EpochId, SUB_NAME, SUBFOLDER_NAMING, TagList, + epoch_traits::{ConfigWritable, Prettiable}, + }, + error::EpochError, +}; + +/// The metadata file stored inside each epoch directory +/// (`epoch//.epochinfo`). +/// +/// It contains only the information that is needed for the engine to +/// reconstruct the state *of that particular epoch* (seed, selected +/// events, parent link, etc.). The full world data will be kept in +/// separate storage (e.g. `world.json`) but is for stored here. +#[derive(Debug, Clone, Serialize, Deserialize, Display, Table)] +#[display( + "Epoch ({epoch_id:>5}) | seed ({rng_seed:<10}) | tags ({tags:<10}) | summary ({summary:<20})" +)] +pub struct EpochInfo { + /// The ID of this epoch - should match the directory name. + #[table(title = "ID")] + pub epoch_id: EpochId, + + /// RNG seed that was used to generate randomised data for + /// this epoch. Keeping it in the file guarantees repeatable + /// behaviour when replaying the same epoch. + #[table(title = "Seed")] + pub rng_seed: u64, + + // /// List of event IDs that were accepted for this epoch. + // /// The engine uses this to replay the world from the + // /// parent epoch to the current one. + // pub selected_events: Vec, + /// Optional tags that help identify the epoch (e.g. `"Winter-B"`). + #[table(title = "Tags")] + pub tags: TagList, + + /// Human-readable description or summary, useful for the `log` command. + #[table(title = "Summary")] + pub summary: String, + // TODO[9]: Store world separately + #[table(skip)] + /// The list of events currently in progress + pub events: Vec, + #[table(skip)] + /// The list of characters currently present + pub characters: Vec, + #[table(skip)] + /// The list of towns currently present + pub towns: Vec, +} + +impl Prettiable for EpochInfo {} + +impl Default for EpochInfo { + fn default() -> Self { + Self { + epoch_id: EpochId::new(0), + rng_seed: 0, + tags: TagList::new(), + summary: String::new(), + events: Vec::new(), + characters: Vec::new(), + towns: Vec::new(), + } + } +} + +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") + } + + /// Create an epoch with only an Id, please note that this function doesn't load the epoch at all + pub(crate) fn with_id(epoch_id: &EpochId) -> Self { + Self { + epoch_id: *epoch_id, + ..Default::default() + } + } +} + +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) + } +} diff --git a/lib_efo/src/epoch/epoch_traits.rs b/lib_efo/src/epoch/epoch_traits.rs new file mode 100644 index 0000000..94b2346 --- /dev/null +++ b/lib_efo/src/epoch/epoch_traits.rs @@ -0,0 +1,112 @@ +//! epoch_traits.rs +//! +//! All traits used by the `lib_efo` library. +//! These traits are marker traits that describe behaviour +//! common to many of the library's element types. +#![warn(clippy::missing_docs_in_private_items)] + +use cli_table::{Style, Table, WithTitle}; +use serde::Serialize; +use std::{fmt::Display, fs::File, io::Write}; + +use crate::{epoch::SaveMode, error::EpochError}; + +/// Elements that can be compared with another instance to produce a diff. +pub trait Diffable { + /// Compare self with another struct of the same type and return a new instance containing the difference + fn delta(&self, other: &Self) -> Self; +} + +/// Elements that can be applied to the current world state. +pub trait Applyable {} + +/// Elements that can advance to a next state over time. +/// +/// Implementors usually provide a `.next()` method that returns the +/// element's state after a time step (e.g., fading or diminishing). +pub trait Nextable {} + +/// Elements that can be rendered into a pretty, human-readable form. +pub trait Prettiable: Display { + /// Shows many items as a table. + /// + /// The table is printed to `stdout` using the `cli_table` crate. + /// + /// # Panics + /// Panics if printing the table to stdout fails. + fn show_as_table(list: Vec<&Self>) + where + for<'a> Vec<&'a Self>: Table + WithTitle, + { + #[allow(clippy::unwrap_used)] // There is no recovery of not being able to print a table + cli_table::print_stdout(list.with_title().bold(true)).unwrap(); + } + + /// Displays the struct as a log entry by printing the output of + /// `as_log()` to stdout. + fn show_as_log(&self) { + println!("{}", self.as_log()) + } + + /// Converts the struct into a pretty log string. + fn as_log(&self) -> String { + format!("{}", self) + } +} + +/// 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; + + /// Serialises the config into a pretty JSON string. + /// + /// # Arguments + /// * `action` - A description of the action for error reporting. + /// + /// # Returns + /// * `Ok(String)` containing the pretty-printed JSON. + /// * `Err(EpochError::Serde)` if serialisation fails. + 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, + }) + } + + /// Saves the config into its nominal path. + /// + /// Existing subdirectories are not created. + /// If `do_not_erase` is `SaveMode::Erase`, an existing file is overwritten. + /// If `do_not_erase` is `SaveMode::DoNotErase`, an error is returned when the + /// file already exists. + /// + /// # Arguments + /// * `action_description` - A human-readable description used in error messages. + /// * `do_not_erase` - Determines whether to overwrite an existing file. + /// + /// # Returns + /// * `Ok(())` on success. + /// * `Err(EpochError::ConfigWrite)` on any serialization error. + /// * `Err(EpochError::ConfigCreation)` on any I/O error. + fn save_with_context( + &self, + // Very unsure about this versus a macro + action_description: &str, + 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.to_owned())?) + .map_err(EpochError::ConfigWrite)?; + Ok(()) + } +} diff --git a/lib_efo/src/epoch_struct.rs b/lib_efo/src/epoch_struct.rs deleted file mode 100644 index 131dd3a..0000000 --- a/lib_efo/src/epoch_struct.rs +++ /dev/null @@ -1,378 +0,0 @@ -//! # Epoch configuration and state -//! -//! The *epoch* system is deliberately split into two tiny, serialisable -//! structures so that the binary can quickly read/write its “current -//! position” without pulling the whole world into memory. -//! -//! * `EpochConfig` – lives in `.epochconfig`. It only remembers -//! which epoch folder should be considered “current” and a few -//! convenience fields (tags, path). It never holds any event or -//! world data. -//! -//! * `EpochInfo` – stored inside `epoch//.epochinfo`. -//! This file contains the *metadata* for that particular epoch -//! (seed, selected events, parent link, etc.). Again, it does **not** -//! hold the full world; that is handled elsewhere in the engine. -//! -//! Keeping these two structs tiny means that switching epochs, logging, -//! or resetting can be done by reading/writing a handful of JSON/YAML -//! files, just like a git repository tracks its commits and -//! `HEAD` pointer. - -use clap::error::ErrorKind; -use serde::{Deserialize, Serialize}; -use std::{ - collections::HashMap, - fmt, - fs::{File, create_dir_all, read_to_string, remove_dir_all}, - io::Write, - path::Path, - str::FromStr, -}; - -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: -/// * the numeric identifier of the selected epoch, -/// * a list of human‑readable tags, -/// * the absolute path to the epoch’s directory. -/// -/// No world or event data lives here – it is purely a lightweight pointer. -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct EpochConfig { - /// The epoch ID that the binary should consider “current”. - pub epoch_id: EpochId, - - /// Optional human‑friendly tags (e.g. `"winter‑B"`, `"post‑war"`). - pub tags: HashMap, - // 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 -/// (`epoch//.epochinfo`). -/// -/// It contains only the information that is needed for the engine to -/// reconstruct the state *of that particular epoch* (seed, selected -/// events, parent link, etc.). The full world data is kept in -/// separate storage (e.g. `world.json`). -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct EpochInfo { - /// The ID of this epoch – should match the directory name. - pub epoch_id: EpochId, - - /// The ID of the parent (previous) epoch, if not a root. - pub parent_id: Option, - - /// RNG seed that was used to generate randomised data for - /// this epoch. Keeping it in the file guarantees repeatable - /// behaviour when replaying the same epoch. - pub rng_seed: u64, - - // /// List of event IDs that were accepted for this epoch. - // /// The engine uses this to replay the world from the - // /// parent epoch to the current one. - // pub selected_events: Vec, - /// Optional tags that help identify the epoch (e.g. `"Winter‑B"`). - pub tags: Vec, - - /// Human‑readable description or summary, useful for the `log` command. - pub summary: Option, -} - -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, 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) - } -} - -impl EpochId { - /// Creates a new `EpochId` from a numeric value. - pub fn new(id: u64) -> Self { - Self { id } - } -} - -impl std::ops::Deref for EpochId { - type Target = u64; - - fn deref(&self) -> &Self::Target { - &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 99914d7..440e444 100644 --- a/lib_efo/src/error.rs +++ b/lib_efo/src/error.rs @@ -1,17 +1,28 @@ //! 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 uuid::Uuid; use thiserror::Error; -use crate::epoch_struct::EpochId; +use crate::{entity::EntityIdentifier, epoch::EpochId, stats::EntityType}; 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[2]: Remove or rethink these errors #[derive(Debug, Error, Diagnostic)] pub enum StorageError { /// Problems with serialisation / deserialisation. @@ -32,153 +43,304 @@ 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 -/// to the user (and to the test‑suite). +/// +/// 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[2]: Split effectively user errors to avoid the usage of advice and such #[derive(Error, Debug, Diagnostic)] +#[allow(dead_code, unused_assignments)] 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, }, - #[error("This directory isn't empty and thus cannot be initialized")] + /// This directory isn't empty and thus cannot be initialized. + #[error("This directory {name:?} 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 + /// Impossible to load the given epoch + #[error("The id ({0}) couldn't be loaded")] + #[diagnostic(code(EpochError::LoadingEpochId))] + LoadingEpochId(EpochId), + + /// Any other error that didn't fit into the above categories. #[error("An unknown error occurred: {0}")] + #[diagnostic(code(EpochError::Unknown))] Unknown(String), + + /// The user tried to parse an acronim that doen't match any stats known to the system. + #[error("Unknown stat acronym: {0}")] + #[diagnostic(code(EpochError::UnknownStatAcronim))] + UnknownStatAcronim(String), + + /// The user gave a stat:identifier pair that was incorrect + #[error("Expected a stat and a number, got: {0}")] + #[diagnostic(code(EpochError::IllFormedStatQualifier))] + IllFormedStatQualifier(String), + + /// User error, meant to be very explicit over what happened and what to do. + #[error("An user facing error")] + #[diagnostic(code(EpochError::UserError))] + UserError(#[help] UserErrors), + + /// An error happened when picking a rng event + #[error("An error happened when trying to pick a rng event for {cause}")] + #[diagnostic(code(EpochError::RNGPickError))] + RNGPickError { + /// The root cause originating the error + cause: String, + #[help] + /// Optionnal help + help: Option, + }, + + /// A non-recoverable error while hashing an epoch identifier. + /// + /// This error should never happen in normal operation. It is surfaced only + /// when the hashing routine fails to produce a unique identifier for a + /// given epoch index. + #[error("Epoch hashing failed for `{0}` (index {1})")] + #[diagnostic(code(EpochError::EpochHashingImpossible))] + #[help("This is an internal error. Please file a bug report.")] + EpochHashingImpossible(&'static str, u32), + + /// The entity with id **`{0}`** could not be found. + #[error("Entity of type with id {0:?} not found")] + #[diagnostic(code(epoch::entity_not_found_by_id))] + #[help( + "Verify that the identifier is correct and that the entity exists in the current epoch." + )] + EntityNotFoundById(Uuid), + + /// The entity could not be found + #[error("Entity of type {0:?} with name {1:?} not found")] + #[diagnostic(code(epoch::entity_not_found))] + #[help( + "Verify that the identifier is correct and that the entity exists in the current epoch." + )] + EntityNotFound(EntityType, Option), + + /// The requested uniform RNG could not be created because the supplied + /// distribution parameters were invalid. + #[error("Failed to create uniform RNG: {0}")] + #[diagnostic(code(EpochError::UniformRngCreation))] + #[help("Ensure that the supplied range bounds satisfy `min < max`.")] + UniformRngCreation(#[from] rand::distr::uniform::Error), + + /// The string did not contain exactly two comma-separated values. + #[error("Invalid position format: expected \"x,y\" found {0}")] + #[diagnostic(code(EpochError::InvalidPositionFormat))] + #[help("Provide exactly two numbers separated by a comma.")] + InvalidPositionFormat(String), + + /// One of the components failed to parse as an `isize`. + #[error("Failed to parse integer: {0}")] + #[diagnostic(code(EpochError::ParsePositionError))] + #[help("Ensure that the input is a valid integer.")] + ParsePositionError(String), + + /// Failed to render a table into its string representation. + #[error("Failed to render table {name} [{id}] as string")] + #[diagnostic(code(EpochError::TableStringConversion))] + #[help("Verify that the table data and schema are compatible with string rendering.")] + TableStringConversionError { + /// The logical name of the table that failed to convert. + name: String, + /// The UUID that uniquely identifies the table instance. + id: Uuid, + }, + + /// Failed to parse a duration string. + #[error("Failed to parse duration: {0}:{1}")] + #[diagnostic(code(EpochError::ParsingDuration))] + #[help( + "Verify that the duration string follows the expected syntax, `permanent` or `duration:X` or `done`." + )] + ParsingDuration(&'static str, String), + + /// Failed to parse a bounds string. + #[error("Failed to parse bounds: {0}:{1}")] + #[diagnostic(code(EpochError::ParsingBounds))] + #[help("Verify that the bounds string follows the expected syntax, `X-X` or `X:X`.")] + ParsingBounds(&'static str, String), + + /// The value started with `@` but the remainder was not a valid id or the name was empty. + #[error("Failed to parse identifier or name")] + #[diagnostic(code(EntityIdentifierError::InvalidIdentifier))] + #[help("Verify that the UUID after `@` is a valid id.")] + EmptyIdentifier, } +/// 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. +/// +/// 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:expr, $($help:expr),*) => {{ $expr.map_err(|e| EpochError::Io { source: e, - help: Some($help.to_owned()), + help: Some(format!($($help),*)), + error_line: line!(), }) }}; } diff --git a/lib_efo/src/lib.rs b/lib_efo/src/lib.rs index 8a5d8e0..12aa6d0 100644 --- a/lib_efo/src/lib.rs +++ b/lib_efo/src/lib.rs @@ -3,23 +3,30 @@ //! 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: -//! - 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. +//! - TODO[1]: `world` - holds the global state (`World`) and a lightweight snapshot (`Context`). +//! - TODO[0]: `epoch` - manages the passage of time and epoch switching. +//! - TODO[1]: `event` - CRUD and evaluation of events that affect the world. +//! - TODO[4]: `org` - organisations, guilds, factions and their history. +//! - TODO[2]: `character` - individual characters, traits and lineage. +//! - TODO[1]: `town` - towns, cities, trade hubs and their populations. +//! - TODO[2]: `link` - relations such as wars, alliances, roads, commerce. +//! - TODO[3]: `storage` - generic persistence layer (`Store`) with JSON/YAML back-ends. +//! - TODO[4]: `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 -pub mod epoch_struct; +#![warn(missing_docs, clippy::missing_docs_in_private_items)] +#![deny(clippy::unwrap_used)] + #[macro_use] +#[allow(dead_code, unused_assignments)] pub mod error; +pub mod entity; +pub mod epoch; +pub mod naming; +pub mod stats; pub mod utils; use std::io::Result as IoResult; @@ -49,3 +56,61 @@ where /// List all ids known to this store. fn list_ids(&self) -> IoResult>; } +/// A trait for types that can be displayed in a command-line tool. +/// +/// Implementors should provide three levels of representation: +/// 1. **Full** - a detailed view suitable for a long-running command. +/// 2. **Short** - a concise, user-friendly view that fits on a single line. +/// 3. **Oneline** - a compact, machine-friendly string that can be embedded +/// inside a `Vec` representation. +/// +/// ## `Vec` support +/// +/// The trait is implemented generically for `Vec` as long as `T: Displayable`. +/// This allows you to call `full_display`, `short_display` or `oneline_display` +/// directly on a vector of displayable items. +pub trait Displayable { + /// Return a fully-described string representation. + fn print_full(&self) { + self.print_short() + } + + /// Return a short, user-friendly string. + fn print_short(&self) { + println!("{}", self.oneline_display()) + } + + /// Return a one-liner string, suitable for embedding in a collection + /// representation (e.g. a `Vec`). Implementations should avoid + /// new-lines to keep the output usable in a single line context. + fn oneline_display(&self) -> String; + + /// Print oneline + fn print_oneline(&self) { + println!("{}", self.oneline_display()) + } +} + +/// Implement `Displayable` for vectors of displayable items. +/// +/// The implementation simply delegates to the underlying `T::oneline_display` +/// method and joins the results with a comma. It works for any `T` that +/// already implements `Displayable`. This is a **blanket implementation**, +/// so you do not need to write a manual impl for each concrete type +impl Displayable for Vec { + fn print_full(&self) { + self.iter().for_each(|e| e.print_full()); + } + + fn print_short(&self) { + self.iter().for_each(|e| e.print_short()); + } + + fn oneline_display(&self) -> String { + // No brackets - just a flat, comma-separated list. + self.iter() + .map(|x| x.oneline_display()) + .collect::>() + .join(",") + } +} diff --git a/lib_efo/src/naming.rs b/lib_efo/src/naming.rs new file mode 100644 index 0000000..d2d2913 --- /dev/null +++ b/lib_efo/src/naming.rs @@ -0,0 +1,388 @@ +//! Autonaming generator +//! Supposed to be loaded with the world if needed +use crate::stats::Symbols; +use once_cell::sync::Lazy; +use rand::prelude::*; +use serde::{Deserialize, Serialize}; +use std::fs; +use std::io; +use std::path::{Path, PathBuf}; + +use crate::Displayable; +use crate::entity::EffectApplication; +use crate::entity::EffectBounds; +use crate::entity::EntityDuration; +use crate::error::EpochError; +use crate::stats::EntityType; +use crate::stats::StatPair; + +/// The structure that holds everything we need for name generation. +#[derive(Debug, Serialize, Deserialize, Default)] +pub struct NamingData { + /// First name for characters + pub first_names: Vec, + /// Last names for characters + pub last_names: Vec, + /// Good prefixes for towns + pub town_prefixes: Vec, + /// Good suffixes for town names + pub town_suffixes: Vec, + + /// Good blocker prefixes + pub blocker_prefixes: Vec, + /// Good blocker suffixes + pub blocker_suffixes: Vec, + /// Character adjectives + pub character_adjectives: Vec, + /// Name prefixes + pub character_prefixes: Vec, + + // Exotics names + /// Exotic name prefixes + pub exotic_prefixes: Vec, + /// Exotic infixes + pub exotic_infixes: Vec, + /// Exotic suffixes + pub exotic_suffixes: Vec, + /// Mighty mystical adjectives + pub mystical_adjectives: Vec, + /// A list of event ideas and characteristic associated to it + pub event_ideas: Vec, +} + +#[derive(Debug, Serialize, Deserialize)] +/// An event with a description +pub struct EventDescription { + /// A short and meaninful name (an id of a sort) + pub name: String, + + /// A short description of the event + pub description: String, + + /// The stats affected by the event, and how much (-20 to +20) + /// (100 being the maximum of a stat, event a change of -10 is meaningful) + pub stats: Vec, + + /// The nature of the event duration + pub duration: EntityDuration, + + /// How the event will be (re)applied + pub application: EffectApplication, + + /// The maximum bounds of the event + pub effect_bounds: EffectBounds, +} + +impl Displayable for EventDescription { + fn oneline_display(&self) -> String { + let (description, _) = self.description.split_at(110.min(self.description.len())); + let line1 = format!( + "├─ {} {} ──────> {}{} \n\ + │ ├─ {}", + self.name, + EntityType::Event.to_symbol(), + self.duration.to_symbol(), + self.effect_bounds.to_symbol(), + description, + ); + + let mut line2 = "│ └─ Stats: ".to_string(); + for effect in &self.stats { + line2.push_str(&format!("{}:{} ", effect.stat.to_shortest(), effect.value,)); + } + + format!("{line1}\n{line2}") + } +} + +impl NamingData { + /// Load the data from the supplied path. + /// If the file does **not** exist, a default (embedded) version is written + /// to that path and returned. + pub fn load_or_create>(path: P) -> io::Result { + let path = path.as_ref(); + + if path.exists() { + // File exists → read & parse + let contents = fs::read_to_string(path)?; + let data: Self = serde_json::from_str(&contents)?; + Ok(data) + } else { + // File does *not* exist → create from embedded default + let default = + serde_json::from_str(DEFAULT_JSON_STR).expect("Default JSON is malformed"); + // Ensure parent dirs exist + if let Some(parent) = path.parent() { + fs::create_dir_all(parent)?; + } + let json = serde_json::to_string_pretty(&default)?; + fs::write(path, json)?; + Ok(default) + } + } + + /// Generate a random **character** name. + pub fn generate_character_name(&self) -> String { + let mut rng = rand::rng(); + + let binding = "Bobman".into(); + let first = self.first_names.choose(&mut rng).unwrap_or(&binding); + let binding = "McBobintown".into(); + let last = self.last_names.choose(&mut rng).unwrap_or(&binding); + format!("{} {}", first, last).trim().to_string() + } + + /// Generate a random **town** name. + pub fn generate_town_name(&self) -> String { + let mut rng = rand::rng(); + let binding = "Bobtown".into(); + let prefix = self.town_prefixes.choose(&mut rng).unwrap_or(&binding); + let suffix = self.town_suffixes.choose(&mut rng).unwrap_or(&binding); + format!("{}{}", prefix, suffix).trim().to_string() + } + + /// Pick a random event idea + #[allow(clippy::unwrap_used)] + pub fn random_event_idea(&self) -> Result<&EventDescription, EpochError> { + let mut rng = rand::rng(); + self.event_ideas + .choose(&mut rng) + .ok_or(EpochError::RNGPickError { + cause: "Picking a random event".into(), + help: None, + }) + } + + /// Pick a random event name + #[allow(clippy::unwrap_used)] + pub fn random_event_name(&self) -> String { + if let Ok(event) = self.random_event_idea() { + event.name.clone() + } else { + "The Great Bobbening".to_owned() + } + } + + /// Generate a random **blocker** name (e.g. “Stone-Gate”, “Witch-Wall”). + /// + /// The name is formed by choosing a random prefix *and* suffix from the + /// corresponding lists. If either list is empty, a sensible default is + /// returned. + pub fn generate_blocker_name(&self) -> String { + let mut rng = rand::rng(); + + let binding = "Mystic ".to_string(); + let prefix = self.blocker_prefixes.choose(&mut rng).unwrap_or(&binding); + + let binding = "Barrier".to_string(); + let suffix = self.blocker_suffixes.choose(&mut rng).unwrap_or(&binding); + + format!("{} {}", prefix, suffix).trim().to_string() + } + + /// Generate a *calamity* name. + /// + /// A calamity is a **complex exotic** word (prefix + 2-4 infixes + optional suffix) + /// followed by a *mystical* adjective. + /// + /// Example output: “Umbral-Shatterfall Cataclysmic” + pub fn generate_calamity_name(&self) -> String { + let mut rng = rand::rng(); + + /* ----- 1️⃣ Build the exotic base --------------------------------- */ + // Pick a prefix (or fall back to "Umbral") + let prefix = self + .exotic_prefixes + .choose(&mut rng) + .unwrap_or(&"Umbral".to_string()) + .clone(); + + // Pick 2-4 infixes (this gives the “complex” feel) + let infix_count = rng.random_range(2..=4); + let infixes: String = (0..infix_count) + .map(|_| { + self.exotic_infixes + .choose(&mut rng) + .expect("exotic_infixes must not be empty") + .clone() + }) + .collect(); + + // Optional suffix - if you don't have a list, this will be an empty string + let suffix = self + .exotic_suffixes + .choose(&mut rng) + .cloned() + .unwrap_or_else(String::new); + + // Combine into the base calamity word + let base = format!("{}{}{}", prefix, infixes, suffix); + + /* ----- 2️⃣ Append a mystical adjective --------------------------- */ + let adjective = self + .mystical_adjectives + .choose(&mut rng) + .unwrap_or(&"Cataclysmic".to_string()) + .clone(); + + format!("{} {}", base, adjective).trim().to_string() + } + + /// Generates something like: + /// “The Magnificent Sir Aurelius Blackthorn the Swift” + /// Random adjective, prefix, base name and suffix are all optional. + /// If a list is empty, that part is omitted. + pub fn generate_long_character_name(&self) -> String { + let mut rng = rand::rng(); + + // Helper: get a random element or None + let adjective = self.character_adjectives.choose(&mut rng).cloned(); + let prefix = self.character_prefixes.choose(&mut rng).cloned(); + + // Base name (first + last) + let base = self.generate_character_name(); + + // Assemble pieces + let mut parts = Vec::new(); + + if let Some(pre) = prefix + && rand::random_bool(0.3) + { + parts.push(pre); + } + + parts.push(base); + + if let Some(adj) = adjective + && rand::random_bool(0.3) + { + parts.push(adj); + } + + parts.join(" ") + } + + /// Generate a exotic character name + #[allow(clippy::unwrap_used)] + pub fn generate_exotic_character_name(&self) -> String { + let mut rng = rand::rng(); + + // Pick a random number of syllables for the *first* part + let first_len = rng.random_range(2..=4); + let pref: &String = self.exotic_prefixes.choose(&mut rng).unwrap(); + let pref2: &String = self.exotic_prefixes.choose(&mut rng).unwrap(); + + let first: String = (0..first_len) + .map(|_| self.exotic_infixes.choose(&mut rng).unwrap()) + .cloned() + .collect(); + + // Same for the *last* part + let last_len = rng.random_range(1..=3); + let last: String = (0..last_len) + .map(|_| self.exotic_infixes.choose(&mut rng).unwrap()) + .cloned() + .collect(); + + // Combine with a space - you could also use a hyphen or nothing + format!("{pref}{} {pref2}{}", &first, &last) + } +} + +// /// Helper to capitalize the first letter of a word +// fn capitalize(word: &str) -> String { +// let mut chars = word.chars(); +// match chars.next() { +// None => String::new(), +// Some(first) => first.to_ascii_uppercase().to_string() + chars.as_str(), +// } +// } + +/// The JSON that ships with the binary. +/// `include_str!` pulls the file at compile time. +const DEFAULT_JSON_STR: &str = include_str!("../naming.json"); + +/// Helper that determines the *runtime* location of the `naming.json` file. +fn naming_file_path() -> PathBuf { + PathBuf::from("naming.json") +} + +/// Global instance that is lazily initialised on first use. +pub static NAMING: Lazy = Lazy::new(|| { + let path = naming_file_path(); + NamingData::load_or_create(path).expect("Failed to load naming data") +}); + +#[cfg(test)] +mod tests { + use super::*; + use crate::stats::ListStats; + use std::collections::HashMap; + + #[test] + fn try_load() {} + #[test] + fn basic_testing() { + // 1. Generate a character name + let character = NAMING.generate_character_name(); + println!("Character: {}", character); + + // 2. Generate a town name + let town = NAMING.generate_town_name(); + println!("Town: {}", town); + + // 3. Pick an event idea + let character = NAMING.generate_long_character_name(); + println!("Event idea: {}", character); + + let _ = NAMING.random_event_idea(); + } + + #[test] + // TODO[Work]: Add this to a recap function + fn test_all_events() { + let mut values: HashMap = HashMap::new(); + for event in &NAMING.event_ideas { + println!("Testing event: {:?}", event); + assert!(event.stats.len() > 1); + + for stat in &event.stats { + if let s @ (ListStats::Demographics + | ListStats::Military + | ListStats::Economy + | ListStats::Social + | ListStats::Infrastructure) = stat.stat + { + panic!("Bad stat used {s:?}") + }; + match stat.value.abs() { + 0..5 => (), + 5..10 => (), + 10..20 => println!("Big stat"), + s => panic!("The event has a stat that is way too big {s}"), + } + let base_value = values.get(&stat.stat).unwrap_or(&0); + values.insert(stat.stat, base_value + 1); + } + } + println!("{values:#?}"); + // panic!() + } + #[test] + fn test_most_naming() { + let _ = NAMING.generate_character_name(); + let _ = NAMING.generate_town_name(); + let _ = NAMING.random_event_idea().expect("Couldn't generate event"); + let _ = NAMING.random_event_name(); + let _ = NAMING.generate_blocker_name(); + let _ = NAMING.generate_calamity_name(); + let _ = NAMING.generate_long_character_name(); + let _ = NAMING.generate_exotic_character_name(); + } + + #[test] + fn event_description() { + let event = NAMING.random_event_idea().expect("Generating event"); + let _ = event.oneline_display(); + } +} diff --git a/lib_efo/src/stats.rs b/lib_efo/src/stats.rs new file mode 100644 index 0000000..8b830f1 --- /dev/null +++ b/lib_efo/src/stats.rs @@ -0,0 +1,595 @@ +//! Module that holds all statistics for an entity and the helper methods that operate on them. +//! +//! The statistics are grouped into thematic sections (Demographics, Economy, Social, Military, +//! Infrastructure). Each field is a `GenericStat`, an internal wrapper around a numeric value +//! that provides convenience methods such as `max()`, `clamp()`, and arithmetic ops. +//! +//! The documentation for each field follows the same three-part template: +//! * **Purpose** - What the stat represents. +//! * **Effect** - Gameplay consequence of the stat. +//! * **Source** - Formula or function that generates the stat value. + +#![allow(dead_code)] +#![deny(clippy::missing_docs_in_private_items)] + +use crate::{error::EpochError, thin_newtype, utils::RngLevel}; +use cli_table::{CellStruct, Color, Style, Table}; +use colored::Colorize; +use derive_more::{Add, Display, Sub}; +use rand::{Rng, distr::Distribution, rngs::ThreadRng}; +use serde::{Deserialize, Serialize}; +mod implementations; + +/// Aggregated statistics for a single entity. +/// +/// The struct is intentionally flat to keep access fast; the fields are logically grouped +/// by comment blocks that describe each thematic section. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +// Derive more +#[derive(Table, Add, Sub)] +pub struct OverallStats { + // ──────────────────────── Demographics ──────────────────────── + /// Total economic health of the entity. + /// + /// **Purpose** - A single value summarizing all economic indicators. + /// **Effect** - Drives tax revenue, spending power, and overall economic influence. + /// **Source** - Sum of `industry`, `science`, `trade`, and other economic contributors. + #[table(title = "DEM", customize_fn = "color_cell_categories")] + pub demographics: GenericStat, + /// Population count. + /// + /// **Purpose** - The number of citizens living in the entity. + /// **Effect** - Determines resource consumption, tax base, and potential unrest. + /// **Source** - Updated by the growth/decay formulas each turn. + #[table(title = "POP", customize_fn = "color_cell")] + pub population: GenericStat, + + /// Per-turn change in population. + /// + /// **Purpose** - The growth rate of the population. + /// **Effect** - Predicts future needs and signals potential social unrest. + /// **Source** - Derived from `population`, `happiness`, and `stability`. + #[table(title = "GRW", customize_fn = "color_cell")] + pub growth_rate: GenericStat, + + /// Crime level (0-1 scale). + /// + /// **Purpose** - How frequently crimes occur. + /// **Effect** - Can trigger riots and reduce stability. + /// **Source** - Result of the crime function (influenced by class disparity and law enforcement). + #[table(title = "CRM", customize_fn = "color_cell")] + pub crime: GenericStat, + + /// Base happiness of the population (0-1 scale). + /// + /// **Purpose** - A measure of citizen contentment. + /// **Effect** - Influences productivity, tax compliance, and unrest. + /// **Source** - Output of the happiness function (affected by class, war, infrastructure). + #[table(title = "HPY", customize_fn = "color_cell")] + pub happiness: GenericStat, + + // ──────────────────────── Economy ──────────────────────── + /// Aggregate economic health of the entity. + /// + /// **Purpose** - A single value summarizing all economic metrics. + /// **Effect** - Drives revenue, spending, and empire-wide economic influence. + /// **Source** - Sum of `food`, `industry`, `science`, `trade`, etc. + #[table(title = "ECO", customize_fn = "color_cell_categories")] + pub economy: GenericStat, + + /// Food produced by the entity. + /// + /// **Purpose** - Amount of consumable resources available. + /// **Effect** - Keeps the population alive and productive. + /// **Source** - `food = farm_yield + tech_level`. + #[table(title = "FOD", customize_fn = "color_cell")] + pub food: GenericStat, + + /// Strength of the industry. + /// + /// **Purpose** - Industrial production capacity. + /// **Effect** - Drives tax revenue and unit production. + /// **Source** - `industry = factory_output + tech_level`. + #[table(title = "IND", customize_fn = "color_cell")] + pub industry: GenericStat, + + /// Scientific output. + /// + /// **Purpose** - Rate of research progress. + /// **Effect** - Determines how quickly new technologies are unlocked. + /// **Source** - `science = research_center_output + tech_level`. + #[table(title = "SCI", customize_fn = "color_cell")] + pub science: GenericStat, + + /// Trade volume / exports. + /// + /// **Purpose** - Measure of export activity. + /// **Effect** - Influences influence and wealth. + /// **Source** - `trade = trade_network_output`. + #[table(title = "TRD", customize_fn = "color_cell")] + pub trade: GenericStat, + // // ──────────────────────── Social ──────────────────────── + // /// Overall social prestige. + // /// + // /// **Purpose** - Reflects the cultural standing of the entity. + // /// **Effect** - Affects diplomacy and citizen morale. + // /// **Source** - Sum of `culture`, `education`, `tourism`, etc. + // #[table(title = "SOC", color = "Color::Blue", bold, customize_fn = "color_cell")] + // pub social: GenericStat, + + // /// Cultural output from arts, theatres, museums, etc. + // /// + // /// **Purpose** - Measure of cultural production. + // /// **Effect** - Drives tourism, prestige, and happiness. + // /// **Source** - `culture = Σ(cultural_building_output)`. + // #[table(title = "CLU", customize_fn = "color_cell")] + // pub culture: GenericStat, + + // /// Level of education/literacy. + // /// + // /// **Purpose** - Measure of the citizenry's knowledge. + // /// **Effect** - Improves productivity, science output, and reduces unrest. + // /// **Source** - `education = Σ(education_building_output)`. + // #[table(title = "EDU", customize_fn = "color_cell")] + // pub education: GenericStat, + + // /// Tourism revenue. + // /// + // /// **Purpose** - Income generated by visitors. + // /// **Effect** - Provides an additional income stream. + // /// **Source** - `tourism = number_of_tourists x price_per_tourist`. + // #[table(title = "TOR", customize_fn = "color_cell")] + // pub tourism: GenericStat, + + // /// Cultural influence over the region. + // /// + // /// **Purpose** - Measure of soft power. + // /// **Effect** - Grants diplomatic bonuses and increases sway in the empire. + // /// **Source** - `influence = culture x population`. + // #[table(title = "INF", customize_fn = "color_cell")] + // pub influence: GenericStat, + + // ──────────────────────── Military ──────────────────────── + /// Overall military power. + /// + /// **Purpose** - Composite measure of combat capability. + /// **Effect** - Determines defensive and offensive strength. + /// **Source** - Sum of `army`, `strength`, `fortification`, etc. + #[table(title = "MIL", customize_fn = "color_cell_categories")] + pub military: GenericStat, + + /// Number of battle-ready units. + /// + /// **Purpose** - Size of the active army. + /// **Effect** - Directly dictates defense and attack potential. + /// **Source** - Sum of all trained and equipped units. + #[table(title = "ARM", customize_fn = "color_cell")] + pub army: GenericStat, + + /// Composite strength of the army. + /// + /// **Purpose** - Tech, training, and equipment bonuses aggregated. + /// **Effect** - Determines combat effectiveness and required force to defeat an enemy. + /// **Source** - `strength = Σ(unit_strength) x tech_bonus x training_bonus`. + #[table(title = "STR", customize_fn = "color_cell")] + pub strength: GenericStat, + + /// Defensive bonus from fortifications. + /// + /// **Purpose** - Wall and tower defenses. + /// **Effect** - Adds a multiplier to overall defense. + /// **Source** - `fortification = Σ(fortification_building_bonus)`. + #[table(title = "FRT", customize_fn = "color_cell")] + pub fortification: GenericStat, + + /// Threat level facing the entity. + /// + /// **Purpose** - Likelihood of being attacked. + /// **Effect** - Triggers early warning alerts and strategic decisions. + /// **Source** - `threat = (enemy_proximity + enemy_strength) / defense`. + #[table(title = "THR", customize_fn = "color_cell")] + pub threat: GenericStat, + + // ──────────────────────── Infrastructure ──────────────────────── + /// Total infrastructure power. + /// + /// **Purpose** - Overall built-environment capacity. + /// **Effect** - Supports population size and efficiency. + /// **Source** - Sum of all infrastructure components. + #[table(title = "IFR", customize_fn = "color_cell_categories")] + pub infrastructure: GenericStat, + + /// Bureaucratic power. + /// + /// **Purpose** - Efficiency of the city's administrative machinery. + /// **Effect** - Improves resource management and policy implementation. + /// **Source** - `bureaucracy = Σ(bureaucracy_building_output)`. + #[table(title = "BUR", customize_fn = "color_cell")] + pub bureaucracy: GenericStat, + + /// Transportation level. + /// + /// **Purpose** - Availability and quality of transport infrastructure. + /// **Effect** - Impacts logistics, mobility, and trade. + /// **Source** - `transportation = Σ(transport_building_output)`. + #[table(title = "TRP", customize_fn = "color_cell")] + pub transportation: GenericStat, + + /// Sprawl / urban density. + /// + /// **Purpose** - Measure of city sprawl and clutter. + /// **Effect** - Affects health, happiness, and infrastructure efficiency. + /// **Source** - `sprawl = Σ(sprawl_factor)`. + #[table(title = "SPR", customize_fn = "color_cell")] + pub sprawl: GenericStat, + + /// Health infrastructure quality. + /// + /// **Purpose** - Public health capacity. + /// **Effect** - Affects population health and can generate unrest. + /// **Source** - `health = output_of_health_function` (influenced by sanitation, disease spread, etc.). + #[table(title = "HLT", customize_fn = "color_cell")] + pub health: GenericStat, +} + +/// Color the base cells +fn color_cell(cell: CellStruct, value: &GenericStat) -> CellStruct { + match (**value).cmp(&0) { + std::cmp::Ordering::Less => cell.foreground_color(Some(Color::Red)), + std::cmp::Ordering::Equal => cell, + std::cmp::Ordering::Greater => cell, //.foreground_color(Some(Color::Green)), + } +} + +/// Color the cell categories +fn color_cell_categories(cell: CellStruct, value: &GenericStat) -> CellStruct { + match (**value).cmp(&0) { + std::cmp::Ordering::Less => cell.foreground_color(Some(Color::Red)).bold(true), + std::cmp::Ordering::Equal => cell.foreground_color(Some(Color::Blue)).bold(true), + std::cmp::Ordering::Greater => cell.foreground_color(Some(Color::Green)).bold(true), + } +} + +impl OverallStats { + /// Create Stats with a given rng distribution + // TODO[6]: Use an iterator over the stat enum + pub(crate) fn create_rng( + rng: &RngLevel, + mut rng_t: &mut ThreadRng, + ) -> Result { + let r = rng.to_rng()?; + let mut overall_stats = Self { + demographics: 0.into(), + population: (r.sample(&mut rng_t) as isize).into(), + growth_rate: (r.sample(&mut rng_t) as isize).into(), + crime: (r.sample(&mut rng_t) as isize).into(), + happiness: (r.sample(&mut rng_t) as isize).into(), + economy: 0.into(), + food: (r.sample(&mut rng_t) as isize).into(), + industry: (r.sample(&mut rng_t) as isize).into(), + science: (r.sample(&mut rng_t) as isize).into(), + trade: (r.sample(&mut rng_t) as isize).into(), + military: 0.into(), + army: (r.sample(&mut rng_t) as isize).into(), + strength: (r.sample(&mut rng_t) as isize).into(), + fortification: (r.sample(&mut rng_t) as isize).into(), + threat: (r.sample(&mut rng_t) as isize).into(), + infrastructure: 0.into(), + bureaucracy: (r.sample(&mut rng_t) as isize).into(), + transportation: (r.sample(&mut rng_t) as isize).into(), + sprawl: (r.sample(&mut rng_t) as isize).into(), + health: (r.sample(&mut rng_t) as isize).into(), + }; + overall_stats.update(); + Ok(overall_stats) + } + + /// Updates the inner meta values + fn update(&mut self) { + self.demographics = + (*(self.population + self.growth_rate + self.happiness - self.crime) / 4).into(); + self.economy = (*(self.food + self.industry + self.trade + self.science) / 4).into(); + self.military = + (*(self.army + self.strength + self.fortification + self.threat) / 4).into(); + self.infrastructure = + (*(self.bureaucracy + self.transportation + self.sprawl + self.health) / 4).into(); + } + + /// Updates with events + /// Updates with leader + /// etc. + // TODO: Fill this + fn apply_exteriors(&mut self) {} + + #[cfg(test)] + pub(crate) fn linear(base: isize) -> OverallStats { + use crate::stats; + + Self { + demographics: stats::GenericStat(1 + base), + population: stats::GenericStat(2 + base), + growth_rate: stats::GenericStat(3 + base), + crime: stats::GenericStat(4 + base), + happiness: stats::GenericStat(5 + base), + economy: stats::GenericStat(6 + base), + food: stats::GenericStat(7 + base), + industry: stats::GenericStat(8 + base), + science: stats::GenericStat(9 + base), + trade: stats::GenericStat(10 + base), + military: stats::GenericStat(11 + base), + army: stats::GenericStat(12 + base), + strength: stats::GenericStat(13 + base), + fortification: stats::GenericStat(14 + base), + threat: stats::GenericStat(15 + base), + infrastructure: stats::GenericStat(16 + base), + bureaucracy: stats::GenericStat(17 + base), + transportation: stats::GenericStat(18 + base), + sprawl: stats::GenericStat(19 + base), + health: stats::GenericStat(20 + base), + } + } +} + +/// Strategic context and meta-data for an entity. +/// +/// All fields are intentionally simple - the logic that interprets them +/// lives in separate modules (e.g. `map`, `network`, `governance`). +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +pub struct MetaStats { + // ──── Location & Spatial Data (hidden) ─────────────────────────────── + /// Cartesian coordinates of the entity on the world map. + /// + /// **Purpose** - Position of the entity in the simulation grid. + /// **Effect** - Used for distance calculations, visibility, and + /// map-based event logic. + /// **Source** - Supplied by the map generator. + pub position: Position, + + /// Identifier for the capital + pub capital: Option, + + // /// List of nearby resource nodes (mines, forests, farms, etc.). + // /// + // /// **Purpose** - Resource map around the entity. + // /// **Effect** - Drives the entity's specialization and determines + // /// the default output mix. + // /// **Source** - `resources = filter(resource_list, distance ≤ detection_radius)`. + // pub resources: Vec, + + // /// The entity's chosen specialization tag + // /// (e.g., “Agricultural Hub”, “Industrial Center”). + // /// + // /// **Purpose** - Identity that dictates default production multipliers. + // /// **Effect** - Alters output curves and trade attractiveness. + // /// **Source** - `specialization = tag_assigned_by_player_or_ai`. + // pub specialization: String, + + // ──── Strategic Positioning (hidden + public) ───────────────────── + /// Current governor or leader assigned to the entity. + /// + /// **Purpose** - Leadership identity. + /// **Effect** - Adds personal bonuses and may modify policies + /// or diplomatic stance. + /// **Source** - `governor = selected_leader_uuid`. + pub governor: Option, + + // /// The entity's classification (capital, trade hub, frontier post, etc.). + // /// + // /// **Purpose** - Functional role within the empire. + // /// **Effect** - Alters base production, tax rates, and + // /// certain event probabilities. + // /// **Source** - `role = tag_assigned_by_player_or_ai`. + // pub role: String, + /// The faction or empire to which the entity currently belongs. + /// + /// **Purpose** - Political affiliation. + /// **Effect** - Determines diplomatic relations, war status, + /// and access to empire-wide bonuses. + /// **Source** - `faction = current_faction_uuid`. + pub faction: Option, + + /// UIDs of all entities the entity is linked to (roads, trade routes, + /// alliances, war declarations, etc.). + /// + /// **Purpose** - Connectivity network. + /// **Effect** - Influences economic, military, and diplomatic + /// interactions. + /// **Source** - `links = Vec` collected from the entity's + /// network manager. + pub links: Vec, + + /// Prestige / reputation of the entity in the eyes of the empire + /// and foreign powers. + /// + /// **Purpose** - Social standing metric. + /// **Effect** - Affects diplomatic influence, trade bonuses, + /// and event outcomes. + /// **Source** - `prestige = calculate_prestige(...)`. + pub prestige: GenericStat, +} + +/// A generic stat pair with (ListStats, GenericStat), used mainly for clap +/// Accepts two forms +/// 1. "cri 10" (two separate tokens) +/// 2. "cri:10" (one token with a separator) +#[derive(Debug, Serialize, Deserialize, Clone)] +pub struct StatPair { + /// The stat selected + pub stat: ListStats, + /// The value of the modifier + pub value: GenericStat, +} + +/// Structure used to indicate position, possess nice helper methods to use as is in the program +#[derive(Debug, Default, Serialize, Deserialize, Clone, Add, Sub)] +pub struct Position(isize, isize); + +/// The grid size, as a static like a degenerate +// TODO[9]: Change to be at least initialized with the world ? +const GRID_SIZE: (i32, i32) = (1920, 1080); +/// The size the map is divided into +const CHUNK_SIZE: isize = 200; + +impl Position { + /// The euclidian distance between two points + fn distance(&self, other: &Self) -> isize { + ((self.0 - other.0).pow(2) + (self.1 * other.1).pow(2)).isqrt() + } + + /// The position in grid coordinates + fn to_grid_distance(&self) -> (isize, isize) { + (self.0 / CHUNK_SIZE, self.1 / CHUNK_SIZE) + } + + /// Create a random position + /// None that there is no concept to either city or continent making this position rather unrelyable + // TODO[2]: Make a create_rng_from_town & create_rng_from_continents + pub fn create_rng(r: &mut ThreadRng) -> Result { + let x = r.random_range(0..GRID_SIZE.0); + let y = r.random_range(0..GRID_SIZE.1); + Ok(Self(x as isize, y as isize)) + } +} +/// A summary of the stats, only for display purposes +#[allow(clippy::missing_docs_in_private_items)] +#[derive(Table)] +pub struct SummaryStats { + #[table(title = "Demo")] + demographics: GenericStat, + #[table(title = "Eco")] + economy: GenericStat, + // #[table(title = "Social")] + // social: GenericStat, + #[table(title = "Milit")] + military: GenericStat, + #[table(title = "Infra")] + infrastructure: GenericStat, +} + +impl From for SummaryStats { + fn from(value: OverallStats) -> Self { + Self { + demographics: value.demographics, + economy: value.economy, + military: value.military, + infrastructure: value.infrastructure, + } + } +} + +/// Bridge between the CLI and the statistics logic. +/// +/// Helps convert clap arguments to OverallStats +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[allow(missing_docs)] +pub enum ListStats { + Demographics, + Population, + Growthrate, + Crime, + Happiness, + Economy, + Food, + Industry, + Science, + Trade, + Social, + Culture, + Education, + Tourism, + Influence, + Military, + Army, + Strength, + Fortification, + Threat, + Infrastructure, + Bureaucracy, + Transportation, + Sprawl, + Health, +} + +/// The list of all types of entities +#[allow(missing_docs)] +#[derive(Serialize, Deserialize, Debug, Clone, Default)] +pub enum EntityType { + Character, + Player, + Town, + Monster, + Blocker, + #[default] + Event, +} + +/// Trait to implement some symbol representations +pub trait Symbols { + /// Have a small Symbol to resume it + fn to_symbol(&self) -> String; + /// Have the shortest display possible + fn to_shortest(&self) -> String { + self.to_symbol() + } +} + +// impl Display for T { +// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +// write!(f, "{}", self.to_symbol()) +// } +// } + +// A stat that is shown to the player *and* can be modified manually. +thin_newtype!(GenericStat, isize); +thin_newtype!(TownId, usize); +thin_newtype!(CharacterId, usize); +thin_newtype!(FactionId, usize); + +// --- TRAITS --------------------------------------------------------------- +/// A stat is a *game value* that can be converted to two different +/// normalised ranges - a 100-point range for “gaming” logic and a +/// 10-point range for “roll & UI” logic. The trait also exposes the +/// underlying raw value and its visibility. +/// +// TODO[7]: Change this with Deref+From +pub trait GameStat { + /// Convert the raw integer to a 50-point scale. + fn to_100(&self) -> isize { + (self.get_value().clamp(0, 120) - 10).min(100) + } + + /// Convert the raw integer to a 10-point scale. + fn to_10(&self) -> isize { + self.to_100() / 10 + } + + /// As a colored delta (when the stat is used as a delta) + fn to_delta(&self) -> String { + let get_value = self.get_value(); + if get_value < 0 { + format!("{}", get_value.to_string().red()) + } else { + format!("{}", get_value.to_string().green()) + } + } + + /// Return the raw integer value, always bound to 0-70 + fn get_value(&self) -> isize; + + /// Return the raw integer value, always bound to 0-70 + fn change_value(&mut self, value: isize); + + /// Create a Gamestat from it's underlying value + fn from_value(value: isize) -> Self + where + Self: Sized; +} + +/// Trait for objects that can expose a stat via a string key. +/// The trait returns a *boxed* trait object so callers do not need to know +/// the concrete type that was stored. +pub trait Accessible { + /// Return the requested stat as a `Box`. + /// `None` if the key does not exist. + fn get_val(&self, key: &str) -> Option>; +} diff --git a/lib_efo/src/stats/implementations.rs b/lib_efo/src/stats/implementations.rs new file mode 100644 index 0000000..bddb4a1 --- /dev/null +++ b/lib_efo/src/stats/implementations.rs @@ -0,0 +1,455 @@ +//! All traits implementatition for the main structs are deffered here + +use crate::stats::GameStat; +use colored::Colorize; +use std::str::FromStr; + +use crate::entity::{EffectApplication, EffectBounds, EntityDuration}; +use crate::error::EpochError; +use crate::stats::{ + EntityType, FactionId, GenericStat, ListStats, OverallStats, Position, Symbols, +}; + +/// Creates a thin, deref-able wrapper around an inner type. +#[macro_export] +macro_rules! thin_newtype { + ($name:ident, $inner:ty) => { + /// Thin wrapper that derefs to the inner type. + /// Ideal for zero-overhead new-type patterns. + #[repr(transparent)] + #[derive( + Debug, + Clone, + Copy, + Default, + PartialEq, + Eq, + PartialOrd, + Ord, + Hash, + Serialize, + Deserialize, + Display, + Add, + Sub, + )] + pub struct $name(pub $inner); + + impl std::ops::Deref for $name { + type Target = $inner; + fn deref(&self) -> &Self::Target { + &self.0 + } + } + + impl std::ops::DerefMut for $name { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } + } + + impl From<$inner> for $name { + fn from(v: $inner) -> Self { + $name(v) + } + } + + impl From<$name> for $inner { + fn from(v: $name) -> Self { + v.0 + } + } + }; +} + +/// Generates an `impl GameStat for ` where the only difference between +/// multiple implementations is the visibility level. +/// +/// # Parameters +/// * `$type`: the concrete type that implements `GameStat` +/// * `$vis`: the enum variant of `VisibilityLevel` to return +macro_rules! impl_game_stat { + ($type:ident) => { + impl GameStat for $type { + fn get_value(&self) -> isize { + self.0 + } + + fn change_value(&mut self, value: isize) { + self.0 = value; + } + + fn from_value(value: isize) -> Self + where + Self: Sized, + { + Self(value) + } + } + }; +} + +/// A field accessor to be able to modify fields on the fly +macro_rules! field_accessor { + ($name:ident { $($field:ident),* }) => { + impl $name { + fn get_field_from_str(&self, key: &str) -> Option<&dyn GameStat> { + match key { + $( + stringify!($field) => Some(&self.$field), + )* + _ => None, + } + } + + fn get_field_mut_from_str(&mut self, key: &str) -> Option<&mut dyn GameStat> { + match key { + $( + stringify!($field) => Some(&mut self.$field), + )* + _ => None, + } + } + } + }; +} + +impl_game_stat!(GenericStat); +field_accessor!(OverallStats { + demographics, + population, + growth_rate, + crime, + happiness, + economy, + food, + industry, + science, + trade, + // social, + // culture, + // education, + // tourism, + // influence, + military, + army, + strength, + fortification, + threat, + infrastructure, + bureaucracy, + transportation, + sprawl, + health +}); + +impl FromStr for ListStats { + type Err = EpochError; + + /// Convert an acronym (e.g. `"cri"`) into the corresponding enum variant. + fn from_str(s: &str) -> Result { + match s.to_ascii_lowercase().as_str() { + "dem" | "demog" | "demographics" | "demo" => Ok(ListStats::Demographics), + "pop" | "popul" | "populations" => Ok(ListStats::Population), + "grow" | "grw" | "growth" => Ok(ListStats::Growthrate), + "cri" | "crim" | "crimes" => Ok(ListStats::Crime), + "hapn" | "happines" | "hap" => Ok(ListStats::Happiness), + "eco" | "economy" | "econ" => Ok(ListStats::Economy), + "food" | "fo" | "agr" | "agri" | "fod" => Ok(ListStats::Food), + "industry" | "indus" | "ind" => Ok(ListStats::Industry), + "science" | "sci" | "sc" => Ok(ListStats::Science), + "trade" | "trd" | "tr" => Ok(ListStats::Trade), + "social" | "soc" | "sl" => Ok(ListStats::Social), + "culture" | "cul" | "cl" => Ok(ListStats::Culture), + "education" | "edu" | "ed" => Ok(ListStats::Education), + "tourism" | "tour" | "tm" => Ok(ListStats::Tourism), + "influence" | "infl" | "influ" => Ok(ListStats::Influence), + "military" | "mil" | "mt" => Ok(ListStats::Military), + "army" | "arm" | "ar" => Ok(ListStats::Army), + "strength" | "str" | "st" => Ok(ListStats::Strength), + "fortification" | "fort" | "ft" => Ok(ListStats::Fortification), + "threat" | "thr" | "th" => Ok(ListStats::Threat), + "infrastructure" | "infra" | "infr" => Ok(ListStats::Infrastructure), + "bureaucracy" | "bureau" | "bur" => Ok(ListStats::Bureaucracy), + "transportation" | "trans" | "trns" => Ok(ListStats::Transportation), + "sprawl" | "spr" | "spra" => Ok(ListStats::Sprawl), + "health" | "hlth" | "hlt" => Ok(ListStats::Health), + _ => Err(EpochError::UnknownStatAcronim(s.to_owned())), + } + } +} + +impl From for &str { + fn from(value: ListStats) -> Self { + match value { + ListStats::Demographics => "demographics", + ListStats::Population => "population", + ListStats::Growthrate => "growthrate", + ListStats::Crime => "crime", + ListStats::Happiness => "happiness", + ListStats::Economy => "economy", + ListStats::Food => "food", + ListStats::Industry => "industry", + ListStats::Science => "science", + ListStats::Trade => "trade", + ListStats::Social => "social", + ListStats::Culture => "culture", + ListStats::Education => "education", + ListStats::Tourism => "tourism", + ListStats::Influence => "influence", + ListStats::Military => "military", + ListStats::Army => "army", + ListStats::Strength => "strength", + ListStats::Fortification => "fortification", + ListStats::Threat => "threat", + ListStats::Infrastructure => "infrastructure", + ListStats::Bureaucracy => "bureaucracy", + ListStats::Transportation => "transportation", + ListStats::Sprawl => "sprawl", + ListStats::Health => "health", + } + } +} + +impl OverallStats { + /// Retrieve a reference to a statistic field by its `ListStats` key. + /// + /// # Arguments + /// + /// * `field` - The `ListStats` variant that selects which statistic to return. + /// + /// # Returns + /// + /// A reference to the selected `GenericStat`. + /// + /// # Panics + /// + /// Panics if `field` is one of the variants that are not yet implemented + /// (`Social`, `Culture`, `Education`, `Tourism`, `Influence`). + pub fn get_field(&self, field: &ListStats) -> &GenericStat { + match field { + ListStats::Demographics => &self.demographics, + ListStats::Population => &self.population, + ListStats::Growthrate => &self.growth_rate, + ListStats::Crime => &self.crime, + ListStats::Happiness => &self.happiness, + ListStats::Economy => &self.economy, + ListStats::Food => &self.food, + ListStats::Industry => &self.industry, + ListStats::Science => &self.science, + ListStats::Trade => &self.trade, + ListStats::Social => unimplemented!("This version doens't implement this stat"), //&self.social, + ListStats::Culture => unimplemented!("This version doens't implement this stat"), //&self.culture, + ListStats::Education => unimplemented!("This version doens't implement this stat"), //&self.education, + ListStats::Tourism => unimplemented!("This version doens't implement this stat"), //&self.tourism, + ListStats::Influence => unimplemented!("This version doens't implement this stat"), //&self.influence, + ListStats::Military => &self.military, + ListStats::Army => &self.army, + ListStats::Strength => &self.strength, + ListStats::Fortification => &self.fortification, + ListStats::Threat => &self.threat, + ListStats::Infrastructure => &self.infrastructure, + ListStats::Bureaucracy => &self.bureaucracy, + ListStats::Transportation => &self.transportation, + ListStats::Sprawl => &self.sprawl, + ListStats::Health => &self.health, + } + } + + /// Retrieve a mutable reference to a statistic field by its `ListStats` key. + /// + /// # Arguments + /// + /// * `field` - The `ListStats` variant that selects which statistic to modify. + /// + /// # Returns + /// + /// A mutable reference to the selected `GenericStat`. + /// + /// # Panics + /// + /// Panics if `field` is one of the variants that are not yet implemented + /// (`Social`, `Culture`, `Education`, `Tourism`, `Influence`). + pub fn get_field_mut(&mut self, field: &ListStats) -> &mut GenericStat { + match field { + ListStats::Demographics => &mut self.demographics, + ListStats::Population => &mut self.population, + ListStats::Growthrate => &mut self.growth_rate, + ListStats::Crime => &mut self.crime, + ListStats::Happiness => &mut self.happiness, + ListStats::Economy => &mut self.economy, + ListStats::Food => &mut self.food, + ListStats::Industry => &mut self.industry, + ListStats::Science => &mut self.science, + ListStats::Trade => &mut self.trade, + ListStats::Social => unimplemented!("This version doens't implement this stat"), //&mut self.social, + ListStats::Culture => unimplemented!("This version doens't implement this stat"), //&mut self.culture, + ListStats::Education => unimplemented!("This version doens't implement this stat"), //&mut self.education, + ListStats::Tourism => unimplemented!("This version doens't implement this stat"), //&mut self.tourism, + ListStats::Influence => unimplemented!("This version doens't implement this stat"), //&mut self.influence, + ListStats::Military => &mut self.military, + ListStats::Army => &mut self.army, + ListStats::Strength => &mut self.strength, + ListStats::Fortification => &mut self.fortification, + ListStats::Threat => &mut self.threat, + ListStats::Infrastructure => &mut self.infrastructure, + ListStats::Bureaucracy => &mut self.bureaucracy, + ListStats::Transportation => &mut self.transportation, + ListStats::Sprawl => &mut self.sprawl, + ListStats::Health => &mut self.health, + } + } +} + +impl Symbols for EntityType { + fn to_shortest(&self) -> String { + match self { + EntityType::Character => "[C]".to_string(), + EntityType::Player => "[P]".to_string(), + EntityType::Town => "[T]".to_string(), + EntityType::Monster => "[M]".to_string(), + EntityType::Blocker => "[B]".to_string(), + EntityType::Event => "[E]".to_string(), + } + } + fn to_symbol(&self) -> String { + match self { + EntityType::Character => "".to_string(), + EntityType::Player => " ".to_string(), + EntityType::Town => "󱡵 ".to_string(), + EntityType::Monster => " ".to_string(), + EntityType::Blocker => " ".to_string(), + EntityType::Event => "".to_string(), + } + } +} + +impl Symbols for EffectApplication { + fn to_symbol(&self) -> String { + match self { + EffectApplication::Recurring => "⟳".to_string(), + EffectApplication::WhenPresent => "⥯".to_string(), + EffectApplication::PermanentEffectToApply => "☈".to_string(), + EffectApplication::PermanentEffectApplied => "✓".to_string(), + } + } +} + +impl Symbols for Position { + fn to_symbol(&self) -> String { + format!("({:4},{:4})⚓", self.0, self.1) + } + fn to_shortest(&self) -> String { + format!("{},{}", self.0, self.1) + } +} + +impl Symbols for EntityDuration { + fn to_symbol(&self) -> String { + match self { + EntityDuration::Permanent => "∞".to_string(), + EntityDuration::Duration(t) => format!("⧗{}", t), + EntityDuration::Done => "✔".to_string(), + } + } +} + +impl Symbols for EffectBounds { + fn to_symbol(&self) -> String { + format!("({} ⭾ {})", self.min, self.max) + } +} + +impl Symbols for OverallStats { + fn to_symbol(&self) -> String { + format!( + "{:2}{} {:2}{} {:2}{} {:2}{}", + self.demographics, + " ".green(), + self.economy, + "💰".yellow(), + self.military, + " ".red(), + self.infrastructure, + "󰡢".cyan(), + ) + } +} + +impl Symbols for ListStats { + fn to_shortest(&self) -> String { + match self { + ListStats::Demographics => "Dem".blue(), + ListStats::Population => "Pop".green(), + ListStats::Growthrate => "Gro".green(), + ListStats::Crime => "Cri".green(), + ListStats::Happiness => "Hap".green(), + ListStats::Economy => "Eco".blue(), + ListStats::Food => "Foo".yellow(), + ListStats::Industry => "Ind".yellow(), + ListStats::Science => "Sci".yellow(), + ListStats::Trade => "Tra".yellow(), + ListStats::Social => "Soc".blue(), + ListStats::Culture => "Cul".purple(), + ListStats::Education => "Edu".purple(), + ListStats::Tourism => "Tou".purple(), + ListStats::Influence => "Inf".purple(), + ListStats::Military => "Mil".blue(), + ListStats::Army => "Arm".red(), + ListStats::Strength => "Str".red(), + ListStats::Fortification => "For".red(), + ListStats::Threat => "Thr".red(), + ListStats::Infrastructure => "Inf".blue(), + ListStats::Bureaucracy => "Bur".cyan(), + ListStats::Transportation => "Tra".cyan(), + ListStats::Sprawl => "Spr".cyan(), + ListStats::Health => "Hea".cyan(), + } + .to_string() + } + fn to_symbol(&self) -> String { + match self { + ListStats::Demographics => " ".blue(), + ListStats::Population => " ".green(), + ListStats::Growthrate => " ".green(), + ListStats::Crime => "󱀣".green(), + ListStats::Happiness => " ".green(), + ListStats::Economy => "💰".blue(), + ListStats::Food => "󰔬".yellow(), + ListStats::Industry => "🏭".yellow(), + ListStats::Science => "󰧑 ".yellow(), + ListStats::Trade => " ".yellow(), + ListStats::Social => "󱕹 ".blue(), + ListStats::Culture => "🎭".purple(), + ListStats::Education => "📚".purple(), + ListStats::Tourism => "🏖️".purple(), + ListStats::Influence => "🌍".purple(), + ListStats::Military => "🪖".blue(), + ListStats::Army => " ".red(), + ListStats::Strength => "󰞇 ".red(), + ListStats::Fortification => "🔒".red(), + ListStats::Threat => "⚡".red(), + ListStats::Infrastructure => "🏗️ ".blue(), + ListStats::Bureaucracy => "🏛️ ".cyan(), + ListStats::Transportation => "󰔬 ".cyan(), + ListStats::Sprawl => "🏙️".cyan(), + ListStats::Health => "".cyan(), + } + .to_string() + } +} + +impl Symbols for Option { + fn to_symbol(&self) -> String { + if let Some(faction) = self { + format!("{faction}") + } else { + "Ø".to_string() + } + } +} + +mod from_impl; + +#[cfg(test)] +pub(crate) mod test; diff --git a/lib_efo/src/stats/implementations/from_impl.rs b/lib_efo/src/stats/implementations/from_impl.rs new file mode 100644 index 0000000..fe89c42 --- /dev/null +++ b/lib_efo/src/stats/implementations/from_impl.rs @@ -0,0 +1,75 @@ +//! All from implementations + +use crate::{ + error::EpochError, + stats::{self, ListStats, Position, StatPair}, +}; +use std::str::FromStr; + +impl FromStr for StatPair { + type Err = EpochError; + + /// Parse a string into a `StatPair`. + /// + /// The input can be either in the form `"stat:value"` or `"stat value"`. + /// If the format is invalid, an `EpochError::IllFormedStatQualifier` + /// is returned. + fn from_str(s: &str) -> Result { + let (stat_str, val_str) = if let Some(idx) = s.find(':') { + (&s[..idx], &s[idx + 1..]) + } else { + let parts: Vec<&str> = s.split_whitespace().collect(); + if parts.len() != 2 { + return Err(EpochError::IllFormedStatQualifier(s.to_owned())); + } + (parts[0], parts[1]) + }; + + let stat: ListStats = stat_str.parse()?; + let value: isize = val_str + .parse() + .map_err(|_| EpochError::IllFormedStatQualifier(val_str.to_owned()))?; + Ok(StatPair { + stat, + value: stats::GenericStat(value), + }) + } +} + +/// Parse a string into a `Position`. +/// +/// The input must be two signed integers separated by a comma, optionally +/// surrounded by whitespace. Leading and trailing whitespace around each +/// component is ignored. +/// +/// # Errors +/// +/// * `ParsePositionError::InvalidFormat` - the string does not contain +/// exactly one comma or there are not exactly two components. +/// * `ParsePositionError::ParseIntError` - one of the components cannot be +/// parsed as an `isize`. +impl std::str::FromStr for Position { + type Err = EpochError; + + fn from_str(s: &str) -> Result { + let parts: Vec<&str> = s.split(',').collect(); + if parts.len() != 2 { + return Err(EpochError::InvalidPositionFormat(s.to_string())); + } + let x: isize = parts[0] + .trim() + .parse() + .map_err(|_| EpochError::ParsePositionError(s.to_string()))?; + let y: isize = parts[1] + .trim() + .parse() + .map_err(|_| EpochError::ParsePositionError(s.to_string()))?; + Ok(Position(x, y)) + } +} + +impl From<(isize, isize)> for Position { + fn from(value: (isize, isize)) -> Self { + Self(value.0, value.1) + } +} diff --git a/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__effect_application_to_symbol.snap b/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__effect_application_to_symbol.snap new file mode 100644 index 0000000..b6b1534 --- /dev/null +++ b/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__effect_application_to_symbol.snap @@ -0,0 +1,8 @@ +--- +source: lib_efo/src/stats/implementations/test.rs +expression: out +--- +⟳:⟳ +⥯:⥯ +☈:☈ +✓:✓ diff --git a/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__entity_duration_to_symbol.snap b/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__entity_duration_to_symbol.snap new file mode 100644 index 0000000..7f56009 --- /dev/null +++ b/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__entity_duration_to_symbol.snap @@ -0,0 +1,7 @@ +--- +source: lib_efo/src/stats/implementations/test.rs +expression: out +--- +∞ +⧗42 +✔ diff --git a/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__entity_type_to_shortest.snap b/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__entity_type_to_shortest.snap new file mode 100644 index 0000000..6a6a463 --- /dev/null +++ b/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__entity_type_to_shortest.snap @@ -0,0 +1,10 @@ +--- +source: lib_efo/src/stats/implementations/test.rs +expression: out +--- +:[C] + :[P] +󱡵 :[T] + :[M] + :[B] +:[E] diff --git a/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__liststats_aliases.snap b/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__liststats_aliases.snap new file mode 100644 index 0000000..df84eca --- /dev/null +++ b/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__liststats_aliases.snap @@ -0,0 +1,67 @@ +--- +source: lib_efo/src/stats/implementations/test.rs +expression: output +--- +demographics: :Dem:34 +demographics: :Dem:34 +demographics: :Dem:34 +demographics: :Dem:34 +population: :Pop:35 +population: :Pop:35 +population: :Pop:35 +growthrate: :Gro:36 +growthrate: :Gro:36 +growthrate: :Gro:36 +crime:󱀣:Cri:37 +crime:󱀣:Cri:37 +crime:󱀣:Cri:37 +happiness: :Hap:38 +happiness: :Hap:38 +happiness: :Hap:38 +economy:💰:Eco:39 +economy:💰:Eco:39 +economy:💰:Eco:39 +food:󰔬:Foo:40 +food:󰔬:Foo:40 +food:󰔬:Foo:40 +food:󰔬:Foo:40 +food:󰔬:Foo:40 +industry:🏭:Ind:41 +industry:🏭:Ind:41 +industry:🏭:Ind:41 +science:󰧑 :Sci:42 +science:󰧑 :Sci:42 +science:󰧑 :Sci:42 +trade: :Tra:43 +trade: :Tra:43 +trade: :Tra:43 +military:🪖:Mil:44 +military:🪖:Mil:44 +military:🪖:Mil:44 +army: :Arm:45 +army: :Arm:45 +army: :Arm:45 +strength:󰞇 :Str:46 +strength:󰞇 :Str:46 +strength:󰞇 :Str:46 +fortification:🔒:For:47 +fortification:🔒:For:47 +fortification:🔒:For:47 +threat:⚡:Thr:48 +threat:⚡:Thr:48 +threat:⚡:Thr:48 +infrastructure:🏗️ :Inf:49 +infrastructure:🏗️ :Inf:49 +infrastructure:🏗️ :Inf:49 +bureaucracy:🏛️ :Bur:50 +bureaucracy:🏛️ :Bur:50 +bureaucracy:🏛️ :Bur:50 +transportation:󰔬 :Tra:51 +transportation:󰔬 :Tra:51 +transportation:󰔬 :Tra:51 +sprawl:🏙️:Spr:52 +sprawl:🏙️:Spr:52 +sprawl:🏙️:Spr:52 +health::Hea:53 +health::Hea:53 +health::Hea:53 diff --git a/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__position_to_symbol.snap b/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__position_to_symbol.snap new file mode 100644 index 0000000..4b83d95 --- /dev/null +++ b/lib_efo/src/stats/implementations/snapshots/lib_efo__stats__implementations__test__position_to_symbol.snap @@ -0,0 +1,6 @@ +--- +source: lib_efo/src/stats/implementations/test.rs +expression: out +--- +12,34( 12, 34)⚓ +0,0( 0, 0)⚓ diff --git a/lib_efo/src/stats/implementations/test.rs b/lib_efo/src/stats/implementations/test.rs new file mode 100644 index 0000000..c331dda --- /dev/null +++ b/lib_efo/src/stats/implementations/test.rs @@ -0,0 +1,274 @@ +#![allow(clippy::unwrap_used)] +use insta::assert_debug_snapshot; +use insta::assert_snapshot; + +use super::*; +use crate::entity::Entity; +use crate::stats::GameStat; +use crate::stats::GenericStat; +use crate::stats::StatPair; +use std::str::FromStr; + +struct Person { + name: GenericStat, + age: GenericStat, + email: GenericStat, +} + +/// Helper that asserts that a string parses to the expected ListStats variant. +fn assert_stat_ok(input: &str, expected: ListStats) { + let parsed = ListStats::from_str(input).expect("should parse"); + assert_eq!(parsed, expected, "input `{}` parsed incorrectly", input); +} + +field_accessor!(Person { name, age, email }); + +#[test] +fn test_field_accessors() { + let person = Person { + name: GenericStat(10), + age: GenericStat(20), + email: GenericStat(120), + }; + let name = person.get_field_from_str("name").unwrap(); + let email = person.get_field_from_str("email").unwrap(); + let age = person.get_field_from_str("age").unwrap(); + assert_eq!(name.to_100(), 0); + assert_eq!(age.to_100(), 10); + assert_eq!(email.to_100(), 100); +} + +#[test] +fn test_clap_serialisation() {} +/// Helper that asserts that a stat pair string parses to the expected `StatPair`. +fn assert_pair_ok(input: &str, expected_stat: ListStats, expected_val: isize) { + let pair = StatPair::from_str(input).expect("should parse"); + assert_eq!(pair.stat, expected_stat, "stat mismatch"); + assert_eq!(pair.value.0, expected_val, "value mismatch"); +} +#[test] +fn test_stat_pair_parsing() { + // Colon syntax + assert_pair_ok("cri:10", ListStats::Crime, 10); + assert_pair_ok("POP:-5", ListStats::Population, -5); + assert_pair_ok("growth:0", ListStats::Growthrate, 0); + + // Space syntax (clap concatenates two separate args into one string) + assert_pair_ok("cri 10", ListStats::Crime, 10); + assert_pair_ok("Pop -5", ListStats::Population, -5); + assert_pair_ok("grow 0", ListStats::Growthrate, 0); +} + +#[test] +fn test_liststats_aliases() { + // Each tuple: (alias, expected enum variant) + let cases = vec![ + // Demographics + ("dem", ListStats::Demographics), + ("DEMOg", ListStats::Demographics), + ("demoGRAphicS", ListStats::Demographics), + ("demo", ListStats::Demographics), + // Population + ("Pop", ListStats::Population), + ("POPUl", ListStats::Population), + ("populations", ListStats::Population), + // Growth rate + ("grow", ListStats::Growthrate), + ("grW", ListStats::Growthrate), + ("Growth", ListStats::Growthrate), + // Crime + ("CRI", ListStats::Crime), + ("crim", ListStats::Crime), + ("Crimes", ListStats::Crime), + // Happiness + ("hapN", ListStats::Happiness), + ("HAPPiNeS", ListStats::Happiness), + ("hap", ListStats::Happiness), + // Economy + ("eco", ListStats::Economy), + ("EconomY", ListStats::Economy), + ("econ", ListStats::Economy), + // Food + ("Food", ListStats::Food), + ("fo", ListStats::Food), + ("agr", ListStats::Food), + ("Agri", ListStats::Food), + ("Fod", ListStats::Food), + // Industry + ("industry", ListStats::Industry), + ("IndUs", ListStats::Industry), + ("ind", ListStats::Industry), + // Science + ("science", ListStats::Science), + ("SCI", ListStats::Science), + ("Sc", ListStats::Science), + // Trade + ("trade", ListStats::Trade), + ("TrD", ListStats::Trade), + ("tr", ListStats::Trade), + // // Social + // ("social", ListStats::Social), + // ("soc", ListStats::Social), + // ("sl", ListStats::Social), + // // Culture + // ("culture", ListStats::Culture), + // ("CUL", ListStats::Culture), + // ("cl", ListStats::Culture), + // // Education + // ("education", ListStats::Education), + // ("edu", ListStats::Education), + // ("ed", ListStats::Education), + // // Tourism + // ("tourism", ListStats::Tourism), + // ("tour", ListStats::Tourism), + // ("tm", ListStats::Tourism), + // // Influence + // ("influence", ListStats::Influence), + // ("infl", ListStats::Influence), + // ("influ", ListStats::Influence), + // Military + ("military", ListStats::Military), + ("mil", ListStats::Military), + ("mt", ListStats::Military), + // Army + ("army", ListStats::Army), + ("arm", ListStats::Army), + ("ar", ListStats::Army), + // Strength + ("strength", ListStats::Strength), + ("str", ListStats::Strength), + ("st", ListStats::Strength), + // Fortification + ("fortification", ListStats::Fortification), + ("fort", ListStats::Fortification), + ("ft", ListStats::Fortification), + // Threat + ("threat", ListStats::Threat), + ("thr", ListStats::Threat), + ("th", ListStats::Threat), + // Infrastructure + ("infrastructure", ListStats::Infrastructure), + ("infra", ListStats::Infrastructure), + ("infr", ListStats::Infrastructure), + // Bureaucracy + ("bureaucracy", ListStats::Bureaucracy), + ("bureau", ListStats::Bureaucracy), + ("bur", ListStats::Bureaucracy), + // Transportation + ("transportation", ListStats::Transportation), + ("trans", ListStats::Transportation), + ("trns", ListStats::Transportation), + // Sprawl + ("sprawl", ListStats::Sprawl), + ("spr", ListStats::Sprawl), + ("spra", ListStats::Sprawl), + // Health + ("health", ListStats::Health), + ("hlth", ListStats::Health), + ("hlt", ListStats::Health), + ]; + let mut s = OverallStats::linear(33); + let mut output = String::new(); + for (alias, expected_variant) in cases { + let val = alias.parse::().unwrap(); + s.get_field_mut_from_str(val.into()); + assert_eq!( + val, expected_variant, + "parsing `{}` should yield {:?}", + alias, expected_variant + ); + output.push_str(&format!( + "{}:{}:{}:{}\n", + std::convert::Into::<&str>::into(val), + val.to_symbol(), + val.to_shortest(), + s.get_field(&val) + )); + { + s.get_field_mut(&val); + } + } + assert_snapshot!(output); +} + +#[test] +fn test_liststats_unknown_alias() { + // Pick a string that is not in the list of known aliases. + let unknown = "unknown_stat_123"; + + // Verify the error type and payload directly. + let err = unknown.parse::().unwrap_err(); + match err { + EpochError::UnknownStatAcronim(msg) => { + assert_eq!(msg, unknown); + } + other => panic!("Expected UnknownStatAcronim, got {:?}", other), + } +} + +#[test] +fn test_entity_type_to_shortest() { + let out = [ + EntityType::Character, + EntityType::Player, + EntityType::Town, + EntityType::Monster, + EntityType::Blocker, + EntityType::Event, + ] + .iter() + .map(|v| format!("{}:{}", v.to_symbol(), v.to_shortest())) + .collect::>() + .join("\n"); + assert_snapshot!(out); +} + +// --------------------------------------------------------------------------- +// EntityType – already tested by your existing example +// --------------------------------------------------------------------------- + +// --------------------------------------------------------------------------- +// EffectApplication – one line per variant +// --------------------------------------------------------------------------- +#[test] +fn test_effect_application_to_symbol() { + let out = [ + EffectApplication::Recurring, + EffectApplication::WhenPresent, + EffectApplication::PermanentEffectToApply, + EffectApplication::PermanentEffectApplied, + ] + .iter() + .map(|v| format!("{}:{}", v.to_symbol(), v.to_shortest())) + .collect::>() + .join("\n"); + assert_snapshot!(out); +} + +// --------------------------------------------------------------------------- +// Position – two variants, tested for both `to_symbol` and `to_shortest` +// --------------------------------------------------------------------------- +#[test] +fn test_position_to_symbol() { + let out = [Position(12, 34), Position(0, 0)] + .iter() + .map(|p| format!("{}{}", p.to_shortest(), p.to_symbol())) + .collect::>() + .join("\n"); + assert_snapshot!(out); +} + +// --------------------------------------------------------------------------- +// EntityDuration – one line per variant +// --------------------------------------------------------------------------- +#[test] +fn test_entity_duration_to_symbol() { + let out = [ + EntityDuration::Permanent, + EntityDuration::Duration(42), + EntityDuration::Done, + ] + .map(|v| v.to_symbol()) + .join("\n"); + assert_snapshot!(out); +} diff --git a/lib_efo/src/utils.rs b/lib_efo/src/utils.rs index c7963dd..fc965cd 100644 --- a/lib_efo/src/utils.rs +++ b/lib_efo/src/utils.rs @@ -4,32 +4,51 @@ //! //! -use std::path::Path; +#![warn(missing_docs, clippy::missing_docs_in_private_items)] + +use clap::ValueEnum; +use rand::distr::Uniform; use crate::error::EpochError; -/// Check whether `path` points to a valid Epoch directory. +/// How to fill in unspecified stat values. /// -/// 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()); +/// When an entity is created or edited, any stat that is not explicitly +/// provided will be assigned a value according to the chosen level. +#[derive(Debug, ValueEnum, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub enum RngLevel { + /// All non specified values are zero + Zero, + /// All non specified values are low + Low, + /// All non specified values are medium + Med, + /// All non specified values are high + High, + /// All non specified values are very high + Legendary, + /// Stats are all over the place + Mixed, + /// All non specified are either high or low + Flawed, +} + +impl RngLevel { + /// Turn into a range for rng generation + pub fn to_range(&self) -> std::ops::Range { + match self { + RngLevel::Zero => 0..1, + RngLevel::Low => 0..20, + RngLevel::Med => 10..40, + RngLevel::High => 20..50, + RngLevel::Legendary => 40..70, + RngLevel::Mixed => 0..70, + RngLevel::Flawed => 0..100, + } } - 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() {} + /// Turn into a rng generator + pub fn to_rng(&self) -> Result, EpochError> { + Ok(Uniform::try_from(self.to_range())?) + } }