fix: make init safe and show repository state

This commit is contained in:
Dandaedre 2026-09-20 20:54:58 +02:00
parent 59a533e2f3
commit a3708a843f
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
7 changed files with 99 additions and 52 deletions

View File

@ -35,7 +35,7 @@ work belongs here before implementation.
isolated temporary directories.
- [ ] Test root and nested help, version output, invalid commands, and exit
status/stderr conventions.
- [ ] Test `init`, including non-empty directories, already initialised repos,
- [x] Test `init`, including non-empty directories, already initialised repos,
and the promised `--force` semantics.
- [ ] Test `status` and repository discovery/error reporting. (Happy-path
status is covered; repository discovery and error cases remain.)
@ -50,14 +50,14 @@ work belongs here before implementation.
## Phase 3 — finish the intended current CLI
- [ ] Make `efo show` inspect actual world state or replace it with a coherent
- [x] Make `efo show` inspect actual world state or replace it with a coherent
command surface; remove its current generated demonstration output.
- [ ] Make `efo status` clearly show current epoch, timeline divergence/future
snapshots, entity totals, and a clean/modified indicator if detectable.
- [x] Implement and test truthful `epoch diff` output.
- [x] Implement `epoch fsck` with read-only checks for config, directories,
parent links, tags, IDs, entity references, and parseability.
- [ ] Make `init --force` safe and explicit; it must not silently destroy an
- [x] Make `init --force` safe and explicit; it must not silently destroy an
existing Epoch Forge repository or unrelated files.
- [ ] Resolve naming inconsistencies (`chr`, calamity mapped to monster,
missing organisation surface) with aliases/deprecation where compatibility

View File

@ -66,9 +66,8 @@ Run `efo --help`, `efo <command> --help`, or see the
| Generation | Generate character, town, event, calamity, blocker, and exotic names | Deterministic seed controls and template packs |
| Interfaces | CLI | TUI (possible stretch goal); GUI/web (out of scope) |
The top-level `show` command is known incomplete and should not be relied upon
until its roadmap item is checked. The per-type commands,
such as `efo chr show`, are the supported way to inspect entities.
`efo show all` gives a world overview; per-type commands such as
`efo chr show Aria` provide targeted or detailed inspection.
## Documentation

View File

@ -37,7 +37,7 @@ use lib_efo::{
epoch::{EpochConfig, EpochInfo, epoch_traits::ConfigWritable},
error::EpochError,
};
use std::fs::read_dir;
use std::{fs::read_dir, path::Path};
use crate::{
error::AppError,
@ -63,14 +63,26 @@ pub struct InitCmd {
pub fn init(args: &InitCmd) -> Result<(), AppError> {
let epoch_config = EpochConfig::default();
let root = epoch_config.save_folder();
let config_path = epoch_config.save_path();
let initial_epoch = EpochInfo::default();
let initial_epoch_path = initial_epoch.save_path();
if read_dir(&root)?.count() != 0 {
if Path::new(&config_path).exists() || Path::new(&initial_epoch_path).exists() {
Err(EpochError::AlreadyInitialized {
advice: Some(
"Use `efo status` to inspect this repository; existing Epoch Forge data was not changed."
.to_string(),
),
})?;
}
if !args.force && read_dir(&root)?.next().is_some() {
Err(EpochError::FolderNotEmpty {
name: root,
show_label: None,
})?;
}
init_epoch(args)?;
init_epoch()?;
epoch_config
.save_with_context(
"Creatig initial config",
@ -91,9 +103,9 @@ pub fn init(args: &InitCmd) -> Result<(), AppError> {
///
/// 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> {
fn init_epoch() -> Result<(), AppError> {
let empty = EpochInfo::default();
_ = empty.create_subfolders();
empty.create_subfolders()?;
empty.save_with_context(
"Creating empty epoch file 0",
&lib_efo::epoch::SaveMode::DoNotErase,

View File

@ -1,51 +1,57 @@
//! The show commands
//! Used to display structures with various degree of verbosity
//! Inspect entities in the current epoch.
use clap::Subcommand;
use lib_efo::{Displayable, entity::Entity, epoch::EpochInfo, naming::NAMING};
use lib_efo::{Displayable, epoch::EpochConfig, stats::EntityType};
use crate::error::AppError;
/// Entity collections that can be displayed from the current epoch.
#[derive(Subcommand, Debug)]
/// Show command
pub enum ShowCmd {
/// Show an event
/// Show all entity collections.
All,
/// Show events.
Event,
/// Show an event
/// Show characters.
Character,
/// Show an event
/// Show towns.
Town,
/// Show calamities.
Calamity,
/// Show blockers.
Blocker,
}
// #[derive(Args)]
// struct Specifics {
// name: String,
// }
/// Handle all show cmds
/// Display the selected collection from the repository's current epoch.
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.short_display(&EpochInfo::default());
println!("\n\n\n LONG");
e.print_full(&EpochInfo::default());
println!("\n\n\n TREE");
println!("{}", e.to_pretty_tree(&EpochInfo::default()));
let mut config = EpochConfig::new_from_path(None)?;
let epoch = config.try_load_current()?;
let selected: &[(&str, EntityType)] = match cmd {
ShowCmd::All => &[
("Characters", EntityType::Character),
("Towns", EntityType::Town),
("Events", EntityType::Event),
("Calamities", EntityType::Monster),
("Blockers", EntityType::Blocker),
],
ShowCmd::Event => &[("Events", EntityType::Event)],
ShowCmd::Character => &[("Characters", EntityType::Character)],
ShowCmd::Town => &[("Towns", EntityType::Town)],
ShowCmd::Calamity => &[("Calamities", EntityType::Monster)],
ShowCmd::Blocker => &[("Blockers", EntityType::Blocker)],
};
for (index, (title, entity_type)) in selected.iter().enumerate() {
if index > 0 {
println!();
}
let entities = epoch.vec_entities(entity_type);
println!("{title} ({})", entities.len());
if entities.is_empty() {
println!(" — none");
} else {
print!("{}", entities.short_display(epoch));
}
}
Ok(())
}
// Show event
// Show diff (char/town)
// Show ....

View File

@ -68,7 +68,7 @@ enum TopLevelCmd {
/// Advance or query the current epoch.
#[command(subcommand)]
Epoch(EpochCmd),
/// Display some elements
/// Inspect entities in the current epoch
#[command(subcommand)]
Show(ShowCmd),
/// Handle characters

View File

@ -73,6 +73,12 @@ fn init_status_diff_and_fsck_workflow() {
assert!(stdout(&status).contains("Epoch 0"));
assert_success(&efo(&repo, &["chr", "add", "Aria"]));
let show = efo(&repo, &["show", "all"]);
assert_success(&show);
let show_text = stdout(&show);
assert!(show_text.contains("Characters (1)"));
assert!(show_text.contains("Aria"));
assert!(show_text.contains("Towns (0)"));
assert_success(&efo(&repo, &["epoch", "next"]));
assert_success(&efo(&repo, &["chr", "edit", "Aria", "--prestige-add", "2"]));
@ -87,6 +93,28 @@ fn init_status_diff_and_fsck_workflow() {
assert!(stdout(&fsck).contains("Repository is consistent (2 epoch(s) checked)"));
}
#[test]
fn init_force_preserves_unrelated_files_and_never_overwrites_a_repository() {
let repo = TestRepo::new();
let notes = repo.path().join("notes.txt");
fs::write(&notes, "keep me").expect("write unrelated file");
let refused = efo(&repo, &["init"]);
assert!(!refused.status.success());
assert!(!repo.path().join(".epoch").exists());
assert_success(&efo(&repo, &["init", "--force"]));
assert_eq!(fs::read_to_string(&notes).expect("read notes"), "keep me");
let config_before = fs::read(repo.path().join(".epoch")).expect("read config");
let refused_again = efo(&repo, &["init", "--force"]);
assert!(!refused_again.status.success());
assert_eq!(
fs::read(repo.path().join(".epoch")).expect("read config again"),
config_before
);
}
#[test]
fn fsck_reports_a_snapshot_with_the_wrong_id_without_panicking() {
let repo = TestRepo::new();

View File

@ -5,9 +5,9 @@ parent directories. `efo <command> --help` is the authoritative syntax.
## Repository and timeline
- `efo init [--force]` creates `.epoch` and `epoch/0/epochinfo.json`. Although
`--force` is accepted in 0.1.0, it currently has no effect and will not allow
a non-empty directory.
- `efo init [--force]` creates `.epoch` and `epoch/0/epochinfo.json`. The normal
form requires an empty directory; `--force` permits unrelated existing files
but never overwrites `.epoch` or epoch 0.
- `efo status [EPOCH_ID]` shows an epoch summary, tags, and entity counts.
- `efo epoch log [-c N]` shows epochs around the current epoch.
- `efo epoch next` creates and checks out the next snapshot. It refuses while
@ -43,7 +43,9 @@ replacing them. See nested help (for example `efo chr add --help`) for exact
syntax and values. Mutations write the current epoch immediately; staging does
not exist yet.
The top-level `show` command is currently demo output. Use `<noun> show`.
`efo show all` lists every collection in the current epoch. `show character`,
`show town`, `show event`, `show calamity`, and `show blocker` select one
collection. Use `<noun> show IDENTIFIER` for full details of one entity.
## Generation and output