From f7f9dabe2b9a4b655dfd90f2f21085a6b25bf540 Mon Sep 17 00:00:00 2001 From: audichuang <72485427+audichuang@users.noreply.github.com> Date: Fri, 27 Nov 2026 05:04:18 +0800 Subject: [PATCH] fix(documents): don't treat a rewrite of the same bytes as a disk conflict (#6195) With unsaved edits, a touch, a tool rewriting the file unchanged, or a git stash/pop the watcher missed was reported as a disk change and stopped autosave, because both the watcher and autosave's check compared only the (mtime, length) stamp. When the mtime moved but the length did not, the file's bytes are now compared with what the clean text encodes to (encoding, BOM, line endings); identical bytes adopt the new stamp. Equal text in other bytes still conflicts, and without a clean text a moved stamp still counts. Co-authored-by: audichuang <72485427+audichuang@users.noreply.github.com> --- crates/ide-workspace/src/documents.rs | 34 +++++++++++- .../src/documents/workspace_edit.rs | 7 +-- crates/ide-workspace/tests/documents.rs | 55 +++++++++++++++++++ crates/ide-workspace/tests/workspace_edits.rs | 11 ++-- 4 files changed, 95 insertions(+), 12 deletions(-) diff --git a/crates/ide-workspace/src/documents.rs b/crates/ide-workspace/src/documents.rs index 8525c771d..35c6f6c28 100644 --- a/crates/ide-workspace/src/documents.rs +++ b/crates/ide-workspace/src/documents.rs @@ -191,6 +191,35 @@ impl DocState { self.disk_conflict = false; self.clean_text = (!self.large).then(|| self.doc.clone()); } + + /// The bytes saving `doc` with this document's encoding, BOM and conversion would write. + fn bytes_for_save(&self, doc: &Document) -> IdeResult> { + let text = doc.text_for_save(); + Ok(if self.native_to_ascii { + ide_vfs::encode_properties_ascii(&text).into_bytes() + } else { + ide_vfs::encode(&text, &self.encoding, self.has_bom)? + }) + } + + /// Whether the file changed on disk since the buffer last matched it. A moved stamp with the + /// same bytes (touch, a tool rewriting the file unchanged) is no change and its stamp is adopted. Reads the file + /// only when the mtime moved but the length did not; without a clean text to compare (large + /// files, a pending encoding, line-ending or BOM change, a reported conflict) a moved stamp counts. + fn changed_on_disk(&mut self, meta: &std::fs::Metadata) -> bool { + let mtime = ide_vfs::mtime_ms(meta); + if mtime == self.disk_mtime && meta.len() == self.disk_len { + return false; + } + let same_bytes = meta.len() == self.disk_len + && self.clean_text.as_ref().is_some_and(|clean| { + self.bytes_for_save(clean).is_ok_and(|bytes| std::fs::read(&self.path).is_ok_and(|disk| disk == bytes)) + }); + if same_bytes { + self.disk_mtime = mtime; + } + !same_bytes + } } fn keys_for(path: &Path) -> Vec { @@ -924,7 +953,7 @@ impl Documents { && !st.disk_conflict && st.uri.is_none() && let Ok(meta) = std::fs::metadata(&st.path) - && (ide_vfs::mtime_ms(&meta) != st.disk_mtime || meta.len() != st.disk_len) + && st.changed_on_disk(&meta) { st.disk_mtime = ide_vfs::mtime_ms(&meta); st.disk_len = meta.len(); @@ -1411,6 +1440,9 @@ impl Documents { return Ok(()); } if st.dirty { + if !st.changed_on_disk(&meta) { + return Ok(()); + } st.disk_mtime = mtime; st.disk_len = meta.len(); st.disk_conflict = true; diff --git a/crates/ide-workspace/src/documents/workspace_edit.rs b/crates/ide-workspace/src/documents/workspace_edit.rs index f01a6adaa..c6eb1a532 100644 --- a/crates/ide-workspace/src/documents/workspace_edit.rs +++ b/crates/ide-workspace/src/documents/workspace_edit.rs @@ -314,12 +314,7 @@ fn hash_disk(hash: &mut blake3::Hasher, path: &Path, unsaved: &HashMap IdeResult> { - let text = state.doc.text_for_save(); - Ok(if state.native_to_ascii { - ide_vfs::encode_properties_ascii(&text).into_bytes() - } else { - ide_vfs::encode(&text, &state.encoding, state.has_bom)? - }) + state.bytes_for_save(&state.doc) } /// A reverted edit may leave the dirty flag set even when all saved bytes match. diff --git a/crates/ide-workspace/tests/documents.rs b/crates/ide-workspace/tests/documents.rs index 8e5c834a8..e13ba0cbf 100644 --- a/crates/ide-workspace/tests/documents.rs +++ b/crates/ide-workspace/tests/documents.rs @@ -350,6 +350,61 @@ fn autosave_checks_the_disk_before_the_watcher_reports_a_change() { ); } +/// Writes `bytes` with an mtime clearly after the current one, whatever the filesystem's granularity. +fn rewrite_later(path: &Path, bytes: &[u8]) { + let mtime = fs::metadata(path).unwrap().modified().unwrap() + std::time::Duration::from_secs(2); + fs::write(path, bytes).unwrap(); + fs::File::options().write(true).open(path).unwrap().set_modified(mtime).unwrap(); +} + +#[test] +fn rewriting_the_same_bytes_is_no_disk_conflict() { + let f = fixture(); + let path = f.root.join("notes.txt"); + fs::write(&path, "alpha\nbeta\n").unwrap(); + let info = f.docs.open(&path).unwrap(); + f.docs.edit(info.id, 0, change(0, 5, "edited")).unwrap(); + // A touch, or a tool rewriting the file unchanged: only the mtime moves. + rewrite_later(&path, b"alpha\nbeta\n"); + f.docs.on_disk_changed(std::slice::from_ref(&path)); + assert!(f.docs.autosave(info.id).unwrap(), "autosave stopped on a file whose bytes did not change"); + assert_eq!(fs::read_to_string(&path).unwrap(), "edited\nbeta\n"); + assert!(!f.events.lock().iter().any(|e| matches!(e, IdeEvent::DocDiskConflict { .. }))); +} + +#[test] +fn autosave_ignores_a_rewrite_of_the_same_bytes_before_the_watcher_reports_it() { + let f = fixture(); + let path = f.root.join("notes.txt"); + fs::write(&path, "alpha\nbeta\n").unwrap(); + let info = f.docs.open(&path).unwrap(); + f.docs.edit(info.id, 0, change(0, 5, "edited")).unwrap(); + rewrite_later(&path, b"alpha\nbeta\n"); + assert!(f.docs.autosave(info.id).unwrap(), "autosave stopped on a file whose bytes did not change"); + assert_eq!(fs::read_to_string(&path).unwrap(), "edited\nbeta\n"); +} + +/// Opens `bytes`, edits the buffer, then rewrites the file as `external` (same text, other bytes). +fn assert_other_bytes_conflict(name: &str, bytes: &[u8], external: &[u8]) { + let f = fixture(); + let path = f.root.join(name); + fs::write(&path, bytes).unwrap(); + let info = f.docs.open(&path).unwrap(); + f.docs.edit(info.id, 0, change(0, 0, "x")).unwrap(); + rewrite_later(&path, external); + f.docs.on_disk_changed(std::slice::from_ref(&path)); + assert!(!f.docs.autosave(info.id).unwrap(), "{name}: autosave overwrote other bytes of the same text"); + assert_eq!(fs::read(&path).unwrap(), external); +} + +#[test] +fn the_same_text_in_other_bytes_is_still_a_disk_conflict() { + assert_other_bytes_conflict("crlf.txt", b"alpha\nbeta\n", b"alpha\r\nbeta\r\n"); + assert_other_bytes_conflict("bom.txt", b"alpha\n", b"\xEF\xBB\xBFalpha\n"); + // Same length: only the byte comparison tells them apart. + assert_other_bytes_conflict("utf16.txt", b"\xFF\xFEa\x00\n\x00", b"\xFE\xFF\x00a\x00\n"); +} + #[test] fn autosave_leaves_a_file_changed_on_disk_after_an_edit() { let f = fixture(); diff --git a/crates/ide-workspace/tests/workspace_edits.rs b/crates/ide-workspace/tests/workspace_edits.rs index af69190c3..0ec927192 100644 --- a/crates/ide-workspace/tests/workspace_edits.rs +++ b/crates/ide-workspace/tests/workspace_edits.rs @@ -138,17 +138,18 @@ fn rollback_keeps_a_disk_conflict_of_an_unsaved_buffer() { let info = docs.open(&first).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(&first, "new")], ..Default::default() }).unwrap(); - // An external write the undo record still accepts (same bytes, new mtime) under the unsaved buffer. - std::thread::sleep(std::time::Duration::from_millis(10)); - std::fs::write(&first, "old\n").unwrap(); + // An external write under the unsaved buffer, warned about before the refactoring. + let mtime = std::fs::metadata(&first).unwrap().modified().unwrap() + std::time::Duration::from_secs(2); + std::fs::write(&first, "ext\n").unwrap(); + std::fs::File::options().write(true).open(&first).unwrap().set_modified(mtime).unwrap(); docs.on_disk_changed(std::slice::from_ref(&first)); + docs.apply_workspace_edit(&WorkspaceEdit { files: vec![edit(&first, "new")], ..Default::default() }).unwrap(); docs.undo_workspace_edit(undo_id(&events)).unwrap(); let snap = docs.snapshot(info.id).unwrap(); assert_eq!(snap.text, "own\n"); assert!(snap.dirty); assert!(!docs.autosave(info.id).unwrap(), "autosave must not overwrite the external change"); - assert_eq!(std::fs::read_to_string(&first).unwrap(), "old\n"); + assert_eq!(std::fs::read_to_string(&first).unwrap(), "ext\n"); } #[test]