diff --git a/crates/ide-host/src/ops/search/commands.rs b/crates/ide-host/src/ops/search/commands.rs index 15b99a1f23..0a7d934e22 100644 --- a/crates/ide-host/src/ops/search/commands.rs +++ b/crates/ide-host/src/ops/search/commands.rs @@ -9,7 +9,11 @@ use std::path::{Path, PathBuf}; struct DocumentsHost<'a>(&'a Documents); impl ReplaceHost for DocumentsHost<'_> { - fn edit_file(&self, path: &Path, compute: &mut dyn FnMut(&str) -> IdeResult>) -> IdeResult { + fn edit_file( + &self, + path: &Path, + compute: &mut dyn FnMut(&str) -> IdeResult>, + ) -> IdeResult<(u32, bool)> { let docs = self.0; let (doc, transient) = match docs.by_path(path) { Some(doc) => (doc, false), @@ -24,7 +28,7 @@ impl ReplaceHost for DocumentsHost<'_> { let snap = docs.text_snapshot(doc)?; let edits = compute(&snap.text)?; if edits.is_empty() { - return Ok(0); + return Ok((0, false)); } if docs.text_snapshot(doc)?.version != snap.version { continue; @@ -33,12 +37,13 @@ impl ReplaceHost for DocumentsHost<'_> { // An open tab's file may have changed on disk before the watcher reported it: // autosave keeps that change and leaves the replacement unsaved. A file opened // just for this was read now. - if transient { + let disk_conflict = if transient { docs.save(doc)?; - } else if save { - docs.autosave(doc)?; - } - return Ok(edits.len() as u32); + false + } else { + save && !docs.autosave(doc)? + }; + return Ok((edits.len() as u32, disk_conflict)); } Err(ide_core::IdeError::unavailable("the file kept changing during Replace")) })(); diff --git a/crates/ide-host/tests/replace_all.rs b/crates/ide-host/tests/replace_all.rs index 91cf339c67..ba15f2bf99 100644 --- a/crates/ide-host/tests/replace_all.rs +++ b/crates/ide-host/tests/replace_all.rs @@ -165,6 +165,8 @@ async fn replace_all_saves_open_buffers_without_unsaved_changes() { std::fs::write(&stale_path, "TOKEN\nexternal\n").unwrap(); let mut search = query("TOKEN", false); search.scope = SearchScope::Directory { path: scope.into() }; + let summary = Arc::new(Mutex::new(None)); + let out = summary.clone(); ops::search::replace_in_files( &host, "main", @@ -174,10 +176,18 @@ async fn replace_all_saves_open_buffers_without_unsaved_changes() { false, vec![], true, - ops::Channel::new(|_| {}), + ops::Channel::new(move |e| { + if let ReplaceEvent::Done { summary } = e { + *out.lock().unwrap() = Some(summary); + } + }), ) .await .unwrap(); + let summary = summary.lock().unwrap().take().expect("Done"); + // #7273: the stale tab is replaced (counted in `files`) and reported as not saved; the + // user's own unsaved buffer is not. + assert_eq!((summary.files, summary.replacements, summary.failed, summary.unsaved), (4, 4, 0, 1)); let disk = |name: &str| std::fs::read_to_string(root.join(name)).unwrap(); assert_eq!(disk("previewed.txt"), "DONE\n"); assert_eq!(disk("closed.txt"), "DONE\n"); diff --git a/crates/ide-search/src/replace.rs b/crates/ide-search/src/replace.rs index db3a5d5db3..b4aee657b8 100644 --- a/crates/ide-search/src/replace.rs +++ b/crates/ide-search/src/replace.rs @@ -57,6 +57,9 @@ pub struct ReplaceSummary { pub files: u32, pub replacements: u32, pub failed: u32, + /// Files changed in the editor but not saved because the file changed on disk first; + /// counted in `files` too. + pub unsaved: u32, pub cancelled: bool, pub elapsed_ms: u32, } @@ -72,9 +75,14 @@ pub struct ReplacePreview { /// Where replacements are applied. `compute` receives the file's current text /// (unsaved editor buffer included) and returns the edits for it; the host -/// applies them atomically and returns how many it applied. +/// applies them atomically and returns how many it applied, and whether they were left +/// unsaved because the file changed on disk. pub trait ReplaceHost: Sync { - fn edit_file(&self, path: &Path, compute: &mut dyn FnMut(&str) -> IdeResult>) -> IdeResult; + fn edit_file( + &self, + path: &Path, + compute: &mut dyn FnMut(&str) -> IdeResult>, + ) -> IdeResult<(u32, bool)>; } /// IDEA's "Preserve case": `FOO` → upper-cases the replacement, `Foo` → @@ -275,10 +283,11 @@ pub fn replace_files_in_context( edits_except(text, query, replacement, preserve, only, skip, found.as_deref()) }); match result { - Ok(n) => { + Ok((n, disk_conflict)) => { if n > 0 { summary.files += 1; summary.replacements += n; + summary.unsaved += u32::from(disk_conflict); } on_event(ReplaceEvent::File { path: target.path.clone(), replacements: n, done, total }); } diff --git a/crates/ide-search/tests/replace.rs b/crates/ide-search/tests/replace.rs index 053ca875d6..9e9ecbe220 100644 --- a/crates/ide-search/tests/replace.rs +++ b/crates/ide-search/tests/replace.rs @@ -51,7 +51,11 @@ impl FakeDocs { } impl ReplaceHost for FakeDocs { - fn edit_file(&self, path: &Path, compute: &mut dyn FnMut(&str) -> IdeResult>) -> IdeResult { + fn edit_file( + &self, + path: &Path, + compute: &mut dyn FnMut(&str) -> IdeResult>, + ) -> IdeResult<(u32, bool)> { let mut files = self.files.lock().unwrap(); let text = files.get(path).cloned().ok_or_else(|| IdeError::not_found("no such file"))?; let edits = compute(&text)?; @@ -62,7 +66,7 @@ impl ReplaceHost for FakeDocs { if let Some(c) = &self.cancel_after_first { c.cancel(); } - Ok(edits.len() as u32) + Ok((edits.len() as u32, false)) } } @@ -125,7 +129,10 @@ fn replace_files_one_step_per_file_with_progress() { assert_eq!(docs.text("a"), "bar bar"); assert_eq!(docs.text("c"), "x bar"); assert_eq!(*docs.steps.lock().unwrap(), vec![(PathBuf::from("a"), 2), (PathBuf::from("c"), 1)]); - assert_eq!((summary.files, summary.replacements, summary.failed, summary.cancelled), (2, 3, 1, false)); + assert_eq!( + (summary.files, summary.replacements, summary.failed, summary.unsaved, summary.cancelled), + (2, 3, 1, 0, false) + ); let events = events.lock().unwrap(); assert_eq!(events.len(), 4); assert!(matches!(&events[0], ReplaceEvent::File { replacements: 2, done: 1, total: 4, .. })); diff --git a/src/bindings.ts b/src/bindings.ts index 4c4193d5f9..967f1af13d 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -15080,6 +15080,11 @@ export type ReplaceSummary = { files: number, replacements: number, failed: number, + /** + * Files changed in the editor but not saved because the file changed on disk first; + * counted in `files` too. + */ + unsaved: number, cancelled: boolean, elapsedMs: number, }; diff --git a/src/features/search/__tests__/replaceFlow.test.ts b/src/features/search/__tests__/replaceFlow.test.ts index 1f388b99fb..0cf65916ef 100644 --- a/src/features/search/__tests__/replaceFlow.test.ts +++ b/src/features/search/__tests__/replaceFlow.test.ts @@ -1,5 +1,7 @@ import { describe, expect, it, vi } from "vitest"; -import type { FileMatches, ReplaceEvent, SearchQuery } from "@/platform/ipc"; +import type { FileMatches, ReplaceEvent, ReplaceSummary, SearchQuery } from "@/platform/ipc"; +import { txTemplate, useI18n } from "@/platform/i18n"; +import zhTW from "@/platform/locales/text/zh-TW.json"; import { preserveCase } from "@/platform/search"; import { matchRows, previewReplacement } from "../find/session"; import { @@ -106,12 +108,53 @@ describe("replace flow model", () => { expect(confirmText({ usages: 1, files: 1 })).toBe("Replace 1 occurrence in 1 file?"); expect(confirmText({ usages: 3, files: 1 })).toBe("Replace 3 occurrences in 1 file?"); expect(confirmText({ usages: 3, files: 2 })).toBe("Replace 3 occurrences in 2 files?"); - expect(summaryText({ files: 2, replacements: 1, failed: 0, cancelled: false, elapsedMs: 3 })).toBe( + expect(summaryText({ files: 2, replacements: 1, failed: 0, unsaved: 0, cancelled: false, elapsedMs: 3 })).toBe( "Replaced 1 occurrence in 2 files", ); - expect(summaryText({ files: 1, replacements: 4, failed: 1, cancelled: true, elapsedMs: 3 })).toBe( + expect(summaryText({ files: 1, replacements: 4, failed: 1, unsaved: 0, cancelled: true, elapsedMs: 3 })).toBe( "Stopped after replacing 4 occurrences in 1 file (1 failed)", ); + expect(summaryText({ files: 3, replacements: 3, failed: 0, unsaved: 1, cancelled: false, elapsedMs: 3 })).toBe( + "Replaced 3 occurrences in 3 files (1 not saved: changed on disk)", + ); + expect(summaryText({ files: 1, replacements: 1, failed: 2, unsaved: 1, cancelled: false, elapsedMs: 3 })).toBe( + "Replaced 1 occurrence in 1 file (2 failed, 1 not saved: changed on disk)", + ); + }); + + it("translates only the unsaved summaries, and no other text (zh-TW catalog)", () => { + const previous = useI18n.getState().texts; + const added = (key: string) => key.includes("not saved: changed on disk"); + const before = Object.fromEntries(Object.entries(zhTW).filter(([key]) => !added(key))); + const summary = (over: Partial) => + summaryText({ files: 3, replacements: 3, failed: 0, unsaved: 0, cancelled: false, elapsedMs: 3, ...over }); + const unchanged = [ + summary({}), + summary({ files: 1, replacements: 1 }), + summary({ failed: 1 }), + summary({ cancelled: true, failed: 1 }), + "Replaced notes.txt", + "build (1 failed)", + "x (1 not saved: changed on disk)", + ]; + try { + const shown = (texts: Record, text: string) => { + useI18n.setState({ texts }); + return txTemplate(text); + }; + for (const text of unchanged) expect(shown(zhTW, text), text).toBe(shown(before, text)); + expect(shown(zhTW, summary({ unsaved: 1 }))).toBe( + "已取代 3 個檔案中的 3 處相符項目(1 個未儲存:已在磁碟上更改)", + ); + expect(shown(zhTW, summary({ files: 1, replacements: 1, unsaved: 1 }))).toBe( + "已取代 1 個檔案中的 1 處相符項目(1 個未儲存:已在磁碟上更改)", + ); + expect(shown(zhTW, summary({ files: 1, replacements: 4, failed: 2, unsaved: 1, cancelled: true }))).toBe( + "已停止,已取代 1 個檔案中的 4 處相符項目(2 個失敗,1 個未儲存:已在磁碟上更改)", + ); + } finally { + useI18n.setState({ texts: previous }); + } }); }); @@ -127,7 +170,7 @@ describe("startReplace", () => { } it("waits for editor sync, streams progress and resolves with the summary", async () => { - const summary = { files: 1, replacements: 2, failed: 1, cancelled: false, elapsedMs: 1 }; + const summary = { files: 1, replacements: 2, failed: 1, unsaved: 0, cancelled: false, elapsedMs: 1 }; const d = deps([ { type: "file", path: "/p/a.ts", replacements: 2, done: 1, total: 2 }, { type: "failed", path: "/p/b.ts", message: "read-only", done: 2, total: 2 }, diff --git a/src/features/search/find/FindInFiles.tsx b/src/features/search/find/FindInFiles.tsx index d4c0049973..376aa62b99 100644 --- a/src/features/search/find/FindInFiles.tsx +++ b/src/features/search/find/FindInFiles.tsx @@ -359,7 +359,7 @@ function FindInFilesDialog() { const summary = await run.result; notifications().notify({ group: "search", - level: summary.failed ? "warning" : "info", + level: summary.failed || summary.unsaved ? "warning" : "info", title: summaryText(summary), body: summary.files === 1 ? basename(usages[0]!.path) : undefined, key: "search.replace", diff --git a/src/features/search/find/FindToolWindow.tsx b/src/features/search/find/FindToolWindow.tsx index f26a2423bc..8a969e92a5 100644 --- a/src/features/search/find/FindToolWindow.tsx +++ b/src/features/search/find/FindToolWindow.tsx @@ -210,7 +210,7 @@ function FindTabView({ tab }: { tab: FindTab }) { const summary = await run.result; notifications().notify({ group: "search", - level: summary.failed ? "warning" : "info", + level: summary.failed || summary.unsaved ? "warning" : "info", title: summaryText(summary), key: "search.replace", }); diff --git a/src/features/search/find/replaceFlow.ts b/src/features/search/find/replaceFlow.ts index dc0377308d..aabf8a0fac 100644 --- a/src/features/search/find/replaceFlow.ts +++ b/src/features/search/find/replaceFlow.ts @@ -194,7 +194,7 @@ export function startReplace( let cancelled = false; const result = (async () => { await deps.synced(r.allInScope ? null : r.targets.map((t) => t.path)); - if (cancelled) return { files: 0, replacements: 0, failed: 0, cancelled: true, elapsedMs: 0 }; + if (cancelled) return { files: 0, replacements: 0, failed: 0, unsaved: 0, cancelled: true, elapsedMs: 0 }; const progress: ReplaceProgress = { done: 0, total: r.targets.length, replacements: 0, failures: [] }; let summary: ReplaceSummary | null = null; await deps.start(request, r, (e) => { @@ -213,6 +213,7 @@ export function startReplace( files: 0, replacements: progress.replacements, failed: progress.failures.length, + unsaved: 0, cancelled, elapsedMs: 0, } @@ -243,9 +244,40 @@ export function loadReplacePreview( export function summaryText(s: ReplaceSummary): string { const occ = `${s.replacements} occurrence${s.replacements === 1 ? "" : "s"}`; const files = `${s.files} file${s.files === 1 ? "" : "s"}`; + if (s.unsaved) return unsavedSummaryText(s); return `${s.cancelled ? "Stopped after replacing" : "Replaced"} ${occ} in ${files}${s.failed ? ` (${s.failed} failed)` : ""}`; } +/** + * Whole sentences, so the notification translates them through its source-text templates; + * each starts with its own words, so they can't match other text such as a file name. + */ +function unsavedSummaryText({ replacements: n, files, failed, unsaved, cancelled }: ReplaceSummary): string { + // A file counts once something was replaced in it, so `n >= files >= 1` here. + if (cancelled) { + if (failed) { + if (n === 1) + return `Stopped after replacing 1 occurrence in 1 file (${failed} failed, ${unsaved} not saved: changed on disk)`; + if (files === 1) + return `Stopped after replacing ${n} occurrences in 1 file (${failed} failed, ${unsaved} not saved: changed on disk)`; + return `Stopped after replacing ${n} occurrences in ${files} files (${failed} failed, ${unsaved} not saved: changed on disk)`; + } + if (n === 1) return `Stopped after replacing 1 occurrence in 1 file (${unsaved} not saved: changed on disk)`; + if (files === 1) + return `Stopped after replacing ${n} occurrences in 1 file (${unsaved} not saved: changed on disk)`; + return `Stopped after replacing ${n} occurrences in ${files} files (${unsaved} not saved: changed on disk)`; + } + if (failed) { + if (n === 1) return `Replaced 1 occurrence in 1 file (${failed} failed, ${unsaved} not saved: changed on disk)`; + if (files === 1) + return `Replaced ${n} occurrences in 1 file (${failed} failed, ${unsaved} not saved: changed on disk)`; + return `Replaced ${n} occurrences in ${files} files (${failed} failed, ${unsaved} not saved: changed on disk)`; + } + if (n === 1) return `Replaced 1 occurrence in 1 file (${unsaved} not saved: changed on disk)`; + if (files === 1) return `Replaced ${n} occurrences in 1 file (${unsaved} not saved: changed on disk)`; + return `Replaced ${n} occurrences in ${files} files (${unsaved} not saved: changed on disk)`; +} + export interface PreviewLine { kind: "same" | "del" | "add"; /** 0-based line in the old text (`same` / `del`) or the new text (`add`). */ diff --git a/src/platform/locales/text/zh-TW.json b/src/platform/locales/text/zh-TW.json index 98357f043b..360a2f9b37 100644 --- a/src/platform/locales/text/zh-TW.json +++ b/src/platform/locales/text/zh-TW.json @@ -3521,6 +3521,18 @@ "Show on Double-Click": "雙擊時顯示", "Follow the Interface": "跟隨介面", "Replace every occurrence in the scope?": "要取代整個範圍內的所有相符項目嗎?", + "Replaced 1 occurrence in 1 file ({failed} failed, {unsaved} not saved: changed on disk)": "已取代 1 個檔案中的 1 處相符項目({failed} 個失敗,{unsaved} 個未儲存:已在磁碟上更改)", + "Replaced 1 occurrence in 1 file ({unsaved} not saved: changed on disk)": "已取代 1 個檔案中的 1 處相符項目({unsaved} 個未儲存:已在磁碟上更改)", + "Replaced {n} occurrences in 1 file ({failed} failed, {unsaved} not saved: changed on disk)": "已取代 1 個檔案中的 {n} 處相符項目({failed} 個失敗,{unsaved} 個未儲存:已在磁碟上更改)", + "Replaced {n} occurrences in 1 file ({unsaved} not saved: changed on disk)": "已取代 1 個檔案中的 {n} 處相符項目({unsaved} 個未儲存:已在磁碟上更改)", + "Replaced {n} occurrences in {files} files ({failed} failed, {unsaved} not saved: changed on disk)": "已取代 {files} 個檔案中的 {n} 處相符項目({failed} 個失敗,{unsaved} 個未儲存:已在磁碟上更改)", + "Replaced {n} occurrences in {files} files ({unsaved} not saved: changed on disk)": "已取代 {files} 個檔案中的 {n} 處相符項目({unsaved} 個未儲存:已在磁碟上更改)", + "Stopped after replacing 1 occurrence in 1 file ({failed} failed, {unsaved} not saved: changed on disk)": "已停止,已取代 1 個檔案中的 1 處相符項目({failed} 個失敗,{unsaved} 個未儲存:已在磁碟上更改)", + "Stopped after replacing 1 occurrence in 1 file ({unsaved} not saved: changed on disk)": "已停止,已取代 1 個檔案中的 1 處相符項目({unsaved} 個未儲存:已在磁碟上更改)", + "Stopped after replacing {n} occurrences in 1 file ({failed} failed, {unsaved} not saved: changed on disk)": "已停止,已取代 1 個檔案中的 {n} 處相符項目({failed} 個失敗,{unsaved} 個未儲存:已在磁碟上更改)", + "Stopped after replacing {n} occurrences in 1 file ({unsaved} not saved: changed on disk)": "已停止,已取代 1 個檔案中的 {n} 處相符項目({unsaved} 個未儲存:已在磁碟上更改)", + "Stopped after replacing {n} occurrences in {files} files ({failed} failed, {unsaved} not saved: changed on disk)": "已停止,已取代 {files} 個檔案中的 {n} 處相符項目({failed} 個失敗,{unsaved} 個未儲存:已在磁碟上更改)", + "Stopped after replacing {n} occurrences in {files} files ({unsaved} not saved: changed on disk)": "已停止,已取代 {files} 個檔案中的 {n} 處相符項目({unsaved} 個未儲存:已在磁碟上更改)", "The search hit its limit, so it runs again to find any additional matches.": "搜尋已達上限,將重新搜尋以找出其餘相符項目。", "Review": "審查", "Commit and Push…": "提交併推送…", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index b9609fc196..39dedc90f2 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -4219,6 +4219,18 @@ "1 occurrence in {files} files": "{files} 个文件中的 1 处匹配项", "{occurrences} occurrences in 1 file": "1 个文件中的 {occurrences} 处匹配项", "{occurrences} occurrences in {files} files": "{files} 个文件中的 {occurrences} 处匹配项", + "Replaced 1 occurrence in 1 file ({failed} failed, {unsaved} not saved: changed on disk)": "已替换 1 个文件中的 1 处匹配项({failed} 个失败,{unsaved} 个未保存:已在磁盘上更改)", + "Replaced 1 occurrence in 1 file ({unsaved} not saved: changed on disk)": "已替换 1 个文件中的 1 处匹配项({unsaved} 个未保存:已在磁盘上更改)", + "Replaced {n} occurrences in 1 file ({failed} failed, {unsaved} not saved: changed on disk)": "已替换 1 个文件中的 {n} 处匹配项({failed} 个失败,{unsaved} 个未保存:已在磁盘上更改)", + "Replaced {n} occurrences in 1 file ({unsaved} not saved: changed on disk)": "已替换 1 个文件中的 {n} 处匹配项({unsaved} 个未保存:已在磁盘上更改)", + "Replaced {n} occurrences in {files} files ({failed} failed, {unsaved} not saved: changed on disk)": "已替换 {files} 个文件中的 {n} 处匹配项({failed} 个失败,{unsaved} 个未保存:已在磁盘上更改)", + "Replaced {n} occurrences in {files} files ({unsaved} not saved: changed on disk)": "已替换 {files} 个文件中的 {n} 处匹配项({unsaved} 个未保存:已在磁盘上更改)", + "Stopped after replacing 1 occurrence in 1 file ({failed} failed, {unsaved} not saved: changed on disk)": "已停止,已替换 1 个文件中的 1 处匹配项({failed} 个失败,{unsaved} 个未保存:已在磁盘上更改)", + "Stopped after replacing 1 occurrence in 1 file ({unsaved} not saved: changed on disk)": "已停止,已替换 1 个文件中的 1 处匹配项({unsaved} 个未保存:已在磁盘上更改)", + "Stopped after replacing {n} occurrences in 1 file ({failed} failed, {unsaved} not saved: changed on disk)": "已停止,已替换 1 个文件中的 {n} 处匹配项({failed} 个失败,{unsaved} 个未保存:已在磁盘上更改)", + "Stopped after replacing {n} occurrences in 1 file ({unsaved} not saved: changed on disk)": "已停止,已替换 1 个文件中的 {n} 处匹配项({unsaved} 个未保存:已在磁盘上更改)", + "Stopped after replacing {n} occurrences in {files} files ({failed} failed, {unsaved} not saved: changed on disk)": "已停止,已替换 {files} 个文件中的 {n} 处匹配项({failed} 个失败,{unsaved} 个未保存:已在磁盘上更改)", + "Stopped after replacing {n} occurrences in {files} files ({unsaved} not saved: changed on disk)": "已停止,已替换 {files} 个文件中的 {n} 处匹配项({unsaved} 个未保存:已在磁盘上更改)", "Replace 1 occurrence in 1 file?": "替换 1 个文件中的 1 处匹配项吗?", "Replace {usages} occurrences in 1 file?": "替换 1 个文件中的 {usages} 处匹配项吗?", "Replace {usages} occurrences in {files} files?": "替换 {files} 个文件中的 {usages} 处匹配项吗?",