From 0bda7b194bc8a5de8080a5d363b15aefdc308af9 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Thu, 3 Dec 2026 19:28:08 +0800 Subject: [PATCH] fix(svn): report the files an update changed instead of "All files are up-to-date" (#7797) An update of a Subversion working copy has no commit range, so the update result always said all files were up to date, even when svn update changed files. Backend::update now returns how many files and folders the update added, deleted, changed or merged (read from svn update's status lines), vcs_remote returns it as an update report, and the result reads "N files updated". Covers Update Project and Update File / Update Directory. --- crates/ide-host/src/ops/vcs/commands.rs | 15 ++++++- crates/ide-host/tests/svn.rs | 9 +++- crates/ide-host/tests/vcs_backends.rs | 6 +-- crates/ide-svn/src/backend.rs | 6 +-- crates/ide-svn/src/ops.rs | 41 ++++++++++++++++++- crates/ide-vcs/src/backend.rs | 5 ++- src/bindings.ts | 10 ++++- .../vcs/__tests__/svnUpdateFiles.test.ts | 20 ++++++++- src/features/vcs/ops.ts | 25 +++++++---- src/platform/locales/text/zh.json | 1 + 10 files changed, 115 insertions(+), 23 deletions(-) diff --git a/crates/ide-host/src/ops/vcs/commands.rs b/crates/ide-host/src/ops/vcs/commands.rs index 8e0e026eb..0a935d665 100644 --- a/crates/ide-host/src/ops/vcs/commands.rs +++ b/crates/ide-host/src/ops/vcs/commands.rs @@ -350,6 +350,15 @@ pub enum RemoteOp { pub enum RemoteOpReport { Push(PushReport), Fetch(FetchReport), + Update(UpdateReport), +} + +/// What an update of a non-Git working copy (`svn update`) changed. +#[derive(Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct UpdateReport { + /// Files and folders added, deleted, changed or merged. + pub updated_files: u32, } #[derive(Serialize, Deserialize, Type)] @@ -1991,7 +2000,11 @@ pub async fn vcs_remote( { let result = with_shelf_batch(&project, shelf_batch, || { project.with_backend_recorded(repo.as_deref(), Some("Update"), |b| { - b.update(paths, &cancel, &out).map(|()| None) + b.update(paths, &cancel, &out).map(|changed| { + Some(RemoteOpReport::Update(UpdateReport { + updated_files: u32::try_from(changed).unwrap_or(u32::MAX), + })) + }) }) }); // An update brings or takes away externals (working copies of their own): the roots diff --git a/crates/ide-host/tests/svn.rs b/crates/ide-host/tests/svn.rs index 31b455ddb..fb198026e 100644 --- a/crates/ide-host/tests/svn.rs +++ b/crates/ide-host/tests/svn.rs @@ -1172,9 +1172,14 @@ async fn update_selected_paths_of_two_working_copies() { let op = vcs::RemoteOp::UpdateFiles { paths }; vcs::vcs_remote(&host, "main", Some(repo.to_path_buf()), ide_core::RequestId::next(), op, channel, None) }; + let updated_files = |report: Option| match report { + Some(vcs::RemoteOpReport::Update(report)) => report.updated_files, + _ => panic!("no update report"), + }; // A file and a folder of one working copy, one file of the other. - update(&boot, vec![boot.join("a.txt"), boot.join("dir")]).await.unwrap(); - update(&antd, vec![antd.join("c.txt")]).await.unwrap(); + assert_eq!(updated_files(update(&boot, vec![boot.join("a.txt"), boot.join("dir")]).await.unwrap()), 2); + assert_eq!(updated_files(update(&antd, vec![antd.join("c.txt")]).await.unwrap()), 1); + assert_eq!(updated_files(update(&antd, vec![antd.join("c.txt")]).await.unwrap()), 0, "already up to date"); let read = |path: PathBuf| std::fs::read_to_string(path).unwrap(); assert_eq!( [read(boot.join("a.txt")), read(boot.join("dir/b.txt")), read(boot.join("c.txt"))], diff --git a/crates/ide-host/tests/vcs_backends.rs b/crates/ide-host/tests/vcs_backends.rs index a042b2d24..32dd6b90b 100644 --- a/crates/ide-host/tests/vcs_backends.rs +++ b/crates/ide-host/tests/vcs_backends.rs @@ -44,10 +44,10 @@ impl Backend for Fake { fn head_label(&self) -> Option { Some(self.head.lock().clone()) } - fn update(&self, _: &[PathBuf], _: &CancellationToken, output: &dyn Fn(String)) -> IdeResult<()> { + fn update(&self, _: &[PathBuf], _: &CancellationToken, output: &dyn Fn(String)) -> IdeResult { std::fs::write(self.root.join("a.txt"), "updated\n")?; output("Updated to revision 8.".into()); - Ok(()) + Ok(1) } fn branches(&self) -> IdeResult> { let head = self.head.lock().clone(); @@ -347,7 +347,7 @@ async fn a_working_copy_answers_the_shared_vcs_commands() { let channel = ide_host::ops::Channel::new(move |line: String| lines.lock().push(line)); let op = vcs::RemoteOp::UpdateProjectBranch { rebase: false }; let report = vcs::vcs_remote(&host, "main", None, ide_core::RequestId::next(), op, channel, None).await.unwrap(); - assert!(report.is_none()); + assert!(matches!(report, Some(vcs::RemoteOpReport::Update(vcs::UpdateReport { updated_files: 1 })))); assert_eq!(*output.lock(), ["Updated to revision 8."]); assert_eq!(std::fs::read_to_string(&file).unwrap(), "updated\n"); let labels: Vec = project.history.list(&file).unwrap().into_iter().map(|e| e.label).collect(); diff --git a/crates/ide-svn/src/backend.rs b/crates/ide-svn/src/backend.rs index 95b0adb8a..944b08624 100644 --- a/crates/ide-svn/src/backend.rs +++ b/crates/ide-svn/src/backend.rs @@ -1350,10 +1350,10 @@ impl Backend for WorkingCopy { /// Update Project, Update File / Update Directory: `svn update` of the whole working copy /// or of `paths`. Conflicts stay for the merge editor. - fn update(&self, paths: &[PathBuf], cancel: &CancellationToken, output: &dyn Fn(String)) -> IdeResult<()> { - let revision = WorkingCopy::update(self, paths, None, cancel)?; + fn update(&self, paths: &[PathBuf], cancel: &CancellationToken, output: &dyn Fn(String)) -> IdeResult { + let (revision, changed) = WorkingCopy::update_counted(self, paths, None, cancel)?; output(format!("Updated to revision {revision}.")); - Ok(()) + Ok(changed) } fn branches(&self) -> IdeResult> { diff --git a/crates/ide-svn/src/ops.rs b/crates/ide-svn/src/ops.rs index 0e9164f99..c1cb614a9 100644 --- a/crates/ide-svn/src/ops.rs +++ b/crates/ide-svn/src/ops.rs @@ -188,6 +188,25 @@ impl Depth { } } +/// The items an `svn update` changed: its lines of four status columns (contents, +/// properties, lock, tree conflict) and a path, as `U a.txt`, ` U dir`, ` C b.txt`. +/// A broken lock alone (` B a.txt`) changes nothing in the working copy. +pub(crate) fn updated_items(output: &str) -> usize { + output + .lines() + .filter(|line| match line.as_bytes() { + [text, props, lock, tree, b' ', _, ..] => { + b"ADUCGER ".contains(text) + && b"UCG ".contains(props) + && b" B".contains(lock) + && b" C".contains(tree) + && (*text != b' ' || *props != b' ' || *tree != b' ') + } + _ => false, + }) + .count() +} + /// The revision `svn update` / `switch` / `checkout` reports reaching: `At /// revision 7.`, `Updated to revision 7.`, `Checked out revision 7.`, and per /// target `Updated 'a' to r7.` @@ -272,11 +291,23 @@ impl WorkingCopy { /// (`None` = the newest); returns the revision reached. Conflicts are left /// for [`resolve`](Self::resolve). pub fn update(&self, paths: &[PathBuf], revision: Option<&str>, cancel: &CancellationToken) -> IdeResult { + self.update_counted(paths, revision, cancel).map(|(revision, _)| revision) + } + + /// [`update`](Self::update), also returning how many files and folders it changed. + pub fn update_counted( + &self, + paths: &[PathBuf], + revision: Option<&str>, + cancel: &CancellationToken, + ) -> IdeResult<(u64, usize)> { let mut argv = args(["update", "--accept", "postpone", "-r", revision.unwrap_or("HEAD")]); argv.extend(targets(&self.paths_or_root(paths)?)); let out = String::from_utf8_lossy(&self.remote(&argv, Some(cancel))?).into_owned(); let _ = self.refresh(); - reached_revision(&out).ok_or_else(|| IdeError::internal(format!("unexpected `svn update` output: {out}"))) + let reached = reached_revision(&out) + .ok_or_else(|| IdeError::internal(format!("unexpected `svn update` output: {out}")))?; + Ok((reached, updated_items(&out))) } /// `svn cleanup`: finishes or rolls back an interrupted operation and releases its lock. @@ -974,6 +1005,14 @@ mod tests { assert_eq!(property_conflicts(deleted)[0].mine, None); } + #[test] + fn counts_updated_items() { + let out = "Updating '.':\nU a.txt\nA src\nA src/c.txt\n U b.txt\n C d.txt\n B e.txt\nD old\nUpdated to revision 7.\nSummary of conflicts:\n Tree conflicts: 1\n"; + assert_eq!(updated_items(out), 6); + assert_eq!(updated_items("Updating '.':\nAt revision 6.\n"), 0); + assert_eq!(updated_items("Updating 'a.txt':\nRestored 'a.txt'\nAt revision 6.\n"), 0); + } + #[test] fn reads_reached_revision() { assert_eq!(reached_revision("Updating '.':\nU a.txt\nUpdated to revision 7.\n"), Some(7)); diff --git a/crates/ide-vcs/src/backend.rs b/crates/ide-vcs/src/backend.rs index 9d61e99e5..576dd15d0 100644 --- a/crates/ide-vcs/src/backend.rs +++ b/crates/ide-vcs/src/backend.rs @@ -218,8 +218,9 @@ pub trait Backend: Send + Sync + Any { /// Update Project (`vcs.update`): brings the working copy up to date with the /// server (`svn update`, `p4 sync`), sending output lines to `output`. `paths` /// limits it to those files and folders (Update File / Update Directory); empty - /// is the whole working copy. Git's pull stays on [`Repo`]. - fn update(&self, _paths: &[PathBuf], _cancel: &CancellationToken, _output: &dyn Fn(String)) -> IdeResult<()> { + /// is the whole working copy. Returns how many files and folders it changed. + /// Git's pull stays on [`Repo`]. + fn update(&self, _paths: &[PathBuf], _cancel: &CancellationToken, _output: &dyn Fn(String)) -> IdeResult { Err(IdeError::unavailable("this version control system cannot update the working copy")) } diff --git a/src/bindings.ts b/src/bindings.ts index b4e0445ff..1b77c0e4c 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -2736,7 +2736,7 @@ export const commands = { branch: string | null, commit: string, } | null, IdeError>(__TAURI_INVOKE("vcs_rebase_with_editor", { repo, operation, request, onOutput, onEdit, expectedRebase })), - vcsRemote: (repo: string | null, request: RequestId, op: RemoteOp, onOutput: Channel, shelfBatch: string | null) => typedError(__TAURI_INVOKE("vcs_remote", { repo, request, op, onOutput, shelfBatch })), + vcsRemote: (repo: string | null, request: RequestId, op: RemoteOp, onOutput: Channel, shelfBatch: string | null) => typedError(__TAURI_INVOKE("vcs_remote", { repo, request, op, onOutput, shelfBatch })), vcsRemotes: (repo: string | null) => typedError(__TAURI_INVOKE("vcs_remotes", { repo })), vcsRemoveWorktree: (repo: string | null, path: string, force: boolean) => typedError(__TAURI_INVOKE("vcs_remove_worktree", { repo, path, force })), vcsRenameBranch: (repo: string | null, from: string, to: string, unsetUpstream: boolean) => typedError(__TAURI_INVOKE("vcs_rename_branch", { repo, from, to, unsetUpstream })), @@ -15607,7 +15607,7 @@ set_upstream?: boolean; no_verify?: boolean } | /** Explicit rebase or merge. Null uses Git's configured pull behavior. */ rebase: boolean | null; options: MergeOptions }; -export type RemoteOpReport = PushReport | FetchReport; +export type RemoteOpReport = PushReport | FetchReport | UpdateReport; export type RemoteProgress = { stage: RemoteStage, @@ -18277,6 +18277,12 @@ export type UpdateProgress = /** Download done; the new version is being written over this one. */ { type: "installing" }; +/** What an update of a non-Git working copy (`svn update`) changed. */ +export type UpdateReport = { + /** Files and folders added, deleted, changed or merged. */ + updatedFiles: number, +}; + export type UpdateSource = "github" | "cnb"; export type UpdateStatus = { diff --git a/src/features/vcs/__tests__/svnUpdateFiles.test.ts b/src/features/vcs/__tests__/svnUpdateFiles.test.ts index 17a4c94e1..6fccd1b61 100644 --- a/src/features/vcs/__tests__/svnUpdateFiles.test.ts +++ b/src/features/vcs/__tests__/svnUpdateFiles.test.ts @@ -6,6 +6,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { RemoteOp } from "@/bindings"; const updates: Array<{ repo: string | null; op: RemoteOp }> = []; +/** Files `svn update` reports changing, per working copy. */ +const changed: Record = {}; +const notified: string[] = []; vi.mock("@tauri-apps/api/core", async (importOriginal) => ({ ...(await importOriginal()), @@ -22,7 +25,7 @@ vi.mock("@/platform/ipc", async (importOriginal) => { ...real.commands, vcsRemote: async (repo: string | null, _request: unknown, op: RemoteOp) => { updates.push({ repo, op }); - return { status: "ok", data: null }; + return { status: "ok", data: repo === null ? null : { updatedFiles: changed[repo] ?? 0 } }; }, vcsMergeBase: async () => ({ status: "error", error: { kind: "invalid", message: "no upstream" } }), vcsBranchInfo: async () => ({ status: "error", error: { kind: "invalid", message: "not Git" } }), @@ -41,12 +44,14 @@ import { svnUpdateFiles } from "../svn"; const [boot, antd, git] = ["/w/boot", "/w/antd", "/w/git"]; beforeEach(() => { - provideNotificationService({ notify: () => {}, expire: () => {} }); + provideNotificationService({ notify: (n) => void notified.push(n.title), expire: () => {} }); useVcs.setState({ roots: [boot, antd, git], root: "/w", kinds: { [boot]: "subversion", [antd]: "subversion" } }); }); afterEach(() => { updates.length = 0; + notified.length = 0; + for (const repo of Object.keys(changed)) delete changed[repo]; useVcs.setState({ remoteBusy: null, roots: [], root: null, status: [], kinds: {} }); useNotifications.setState({ items: [] }); }); @@ -82,4 +87,15 @@ describe("Subversion › Update File / Update Directory", () => { await svnUpdateFiles([`${git}/x.txt`]); expect(updates).toEqual([]); }); + + it("reports the files the updates changed, across working copies", async () => { + Object.assign(changed, { [boot]: 2, [antd]: 1 }); + await svnUpdateFiles([`${boot}/a.txt`, `${boot}/src`, `${antd}/b.txt`]); + expect(notified.at(-1)).toBe("3 files updated"); + }); + + it("says the files are up to date when an update changed none", async () => { + await svnUpdateFiles([`${boot}/a.txt`]); + expect(notified.at(-1)).toBe("All files are up-to-date"); + }); }); diff --git a/src/features/vcs/ops.ts b/src/features/vcs/ops.ts index dfaee9dc8..c49990a80 100644 --- a/src/features/vcs/ops.ts +++ b/src/features/vcs/ops.ts @@ -360,6 +360,8 @@ export async function runRemoteRound( // repositories that have nothing to pull from (detached HEAD, e.g. submodules; no upstream). const failures: RemoteFailure[] = []; const updated: UpdatedRange[] = []; + // Files an update of a non-Git working copy (`svn update`) changed; it has no commit range. + let workingCopyFiles = 0; const pushed: RepoPushOutcome[] = []; const fetched: Array = []; let hasFetchReport = false; @@ -483,7 +485,8 @@ export async function runRemoteRound( const firstError = errors[0]; if (firstError) throw new IpcError({ ...firstError, message: errors.map(({ message }) => message).join("\n") }); - } else if (report) recordPush(root, describePush(report)); + } else if (report && "updatedFiles" in report) workingCopyFiles += report.updatedFiles; + else if (report) recordPush(root, describePush(report)); else if (isPush(op)) { const fallback = op.op === "pushTag" ? tx`Pushed tag ${op.tag} to ${op.remote}` : tx("Push successful"); recordPush(root, [legacyPush ?? fallback]); @@ -591,7 +594,8 @@ export async function runRemoteRound( actions: actions.length ? actions : undefined, }); } - if (!reported && isUpdate(first) && updated.length) await notifyUpdated(updated, "vcs.remote.updated"); + if (!reported && isUpdate(first) && (updated.length || workingCopyFiles)) + await notifyUpdated(updated, "vcs.remote.updated", workingCopyFiles); return failures; } if (restoreError !== null) { @@ -602,7 +606,7 @@ export async function runRemoteRound( lastRemoteError = null; if (detached === targets.length) notify({ level: "info", key: "vcs.remote", title: "Nothing to update" }); else if (isUpdate(first)) { - await notifyUpdated(updated); + await notifyUpdated(updated, "vcs.remote", workingCopyFiles); // An update that leaves conflicts and still succeeds (`svn update --accept postpone`; a // conflicted Git pull fails instead, above) opens the conflicts as a pull does. if (targets.some(({ repo }) => vcsKindOf(repo ?? primary) !== "git")) await refreshNow(); @@ -806,14 +810,17 @@ async function openUpdateInfo(updated: readonly UpdatedRange[]) { toolWindowService().show("git", true); } -/** IDEA's Update Project result: "N files updated in M commits" with View Commits. */ -export async function notifyUpdated(updated: readonly UpdatedRange[], key = "vcs.remote") { +/** + * Update Project's result: "N files updated in M commits" with View Commits, or "N files + * updated" for working copies of other systems (`workingCopyFiles`), which have no commit range. + */ +export async function notifyUpdated(updated: readonly UpdatedRange[], key = "vcs.remote", workingCopyFiles = 0) { const project = useProject.getState().project; - if (!updated.length) { + if (!updated.length && !workingCopyFiles) { notify({ level: "info", key, title: "All files are up-to-date" }); return; } - let files = 0; + let files = workingCopyFiles; let commits = 0; await Promise.all( updated.map(async ({ repo, from, to }) => { @@ -836,6 +843,10 @@ export async function notifyUpdated(updated: readonly UpdatedRange[], key = "vcs }), ); if (useProject.getState().project !== project) return; + if (!updated.length) { + notify({ level: "info", key, title: `${filesText(files)} updated` }); + return; + } notify({ level: "info", key, diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 44dc037aa..457561f5e 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -5731,6 +5731,7 @@ "Label '{value}' added to Local History": "已将标签 '{value}' 添加到本地历史记录", "{doneTitle} successful": "{doneTitle}成功", "{file} updated in {commit}": "已在 {commit}中更新 {file}", + "{file} updated": "已更新 {file}", "Shelved {length} file": "已搁置 {length} 个文件", "Shelved {length} files": "已搁置 {length} 个文件", "{what}: {length} file with conflicts": "{what}:{length} 个文件存在冲突",