дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-30 06:12:33 +02:00
fix(editor): don't save stale text over a file replaced by binary content (#6840)
reload_from_disk treated a file that now loads as binary like a document opened as binary: it refreshed the disk stamp without a disk-change report, so autosave wrote the next edit over the binary file. A detected-encoding buffer now gets the disk conflict too. Reopening a file whose closed tab kept unsaved changes shows that buffer as text instead of a binary viewer that hid what Save would write. A clean buffer gets its own disk-change wording. Co-authored-by: audichuang <[email protected]>
Цей коміт міститься в:
1 джерело
3d6ad2e254
коміт
08eb9e3ff9
6 files changed
+105
-12
No files matched your search
@@ -1592,14 +1592,14 @@ impl Documents {
|
||||
st.native_to_ascii = native_to_ascii;
|
||||
loaded
|
||||
};
|
||||
if loaded.binary || st.binary {
|
||||
if st.binary {
|
||||
st.disk_mtime = loaded.mtime_ms;
|
||||
st.disk_len = disk_len(&st.path);
|
||||
st.disk_conflict = false;
|
||||
return Ok(());
|
||||
}
|
||||
// Keep the text, and keep autosave from writing it over the binary file.
|
||||
if turned_binary(st, &loaded)? {
|
||||
if loaded.binary || turned_binary(st, &loaded)? {
|
||||
self.disk_conflict(id, st, &meta);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
@@ -2035,3 +2035,41 @@ fn a_file_opened_as_text_despite_nul_bytes_keeps_reloading() {
|
||||
assert_eq!(f.docs.snapshot(doc.id).unwrap().text, "key\0other value\n");
|
||||
assert_eq!(disk_conflicts(&f, &path), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_detected_text_file_replaced_by_binary_content_is_reported_and_not_autosaved() {
|
||||
let binary = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00".to_vec();
|
||||
let mut failures = Vec::new();
|
||||
for dirty in [false, true] {
|
||||
let f = fixture();
|
||||
let path = f.root.join("notes.txt");
|
||||
fs::write(&path, "hello\n").unwrap();
|
||||
let doc = f.docs.open(&path).unwrap();
|
||||
if dirty {
|
||||
f.docs.edit(doc.id, doc.version, change(0, 0, "x")).unwrap();
|
||||
}
|
||||
let before = f.docs.snapshot(doc.id).unwrap();
|
||||
fs::write(&path, &binary).unwrap();
|
||||
// The file watcher's path, as the editor sees it: reported on the first event, and
|
||||
// the next edit is not autosaved over the file.
|
||||
f.docs.on_disk_changed(std::slice::from_ref(&path));
|
||||
let reported = disk_conflicts(&f, &path);
|
||||
let after = f.docs.snapshot(doc.id).unwrap();
|
||||
f.docs.edit(doc.id, after.version, change(0, 0, "y")).unwrap();
|
||||
let autosaved = f.docs.autosave(doc.id).unwrap();
|
||||
let on_disk = fs::read(&path).unwrap();
|
||||
// The same disk state again, through every sync path: reported once.
|
||||
f.docs.on_disk_changed(std::slice::from_ref(&path));
|
||||
f.docs.sync_after_disk_change();
|
||||
f.docs.sync_from_disk();
|
||||
let conflicts = disk_conflicts(&f, &path);
|
||||
if after.text != before.text || reported != 1 || conflicts != 1 || autosaved || on_disk != binary {
|
||||
failures.push(format!(
|
||||
"dirty {dirty}: text {:?} reported {reported} conflicts {conflicts} autosaved {autosaved} disk kept {}",
|
||||
after.text,
|
||||
on_disk == binary
|
||||
));
|
||||
}
|
||||
}
|
||||
assert!(failures.is_empty(), "{failures:#?}");
|
||||
}
|
||||
@@ -1355,17 +1355,20 @@ export class EditorController implements SlotHost {
|
||||
await this.projectTransition;
|
||||
this.checkOpening(generation);
|
||||
// Files opened with another application, then images/binary/huge files in a
|
||||
// contributed viewer, unless already open as text.
|
||||
// contributed viewer, unless already open as text: in a tab, or kept without one for its
|
||||
// unsaved changes, which a viewer without its own document would hide while Save writes them.
|
||||
if (!o.asText && !findTab(useTabs.getState(), fileKey(path))) {
|
||||
if (o.external === false ? opensExternally(path) : await openFileExternally(path)) return;
|
||||
const kept = this.manager.get(path)?.getMeta().dirty;
|
||||
if (!kept && (o.external === false ? opensExternally(path) : await openFileExternally(path))) return;
|
||||
const viewer = await resolveFileEditor(path);
|
||||
if (viewer) {
|
||||
const hides = kept && !documentLifecycle(viewer.input, useContributions.getState().editorKinds);
|
||||
try {
|
||||
await this.admitInput(viewer.input, o, generation, viewer);
|
||||
if (!hides) await this.admitInput(viewer.input, o, generation, viewer);
|
||||
} finally {
|
||||
await viewer.rollback();
|
||||
}
|
||||
return;
|
||||
if (!hides) return;
|
||||
}
|
||||
}
|
||||
await this.admitInput(fileInput(path), o, generation);
|
||||
@@ -1991,8 +1994,9 @@ export class EditorController implements SlotHost {
|
||||
}
|
||||
/** Reload from Disk: re-reads the open, unmodified documents of `paths`. */
|
||||
/**
|
||||
* A file changed on disk while its buffer had unsaved changes: the buffer keeps them (autosave
|
||||
* leaves the file alone) until the user loads the disk version or saves over it.
|
||||
* A file changed on disk while its buffer had unsaved changes, or turned binary under a clean
|
||||
* one: the buffer keeps its text (autosave leaves the file alone) until the user loads the disk
|
||||
* version or saves over it.
|
||||
*/
|
||||
private onDiskConflict(path: string) {
|
||||
const key = `disk-conflict:${path}`;
|
||||
@@ -2001,9 +2005,13 @@ export class EditorController implements SlotHost {
|
||||
key,
|
||||
sticky: true,
|
||||
title: tx`${basename(path)} changed on disk`,
|
||||
body: tx(
|
||||
"The file was changed outside the IDE while it has unsaved changes in the editor. Saving keeps the editor's version and overwrites the file.",
|
||||
),
|
||||
body: this.manager.get(path)?.getMeta().dirty
|
||||
? tx(
|
||||
"The file was changed outside the IDE while it has unsaved changes in the editor. Saving keeps the editor's version and overwrites the file.",
|
||||
)
|
||||
: tx(
|
||||
"The file was replaced outside the IDE with content that can't be shown as text. Saving keeps the editor's version and overwrites the file.",
|
||||
),
|
||||
actions: [
|
||||
{
|
||||
label: tx("Load Changes from Disk"),
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { registerExternalFileOpenHandler, registerFileEditorProvider } from "@/workbench/contributions";
|
||||
import {
|
||||
registerEditorKind,
|
||||
registerExternalFileOpenHandler,
|
||||
registerFileEditorProvider,
|
||||
} from "@/workbench/contributions";
|
||||
import { EditorController, openFilePaths, useTabs } from "./controller";
|
||||
import { createMemoryBackend } from "./backend";
|
||||
import { storeSession } from "./model/session";
|
||||
@@ -328,4 +332,45 @@ describe("file open order", () => {
|
||||
expect(activePath()).toBe("/p/b.ts");
|
||||
expect(tabFor("/p/a.ts")).toBeUndefined();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["file", "a viewer of the file", "image"],
|
||||
["shared-doc-test", "an editor sharing the document", "shared-doc-test"],
|
||||
])("reopens a closed tab's unsaved buffer as %s when %s handles it", async (reopened, _, viewerKind) => {
|
||||
useProject.setState({ settings: { files: { autoSave: false } } as never });
|
||||
const unregister = registerEditorKind({
|
||||
kind: "shared-doc-test",
|
||||
component: () => null,
|
||||
title: (i) => i.key,
|
||||
document: {
|
||||
isDirty: () => false,
|
||||
flush: async () => {},
|
||||
save: async () => {},
|
||||
prepareClose: async () => {},
|
||||
cancelClose: () => {},
|
||||
discard: async () => {},
|
||||
close: async () => {},
|
||||
},
|
||||
});
|
||||
const viewer = registerFileEditorProvider({
|
||||
id: "binary-viewer",
|
||||
resolve: async (path) => (path === "/p/a.ts" ? { kind: viewerKind, key: `${viewerKind}:/p/a.ts`, path } : null),
|
||||
});
|
||||
dispose = () => {
|
||||
viewer();
|
||||
unregister();
|
||||
};
|
||||
const controller = setup();
|
||||
await controller.openFile("/p/a.ts", { asText: true, focus: false });
|
||||
const slot = controller.activeSlot!;
|
||||
slot.dispatchLocal({ changes: { from: 0, insert: "x" }, userEvent: "input.type" });
|
||||
await vi.waitFor(() => expect(slot.model.getMeta().dirty).toBe(true));
|
||||
const tab = tabFor("/p/a.ts")!;
|
||||
const pane = Object.values(useTabs.getState().panes).find((p) => p.tabs.includes(tab))!;
|
||||
await controller.closeTab(pane.id, tab.id);
|
||||
expect(tabFor("/p/a.ts")).toBeUndefined();
|
||||
expect(controller.manager.get("/p/a.ts")?.getMeta().dirty).toBe(true);
|
||||
await controller.openFile("/p/a.ts", { focus: false });
|
||||
expect(tabFor("/p/a.ts")?.input.kind).toBe(reopened);
|
||||
});
|
||||
});
|
||||
@@ -3878,6 +3878,7 @@
|
||||
"Managed in {location}": "Managed in {location}",
|
||||
"{name} changed on disk": "{name} changed on disk",
|
||||
"The file was changed outside the IDE while it has unsaved changes in the editor. Saving keeps the editor's version and overwrites the file.": "The file was changed outside the IDE while it has unsaved changes in the editor. Saving keeps the editor's version and overwrites the file.",
|
||||
"The file was replaced outside the IDE with content that can't be shown as text. Saving keeps the editor's version and overwrites the file.": "The file was replaced outside the IDE with content that can't be shown as text. Saving keeps the editor's version and overwrites the file.",
|
||||
"Load Changes from Disk": "Load Changes from Disk",
|
||||
"Keep Editor Changes": "Keep Editor Changes",
|
||||
"Branches have diverged": "Branches have diverged",
|
||||
|
||||
@@ -10388,6 +10388,7 @@
|
||||
"Managed in {location}": "由 {location} 管理",
|
||||
"{name} changed on disk": "{name} 已在磁盘上更改",
|
||||
"The file was changed outside the IDE while it has unsaved changes in the editor. Saving keeps the editor's version and overwrites the file.": "该文件在 IDE 外被修改,而编辑器中还有未保存的更改。保存会保留编辑器中的版本并覆盖该文件。",
|
||||
"The file was replaced outside the IDE with content that can't be shown as text. Saving keeps the editor's version and overwrites the file.": "该文件在 IDE 外被替换为无法以文本显示的内容。保存会保留编辑器中的版本并覆盖该文件。",
|
||||
"Load Changes from Disk": "从磁盘加载更改",
|
||||
"Keep Editor Changes": "保留编辑器中的更改",
|
||||
"Diagnose with Agent": "用智能体诊断",
|
||||
|
||||
Reference in new issue
Заблокувати користувача