diff --git a/crates/ide-workspace/src/file_moves.rs b/crates/ide-workspace/src/file_moves.rs index 49825af088..be3e5cf931 100644 --- a/crates/ide-workspace/src/file_moves.rs +++ b/crates/ide-workspace/src/file_moves.rs @@ -99,7 +99,9 @@ impl FileMoves { /// Applies `edit` (paths as before the move, as `workspace/willRenameFiles` /// returns them), then performs `moves`. Edited files are snapshotted in - /// Local History first. On failure everything done so far is rolled back. + /// Local History first. `apply_edit` must be transactional: on error it leaves none of + /// its own changes behind, so a rejected edit keeps external changes. A failed + /// file move rolls back the applied edits. /// Returns the id for [`undo`](Self::undo). pub fn perform( &self, @@ -134,11 +136,8 @@ impl FileMoves { } before.push(text); } - if !paths.is_empty() - && let Err(e) = apply_edit(edit) - { - restore(documents, &paths, &before); - return Err(e); + if !paths.is_empty() { + apply_edit(edit)?; } if let Err(e) = crate::file_ops::move_files(moves) { restore(documents, &paths, &before); @@ -305,6 +304,37 @@ mod tests { assert_eq!(fs::read_to_string(root.join("Use.java")).unwrap(), "Bar f; // edited\n"); } + #[test] + fn rejected_reference_edits_preserve_changes_after_the_snapshot() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + fs::write(root.join("source.ts"), "source\n").unwrap(); + fs::write(root.join("main.ts"), "old\n").unwrap(); + let docs = documents(); + let mut edit = WorkspaceEdit { + files: vec![FileEdit::Edit { + path: root.join("main.ts").into(), + version: None, + edits: vec![TextEdit { range: Range::new(Pos::new(0, 0), Pos::new(0, 3)), new_text: "updated".into() }], + }], + ..Default::default() + }; + docs.prepare_workspace_edit(&mut edit).unwrap(); + let apply_edit = |edit: &WorkspaceEdit| { + // An external writer lands after perform captured its rollback text. + fs::write(root.join("main.ts"), "external edit after snapshot\n").unwrap(); + docs.apply_file_move_edits(edit) + }; + let moves = FileMoves::new(); + let mv = vec![FileMove { from: root.join("source.ts").into(), to: root.join("renamed.ts").into() }]; + let error = moves.perform(&docs, None, &mv, &edit, "Move", &apply_edit).unwrap_err(); + assert_eq!(error.kind, ide_core::error::ErrorKind::OutOfSync); + assert_eq!(fs::read_to_string(root.join("main.ts")).unwrap(), "external edit after snapshot\n"); + assert_eq!(fs::read_to_string(root.join("source.ts")).unwrap(), "source\n"); + assert!(!root.join("renamed.ts").exists()); + assert_eq!(moves.last(), None); + } + #[test] fn moved_paths() { let mv = vec![FileMove { from: "/p/a".into(), to: "/p/b/a".into() }];