feat: add format 2 staging and restore workflow

This commit is contained in:
Dandaedre 2026-09-21 00:25:33 +02:00
parent 3332810491
commit d938e27288
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
14 changed files with 683 additions and 15 deletions

View File

@ -102,7 +102,7 @@ portable release gates.
recovery.
- [ ] Extend transactions across multi-file commits and add automatic
pre-commit migration rollback.
- [ ] Implement worktree/index-aware `status`, `diff`, `stage`, and both restore
- [x] Implement worktree/index-aware `status`, `diff`, `stage`, and both restore
directions without changing immutable epochs.
- [ ] Implement committed epochs, `log`, conflict-safe `revert`, and backed-up
`prune-future`; retire the destructive `reset` spelling through deprecation.

View File

@ -9,9 +9,10 @@ current state, advance it, compare it with history, and deliberately discard a
future timeline when needed.
The current release manages organisations, characters, towns, events,
calamities, and blockers with statistics and relationships. Custom fields,
pseudo-staging, complete restore/revert workflows, and a TUI are planned—not
implemented. There is no GUI or web interface.
calamities, and blockers with statistics and relationships. Format-2 worktree,
staging, diff, and restore are available after explicit migration. Custom
fields, committed format-2 history/revert, and a TUI remain planned. There is no
GUI or web interface.
> Epoch Forge is not yet suitable as the only copy of important campaign data.
> Keep the repository in Git or make a directory backup before destructive

View File

@ -16,6 +16,7 @@ pub mod migrate;
pub mod safety;
// pub mod roll;
pub mod show;
pub mod state;
pub mod status;
// pub mod diff;
// pub mod utils;

View File

@ -82,6 +82,7 @@ use lib_efo::{
utils::RngLevel,
};
use log::{info, trace};
use std::collections::HashMap;
use crate::error::AppError;
use crate::success::{SuccessMessages, display_success};
@ -302,7 +303,46 @@ pub fn handle_entity_commands(
entity_sub_commands: &EntitySubCommands,
e_type: &stats::EntityType,
) -> Result<(), AppError> {
let mut main_epoch = EpochConfig::new_from_path(None)?;
let is_current = std::fs::read(".epoch")
.ok()
.and_then(|bytes| lib_efo::repository_format::detect_manifest(&bytes).ok())
.is_some_and(|manifest| {
matches!(
manifest,
lib_efo::repository_format::DetectedManifest::Current(_)
)
});
let mut workspace = if is_current {
Some(lib_efo::workspace::Workspace::open(std::path::Path::new(
".",
))?)
} else {
None
};
let mut main_epoch = if let Some(state) = &workspace {
let mut epochs = HashMap::new();
for entry in std::fs::read_dir("epoch")? {
let entry = entry?;
if entry.file_type()?.is_dir()
&& let Ok(id) = entry.file_name().to_string_lossy().parse()
{
epochs.insert(id, None);
}
}
epochs.insert(state.manifest.epoch_id, Some(state.worktree.world.clone()));
EpochConfig {
epoch_id: state.manifest.epoch_id,
version: state.manifest.version.clone(),
tags: state.manifest.tags.clone().into_iter().collect(),
list_existing_epochs: epochs,
}
} else {
EpochConfig::new_from_path(None)?
};
let mutates = matches!(
entity_sub_commands,
EntitySubCommands::Add(_) | EntitySubCommands::Del(_) | EntitySubCommands::Edit(_)
);
match entity_sub_commands {
EntitySubCommands::Add(entity_args) => {
handle_create_entity(entity_args, e_type, &mut main_epoch)
@ -323,6 +363,15 @@ pub fn handle_entity_commands(
handle_diff_entity(entity_args, e_type, &mut main_epoch)
}
}?;
if mutates {
let changed = main_epoch.loaded_epoch(main_epoch.epoch_id)?.clone();
if let Some(state) = &mut workspace {
state.worktree.world = changed;
state.save_worktree("entity edit")?;
} else {
changed.save_with_context("Saving entity change", &lib_efo::epoch::SaveMode::Erase)?;
}
}
Ok(())
}
@ -382,8 +431,6 @@ pub(crate) fn handle_create_entity(
vec_entities.push(entity.clone());
entity.print_full(epoch_info);
// Save changes
epoch_info.save_with_context("Created entity", &lib_efo::epoch::SaveMode::Erase)?;
display_success(message);
Ok(())
@ -413,7 +460,6 @@ fn handle_delete_entity(
// // Delete either a governor or capital
// }
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(),
@ -512,8 +558,6 @@ fn handle_edit_entity(
entity.print_full(epoch_info);
// Only swap if a swap is needed
epoch_info.swap_entity(entity)?;
epoch_info.save_with_context("Deleted entity", &lib_efo::epoch::SaveMode::Erase)?;
display_success(&edited_entity);
Ok(())
}

View File

@ -26,8 +26,26 @@ pub enum ShowCmd {
/// Display the selected collection from the repository's current epoch.
pub fn handle_show_cmd(cmd: &ShowCmd) -> Result<(), AppError> {
if std::fs::read(".epoch")
.ok()
.and_then(|bytes| lib_efo::repository_format::detect_manifest(&bytes).ok())
.is_some_and(|manifest| {
matches!(
manifest,
lib_efo::repository_format::DetectedManifest::Current(_)
)
})
{
let workspace = lib_efo::workspace::Workspace::open(std::path::Path::new("."))?;
return render(cmd, &workspace.worktree.world);
}
let mut config = EpochConfig::new_from_path(None)?;
let epoch = config.try_load_current()?;
render(cmd, epoch)
}
/// Render selected collections from an already loaded world.
fn render(cmd: &ShowCmd, epoch: &lib_efo::epoch::EpochInfo) -> Result<(), AppError> {
let selected: &[(&str, EntityType)] = match cmd {
ShowCmd::All => &[
("Characters", EntityType::Character),

View File

@ -0,0 +1,211 @@
//! Format-2 status, diff, staging, and restoration.
use std::path::Path;
use clap::{Args, ValueEnum};
use lib_efo::{
entity::EntityIdentifier, epoch::EpochInfo, stats::EntityType, workspace::Workspace,
};
use crate::error::AppError;
/// CLI-safe names for persisted entity collections.
#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum EntityKind {
/// Characters.
Character,
/// Towns.
Town,
/// Events.
Event,
/// Calamities.
Calamity,
/// Organisations.
Organization,
/// Blockers.
Blocker,
}
impl From<EntityKind> for EntityType {
fn from(value: EntityKind) -> Self {
match value {
EntityKind::Character => Self::Character,
EntityKind::Town => Self::Town,
EntityKind::Event => Self::Event,
EntityKind::Calamity => Self::Calamity,
EntityKind::Organization => Self::Organization,
EntityKind::Blocker => Self::Blocker,
}
}
}
/// Select all state or named entities of one kind.
#[derive(Args, Debug)]
#[command(
after_long_help = "EXAMPLES:\n efo stage --all\n efo stage --kind character Aria @UUID"
)]
pub struct StageCmd {
/// Stage the complete worktree.
#[arg(long, conflicts_with = "kind")]
all: bool,
/// Stage only matching entities of this kind.
#[arg(long, value_enum, required_unless_present = "all")]
kind: Option<EntityKind>,
/// Names or stable `@UUID` identifiers selected with `--kind`.
#[arg(required_unless_present = "all")]
identifiers: Vec<EntityIdentifier>,
}
/// Select a source layer and state to restore.
#[derive(Args, Debug)]
#[command(
after_long_help = "EXAMPLES:\n efo restore --staged --all\n efo restore --worktree --kind town Durn"
)]
pub struct RestoreCmd {
/// Copy HEAD into the index (unstage).
#[arg(long, group = "layer", required = true)]
staged: bool,
/// Copy the index into the editable worktree.
#[arg(long, group = "layer", required = true)]
worktree: bool,
/// Restore the complete selected layer.
#[arg(long, conflicts_with = "kind")]
all: bool,
/// Restore only matching entities of this kind.
#[arg(long, value_enum, required_unless_present = "all")]
kind: Option<EntityKind>,
/// Names or stable `@UUID` identifiers selected with `--kind`.
#[arg(required_unless_present = "all")]
identifiers: Vec<EntityIdentifier>,
}
/// Choose the diff boundary.
#[derive(Args, Debug)]
pub struct StateDiffCmd {
/// Compare HEAD to index instead of index to worktree.
#[arg(long)]
staged: bool,
}
/// Print format-2 state status.
pub fn status() -> Result<(), AppError> {
let workspace = Workspace::open(Path::new("."))?;
println!("Epoch {} (HEAD)", workspace.manifest.epoch_id);
println!(
"├─ Staged {}",
label(workspace.has_staged_changes(), "changes", "clean")
);
println!(
"├─ Worktree {}",
label(workspace.has_unstaged_changes(), "changes", "clean")
);
println!("└─ Next epoch {}", workspace.manifest.next_epoch_id);
if workspace.has_staged_changes() {
println!("Use `efo diff --staged` to review the next commit.");
}
if workspace.has_unstaged_changes() {
println!("Use `efo diff` to review edits, then `efo stage ...`.");
}
Ok(())
}
/// Stage selected format-2 state.
pub fn stage(command: &StageCmd) -> Result<(), AppError> {
let mut workspace = Workspace::open(Path::new("."))?;
if command.all {
workspace.stage_all()?;
println!("✓ Staged the complete worktree.");
} else if let Some(kind) = command.kind {
workspace.stage_entities(kind.into(), &command.identifiers)?;
println!(
"✓ Staged {} selected entity/ies.",
command.identifiers.len()
);
}
Ok(())
}
/// Restore selected format-2 state from the explicitly named source layer.
pub fn restore(command: &RestoreCmd) -> Result<(), AppError> {
let mut workspace = Workspace::open(Path::new("."))?;
match (command.staged, command.worktree, command.all, command.kind) {
(true, false, true, _) => workspace.restore_index()?,
(false, true, true, _) => workspace.restore_worktree()?,
(true, false, false, Some(kind)) => {
workspace.restore_index_entities(kind.into(), &command.identifiers)?
}
(false, true, false, Some(kind)) => {
workspace.restore_worktree_entities(kind.into(), &command.identifiers)?
}
_ => unreachable!("clap enforces layer and selection groups"),
}
println!("✓ Restored the selected state.");
println!(" Run `efo status` to review what remains.");
Ok(())
}
/// Display deterministic entity-level differences between state layers.
pub fn diff(command: &StateDiffCmd) -> Result<(), AppError> {
let workspace = Workspace::open(Path::new("."))?;
let (from, to, title) = if command.staged {
(&workspace.head, &workspace.index.world, "HEAD → index")
} else {
(
&workspace.index.world,
&workspace.worktree.world,
"index → worktree",
)
};
println!("{title}");
print_diff(from, to);
Ok(())
}
/// Render added, removed, and modified entities deterministically.
fn print_diff(from: &EpochInfo, to: &EpochInfo) {
let collections = [
("characters", &from.characters, &to.characters),
("towns", &from.towns, &to.towns),
("events", &from.events, &to.events),
("calamities", &from.calamities, &to.calamities),
("organisations", &from.organizations, &to.organizations),
("blockers", &from.blockers, &to.blockers),
];
let mut count = 0;
for (name, old, new) in collections {
for entity in new
.iter()
.filter(|item| !old.iter().any(|prior| prior.id == item.id))
{
println!(" + {name}: {} @{}", entity.name, entity.id);
count += 1;
}
for entity in old
.iter()
.filter(|item| !new.iter().any(|next| next.id == item.id))
{
println!(" - {name}: {} @{}", entity.name, entity.id);
count += 1;
}
for entity in new.iter().filter(|item| {
old.iter()
.find(|prior| prior.id == item.id)
.is_some_and(|prior| {
serde_json::to_value(prior).ok() != serde_json::to_value(*item).ok()
})
}) {
println!(" ~ {name}: {} @{}", entity.name, entity.id);
count += 1;
}
}
if count == 0 {
println!(" No changes.");
} else {
println!("{count} change(s)");
}
}
/// Human-readable boolean state without relying on colour or icons.
fn label(changed: bool, changed_label: &'static str, clean_label: &'static str) -> &'static str {
if changed { changed_label } else { clean_label }
}

View File

@ -1,7 +1,10 @@
//! Concise repository and current-epoch status.
use clap::Args;
use lib_efo::epoch::{EpochConfig, EpochId};
use lib_efo::{
epoch::{EpochConfig, EpochId},
repository_format::{DetectedManifest, detect_manifest},
};
/// Arguments for the `status` subcommand.
#[derive(Args, Debug)]
@ -12,6 +15,13 @@ pub struct StatusCmd {
/// Print the selected epoch's annotations, timeline state, and entity totals.
pub(crate) fn status(cmd: &StatusCmd) -> Result<(), crate::error::AppError> {
if std::fs::read(".epoch")
.ok()
.and_then(|bytes| detect_manifest(&bytes).ok())
.is_some_and(|manifest| matches!(manifest, DetectedManifest::Current(_)))
{
return crate::commands::state::status();
}
let mut config = EpochConfig::new_from_path(None)?;
let selected_id = cmd.custom_id.unwrap_or(config.epoch_id);
let is_current = selected_id == config.epoch_id;

View File

@ -8,7 +8,9 @@
use lib_efo::{
error::{EpochError, StorageError},
migration::MigrationError,
repository_format::FormatError,
transaction::TransactionError,
workspace::WorkspaceError,
};
use miette::Diagnostic;
use thiserror::Error;
@ -43,6 +45,14 @@ pub enum AppError {
/// Exclusive locking or interrupted-write recovery failed safely.
#[error("Repository safety check stopped: {0}")]
Transaction(#[from] TransactionError),
/// Format-2 state is missing, inconsistent, or unsafe to change.
#[error("Repository state error: {0}")]
Workspace(#[from] WorkspaceError),
/// Repository manifest format detection failed.
#[error("Repository format error: {0}")]
Format(#[from] FormatError),
// /// Anything else we didn't anticipate.
// #[error("Unknown error: {0}")]
// Other(String),

View File

@ -36,6 +36,7 @@ use crate::{
migrate::MigrateCmd,
safety::{LockCmd, RecoverCmd},
show::ShowCmd,
state::{RestoreCmd, StageCmd, StateDiffCmd},
status::StatusCmd,
},
error::AppError,
@ -79,6 +80,12 @@ enum TopLevelCmd {
/// Inspect or explicitly break the repository writer lock.
#[command(subcommand)]
Lock(LockCmd),
/// Show unstaged changes, or staged changes with `--staged`.
Diff(StateDiffCmd),
/// Copy worktree changes into the index.
Stage(StageCmd),
/// Restore index or worktree state from its prior layer.
Restore(RestoreCmd),
/// Gives a very simple status.
Status(StatusCmd),
/// Advance or query the current epoch.
@ -161,6 +168,9 @@ fn exec_dispatch(cli: Cli) -> Result<(), AppError> {
TopLevelCmd::Migrate(cmd) => commands::migrate::migrate(&cmd),
TopLevelCmd::Recover(cmd) => commands::safety::handle_recover(&cmd),
TopLevelCmd::Lock(cmd) => commands::safety::handle_lock(&cmd),
TopLevelCmd::Diff(cmd) => commands::state::diff(&cmd),
TopLevelCmd::Stage(cmd) => commands::state::stage(&cmd),
TopLevelCmd::Restore(cmd) => commands::state::restore(&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),

View File

@ -188,9 +188,25 @@ fn migration_is_dry_run_by_default_and_backs_up_before_commit() {
legacy_manifest
);
let protected = efo(&repo, &["status"]);
assert!(!protected.status.success());
assert!(stderr(&protected).contains("does not yet support repository format 2"));
let status = efo(&repo, &["status"]);
assert_success(&status);
assert!(stdout(&status).contains("Staged clean"));
assert_success(&efo(&repo, &["chr", "add", "Bryn"]));
assert!(stdout(&efo(&repo, &["status"])).contains("Worktree changes"));
let diff = efo(&repo, &["diff"]);
assert_success(&diff);
assert!(stdout(&diff).contains("+ characters: Bryn"));
assert_success(&efo(&repo, &["stage", "--kind", "character", "Bryn"]));
let status = stdout(&efo(&repo, &["status"]));
assert!(status.contains("Staged changes"));
assert!(status.contains("Worktree clean"));
assert_success(&efo(&repo, &["restore", "--staged", "--all"]));
assert_success(&efo(&repo, &["restore", "--worktree", "--all"]));
let show = efo(&repo, &["show", "character"]);
assert_success(&show);
assert!(!stdout(&show).contains("Bryn"));
let recovery = efo(&repo, &["recover"]);
assert_success(&recovery);

View File

@ -50,7 +50,11 @@ Common add/edit options include `--stats key:value ...`, `--position x,y`,
options, and prestige controls. `edit --delta` adds supplied stats rather than
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 in format 1.
not exist in format 1. After format-2 migration, entity mutations edit only the
worktree. Use `efo diff`, `efo stage --all` or `efo stage --kind KIND ID...`,
and `efo diff --staged` to prepare history. `efo restore --staged ...` copies
HEAD into the index; `efo restore --worktree ...` copies the index into the
worktree. Both restore modes require either `--all` or an entity kind and IDs.
`efo show all` lists every collection in the current epoch. `show character`,
`show town`, `show event`, `show calamity`, and `show blocker` select one

View File

@ -23,6 +23,7 @@ pub mod repository_format;
pub mod stats;
pub mod transaction;
pub mod utils;
pub mod workspace;
// use std::io::Result as IoResult;

269
lib_efo/src/workspace.rs Normal file
View File

@ -0,0 +1,269 @@
//! Format-2 HEAD, index, and worktree access.
use std::{
fs,
path::{Path, PathBuf},
};
use serde::Serialize;
use crate::{
entity::EntityIdentifier,
epoch::EpochInfo,
repository_format::{
DetectedManifest, FormatError, RepositoryManifest, RepositorySnapshot, detect_manifest,
},
stats::EntityType,
transaction::{TransactionError, replace_file},
};
/// A validated format-2 repository and its three state layers.
#[derive(Debug, Clone)]
pub struct Workspace {
/// Canonical repository root.
root: PathBuf,
/// Current repository manifest.
pub manifest: RepositoryManifest,
/// Immutable HEAD world.
pub head: EpochInfo,
/// Staged complete snapshot.
pub index: RepositorySnapshot,
/// Editable complete snapshot.
pub worktree: RepositorySnapshot,
}
/// Failures while accessing format-2 state.
#[derive(Debug, thiserror::Error)]
pub enum WorkspaceError {
/// Filesystem access failed.
#[error("cannot access repository state `{path}`: {source}")]
Io {
/// Affected path.
path: PathBuf,
/// Underlying error.
#[source]
source: std::io::Error,
},
/// Stored JSON is malformed.
#[error("invalid repository state `{path}`: {source}")]
Json {
/// Affected path.
path: PathBuf,
/// Decode error.
#[source]
source: serde_json::Error,
},
/// Manifest detection failed.
#[error(transparent)]
Format(#[from] FormatError),
/// A legacy repository needs migration.
#[error("repository uses format 1; run `efo migrate --to 2` first")]
Legacy,
/// State layers do not belong together.
#[error("repository state is inconsistent: {0}")]
Inconsistent(String),
/// A requested entity selector did not resolve safely.
#[error("entity selector `{0}` did not match exactly one entity")]
Selector(String),
/// Transaction safety rejected the write.
#[error(transparent)]
Transaction(#[from] TransactionError),
}
impl Workspace {
/// Open and cross-check a format-2 repository.
pub fn open(root: &Path) -> Result<Self, WorkspaceError> {
let root = root.canonicalize().map_err(|source| io(root, source))?;
let manifest_path = root.join(".epoch");
let manifest = match detect_manifest(&read(&manifest_path)?)? {
DetectedManifest::Legacy(_) => return Err(WorkspaceError::Legacy),
DetectedManifest::Current(manifest) => manifest,
};
let head_path = root.join(format!("epoch/{}/epochinfo.json", manifest.epoch_id));
let head: EpochInfo = decode(&head_path)?;
let index_path = root.join(".efo/index.json");
let worktree_path = root.join(".efo/worktree.json");
let index: RepositorySnapshot = decode(&index_path)?;
let worktree: RepositorySnapshot = decode(&worktree_path)?;
for (name, snapshot) in [("index", &index), ("worktree", &worktree)] {
if snapshot.repository_id != manifest.repository_id {
return Err(WorkspaceError::Inconsistent(format!(
"{name} belongs to another repository"
)));
}
if snapshot.base_epoch_id != manifest.epoch_id {
return Err(WorkspaceError::Inconsistent(format!(
"{name} is based on epoch {}, but HEAD is {}",
snapshot.base_epoch_id, manifest.epoch_id
)));
}
}
if head.epoch_id != manifest.epoch_id {
return Err(WorkspaceError::Inconsistent(
"HEAD snapshot ID does not match manifest".into(),
));
}
Ok(Self {
root,
manifest,
head,
index,
worktree,
})
}
/// Whether index differs from immutable HEAD.
pub fn has_staged_changes(&self) -> bool {
!same(&self.head, &self.index.world)
}
/// Whether worktree differs from index.
pub fn has_unstaged_changes(&self) -> bool {
!same(&self.index.world, &self.worktree.world)
}
/// Copy the complete worktree into the index.
pub fn stage_all(&mut self) -> Result<(), WorkspaceError> {
self.index.world = self.worktree.world.clone();
self.save_index("stage --all")
}
/// Copy selected entities from worktree into index, including deletions.
pub fn stage_entities(
&mut self,
kind: EntityType,
selectors: &[EntityIdentifier],
) -> Result<(), WorkspaceError> {
copy_entities(&self.worktree.world, &mut self.index.world, kind, selectors)?;
self.save_index("stage entities")
}
/// Restore the complete index from HEAD.
pub fn restore_index(&mut self) -> Result<(), WorkspaceError> {
self.index.world = self.head.clone();
self.save_index("restore --staged --all")
}
/// Restore the complete worktree from the index.
pub fn restore_worktree(&mut self) -> Result<(), WorkspaceError> {
self.worktree.world = self.index.world.clone();
self.save_worktree("restore --worktree --all")
}
/// Restore selected index entities from HEAD.
pub fn restore_index_entities(
&mut self,
kind: EntityType,
selectors: &[EntityIdentifier],
) -> Result<(), WorkspaceError> {
copy_entities(&self.head, &mut self.index.world, kind, selectors)?;
self.save_index("restore --staged")
}
/// Restore selected worktree entities from index.
pub fn restore_worktree_entities(
&mut self,
kind: EntityType,
selectors: &[EntityIdentifier],
) -> Result<(), WorkspaceError> {
copy_entities(&self.index.world, &mut self.worktree.world, kind, selectors)?;
self.save_worktree("restore --worktree")
}
/// Persist a caller-modified worktree through the transaction layer.
pub fn save_worktree(&self, command: &str) -> Result<(), WorkspaceError> {
save(&self.root, ".efo/worktree.json", &self.worktree, command)
}
/// Persist a caller-modified index through the transaction layer.
pub fn save_index(&self, command: &str) -> Result<(), WorkspaceError> {
save(&self.root, ".efo/index.json", &self.index, command)
}
}
/// Copy selected collection entries with delete semantics.
fn copy_entities(
source: &EpochInfo,
destination: &mut EpochInfo,
kind: EntityType,
selectors: &[EntityIdentifier],
) -> Result<(), WorkspaceError> {
for selector in selectors {
let source_matches = matches(source.vec_entities(&kind), selector);
let destination_matches = matches(destination.vec_entities(&kind), selector);
let identity = match (source_matches.as_slice(), destination_matches.as_slice()) {
([entity], _) => entity.id,
([], [entity]) => entity.id,
_ => return Err(WorkspaceError::Selector(selector.to_string())),
};
let replacement = source
.vec_entities(&kind)
.iter()
.find(|entity| entity.id == identity)
.cloned();
let target = destination.vec_entities_mut(&kind);
target.retain(|entity| entity.id != identity);
if let Some(entity) = replacement {
target.push(entity);
}
}
Ok(())
}
/// Find collection entries matching the public CLI identifier rules.
fn matches<'a>(
entities: &'a [crate::entity::Entity],
selector: &EntityIdentifier,
) -> Vec<&'a crate::entity::Entity> {
entities
.iter()
.filter(|entity| match selector {
EntityIdentifier::Name(name) => {
entity.name.to_lowercase().starts_with(&name.to_lowercase())
}
EntityIdentifier::Id(id) => entity.id.to_string().starts_with(id),
})
.collect()
}
/// Compare serializable worlds exactly.
fn same(left: &EpochInfo, right: &EpochInfo) -> bool {
serde_json::to_value(left).ok() == serde_json::to_value(right).ok()
}
/// Decode one repository JSON file.
fn decode<T: serde::de::DeserializeOwned>(path: &Path) -> Result<T, WorkspaceError> {
serde_json::from_slice(&read(path)?).map_err(|source| WorkspaceError::Json {
path: path.to_path_buf(),
source,
})
}
/// Read one repository file with path-aware diagnostics.
fn read(path: &Path) -> Result<Vec<u8>, WorkspaceError> {
fs::read(path).map_err(|source| io(path, source))
}
/// Serialize and transactionally replace one state layer.
fn save<T: Serialize>(
root: &Path,
relative: &str,
value: &T,
command: &str,
) -> Result<(), WorkspaceError> {
let path = root.join(relative);
let bytes = serde_json::to_vec_pretty(value).map_err(|source| WorkspaceError::Json {
path: path.clone(),
source,
})?;
replace_file(root, &path, &bytes, command)?;
Ok(())
}
/// Attach the attempted path to an I/O error.
fn io(path: &Path, source: std::io::Error) -> WorkspaceError {
WorkspaceError::Io {
path: path.to_path_buf(),
source,
}
}

View File

@ -0,0 +1,73 @@
use std::{collections::BTreeMap, fs};
use lib_efo::{
entity::{Entity, EntityIdentifier},
epoch::{EpochId, EpochInfo},
migration::{execute_migration, plan_migration},
repository_format::LegacyManifest,
stats::EntityType,
workspace::Workspace,
};
fn migrated_repository() -> tempfile::TempDir {
let directory = tempfile::tempdir().expect("temporary repository");
let epoch_directory = directory.path().join("epoch/0");
fs::create_dir_all(&epoch_directory).expect("epoch directory");
let manifest = LegacyManifest {
epoch_id: EpochId::new(0),
version: "fixture".into(),
tags: BTreeMap::new(),
};
fs::write(
directory.path().join(".epoch"),
serde_json::to_vec_pretty(&manifest).expect("manifest JSON"),
)
.expect("manifest");
fs::write(
epoch_directory.join("epochinfo.json"),
serde_json::to_vec_pretty(&EpochInfo::default()).expect("epoch JSON"),
)
.expect("epoch");
let plan = plan_migration(directory.path()).expect("migration plan");
execute_migration(&plan).expect("migration");
directory
}
#[test]
fn all_layers_begin_clean_and_complete() {
let directory = migrated_repository();
let workspace = Workspace::open(directory.path()).expect("workspace");
assert!(!workspace.has_staged_changes());
assert!(!workspace.has_unstaged_changes());
assert_eq!(workspace.head.epoch_id, EpochId::new(0));
}
#[test]
fn entity_staging_and_both_restore_directions_are_isolated() {
let directory = migrated_repository();
let mut workspace = Workspace::open(directory.path()).expect("workspace");
let mut aria = Entity::default();
aria.name = "Aria".into();
aria.entity_type = EntityType::Character;
workspace.worktree.world.characters.push(aria);
workspace.save_worktree("test edit").expect("save worktree");
let mut workspace = Workspace::open(directory.path()).expect("changed workspace");
assert!(workspace.has_unstaged_changes());
assert!(!workspace.has_staged_changes());
workspace
.stage_entities(
EntityType::Character,
&[EntityIdentifier::Name("Aria".into())],
)
.expect("stage Aria");
assert!(workspace.has_staged_changes());
assert!(!workspace.has_unstaged_changes());
workspace.restore_index().expect("unstage all");
assert!(!workspace.has_staged_changes());
assert!(workspace.has_unstaged_changes());
workspace.restore_worktree().expect("discard worktree");
assert!(!workspace.has_unstaged_changes());
assert!(workspace.worktree.world.characters.is_empty());
}