дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-29 05:52:23 +02:00
fix(workspace): don't let refactoring undo overwrite an external write under an unsaved buffer
Fingerprints hash an unsaved buffer in place of its file, so a file another program wrote after a refactoring went unnoticed while its buffer had unsaved changes, and undo (or redo) wrote the snapshot over it. Each document now counts the disk conflicts it has seen (external writes while the buffer had unsaved changes). The undo record keeps the counts as of the refactoring; undo and redo first check unsaved buffers' files for a write the watcher hasn't reported yet, then refuse when a count moved. The IDE's own saves don't count, so saving and undoing typing before undoing the refactoring still works, and a conflict from before the refactoring doesn't block it. Fixes #6264
Цей коміт міститься в:
1 джерело
a88073d6fb
коміт
b241f72505
3 files changed
+147
-21
No files matched your search
@@ -174,6 +174,9 @@ struct DocState {
|
||||
/// The file changed on disk while this buffer had unsaved changes; autosave leaves it
|
||||
/// alone until the user saves explicitly or the buffer is reloaded.
|
||||
disk_conflict: bool,
|
||||
/// External changes seen while the buffer had unsaved changes (each `disk_conflict`), so an
|
||||
/// undo of a refactoring can tell a write by another program from the IDE's own saves.
|
||||
external_writes: u64,
|
||||
/// Text as of that disk state: an edit that returns to it (undo) leaves the document clean.
|
||||
/// `None` for large files (no second copy), virtual documents, and once a pending encoding,
|
||||
/// line-ending or BOM change makes the buffer differ from the file whatever the text.
|
||||
@@ -540,6 +543,7 @@ impl Documents {
|
||||
disk_mtime: loaded.mtime_ms,
|
||||
disk_len: disk_len(path),
|
||||
disk_conflict: false,
|
||||
external_writes: 0,
|
||||
clean_text: None,
|
||||
closed: false,
|
||||
uri: None,
|
||||
@@ -616,6 +620,7 @@ impl Documents {
|
||||
disk_mtime: 0.0,
|
||||
disk_len: 0,
|
||||
disk_conflict: false,
|
||||
external_writes: 0,
|
||||
clean_text: None,
|
||||
closed: false,
|
||||
uri: Some(uri.to_owned()),
|
||||
@@ -676,6 +681,7 @@ impl Documents {
|
||||
disk_mtime: 0.0,
|
||||
disk_len: 0,
|
||||
disk_conflict: false,
|
||||
external_writes: 0,
|
||||
clean_text: None,
|
||||
closed: false,
|
||||
uri: Some(key.to_string_lossy().into_owned()),
|
||||
@@ -948,20 +954,7 @@ impl Documents {
|
||||
/// on disk after this buffer was edited, which only an explicit save may overwrite.
|
||||
pub fn autosave(&self, doc: DocId) -> IdeResult<bool> {
|
||||
self.with_doc(doc, |st| {
|
||||
// The watcher event for an external write may not have arrived yet: check the stamp now.
|
||||
if st.dirty
|
||||
&& !st.disk_conflict
|
||||
&& st.uri.is_none()
|
||||
&& let Ok(meta) = std::fs::metadata(&st.path)
|
||||
&& st.changed_on_disk(&meta)
|
||||
{
|
||||
st.disk_mtime = ide_vfs::mtime_ms(&meta);
|
||||
st.disk_len = meta.len();
|
||||
st.disk_conflict = true;
|
||||
// The text read before no longer matches the file: undoing back to it is not clean.
|
||||
st.clean_text = None;
|
||||
self.sink.emit(IdeEvent::DocDiskConflict { doc, path: st.path.to_string_lossy().into_owned() });
|
||||
}
|
||||
self.check_disk_conflict(doc, st);
|
||||
if st.dirty && st.disk_conflict {
|
||||
return Ok(false);
|
||||
}
|
||||
@@ -969,6 +962,29 @@ impl Documents {
|
||||
})
|
||||
}
|
||||
|
||||
/// An unsaved buffer whose file another program wrote: the watcher event may not have arrived
|
||||
/// yet, so check the stamp now.
|
||||
fn check_disk_conflict(&self, doc: DocId, st: &mut DocState) {
|
||||
if st.dirty
|
||||
&& !st.disk_conflict
|
||||
&& st.uri.is_none()
|
||||
&& let Ok(meta) = std::fs::metadata(&st.path)
|
||||
&& st.changed_on_disk(&meta)
|
||||
{
|
||||
self.disk_conflict(doc, st, &meta);
|
||||
}
|
||||
}
|
||||
|
||||
fn disk_conflict(&self, doc: DocId, st: &mut DocState, meta: &std::fs::Metadata) {
|
||||
st.disk_mtime = ide_vfs::mtime_ms(meta);
|
||||
st.disk_len = meta.len();
|
||||
st.disk_conflict = true;
|
||||
st.external_writes += 1;
|
||||
// The text read before no longer matches the file: undoing back to it is not clean.
|
||||
st.clean_text = None;
|
||||
self.sink.emit(IdeEvent::DocDiskConflict { doc, path: st.path.to_string_lossy().into_owned() });
|
||||
}
|
||||
|
||||
fn write(&self, doc: DocId, st: &mut DocState) -> IdeResult<()> {
|
||||
{
|
||||
if !st.dirty || st.uri.is_some() {
|
||||
@@ -1443,12 +1459,7 @@ impl Documents {
|
||||
if !st.changed_on_disk(&meta) {
|
||||
return Ok(());
|
||||
}
|
||||
st.disk_mtime = mtime;
|
||||
st.disk_len = meta.len();
|
||||
st.disk_conflict = true;
|
||||
// The text read before no longer matches the file: undoing back to it is not clean.
|
||||
st.clean_text = None;
|
||||
self.sink.emit(IdeEvent::DocDiskConflict { doc: id, path: st.path.to_string_lossy().into_owned() });
|
||||
self.disk_conflict(id, st, &meta);
|
||||
return Ok(());
|
||||
}
|
||||
let loaded = if force_clean {
|
||||
|
||||
@@ -100,6 +100,8 @@ struct Record {
|
||||
paths: Vec<SavedPath>,
|
||||
documents: Vec<(DocId, DocState)>,
|
||||
after: Vec<WorkspaceEditPrecondition>,
|
||||
/// External writes seen by each open document as of `after` (see [`Documents::external_writes`]).
|
||||
writes: Vec<(DocId, u64)>,
|
||||
}
|
||||
|
||||
fn stale(path: &Path) -> IdeError {
|
||||
@@ -369,6 +371,35 @@ impl Documents {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// How many external writes each open document under `roots` has seen, with its path. An
|
||||
/// unsaved buffer's file is checked first, for a write the watcher hasn't reported yet.
|
||||
fn external_writes(&self, roots: &[PathBuf]) -> IdeResult<Vec<(DocId, u64, PathBuf)>> {
|
||||
let mut writes = Vec::new();
|
||||
for id in self.open_documents() {
|
||||
self.with_doc(id, |state| {
|
||||
if roots.iter().any(|p| text_path(&state.path).is_ok_and(|file| file.starts_with(p))) {
|
||||
self.check_disk_conflict(id, state);
|
||||
writes.push((id, state.external_writes, state.path.clone()));
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
Ok(writes)
|
||||
}
|
||||
|
||||
/// Fingerprints see an unsaved buffer in place of its file, so another program writing that
|
||||
/// file since the record was made shows only as a disk conflict. The IDE's own saves don't count.
|
||||
fn validate_external_writes(&self, record: &Record, roots: &[PathBuf]) -> IdeResult<()> {
|
||||
for (id, writes, path) in self.external_writes(roots)? {
|
||||
// A document opened since then starts at zero.
|
||||
let before = record.writes.iter().find(|(doc, _)| *doc == id).map_or(0, |(_, writes)| *writes);
|
||||
if writes != before {
|
||||
return Err(stale(&path));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_preconditions(&self, expected: &[WorkspaceEditPrecondition]) -> IdeResult<()> {
|
||||
let current = self.fingerprints(&expected.iter().map(|p| p.path.to_path_buf()).collect::<Vec<_>>())?;
|
||||
for (before, after) in expected.iter().zip(current) {
|
||||
@@ -469,6 +500,10 @@ impl Documents {
|
||||
Ok(after) => after,
|
||||
Err(error) => return Err(self.recover(record, error)),
|
||||
};
|
||||
record.writes = match self.external_writes(&roots) {
|
||||
Ok(writes) => writes.into_iter().map(|(id, writes, _)| (id, writes)).collect(),
|
||||
Err(error) => return Err(self.recover(record, error)),
|
||||
};
|
||||
if let Err(error) = fs::remove_file(record.directory.path().join("recovery")) {
|
||||
return Err(self.recover(record, error.into()));
|
||||
}
|
||||
@@ -568,6 +603,7 @@ impl Documents {
|
||||
paths,
|
||||
documents,
|
||||
after: Vec::new(),
|
||||
writes: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -869,8 +905,9 @@ impl Documents {
|
||||
if record.undone != redo {
|
||||
return Err(IdeError::invalid("the refactoring is already in the requested history state"));
|
||||
}
|
||||
self.validate_preconditions(&record.after)?;
|
||||
let roots = record.paths.iter().map(|p| p.path.clone()).collect::<Vec<_>>();
|
||||
self.validate_external_writes(record, &roots)?;
|
||||
self.validate_preconditions(&record.after)?;
|
||||
let mut current = self.backup(&roots)?;
|
||||
fs::write(current.directory.path().join("recovery"), b"history restore in progress")?;
|
||||
let _active = ActiveEdit::new(&self.workspace_edit_active);
|
||||
@@ -881,6 +918,10 @@ impl Documents {
|
||||
Ok(after) => after,
|
||||
Err(error) => return Err(self.recover(current, error)),
|
||||
};
|
||||
current.writes = match self.external_writes(&roots) {
|
||||
Ok(writes) => writes.into_iter().map(|(id, writes, _)| (id, writes)).collect(),
|
||||
Err(error) => return Err(self.recover(current, error)),
|
||||
};
|
||||
current.undone = !redo;
|
||||
current.created = record.created;
|
||||
if let Err(error) = fs::remove_file(current.directory.path().join("recovery")) {
|
||||
|
||||
@@ -426,6 +426,80 @@ fn undo_refuses_later_changes_and_retains_the_record() {
|
||||
assert_eq!(std::fs::read_to_string(a).unwrap(), "old\n");
|
||||
}
|
||||
|
||||
/// An open file with unsaved typing, refactored: its buffer holds `new`, the disk still `old`.
|
||||
fn refactored_unsaved(path: &Path) -> (Documents, Arc<Mutex<Vec<IdeEvent>>>, ide_core::DocId) {
|
||||
std::fs::write(path, "old\n").unwrap();
|
||||
let (docs, events) = recorded_documents();
|
||||
let info = docs.open(path).unwrap();
|
||||
docs.edit(info.id, info.version, ChangeSet { changes: vec![TextChange { from: 0, to: 3, insert: "own".into() }] })
|
||||
.unwrap();
|
||||
docs.apply_workspace_edit(&WorkspaceEdit { files: vec![edit(path, "new")], ..Default::default() }).unwrap();
|
||||
assert_eq!(docs.snapshot(info.id).unwrap().text, "new\n");
|
||||
(docs, events, info.id)
|
||||
}
|
||||
|
||||
fn type_text(docs: &Documents, id: ide_core::DocId, text: &str) {
|
||||
let snapshot = docs.snapshot(id).unwrap();
|
||||
let to = snapshot.text.encode_utf16().count() as u32;
|
||||
docs.edit(id, snapshot.version, ChangeSet { changes: vec![TextChange { from: 0, to, insert: text.into() }] })
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_keeps_an_external_write_under_an_unsaved_buffer() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let path = tmp.path().join("a.txt");
|
||||
let (docs, events, id) = refactored_unsaved(&path);
|
||||
// Not reported by a watcher: undo itself notices the write.
|
||||
std::fs::write(&path, "external\n").unwrap();
|
||||
assert_eq!(docs.undo_workspace_edit(undo_id(&events)).unwrap_err().kind, ErrorKind::OutOfSync);
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), "external\n");
|
||||
assert_eq!(docs.snapshot(id).unwrap().text, "new\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_after_saving_and_undoing_the_typing_is_allowed() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let path = tmp.path().join("a.txt");
|
||||
let (docs, events, id) = refactored_unsaved(&path);
|
||||
type_text(&docs, id, "typed later\n");
|
||||
docs.save(id).unwrap();
|
||||
// The typing undone: the buffer is back to the refactoring's text, the IDE's own save on disk.
|
||||
type_text(&docs, id, "new\n");
|
||||
docs.undo_workspace_edit(undo_id(&events)).unwrap();
|
||||
assert_eq!(docs.snapshot(id).unwrap().text, "own\n");
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), "old\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_allows_a_disk_conflict_from_before_the_refactoring() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let path = tmp.path().join("a.txt");
|
||||
std::fs::write(&path, "old\n").unwrap();
|
||||
let (docs, events) = recorded_documents();
|
||||
let info = docs.open(&path).unwrap();
|
||||
type_text(&docs, info.id, "own\n");
|
||||
std::fs::write(&path, "external\n").unwrap();
|
||||
assert!(!docs.autosave(info.id).unwrap(), "the external write is a disk conflict");
|
||||
docs.apply_workspace_edit(&WorkspaceEdit { files: vec![edit(&path, "new")], ..Default::default() }).unwrap();
|
||||
docs.undo_workspace_edit(undo_id(&events)).unwrap();
|
||||
assert_eq!(docs.snapshot(info.id).unwrap().text, "own\n");
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), "external\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redo_keeps_an_external_write_made_after_the_undo() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let path = tmp.path().join("a.txt");
|
||||
let (docs, events, id) = refactored_unsaved(&path);
|
||||
let undo = undo_id(&events);
|
||||
docs.undo_workspace_edit(undo).unwrap();
|
||||
std::fs::write(&path, "external\n").unwrap();
|
||||
assert_eq!(docs.redo_workspace_edit(undo).unwrap_err().kind, ErrorKind::OutOfSync);
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), "external\n");
|
||||
assert_eq!(docs.snapshot(id).unwrap().text, "own\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ordered_resource_operations_and_binary_deletion_are_undoable() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
Reference in new issue
Заблокувати користувача