epoch_forge/bin_efo/src/commands/show.rs

256 lines
8.4 KiB
Rust

//! Unified entity and epoch inspection.
use std::path::Path;
use clap::{Args, ValueEnum};
use lib_efo::{
Displayable,
entity::Entity,
epoch::{EpochId, EpochIdentifier, EpochInfo},
stats::{EntityType, Position},
workspace::Workspace,
};
use crate::error::AppError;
/// Collection selected by `efo show`.
#[derive(Debug, Clone, Copy, Default, ValueEnum)]
pub enum ShowKind {
/// Every entity collection.
#[default]
All,
/// Events.
Event,
/// Characters.
#[value(alias = "chr")]
Character,
/// Towns.
Town,
/// Calamities.
Calamity,
/// Organisations.
#[value(aliases = ["org", "organisation"])]
Organization,
/// Blockers.
Blocker,
/// Committed epoch summaries.
Epoch,
}
/// Amount of information rendered for each match.
#[derive(Debug, Clone, Copy, Default, ValueEnum)]
pub enum ShowDetail {
/// Compact identity, position, and aggregate statistics.
#[default]
Short,
/// Short output plus descriptions and epoch metadata.
Long,
/// Complete entity trees/stat tables or persisted epoch JSON.
Full,
}
/// Search and rendering options for `efo show`.
#[derive(Args, Debug)]
#[command(
after_long_help = "EXAMPLES:\n efo show\n efo show town\n efo show all --name north\n efo show calamity --text dragon --detail long\n efo show town --position 66,57\n efo show epoch --detail long\n efo show epoch --epoch 3 --detail full"
)]
pub struct ShowArgs {
/// Collection to inspect; defaults to all entities.
#[arg(value_enum, default_value_t)]
kind: ShowKind,
/// Case-insensitive substring of the entity name.
#[arg(long)]
name: Option<String>,
/// Case-insensitive substring of the name or description.
#[arg(long)]
text: Option<String>,
/// Exact entity position.
#[arg(long)]
position: Option<Position>,
/// Read a committed epoch by numeric ID or exact tag instead of the worktree.
#[arg(long)]
epoch: Option<EpochIdentifier>,
/// Output detail level.
#[arg(long, value_enum, default_value_t)]
detail: ShowDetail,
}
/// Display filtered repository content through one command surface.
pub fn handle_show_cmd(args: &ShowArgs) -> Result<(), AppError> {
let workspace = Workspace::open(Path::new("."))?;
if matches!(args.kind, ShowKind::Epoch) {
print!("{}", render_epochs(args, &workspace)?);
return Ok(());
}
let world = args
.epoch
.as_ref()
.map(|identifier| resolve(&workspace, identifier))
.transpose()?
.map(|id| workspace.load_epoch(id))
.transpose()?
.unwrap_or_else(|| workspace.worktree.world.clone());
print!("{}", render_entities(args, &world));
Ok(())
}
/// Render selected entity collections and filters.
fn render_entities(args: &ShowArgs, world: &EpochInfo) -> String {
let mut output = String::new();
let selected: &[(&str, EntityType)] = match args.kind {
ShowKind::All => &[
("Characters", EntityType::Character),
("Towns", EntityType::Town),
("Events", EntityType::Event),
("Calamities", EntityType::Calamity),
("Organisations", EntityType::Organization),
("Blockers", EntityType::Blocker),
],
ShowKind::Event => &[("Events", EntityType::Event)],
ShowKind::Character => &[("Characters", EntityType::Character)],
ShowKind::Town => &[("Towns", EntityType::Town)],
ShowKind::Calamity => &[("Calamities", EntityType::Calamity)],
ShowKind::Organization => &[("Organisations", EntityType::Organization)],
ShowKind::Blocker => &[("Blockers", EntityType::Blocker)],
ShowKind::Epoch => unreachable!("epochs are dispatched separately"),
};
for (section, (title, entity_type)) in selected.iter().enumerate() {
if section > 0 {
output.push('\n');
}
let matches = world
.vec_entities(entity_type)
.iter()
.filter(|entity| matches_filters(entity, args))
.collect::<Vec<_>>();
output.push_str(&format!("{title} ({})\n", matches.len()));
if matches.is_empty() {
output.push_str(" — none\n");
continue;
}
for entity in matches {
match args.detail {
ShowDetail::Short => {
output.push_str(&entity.short_display(world));
output.push('\n');
}
ShowDetail::Long => {
output.push_str(&entity.short_display(world));
output.push('\n');
if !entity.description.trim().is_empty() {
output.push_str(&format!(" {}\n", entity.description));
}
}
ShowDetail::Full => {
output.push_str(&entity.full_display(world));
output.push('\n');
}
}
}
}
output
}
/// Apply all requested entity predicates.
fn matches_filters(entity: &Entity, args: &ShowArgs) -> bool {
let name = entity.name.to_lowercase();
let description = entity.description.to_lowercase();
args.name
.as_ref()
.is_none_or(|query| name.contains(&query.to_lowercase()))
&& args.text.as_ref().is_none_or(|query| {
let query = query.to_lowercase();
name.contains(&query) || description.contains(&query)
})
&& args
.position
.as_ref()
.is_none_or(|position| entity.position().distance(position) == 0)
}
/// Render one epoch or every stored epoch in numeric order.
fn render_epochs(args: &ShowArgs, workspace: &Workspace) -> Result<String, AppError> {
let mut output = String::new();
let ids = if let Some(identifier) = &args.epoch {
vec![resolve(workspace, identifier)?]
} else {
let mut ids = std::fs::read_dir(workspace.root().join("epoch"))?
.filter_map(Result::ok)
.filter_map(|entry| entry.file_name().to_string_lossy().parse::<EpochId>().ok())
.collect::<Vec<_>>();
ids.sort_unstable();
ids
};
for id in ids {
let epoch = workspace.load_epoch(id)?;
let head = if id == workspace.manifest.epoch_id {
"*"
} else {
" "
};
match args.detail {
ShowDetail::Short => {
output.push_str(&format!("{head} epoch {id} — {}\n", message(&epoch)));
}
ShowDetail::Long => {
output.push_str(&format!("{head} epoch {id} — {}\n", message(&epoch)));
output.push_str(&format!(
" parent: {} · entities: {} · tags: {}\n",
epoch
.parent_epoch
.map_or_else(|| "—".into(), |id| id.to_string()),
entity_count(&epoch),
if epoch.tags.is_empty() {
"—".into()
} else {
epoch.tags.to_string()
}
));
if !epoch.summary.is_empty() {
output.push_str(&format!(" summary: {}\n", epoch.summary));
}
}
ShowDetail::Full => {
output.push_str(
&serde_json::to_string_pretty(&epoch)
.map_err(lib_efo::error::StorageError::from)?,
);
output.push('\n');
}
}
}
Ok(output)
}
/// Resolve a numeric epoch ID or exact tag.
fn resolve(workspace: &Workspace, identifier: &EpochIdentifier) -> Result<EpochId, AppError> {
match identifier {
EpochIdentifier::Id(id) => Ok(*id),
EpochIdentifier::Tag(tag) => workspace
.manifest
.tags
.get(tag)
.copied()
.ok_or_else(|| lib_efo::error::EpochError::EpochNotFound(tag.clone()).into()),
}
}
/// Human commit-message fallback.
fn message(epoch: &EpochInfo) -> &str {
if epoch.commit_message.is_empty() {
"initial snapshot"
} else {
&epoch.commit_message
}
}
/// Total entities in an epoch.
fn entity_count(epoch: &EpochInfo) -> usize {
epoch.characters.len()
+ epoch.towns.len()
+ epoch.events.len()
+ epoch.calamities.len()
+ epoch.organizations.len()
+ epoch.blockers.len()
}