feat: clarify revert and add hard reset
This commit is contained in:
parent
8d0a1538a1
commit
c52bc49d05
|
|
@ -41,6 +41,11 @@ governance links, and active events is tracked under
|
|||
[`examples/ravenous-draan`](examples/ravenous-draan/README.md). Integration
|
||||
tests open it as a real repository and validate its map and world invariants.
|
||||
|
||||
**History semantics checkpoint: complete.** `revert` now defaults to a
|
||||
reviewable worktree inverse, `revert --commit` warns before adding history, and
|
||||
`reset --hard` provides a previewed, explicitly confirmed destructive rewind.
|
||||
Recoverable future pruning remains the recommended alternative.
|
||||
|
||||
## Phase 0 — audit and guardrails
|
||||
|
||||
- [x] Inventory workspace crates, commands, persistence files, CI, and tests.
|
||||
|
|
@ -128,8 +133,8 @@ tests open it as a real repository and validate its map and world invariants.
|
|||
recovery for interrupted writes.
|
||||
- [x] Implement worktree/index-aware `status`, `diff`, `stage`, and both restore
|
||||
directions without changing immutable epochs.
|
||||
- [x] Implement committed epochs, `log`, conflict-safe `revert`, and backed-up
|
||||
`prune-future`; retire the destructive `reset` spelling through deprecation.
|
||||
- [x] Implement committed epochs, `log`, reviewable and conflict-safe `revert`,
|
||||
backed-up `prune-future`, and explicit previewed `reset --hard` destruction.
|
||||
- [x] Complete Phase 4 only after every ordinary mistake is reversible without
|
||||
manual JSON editing and both default and portable release gates pass.
|
||||
|
||||
|
|
|
|||
|
|
@ -72,7 +72,7 @@ Run `efo --help`, `efo <command> --help`, or see the
|
|||
| Area | Available now | Not available yet |
|
||||
|---|---|---|
|
||||
| Repository | Initialise format 1.0; inspect; lock and recover transactional writes | Future 1.x migration tooling; discovery from child directories; integrity repair |
|
||||
| Timeline | Commit, advance, switch, log, tag, summarise, diff, restore, revert, and backed-up future pruning | Branching and merging |
|
||||
| Timeline | Commit, advance, switch, log, tag, summarise, diff, reviewable/committed revert, backed-up pruning, and explicit hard reset | Branching and merging |
|
||||
| Entities | Add, edit, list, inspect, diff, and delete six built-in types | Custom types and custom fields; bulk operations |
|
||||
| Generation | Generate names and deterministic seeded events, settlements, regions, or worlds from embedded/override configuration | Roads, diffusion, and setting template packs |
|
||||
| Interfaces | Complete CLI; `efo-tui` browser and entity editor | TUI staging/commits; GUI/web (out of scope) |
|
||||
|
|
|
|||
|
|
@ -41,7 +41,7 @@ pub fn handle_cmd(cmd: &cli_epoch::EpochCmd) -> Result<(), AppError> {
|
|||
}
|
||||
cli_epoch::EpochCmd::Reset(_) => {
|
||||
return Err(EpochError::Unknown(
|
||||
"`epoch reset` is removed; use `efo prune-future` for a preview and recoverable backup"
|
||||
"`epoch reset` is removed; use recoverable `efo prune-future`, or explicit `efo reset --hard <epoch>` for permanent deletion"
|
||||
.into(),
|
||||
)
|
||||
.into());
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@
|
|||
//! * **`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.
|
||||
//! * **`reset`** - compatibility diagnostic for the removed spelling.
|
||||
//! * **`diff`** - show differences between two epochs.
|
||||
//! * **`tag`** - add a tag to the current epoch.
|
||||
//! * **`fsck`** - perform basic filesystem level maintenance.
|
||||
|
|
@ -77,10 +77,10 @@ pub struct Switch {
|
|||
#[derive(Args, Debug)]
|
||||
pub struct Next;
|
||||
|
||||
/// Deletes all future epochs after the current epoch.
|
||||
/// Reports the replacement commands for the removed spelling.
|
||||
#[derive(Args, Debug)]
|
||||
#[command(
|
||||
after_long_help = "REMOVED: use `efo prune-future` for preview, backup, and restoration."
|
||||
after_long_help = "REMOVED: use `efo prune-future` for recoverable removal, or `efo reset --hard <epoch>` for permanent deletion."
|
||||
)]
|
||||
pub struct Reset;
|
||||
|
||||
|
|
|
|||
|
|
@ -38,9 +38,31 @@ pub struct SwitchCmd {
|
|||
|
||||
/// Create a new commit that inverses one historical epoch.
|
||||
#[derive(Args, Debug)]
|
||||
#[command(
|
||||
after_long_help = "EXAMPLES:\n efo revert 4\n efo diff\n efo stage --all\n efo commit -m 'Revert epoch 4'\n efo revert 4 --commit\n\nThe default is reviewable and changes only the worktree. --commit creates a new epoch; it does not move HEAD backward."
|
||||
)]
|
||||
pub struct RevertCmd {
|
||||
/// Epoch ID or tag whose introduced changes should be inverted.
|
||||
target: EpochIdentifier,
|
||||
/// Immediately stage and commit the inverse instead of leaving it in the worktree.
|
||||
#[arg(long)]
|
||||
commit: bool,
|
||||
}
|
||||
|
||||
/// Options for permanently rewinding repository history.
|
||||
#[derive(Args, Debug)]
|
||||
#[command(
|
||||
after_long_help = "EXAMPLES:\n efo reset --hard 3\n efo reset --hard 3 --yes\n\nWithout --yes, this command is a read-only preview. For recoverable removal, use `efo switch 3` followed by `efo prune-future --yes`."
|
||||
)]
|
||||
pub struct ResetCmd {
|
||||
/// Required acknowledgement that worktree changes and newer commits will be destroyed.
|
||||
#[arg(long, required = true)]
|
||||
hard: bool,
|
||||
/// Epoch ID or tag to retain as the new HEAD.
|
||||
target: EpochIdentifier,
|
||||
/// Perform the reset after displaying its destructive scope.
|
||||
#[arg(long)]
|
||||
yes: bool,
|
||||
}
|
||||
|
||||
/// Preview, apply, or restore backed-up future-history pruning.
|
||||
|
|
@ -107,8 +129,46 @@ pub fn switch(command: &SwitchCmd) -> Result<(), AppError> {
|
|||
pub fn revert(command: &RevertCmd) -> Result<(), AppError> {
|
||||
let mut workspace = Workspace::open(Path::new("."))?;
|
||||
let target = resolve(&workspace, &command.target)?;
|
||||
let new_id = workspace.revert(target)?;
|
||||
println!("✓ Reverted epoch {target} in new epoch {new_id}.");
|
||||
if command.commit {
|
||||
println!("Warning: `revert --commit` creates a new epoch; it does not move HEAD backward.");
|
||||
let new_id = workspace.revert(target)?;
|
||||
println!("✓ Reverted epoch {target} in new epoch {new_id}.");
|
||||
} else {
|
||||
workspace.revert_to_worktree(target)?;
|
||||
println!("✓ Applied the inverse of epoch {target} to the worktree.");
|
||||
println!(
|
||||
" Review with `efo diff`, then stage and commit it—or undo with `efo restore --worktree --all`."
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Preview or perform an unrecoverable history reset.
|
||||
pub fn reset(command: &ResetCmd) -> Result<(), AppError> {
|
||||
debug_assert!(command.hard, "clap requires --hard");
|
||||
let mut workspace = Workspace::open(Path::new("."))?;
|
||||
let target = resolve(&workspace, &command.target)?;
|
||||
workspace.load_epoch(target)?;
|
||||
let removed = workspace.epochs_after(target)?;
|
||||
println!("Hard-reset preview: HEAD, index, and worktree → epoch {target}");
|
||||
println!("Uncommitted changes will be permanently discarded.");
|
||||
println!("Newer epochs to destroy: {}", removed.len());
|
||||
for id in &removed {
|
||||
println!(" epoch {id}");
|
||||
}
|
||||
if !command.yes {
|
||||
println!("Nothing changed. Run again with `--yes` to permanently destroy this state.");
|
||||
println!("Safer alternative: switch to the epoch, then use `efo prune-future --yes`.");
|
||||
return Ok(());
|
||||
}
|
||||
let removed = workspace.hard_reset(target)?;
|
||||
println!(
|
||||
"✓ Hard-reset to epoch {target}; destroyed {} newer epoch(s).",
|
||||
removed.len()
|
||||
);
|
||||
println!(
|
||||
" This operation has no Epoch Forge undo; recovery requires an external backup or Git."
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -32,7 +32,7 @@ use crate::{
|
|||
entity_generic::EntitySubCommands,
|
||||
epoch::cli_epoch::EpochCmd,
|
||||
generate::GenCmd,
|
||||
history::{CommitCmd, LogCmd, PruneFutureCmd, RevertCmd, SwitchCmd},
|
||||
history::{CommitCmd, LogCmd, PruneFutureCmd, ResetCmd, RevertCmd, SwitchCmd},
|
||||
init::InitCmd,
|
||||
safety::{LockCmd, RecoverCmd},
|
||||
show::ShowCmd,
|
||||
|
|
@ -90,8 +90,10 @@ enum TopLevelCmd {
|
|||
Log(LogCmd),
|
||||
/// Switch clean state to an existing epoch.
|
||||
Switch(SwitchCmd),
|
||||
/// Invert a historical change in a new commit.
|
||||
/// Apply the inverse of a historical change to the worktree.
|
||||
Revert(RevertCmd),
|
||||
/// Permanently move HEAD backward and destroy newer state.
|
||||
Reset(ResetCmd),
|
||||
/// Preview or safely back up future history; restore with `--restore`.
|
||||
PruneFuture(PruneFutureCmd),
|
||||
/// Gives a very simple status.
|
||||
|
|
@ -182,6 +184,7 @@ fn exec_dispatch(cli: Cli) -> Result<(), AppError> {
|
|||
TopLevelCmd::Log(cmd) => commands::history::log(&cmd),
|
||||
TopLevelCmd::Switch(cmd) => commands::history::switch(&cmd),
|
||||
TopLevelCmd::Revert(cmd) => commands::history::revert(&cmd),
|
||||
TopLevelCmd::Reset(cmd) => commands::history::reset(&cmd),
|
||||
TopLevelCmd::PruneFuture(cmd) => commands::history::prune_future(&cmd),
|
||||
TopLevelCmd::Epoch(cmd) => commands::epoch::handle_cmd(&cmd),
|
||||
TopLevelCmd::Show(cmd) => commands::show::handle_show_cmd(&cmd),
|
||||
|
|
|
|||
|
|
@ -201,6 +201,13 @@ fn native_staging_commit_restore_and_recovery_workflow() {
|
|||
let show = efo(&repo, &["show", "character"]);
|
||||
assert_success(&show);
|
||||
assert!(!stdout(&show).contains("Bryn"));
|
||||
let diff = efo(&repo, &["diff"]);
|
||||
assert_success(&diff);
|
||||
assert!(stdout(&diff).contains("- characters: Bryn"));
|
||||
assert_success(&efo(&repo, &["restore", "--worktree", "--all"]));
|
||||
let committed_revert = efo(&repo, &["revert", "1", "--commit"]);
|
||||
assert_success(&committed_revert);
|
||||
assert!(stdout(&committed_revert).contains("creates a new epoch"));
|
||||
assert_success(&efo(&repo, &["switch", "first"]));
|
||||
let preview = efo(&repo, &["prune-future"]);
|
||||
assert_success(&preview);
|
||||
|
|
@ -230,6 +237,42 @@ fn native_staging_commit_restore_and_recovery_workflow() {
|
|||
assert!(stdout(&recovery).contains("no recovery is needed"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hard_reset_previews_then_destroys_newer_history_and_dirty_state() {
|
||||
let repo = TestRepo::new();
|
||||
assert_success(&efo(&repo, &["init"]));
|
||||
assert_success(&efo(&repo, &["chr", "add", "Aria"]));
|
||||
assert_success(&efo(&repo, &["stage", "--all"]));
|
||||
assert_success(&efo(&repo, &["commit", "-m", "Add Aria"]));
|
||||
assert_success(&efo(&repo, &["chr", "add", "Bryn"]));
|
||||
assert_success(&efo(&repo, &["stage", "--all"]));
|
||||
assert_success(&efo(&repo, &["commit", "-m", "Add Bryn"]));
|
||||
assert_success(&efo(&repo, &["chr", "add", "Uncommitted Cora"]));
|
||||
|
||||
let preview = efo(&repo, &["reset", "--hard", "0"]);
|
||||
assert_success(&preview);
|
||||
assert!(stdout(&preview).contains("Newer epochs to destroy: 2"));
|
||||
assert!(stdout(&preview).contains("Nothing changed"));
|
||||
assert!(repo.path().join("epoch/2").is_dir());
|
||||
|
||||
let reset = efo(&repo, &["reset", "--hard", "0", "--yes"]);
|
||||
assert_success(&reset);
|
||||
assert!(stdout(&reset).contains("no Epoch Forge undo"));
|
||||
assert!(!repo.path().join("epoch/1").exists());
|
||||
assert!(!repo.path().join("epoch/2").exists());
|
||||
let show = efo(&repo, &["show", "character"]);
|
||||
assert_success(&show);
|
||||
assert!(!stdout(&show).contains("Aria"));
|
||||
assert!(!stdout(&show).contains("Bryn"));
|
||||
assert!(!stdout(&show).contains("Cora"));
|
||||
|
||||
let manifest: serde_json::Value =
|
||||
serde_json::from_slice(&fs::read(repo.path().join(".epoch")).expect("hard-reset manifest"))
|
||||
.expect("parse hard-reset manifest");
|
||||
assert_eq!(manifest["epoch_id"]["id"], 0);
|
||||
assert_eq!(manifest["next_epoch_id"]["id"], 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn init_force_preserves_unrelated_files_and_never_overwrites_a_repository() {
|
||||
let repo = TestRepo::new();
|
||||
|
|
|
|||
|
|
@ -25,7 +25,11 @@ parent directories. `efo <command> --help` is the authoritative syntax.
|
|||
- `efo epoch fsck` performs a read-only consistency check of epoch IDs, tags,
|
||||
and entity UUIDs. It does not repair damage.
|
||||
- `efo prune-future` previews later history; `--yes` moves it to a restorable
|
||||
backup. The destructive `efo epoch reset` spelling is removed.
|
||||
backup.
|
||||
- `efo reset --hard ID_OR_TAG` previews a destructive rewind. Add `--yes` to
|
||||
align HEAD, index, and worktree to the target and permanently delete every
|
||||
newer epoch. This has no built-in undo; prefer `switch` plus `prune-future`
|
||||
when recovery may be needed.
|
||||
|
||||
## Entities
|
||||
|
||||
|
|
@ -57,10 +61,15 @@ worktree. Both restore modes require either `--all` or an entity kind and IDs.
|
|||
epoch using a manifest-last transaction, and realigns all three layers.
|
||||
`efo log` shows the resulting parent-linked history newest first.
|
||||
`efo switch ID` requires clean state and changes all layers without reusing
|
||||
epoch IDs. `efo revert ID` applies that epoch's inverse and commits it; overlap
|
||||
with later changes aborts without mutation. `efo prune-future` previews future
|
||||
epochs, while `--yes` moves them into a backup. Restore using the exact command
|
||||
printed after pruning.
|
||||
epoch IDs. `efo revert ID` applies that epoch's inverse to the worktree for
|
||||
review; it can be undone with `restore --worktree --all`. `revert ID --commit`
|
||||
prints a warning and immediately creates the inverse commit. Overlap with later
|
||||
changes aborts without mutation. `efo prune-future` previews future epochs,
|
||||
while `--yes` moves them into a backup. Restore using the exact command printed
|
||||
after pruning. `efo reset --hard ID --yes` is the explicitly destructive
|
||||
alternative: it discards transient changes, removes newer epochs without a
|
||||
backup, removes tags that point to them, and restarts the epoch allocator after
|
||||
the retained target.
|
||||
|
||||
`efo epoch summary` and `efo epoch tag` edit worktree metadata;
|
||||
`stage --world` selects it. `efo epoch next` requires a clean worktree, includes
|
||||
|
|
|
|||
|
|
@ -1,43 +1,41 @@
|
|||
# Reversing changes
|
||||
|
||||
Epoch Forge edits the checked-out epoch immediately; there is no staging area
|
||||
yet. The reliable workflow is therefore to create a checkpoint before a risky
|
||||
session:
|
||||
Epoch Forge keeps committed HEAD, a staging index, and an editable worktree.
|
||||
Inspect each recovery operation before choosing the destructive one:
|
||||
|
||||
```bash
|
||||
efo status
|
||||
efo epoch next
|
||||
# Make edits in the new epoch.
|
||||
efo diff # worktree versus index
|
||||
efo diff --staged # index versus HEAD
|
||||
efo restore --worktree --all # discard only unstaged changes
|
||||
efo restore --staged --all # unstage everything
|
||||
```
|
||||
|
||||
The former state remains in the prior epoch. Inspect it without destroying the
|
||||
new work with `efo epoch switch <old-id-or-tag>`. Switch back if the changes are
|
||||
good. To abandon them, remain on the older epoch, make an external backup, then
|
||||
run `efo epoch reset`.
|
||||
|
||||
## Recovery matrix
|
||||
|
||||
| Mutation | Recovery before `epoch reset` | Recovery after destructive removal |
|
||||
| Mutation | Built-in recovery | After `reset --hard` |
|
||||
|---|---|---|
|
||||
| Entity `add`, `edit`, `del` | Switch to the checkpoint epoch | Restore `.epoch` and `epoch/` from Git/backup |
|
||||
| `epoch summary`, `epoch tag` | Switch to the checkpoint epoch | Restore from Git/backup |
|
||||
| `epoch next` | Switch to the prior epoch; the new epoch remains available | Not applicable |
|
||||
| `epoch switch` | Switch back to the previous ID/tag | Not applicable |
|
||||
| `epoch reset` | No built-in undo | Restore deleted epoch directories and `.epoch` from Git/backup |
|
||||
| `init` | Remove only the newly-created `.epoch` and `epoch/` after verifying their contents | Restore the containing directory from backup |
|
||||
| Unstaged entity or metadata edit | `restore --worktree` | Restore the complete repository from Git/backup |
|
||||
| Staged change | `restore --staged`, then optionally restore the worktree | Restore from Git/backup |
|
||||
| Commit or `epoch next` | `revert`, or switch to an older epoch | Restore from Git/backup if its epoch was destroyed |
|
||||
| `revert ID` | `restore --worktree --all` | Restore from Git/backup |
|
||||
| `revert ID --commit` | Revert the inverse commit | Restore from Git/backup |
|
||||
| `switch` | Switch back to the previous ID/tag | Not applicable |
|
||||
| `prune-future --yes` | Use the printed `prune-future --restore … --yes` command | Not applicable |
|
||||
| `reset --hard ID --yes` | None | Restore the complete repository from Git/backup |
|
||||
|
||||
Before `epoch reset`, preserve the complete repository—not only the current
|
||||
snapshot:
|
||||
Before a hard reset, preserve the complete repository—not only the current
|
||||
snapshot. Run the preview first:
|
||||
|
||||
```bash
|
||||
git add .epoch epoch/
|
||||
efo reset --hard <target>
|
||||
git add .epoch .efo/ epoch/
|
||||
git commit -m "checkpoint before abandoning future epochs"
|
||||
efo epoch reset
|
||||
efo reset --hard <target> --yes
|
||||
```
|
||||
|
||||
Never reconstruct UUIDs or tag maps manually when a known-good backup exists.
|
||||
`efo epoch fsck` is read-only and can identify damage, but deliberately does not
|
||||
guess repairs.
|
||||
|
||||
Native `restore`, `revert`, and pseudo-staging commands belong to the next
|
||||
repository-format milestone and are specified in the roadmap.
|
||||
For a recoverable history rewrite, use `efo switch <target>` followed by
|
||||
`efo prune-future --yes`; the latter prints the exact restoration command.
|
||||
|
|
|
|||
|
|
@ -35,9 +35,17 @@ epoch from the index and aligns all three layers. `efo restore` always names
|
|||
which layer it replaces. IDs are monotonic and never reused.
|
||||
|
||||
`efo switch` requires clean state and never deletes later history. `efo revert`
|
||||
creates a new inverse commit. `efo prune-future` previews later epochs and,
|
||||
with confirmation, moves them into a restorable backup rather than deleting
|
||||
them. The old destructive `epoch reset` behavior is not supported.
|
||||
places an inverse change in the worktree by default; `--commit` explicitly
|
||||
creates a new inverse commit and warns before doing so. `efo prune-future`
|
||||
previews later epochs and, with confirmation, moves them into a restorable
|
||||
backup rather than deleting them.
|
||||
|
||||
`efo reset --hard TARGET --yes` is the exceptional destructive path. It resets
|
||||
HEAD, index, and worktree, permanently deletes all newer epoch directories,
|
||||
removes tags that point to them, and permits their numeric IDs to be reused.
|
||||
There is deliberately no Epoch Forge undo. Run it without `--yes` first to see
|
||||
the exact scope, and keep important repositories under external version
|
||||
control or backup.
|
||||
|
||||
## Transaction safety and recovery
|
||||
|
||||
|
|
|
|||
|
|
@ -73,13 +73,17 @@ reinforce meaning, but never carry meaning alone.
|
|||
resets both transient snapshots to the selected commit. `--force` is not a
|
||||
shortcut; users must explicitly restore or commit first.
|
||||
- `efo revert <epoch>` computes the inverse of that epoch relative to its
|
||||
predecessor and applies it to the current index. It then creates a new commit
|
||||
after confirmation. It never deletes history. Conflicts abort without
|
||||
predecessor and applies it to the current worktree for review. `--commit`
|
||||
explicitly stages and commits that inverse, after warning that HEAD is not
|
||||
being moved backward. It never deletes history. Conflicts abort without
|
||||
changing any layer and list affected fields.
|
||||
- The destructive historical `reset` operation is renamed `prune-future`.
|
||||
`reset` remains a deprecated alias for one release. Pruning always shows a
|
||||
dry-run, requires confirmation unless `--yes` is supplied, never rewinds the
|
||||
ID allocator, and leaves a migration-style backup that can be restored.
|
||||
- `efo prune-future` is the recoverable history-removal operation. It always
|
||||
shows a dry-run, requires `--yes`, never rewinds the ID allocator, and leaves
|
||||
a backup that can be restored.
|
||||
- `efo reset --hard <epoch>` is a separate, deliberately destructive escape
|
||||
hatch modelled after Git. It previews by default and requires `--yes` to
|
||||
discard transient state, move HEAD, delete newer epochs and their tags, and
|
||||
rewind the allocator. Recovery requires Git or another external backup.
|
||||
|
||||
Mutating commands refuse to proceed with an invalid layer. Errors state what
|
||||
happened, what was left unchanged, and the safest recovery command.
|
||||
|
|
|
|||
|
|
@ -132,13 +132,17 @@ pub enum EpochError {
|
|||
EpochFolderMissing(EpochId, PathBuf),
|
||||
|
||||
/// A future epoch exists, so computing `next` would overwrite history.
|
||||
#[diagnostic(help("Use epoch reset if you want to erase all future epochs first"))]
|
||||
#[diagnostic(help(
|
||||
"Use `efo prune-future` for recoverable removal or `efo reset --hard` for permanent deletion"
|
||||
))]
|
||||
#[error("Cannot compute `next` because future epoch exists")]
|
||||
#[diagnostic(code(EpochError::FutureEpochExist))]
|
||||
FutureEpochExist,
|
||||
|
||||
/// A specific epoch already exists, preventing the requested operation.
|
||||
#[diagnostic(help("Use epoch reset or manually delete the epoch {0}"))]
|
||||
#[diagnostic(help(
|
||||
"Use `efo prune-future` for recoverable removal; do not manually edit epoch directories"
|
||||
))]
|
||||
#[error("Epoch {0} already exists, so the operation was not performed")]
|
||||
#[diagnostic(code(EpochError::EpochAlreadyExists))]
|
||||
EpochAlreadyExists(EpochId),
|
||||
|
|
|
|||
|
|
@ -456,6 +456,61 @@ impl Workspace {
|
|||
&mut self,
|
||||
target: crate::epoch::EpochId,
|
||||
) -> Result<crate::epoch::EpochId, WorkspaceError> {
|
||||
self.apply_revert(target)?;
|
||||
self.index.world = self.worktree.world.clone();
|
||||
self.commit(format!("Revert epoch {target}"))
|
||||
}
|
||||
|
||||
/// Invert one historical epoch into the worktree without staging or committing it.
|
||||
pub fn revert_to_worktree(
|
||||
&mut self,
|
||||
target: crate::epoch::EpochId,
|
||||
) -> Result<(), WorkspaceError> {
|
||||
self.apply_revert(target)?;
|
||||
self.save_worktree("revert historical change")
|
||||
}
|
||||
|
||||
/// Permanently move all state to `target` and delete every newer epoch.
|
||||
pub fn hard_reset(
|
||||
&mut self,
|
||||
target: crate::epoch::EpochId,
|
||||
) -> Result<Vec<crate::epoch::EpochId>, WorkspaceError> {
|
||||
let world = self.load_epoch(target)?;
|
||||
let removed = self
|
||||
.all_epoch_ids()?
|
||||
.into_iter()
|
||||
.filter(|id| *id > target)
|
||||
.collect::<Vec<_>>();
|
||||
let mut manifest = self.manifest.clone();
|
||||
manifest.epoch_id = target;
|
||||
manifest.next_epoch_id = crate::epoch::EpochId::new(target.id + 1);
|
||||
manifest.tags.retain(|_, id| *id <= target);
|
||||
let snapshot = RepositorySnapshot::new(manifest.repository_id, target, world.clone());
|
||||
let replacements = [
|
||||
(
|
||||
self.root.join(".efo/index.json"),
|
||||
encode(&snapshot, "index")?,
|
||||
),
|
||||
(
|
||||
self.root.join(".efo/worktree.json"),
|
||||
encode(&snapshot, "worktree")?,
|
||||
),
|
||||
(self.root.join(".epoch"), encode(&manifest, "manifest")?),
|
||||
];
|
||||
replace_files(&self.root, &replacements, "hard reset")?;
|
||||
for id in &removed {
|
||||
let path = self.root.join("epoch").join(id.to_string());
|
||||
fs::remove_dir_all(&path).map_err(|source| io(&path, source))?;
|
||||
}
|
||||
self.manifest = manifest;
|
||||
self.head = world;
|
||||
self.index = snapshot.clone();
|
||||
self.worktree = snapshot;
|
||||
Ok(removed)
|
||||
}
|
||||
|
||||
/// Calculate an inverse historical change in the worktree.
|
||||
fn apply_revert(&mut self, target: crate::epoch::EpochId) -> Result<(), WorkspaceError> {
|
||||
if self.has_staged_changes() || self.has_unstaged_changes() {
|
||||
return Err(WorkspaceError::Dirty);
|
||||
}
|
||||
|
|
@ -470,9 +525,8 @@ impl Workspace {
|
|||
result.epoch_id = self.manifest.epoch_id;
|
||||
result.parent_epoch = self.head.parent_epoch;
|
||||
result.commit_message = self.head.commit_message.clone();
|
||||
self.index.world = result.clone();
|
||||
self.worktree.world = result;
|
||||
self.commit(format!("Revert epoch {target}"))
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Advance entity time in the index and commit it with any staged changes.
|
||||
|
|
@ -496,6 +550,23 @@ impl Workspace {
|
|||
|
||||
/// List snapshots numerically newer than current HEAD.
|
||||
pub fn future_epochs(&self) -> Result<Vec<crate::epoch::EpochId>, WorkspaceError> {
|
||||
self.epochs_after(self.manifest.epoch_id)
|
||||
}
|
||||
|
||||
/// List committed epoch directories newer than `target`.
|
||||
pub fn epochs_after(
|
||||
&self,
|
||||
target: crate::epoch::EpochId,
|
||||
) -> Result<Vec<crate::epoch::EpochId>, WorkspaceError> {
|
||||
Ok(self
|
||||
.all_epoch_ids()?
|
||||
.into_iter()
|
||||
.filter(|id| *id > target)
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// List every numeric epoch directory.
|
||||
fn all_epoch_ids(&self) -> Result<Vec<crate::epoch::EpochId>, WorkspaceError> {
|
||||
let mut ids = Vec::new();
|
||||
for entry in fs::read_dir(self.root.join("epoch"))
|
||||
.map_err(|source| io(&self.root.join("epoch"), source))?
|
||||
|
|
@ -509,7 +580,6 @@ impl Workspace {
|
|||
.file_name()
|
||||
.to_string_lossy()
|
||||
.parse::<crate::epoch::EpochId>()
|
||||
&& id > self.manifest.epoch_id
|
||||
{
|
||||
ids.push(id);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -151,3 +151,43 @@ fn revert_aborts_when_later_edits_overlap_the_target_change() {
|
|||
assert_eq!(workspace.manifest.epoch_id, EpochId::new(2));
|
||||
assert!(!directory.path().join("epoch/3").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revert_to_worktree_is_reviewable_and_restorable() {
|
||||
let directory = repository();
|
||||
let mut workspace = Workspace::open(directory.path()).expect("workspace");
|
||||
let mut aria = Entity::default();
|
||||
aria.id = uuid::Uuid::from_u128(1);
|
||||
aria.name = "Aria".into();
|
||||
aria.entity_type = EntityType::Character;
|
||||
workspace.worktree.world.characters.push(aria);
|
||||
workspace.stage_all().expect("stage Aria");
|
||||
workspace.commit("Add Aria".into()).expect("commit Aria");
|
||||
|
||||
workspace
|
||||
.revert_to_worktree(EpochId::new(1))
|
||||
.expect("apply inverse");
|
||||
assert!(workspace.worktree.world.characters.is_empty());
|
||||
assert!(workspace.has_unstaged_changes());
|
||||
assert!(!workspace.has_staged_changes());
|
||||
workspace.restore_worktree().expect("restore inverse");
|
||||
assert_eq!(workspace.worktree.world.characters.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hard_reset_discards_transient_state_and_newer_epochs() {
|
||||
let directory = repository();
|
||||
let mut workspace = Workspace::open(directory.path()).expect("workspace");
|
||||
workspace.worktree.world.summary = "committed".into();
|
||||
workspace.stage_all().expect("stage summary");
|
||||
workspace.commit("First".into()).expect("first commit");
|
||||
workspace.worktree.world.summary = "dirty".into();
|
||||
|
||||
let removed = workspace.hard_reset(EpochId::new(0)).expect("hard reset");
|
||||
|
||||
assert_eq!(removed, vec![EpochId::new(1)]);
|
||||
assert_eq!(workspace.manifest.epoch_id, EpochId::new(0));
|
||||
assert_eq!(workspace.manifest.next_epoch_id, EpochId::new(1));
|
||||
assert!(workspace.worktree.world.summary.is_empty());
|
||||
assert!(!directory.path().join("epoch/1").exists());
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue