From 8138a2c5b6c1c0505b52c59e1164a5008ec943c1 Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 14:37:58 +0100 Subject: [PATCH] feat(workspace): finish a working-copy move a crash cut short A command that moves the working copy checks out its files, then points `workspace` at the new revision. A crash or a power loss in between left the files half checked out, with nothing to say what they were moving from or to. A move that changes files now first publishes `.origin/moving`, durably, naming the files it starts from, those it goes to, and their revision. It removes the marker, durably too, once `workspace` points at the revision. The next command to open the workspace finishes the move, or takes it back if its revision wasn't written. It only touches the files that are still on one side of the move, by content, so edits and new files made since stay, in the draft the command's snapshot finds. A refused checkout takes its files back as a move of its own, publishing the marker again first, so a crash then finishes taking them back, not the refused move. A marker that can't be parsed, or a move that can't be finished, such as one whose blob can't be read, leaves the files as they are rather than fail every command; restoring reads every blob before it changes any file. A marker that can't be read at all is kept and reported, and the working copy doesn't move until it's removed. --- apps/origin-src/src/oplog.rs | 24 +- apps/origin-src/src/workspace/mod.rs | 236 ++++++++++++++++-- apps/origin-src/src/workspace/registry.rs | 1 + apps/origin-src/src/worktree.rs | 30 ++- apps/origin-src/tests/cli.rs | 280 +++++++++++++++++++++- 5 files changed, 548 insertions(+), 23 deletions(-) diff --git a/apps/origin-src/src/oplog.rs b/apps/origin-src/src/oplog.rs index d2ea1ca2..a6b5cd91 100644 --- a/apps/origin-src/src/oplog.rs +++ b/apps/origin-src/src/oplog.rs @@ -49,10 +49,12 @@ //! some of a batch's records were published, or none; an acceptance was //! written but the target's head didn't move to it (the next landing on the //! target publishes it, and logs the acceptance again); a waiting landing -//! wasn't kept; a working copy didn't move. Its writer's lock file is then -//! left behind, unlocked: readers sync the segments holding its entries, -//! which may not be durable, remove the file, and take the entries' effects -//! as what they find published. So a crashed writer holds nothing back. +//! wasn't kept; a working copy didn't move (see +//! [`workspace`](crate::workspace) for how a move cut short is finished). +//! Its writer's lock file is then left behind, unlocked: readers sync the +//! segments holding its entries, which may not be durable, remove the file, +//! and take the entries' effects as what they find published. So a crashed +//! writer holds nothing back. //! //! **Damage.** A crash in the middle of an append leaves part of a frame at //! the end of the last segment. It never was an entry: readers skip it, and @@ -245,6 +247,17 @@ pub enum Why { Undo(u64), } +impl Why { + /// Parses what [`Why`]'s `Display` writes. + pub(crate) fn parse(text: &str) -> Option { + Some(match text { + "draft" => Self::Draft, + "command" => Self::Command, + _ => Self::Undo(text.strip_prefix("undo ")?.parse().ok()?), + }) + } +} + impl fmt::Display for Why { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { @@ -1026,6 +1039,9 @@ mod tests { let payload = &frame[4..frame.len() - Frames::FRAMING + 4]; assert_eq!(Entry::decode(payload), Ok(entry)); } + for why in [Why::Draft, Why::Command, Why::Undo(12)] { + assert_eq!(Why::parse(&why.to_string()), Some(why)); + } } #[test] diff --git a/apps/origin-src/src/workspace/mod.rs b/apps/origin-src/src/workspace/mod.rs index f08427e0..ac3e8f1d 100644 --- a/apps/origin-src/src/workspace/mod.rs +++ b/apps/origin-src/src/workspace/mod.rs @@ -7,11 +7,12 @@ //! workspaces/ the other workspaces, see `registry` //! workspace the revision the working copy is //! state the stat cache of the last snapshot +//! moving the move in progress, if a checkout is //! ``` //! //! A repository can have several working copies, its workspaces, which -//! share its store and op log. The others have only `workspace` and -//! `state` in their `.origin`, and a `repository` file naming the main +//! share its store and op log. The others have only `workspace`, `state` +//! and `moving` in their `.origin`, and a `repository` file naming the main //! one's. //! //! The working copy is always on a revision of the current change. Every @@ -40,7 +41,27 @@ //! the others refuse to build on it. //! //! Every move of the working copy is logged in the op log, in an entry made -//! durable with the `workspace` file naming the new revision. +//! durable with the `workspace` file naming the new revision. A move that +//! changes the files first publishes `moving`, durably, naming the files it +//! starts from, those it goes to and their revision. It then checks the +//! files out and makes them durable, writes the revision if it's new, +//! points `workspace` at it, and removes `moving`, durably too. A crash, or +//! a power loss, can leave the files half checked out, with `moving` +//! behind, and the user may edit them before the next command to open the +//! workspace finishes the move. It only touches the files the move changes +//! that are still on one side of it, by content: it takes them to the +//! revision and points `workspace` at it, or back where they were if the +//! revision wasn't written. Every other file, edited or created since, +//! stays as it is, in the draft the command's snapshot finds. So does every +//! file with a `moving` it cannot finish, such as where a file would +//! replace a directory that holds what no snapshot tracks, or a blob it +//! needs cannot be read, or with one it cannot parse, which no move writes: +//! an error that lasts would fail every command otherwise. A `moving` it +//! cannot read at all is kept, and reported: the working copy doesn't move +//! until it's removed. Taking back a checkout that failed, such as one a +//! file edited since refused, is a move too, back to the working copy, +//! which publishes `moving` again first: a crash then finishes taking the +//! files back, not the move that failed. mod annotate; mod land; @@ -48,6 +69,7 @@ mod registry; pub use annotate::{Annotated, Payload}; +use std::fmt; use std::fs; use std::io; use std::path::{Path, PathBuf}; @@ -82,6 +104,9 @@ pub struct Workspace { /// The move recording the draft made, saved with the command's own /// records, which is logged with the command's own move. unlogged: Option, + /// The `moving` of a move a crash cut short, which couldn't be read: + /// the working copy doesn't move while it's there. + unreadable_move: Option, } /// The working copy as of a snapshot. @@ -120,6 +145,55 @@ enum Behind { Rebased(RevisionId), } +/// A move of the working copy in progress, as `moving` records it, so the +/// next command can finish it if a crash cuts it short. +#[derive(Debug, PartialEq, Eq)] +struct Moving { + /// The files the move found. + from: TreeId, + /// The files of `revision`. + to: TreeId, + /// Where the move goes, which is only written once its files are, if + /// it's new. + revision: RevisionId, + why: Why, +} + +impl Moving { + /// The move that takes this one back, to `revision`, the working copy. + fn back(&self, revision: RevisionId) -> Self { + Self { + from: self.to, + to: self.from, + revision, + why: self.why, + } + } + + /// Parses ` `, as written. + fn parse(bytes: &[u8]) -> Option { + let mut fields = str::from_utf8(bytes).ok()?.trim_end().splitn(4, ' '); + Some(Self { + from: fields.next()?.parse().ok()?, + to: fields.next()?.parse().ok()?, + revision: fields.next()?.parse().ok()?, + why: Why::parse(fields.next()?)?, + }) + } +} + +impl fmt::Display for Moving { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let Self { + from, + to, + revision, + why, + } = self; + writeln!(f, "{from} {to} {revision} {why}") + } +} + impl WorkingCopy { /// The change `prefix` names: `@` for the working copy's, or a unique /// prefix of its id. @@ -146,6 +220,10 @@ impl Workspace { /// one's, which holds the store. const REPOSITORY: &str = "repository"; + /// The file in [`Workspace::META_DIR`] recording the move of a checkout + /// in progress: see [`Moving`]. + const MOVING: &str = "moving"; + /// `origin init`: creates a repository in `root`, with the `policy` /// target naming this node the authority of `policy` and `main`, an /// empty `main`, and a first change on top of it. @@ -188,6 +266,7 @@ impl Workspace { config, revision: encoded.id().into(), unlogged: None, + unreadable_move: None, }; workspace.write(&[vec![empty_description], vec![encoded]])?; workspace.publish_pointer(None, workspace.revision, Why::Command)?; @@ -246,7 +325,7 @@ impl Workspace { /// Opens the working copy at `root`: the main one, whose `.origin` holds /// the store, or another workspace, whose `.origin/repository` names - /// the main one's. + /// the main one's. Finishes a move a crash cut short first. fn open(root: &Path, config: UserConfig, actor: &Actor) -> Result { let root = &Self::canonical(root)?; let meta = root.join(Self::META_DIR); @@ -261,14 +340,82 @@ impl Workspace { }; let revision = Self::read_pointer(root)?.ok_or_else(|| WorkspaceError::Incomplete(root.to_owned()))?; - Ok(Self { + let mut workspace = Self { root: root.to_owned(), store: Store::open_writable(store, Native::default())? .with_actor(actor.in_workspace(root)), config, revision, unlogged: None, - }) + unreadable_move: None, + }; + workspace.finish_move()?; + Ok(workspace) + } + + /// Finishes the move `moving` records, if a crash cut it short, as the + /// module explains: takes the files still as the move found them to + /// where it went, and points the working copy there, if the move's + /// revision was written, or else takes the files it changed back. Files + /// on neither side, edited since, stay as they are. So does every file, + /// with a `moving` it cannot parse, or that it fails to finish. One it + /// cannot read is kept, and reported. + fn finish_move(&mut self) -> Result<(), WorkspaceError> { + let path = self.meta(Self::MOVING); + let moving = match fs::read(&path) { + Ok(moving) => moving, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()), + Err(error) => { + // Kept, so no move replaces it, or is undone by it if it can + // be read later: the user decides what it was. + eprintln!( + "warning: cannot read {}, the marker of a move of the working copy a crash \ + cut short ({error}): its files stay as they are, and the working copy \ + doesn't move until it's removed", + path.display() + ); + self.unreadable_move = Some(path); + return Ok(()); + } + }; + let Some(moving) = Moving::parse(&moving) else { + self.moved()?; + println!( + "Found a move of the working copy a crash cut short: its files stay as they are" + ); + return Ok(()); + }; + let written = self.store.contains(moving.revision.into())?; + let (from, to) = if written { + (moving.from, moving.to) + } else { + (moving.to, moving.from) + }; + if let Err(error) = self.restore(from, to) { + self.moved()?; + println!( + "Cannot finish a move of the working copy a crash cut short, so its files stay as they are: {:#}", + anyhow::Error::from(error) + ); + return Ok(()); + } + if !written { + self.moved()?; + println!( + "Took back a move of the working copy a crash cut short, before its revision was written" + ); + return Ok(()); + } + if self.revision != moving.revision { + self.point_at(moving.revision, moving.why)?; + } + self.moved()?; + let revision = self.store.get(moving.revision)?; + println!( + "Finished moving the working copy to {}, which a crash cut short", + self.headline(&revision)? + ); + Ok(()) } /// The revision the working copy at `root` is, if it has one. @@ -337,6 +484,8 @@ impl Workspace { if working_copy.files == working_copy.revision.snapshot || working_copy.behind.is_some() { return Ok(working_copy); } + // The draft is a move of the working copy, before anything is written. + self.may_move()?; let revision = Revision { predecessors: vec![working_copy.id], snapshot: working_copy.files, @@ -517,6 +666,9 @@ impl Workspace { why: Why, index: &mut Index, ) -> Result<(), WorkspaceError> { + // Before the revision exists, or it would be a head of its change + // the working copy isn't. + self.may_move()?; self.write(layers)?; index.add(layers.iter().flatten())?; self.point_at(revision, why)?; @@ -538,6 +690,15 @@ impl Workspace { self.publish_pointer(Some(self.revision), revision, why) } + /// Refuses to move the working copy while a `moving` that couldn't be + /// read is there. + fn may_move(&self) -> Result<(), WorkspaceError> { + match &self.unreadable_move { + Some(marker) => Err(WorkspaceError::UnreadableMove(marker.clone())), + None => Ok(()), + } + } + /// Durably records that the working copy moved from `from`, or was /// created, to `to`, with the op log entry saying so, after the move of /// a snapshot the command saved: the entries are durable with @@ -548,6 +709,7 @@ impl Workspace { to: RevisionId, why: Why, ) -> Result<(), WorkspaceError> { + self.may_move()?; // The draft's move stays to log until this commit logs it. let mut moves: Vec<_> = self.unlogged.into_iter().collect(); moves.push(Move { from, to, why }); @@ -563,12 +725,14 @@ impl Workspace { } /// Moves the working copy, whose files `working_copy` found, to - /// `revision`, `to`: checks it out over them, then writes `unwritten`, - /// the layers that write it if it's new, and makes it the working copy. - /// A checkout that fails, such as one refused by a file edited since - /// the snapshot, writes nothing, and takes back the files it changed as - /// best it can, so the working copy and its change stay where they - /// were. + /// `revision`, `to`, as the module explains: checks it out over them, + /// then writes `unwritten`, the layers that write it if it's new, and + /// makes it the working copy. A crash before it's done leaves `moving` + /// behind, so the next command finishes the move, or takes it back if + /// the revision wasn't written. A checkout that fails, such as one + /// refused by a file edited since the snapshot, writes nothing, and + /// takes back the files it changed as best it can, as a move of its + /// own, so the working copy and its change stay where they were. fn switch_to( &mut self, working_copy: &WorkingCopy, @@ -577,18 +741,52 @@ impl Workspace { unwritten: &[Vec], why: Why, ) -> Result<(), WorkspaceError> { + // Before changing any file. + self.may_move()?; + // The files stay as they are: there's nothing to finish. + if revision.snapshot == working_copy.files { + self.write(unwritten)?; + return self.point_at(to, why); + } + let moving = Moving { + from: working_copy.files, + to: revision.snapshot, + revision: to, + why, + }; + self.publish_moving(&moving)?; let checkout = self.checkout( working_copy.files, revision.snapshot, Some(&working_copy.cache), ); if let Err(error) = checkout { - // Best effort: the checkout's error says what went wrong. - let _ = self.restore(revision.snapshot, working_copy.files); + // So a crash finishes taking the files back, not the move, whose + // revision may exist. Best effort: the checkout's error says + // what went wrong, and whichever move is left behind, the next + // command finishes. + let back = moving.back(working_copy.id); + let _ = self + .publish_moving(&back) + .and_then(|()| self.restore(back.from, back.to)) + .and_then(|()| self.moved()); return Err(error); } self.write(unwritten)?; - self.point_at(to, why) + self.point_at(to, why)?; + self.moved() + } + + /// Publishes `moving`, durably, before its move changes any file. + fn publish_moving(&self, moving: &Moving) -> Result<(), WorkspaceError> { + self.write_durably(self.meta(Self::MOVING), moving.to_string().as_bytes()) + } + + /// Removes `moving`, durably, once its move is done. + fn moved(&self) -> Result<(), WorkspaceError> { + let path = self.meta(Self::MOVING); + fs::remove_file(&path).map_err(|source| WorkspaceError::io(&path, source))?; + Ok(self.store.sync_dir(&self.root.join(Self::META_DIR))?) } /// Durably replaces a metadata file. @@ -1380,6 +1578,14 @@ pub enum WorkspaceError { /// The revision it names. revision: RevisionId, }, + /// A move would replace the marker of one a crash cut short, which no + /// command could read. + #[error( + "{} holds a move of the working copy a crash cut short, which cannot be read: \ + check the files, then remove it", + .0.display() + )] + UnreadableMove(PathBuf), /// `annotate --withdraw` found only a promotion of the user's /// statement, which they withdraw about the revision it's about. #[error( diff --git a/apps/origin-src/src/workspace/registry.rs b/apps/origin-src/src/workspace/registry.rs index 66c31980..d8a2d910 100644 --- a/apps/origin-src/src/workspace/registry.rs +++ b/apps/origin-src/src/workspace/registry.rs @@ -78,6 +78,7 @@ impl Workspace { config: self.config.clone(), revision: id, unlogged: None, + unreadable_move: None, }; let empty = Tree::default().encode().id().into(); workspace.checkout(empty, revision.snapshot, None)?; diff --git a/apps/origin-src/src/worktree.rs b/apps/origin-src/src/worktree.rs index b92149dd..3587c88f 100644 --- a/apps/origin-src/src/worktree.rs +++ b/apps/origin-src/src/worktree.rs @@ -557,7 +557,8 @@ impl<'a, P: Platform> Worktree<'a, P> { /// /// # Errors /// - /// Fails like [`Worktree::checkout`]. + /// Fails like [`Worktree::checkout`], and before changing any file if + /// the content of one it writes cannot be read. pub fn restore(&self, changes: &[FileChange]) -> Result<(), SnapshotError> { let cache = StatCache::default(); let seen = Self::par_map(changes, |change| { @@ -575,6 +576,13 @@ impl<'a, P: Platform> Worktree<'a, P> { if changes.is_empty() { return Ok(()); } + // Every content it writes can be read before anything changes, so + // a store that fails it leaves the files as they are. + Self::par_map(&changes, |change| { + change + .new + .map_or(Ok(()), |entry| Ok(self.store.read(entry.id).map(drop)?)) + })?; self.apply(&changes, Some(&seen), &[]) } @@ -1347,6 +1355,26 @@ mod tests { assert_eq!(fixture.snapshot(&StatCache::default()).0, dir); } + #[test] + fn restoring_reads_every_content_before_changing_a_file() { + let fixture = Fixture::new(); + fixture.write("removed", "old"); + let (old, _) = fixture.snapshot(&StatCache::default()); + fs::remove_file(fixture.dir.path().join("removed")).unwrap(); + fixture.write("lost", "content the store no longer has"); + let (new, _) = fixture.snapshot(&StatCache::default()); + let changes = fixture.store.diff(old, new).unwrap(); + let lost = EncodedObject::blob(b"content the store no longer has"); + fs::remove_file(fixture.store.path(lost.id())).unwrap(); + + // The files as the move found them: it fails before removing one. + fs::remove_file(fixture.dir.path().join("lost")).unwrap(); + fixture.write("removed", "old"); + assert!(fixture.worktree().restore(&changes).is_err()); + let removed = fs::read_to_string(fixture.dir.path().join("removed")); + assert_eq!(removed.unwrap(), "old", "untouched"); + } + #[test] fn restoring_keeps_files_edited_since() { let fixture = Fixture::new(); diff --git a/apps/origin-src/tests/cli.rs b/apps/origin-src/tests/cli.rs index c8165059..5b0fa69f 100644 --- a/apps/origin-src/tests/cli.rs +++ b/apps/origin-src/tests/cli.rs @@ -1,12 +1,15 @@ //! End-to-end tests of the change workflow and workspaces, driving the real //! `origin` binary. -use std::fs; +use std::fs::{self, OpenOptions}; use std::io::Write; use std::os::unix::fs::{MetadataExt, PermissionsExt}; -use std::path::Path; +use std::path::{Path, PathBuf}; use std::process::{Command, Output, Stdio}; use std::slice; +use std::sync::mpsc; +use std::thread; +use std::time::{Duration, Instant}; use origin_platform::Native; use origin_shared::{ @@ -47,6 +50,11 @@ impl Repo { self.command(cwd, args).output().unwrap() } + /// The revision the working copy is, in full. + fn revision(&self) -> String { + self.read(".origin/workspace").trim_end().to_owned() + } + /// Runs a command that must succeed, returning its output. fn ok(&self, args: &[&str]) -> String { self.ok_in(self.dir.path(), args) @@ -258,6 +266,7 @@ fn a_directory_holding_untracked_files_refuses_to_become_a_file() { // The files it removed are back, and the working copy stays. assert_eq!(repo.read("a/b"), "in a directory\n"); assert_eq!(repo.read("a/.git/HEAD"), "ref\n"); + assert!(!repo.path(".origin/moving").exists()); let status = repo.ok(&["status"]); assert!(status.contains(" Directory\n"), "{status}"); assert_eq!(fs::read_to_string(&pointer).unwrap(), revision); @@ -452,7 +461,7 @@ fn abandoning_the_current_change_restores_its_base() { /// The working copy's revision, in full. fn revision_of(repo: &Repo) -> RevisionId { - repo.read(".origin/workspace").trim().parse().unwrap() + repo.revision().parse().unwrap() } #[test] @@ -909,6 +918,49 @@ fn an_argument_that_is_not_utf8_is_no_panic() { assert!(stderr.starts_with("error: "), "{stderr}"); } +#[test] +fn a_move_marker_that_cannot_be_read_is_kept_and_stops_moves() { + let repo = Repo::new(); + repo.write("a", "a\n"); + repo.ok(&["describe", "First"]); + let first = repo.change(); + repo.ok(&["new", "Second"]); + let second = repo.change(); + repo.write("b", "b\n"); + // Recorded, so the refused `describe` below changes no file. + repo.ok(&["describe", "Second"]); + // A marker that can't be read, even as root. + let marker = repo.path(".origin/moving"); + fs::create_dir(&marker).unwrap(); + + let status = repo.run(repo.dir.path(), &["status"]); + let warning = String::from_utf8_lossy(&status.stderr); + assert!(status.status.success(), "{warning}"); + assert!(warning.starts_with("warning: cannot read "), "{warning}"); + assert!(marker.is_dir(), "kept"); + // Nor does it move without changing files. + let pointer = repo.read(".origin/workspace"); + let refused = repo.fails(&["describe", "Second, still"]); + assert!( + refused.contains("cannot be read: check the files"), + "{refused}" + ); + assert_eq!(repo.read(".origin/workspace"), pointer); + let refused = repo.fails(&["edit", &first]); + assert!( + refused.contains("cannot be read: check the files"), + "{refused}" + ); + assert_eq!(repo.read("b"), "b\n"); + fs::remove_dir(&marker).unwrap(); + // Nothing the refused commands made remains, to make the change diverge. + let evolog = repo.ok(&["evolog", &second]); + assert!(!evolog.contains("Second, still"), "{evolog}"); + repo.ok(&["describe", "Second, at last"]); + assert!(!repo.ok(&["status"]).contains("divergent")); + repo.ok(&["edit", &first]); +} + #[test] fn statements_are_promoted_where_their_inputs_are_unchanged() { let repo = Repo::new(); @@ -1655,3 +1707,225 @@ fn a_refused_pull_writes_nothing() { let status = repo.ok_in(&other, &["status"]); assert!(!status.contains("divergent"), "{status}"); } + +impl Repo { + /// The file the store keeps the object holding `content` in. + fn stored_object(&self, content: &[u8]) -> PathBuf { + let hex = origin_shared::EncodedObject::blob(content).id().to_hex(); + self.path(&format!( + ".origin/objects/loose/{}/{}", + &hex[..2], + &hex[2..] + )) + } + + /// Runs `origin ` in `cwd` until it reads the stored object + /// holding `content`, then once `ready`, kills it, as a crash would, + /// and stores the object again. + fn crash_reading(&self, cwd: &Path, content: &[u8], args: &[&str], ready: impl Fn() -> bool) { + let stored = self.stored_object(content); + let object = fs::read(&stored).unwrap(); + fs::remove_file(&stored).unwrap(); + let fifo = Command::new("mkfifo").arg(&stored).status().unwrap(); + assert!(fifo.success()); + let mut child = self + .command(cwd, args) + .stdout(Stdio::null()) + .spawn() + .unwrap(); + // Opening the pipe to write waits for the command to open it to + // read, which it then waits on, for as long as the pipe is open. + let (opened, open) = mpsc::channel(); + let pipe = stored.clone(); + thread::spawn(move || opened.send(OpenOptions::new().write(true).open(pipe))); + let deadline = Instant::now() + Duration::from_secs(20); + let _pipe = loop { + if let Ok(pipe) = open.recv_timeout(Duration::from_millis(20)) { + break pipe.unwrap(); + } + assert!(child.try_wait().unwrap().is_none(), "it never read it"); + assert!(Instant::now() < deadline, "it never read it in time"); + }; + while !ready() { + assert!(Instant::now() < deadline, "never ready"); + thread::sleep(Duration::from_millis(20)); + } + child.kill().unwrap(); + child.wait().unwrap(); + fs::remove_file(&stored).unwrap(); + fs::write(&stored, object).unwrap(); + fs::set_permissions(&stored, fs::Permissions::from_mode(0o444)).unwrap(); + } +} + +#[test] +fn a_move_cut_short_is_finished_without_losing_edits() { + let repo = Repo::new(); + repo.write("a", "a\n"); + repo.write("keep", "keep\n"); + repo.write("ro/b", "b\n"); + repo.ok(&["describe", "First"]); + let first = repo.change(); + let revision = repo.revision(); + repo.ok(&["new", "Second"]); + repo.write("a", "changed\n"); + fs::remove_file(repo.path("ro/b")).unwrap(); + + // `edit` back to the first change crashes after writing `a`. + repo.crash_reading(repo.dir.path(), b"b\n", &["edit", &first], || { + fs::read_to_string(repo.path("a")).is_ok_and(|a| a == "a\n") + }); + assert!(repo.path(".origin/moving").exists()); + // Edits made before the next command finishes the move. + repo.write("notes", "mine\n"); + repo.write("keep", "edited\n"); + + let status = repo.ok(&["status"]); + assert!( + status.starts_with("Finished moving the working copy to "), + "{status}" + ); + assert!( + status.contains("Working copy: ") && status.contains("A notes\n"), + "{status}" + ); + assert_eq!(repo.read("ro/b"), "b\n"); + assert_eq!(repo.read("keep"), "edited\n"); + assert_eq!(repo.read("notes"), "mine\n"); + assert!(!repo.path(".origin/moving").exists()); + // The edits are a draft on the move's revision. + assert_eq!(repo.revision(), revision); + let evolog = repo.ok(&["evolog", &first]); + assert!(evolog.contains(&revision[..12]), "{evolog}"); +} + +#[test] +fn a_move_cut_short_before_its_revision_is_written_is_taken_back() { + let repo = Repo::new(); + repo.write("own", "own\n"); + repo.ok(&["describe", "Feature"]); + let change = repo.change(); + let others = tempfile::tempdir().unwrap(); + let other = others.path().join("other"); + repo.workspace(&other, &["--change", &change]); + repo.ok(&["new", "--on", "main"]); + repo.write("upstream", "upstream\n"); + repo.write("ro/b", "b\n"); + assert!(repo.ok(&["land"]).contains(" on main #1\n")); + + // `pull` crashes as it writes `upstream`, before writing its merge. + // Main's copy would be cloned instead of read. + fs::remove_file(repo.path("upstream")).unwrap(); + let evolog = repo.ok_in(&other, &["evolog", &change]); + repo.crash_reading(&other, b"upstream\n", &["pull"], || { + fs::read_to_string(other.join("ro/b")).is_ok_and(|b| b == "b\n") + }); + assert!(other.join(".origin/moving").exists()); + fs::write(other.join("own"), "edited\n").unwrap(); + + let status = repo.ok_in(&other, &["status"]); + assert!(status.starts_with("Took back a move"), "{status}"); + assert!(!other.join("ro/b").exists()); + assert!(!other.join("upstream").exists()); + assert_eq!(fs::read_to_string(other.join("own")).unwrap(), "edited\n"); + assert!(!other.join(".origin/moving").exists()); + assert_eq!(repo.ok_in(&other, &["evolog", &change]), evolog); + let pulled = repo.ok_in(&other, &["pull"]); + assert!(pulled.contains("On top of: main #1\n"), "{pulled}"); +} + +#[test] +fn an_unreadable_move_marker_leaves_the_files() { + let repo = Repo::new(); + repo.write("a", "a\n"); + repo.ok(&["describe", "First"]); + let first = repo.revision(); + // A marker no move writes: where it went is unknown. + fs::write(repo.path(".origin/moving"), b"").unwrap(); + repo.write("a", "half checked out\n"); + let status = repo.ok(&["status"]); + assert!( + status.starts_with("Found a move of the working copy a crash cut short"), + "{status}" + ); + assert_eq!(repo.read("a"), "half checked out\n"); + assert_eq!(repo.revision(), first, "the draft has it"); + assert!(!repo.path(".origin/moving").exists()); + assert_eq!( + fs::read_dir(repo.path(".origin/oplog/writers")) + .unwrap() + .count(), + 0, + "every write is done, and durable" + ); +} + +/// Makes the stored object holding `content` unreadable, or readable +/// again. Writers skip it all the same: the store has it. +fn unreadable_object(repo: &Repo, content: &[u8], unreadable: bool) { + let stored = repo.stored_object(content); + let mode = if unreadable { 0o000 } else { 0o444 }; + fs::set_permissions(stored, fs::Permissions::from_mode(mode)).unwrap(); +} + +#[test] +fn a_refused_move_cut_short_is_taken_back() { + let repo = Repo::new(); + repo.write("a", "a file\n"); + repo.ok(&["describe", "File"]); + let file = repo.change(); + repo.ok(&["new", "Directory"]); + fs::remove_file(repo.path("a")).unwrap(); + repo.write("a/b", "in a directory\n"); + repo.write("only here", "only here\n"); + repo.ok(&["describe", "Directory"]); + let revision = repo.revision(); + repo.write("a/.git/HEAD", "ref\n"); + + // `edit` removes `only here`, then is refused at `a`, and taking it + // back stops before writing `only here` again. + unreadable_object(&repo, b"only here\n", true); + repo.fails(&["edit", &file]); + assert!(repo.path(".origin/moving").exists()); + unreadable_object(&repo, b"only here\n", false); + + // The next command finishes taking it back, not the refused move. + let status = repo.ok(&["status"]); + assert!(status.contains(" Directory\n"), "{status}"); + assert_eq!(repo.read("only here"), "only here\n"); + assert_eq!(repo.read("a/b"), "in a directory\n"); + assert_eq!(repo.revision(), revision); + assert!(!repo.path(".origin/moving").exists()); +} + +#[test] +fn a_move_that_cannot_be_finished_leaves_the_files() { + let repo = Repo::new(); + repo.write("a", "a\n"); + repo.write("ro/b", "b\n"); + repo.ok(&["describe", "First"]); + let first = repo.change(); + repo.ok(&["new", "Second"]); + repo.write("a", "changed\n"); + fs::remove_file(repo.path("ro/b")).unwrap(); + repo.ok(&["status"]); + + // `edit` crashes after writing `a`, and the content finishing it + // needs can't be read. + repo.crash_reading(repo.dir.path(), b"b\n", &["edit", &first], || { + fs::read_to_string(repo.path("a")).is_ok_and(|a| a == "a\n") + }); + assert!(repo.path(".origin/moving").exists()); + unreadable_object(&repo, b"b\n", true); + + // Every command would fail: the files stay as they are instead. + let status = repo.ok(&["status"]); + assert!( + status.starts_with("Cannot finish a move of the working copy a crash cut short"), + "{status}" + ); + assert!(status.contains(" Second\n"), "{status}"); + assert_eq!(repo.read("a"), "a\n"); + assert!(!repo.path(".origin/moving").exists()); + repo.ok(&["log"]); +}