From 0a7a292d826d562bdda4887c79a50caa016d07fc Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Sun, 22 Nov 2026 01:16:19 +0900 Subject: [PATCH] feat(vcs): synchronize compared directories with per-row operations (#4974) Each Compare Directories row carries IDEA's synchronisation operation in the marker column: copy to the right, copy to the left, delete (one-sided entries) or do nothing; Space or a click cycles it. Synchronize Selected and Synchronize All run the operations as one batch after a single confirmation counting deletions and overwrites. The new fs_synchronize_directories command validates every path, runs the operations on the blocking pool through the existing copy/merge and delete paths (Local History, VCS delete hooks), continues past failures and returns them; cancelling stops before the next entry. The per-row operations replace the single-entry Copy to Left / Copy to Right / Delete buttons. Refs #3925 Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com> --- crates/ide-host/src/ops/fs.rs | 144 ++++++++--- crates/ide-host/tests/directory_sync.rs | 112 +++++++++ crates/ide-vfs/src/compare.rs | 36 +++ crates/ide-vfs/src/lib.rs | 4 +- src-tauri/tests/commands.snap | 1 + src/bindings.ts | 28 +++ src/features/vcs/DirectoryCompare.module.css | 21 ++ src/features/vcs/DirectoryCompare.tsx | 223 +++++++++++++----- .../vcs/__tests__/directoryCompare.test.tsx | 129 +++++----- src/platform/locales/text/es.json | 3 - src/platform/locales/text/fr.json | 3 - src/platform/locales/text/ko.json | 3 - src/platform/locales/text/pl.json | 3 - src/platform/locales/text/pt.json | 3 - src/platform/locales/text/tr.json | 3 - src/platform/locales/text/zh-TW.json | 3 - src/platform/locales/text/zh.json | 6 +- 17 files changed, 541 insertions(+), 184 deletions(-) create mode 100644 crates/ide-host/tests/directory_sync.rs diff --git a/crates/ide-host/src/ops/fs.rs b/crates/ide-host/src/ops/fs.rs index f008048ea..b157eee0b 100644 --- a/crates/ide-host/src/ops/fs.rs +++ b/crates/ide-host/src/ops/fs.rs @@ -1,5 +1,5 @@ use super::Channel; -use crate::Host; +use crate::{Host, Project}; use ide_command::command; use ide_core::{IdeError, IdeResult, RequestId}; use ide_vfs::FileEntry; @@ -51,6 +51,37 @@ pub async fn fs_compare_directories( result } +fn comparison_entry_path(path: &Path) -> IdeResult<()> { + if path.as_os_str().is_empty() || path.components().any(|c| !matches!(c, std::path::Component::Normal(_))) { + return Err(IdeError::invalid("expected a relative comparison entry path")); + } + Ok(()) +} + +fn copy_entry( + project: &Project, + source_root: &Path, + destination_root: &Path, + path: &Path, + overwrite: bool, +) -> IdeResult<()> { + let from = source_root.join(path); + let to = destination_root.join(path); + if overwrite { + project.history.record_deletion(&to, DELETE_SNAPSHOT_LIMIT); + } + project.with_disk_sync(|| { + ide_vfs::copy_merge( + &from, + &to, + overwrite, + Some(&project.root), + &project.exclude_globs(), + (source_root, destination_root), + ) + }) +} + #[command(trust = always)] pub async fn fs_copy_merge( host: &Host, @@ -60,28 +91,63 @@ pub async fn fs_copy_merge( path: PathBuf, overwrite: bool, ) -> IdeResult<()> { - if path.as_os_str().is_empty() || path.components().any(|c| !matches!(c, std::path::Component::Normal(_))) { - return Err(ide_core::IdeError::invalid("expected a relative comparison entry path")); + comparison_entry_path(&path)?; + let project = host.project(window)?; + host.blocking(move || copy_entry(&project, &source_root, &destination_root, &path, overwrite)).await +} + +/// Runs Compare Directories' synchronisation operations in order. A failed operation is +/// reported and the rest still run; cancellation stops before the next one. +#[command(trust = always)] +pub async fn fs_synchronize_directories( + host: &Host, + window: &str, + left: PathBuf, + right: PathBuf, + operations: Vec, + request: RequestId, + on_progress: Channel, +) -> IdeResult> { + for op in &operations { + comparison_entry_path(Path::new(&op.path))?; } let project = host.project(window)?; - host.blocking(move || { - let from = source_root.join(&path); - let to = destination_root.join(&path); - if overwrite { - project.history.record_deletion(&to, DELETE_SNAPSHOT_LIMIT); - } - project.with_disk_sync(|| { - ide_vfs::copy_merge( - &from, - &to, - overwrite, - Some(&project.root), - &project.exclude_globs(), - (&source_root, &destination_root), - ) + let cancel = host.begin_request(request); + let result = host + .blocking(move || { + use ide_vfs::DirectorySyncAction::*; + let total = operations.len() as u32; + let mut failures = Vec::new(); + for (done, op) in operations.into_iter().enumerate() { + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + let _ = on_progress.send(ide_vfs::DirectorySyncProgress { + done: done as u32, + total, + path: op.path.clone(), + }); + let path = Path::new(&op.path); + let result = match op.action { + CopyToLeft => copy_entry(&project, &right, &left, path, op.overwrite), + CopyToRight => copy_entry(&project, &left, &right, path, op.overwrite), + DeleteLeft => delete_recorded(Some(&project), &left.join(path), false).map(|_| ()), + DeleteRight => delete_recorded(Some(&project), &right.join(path), false).map(|_| ()), + }; + if let Err(e) = result { + failures.push(ide_vfs::DirectorySyncFailure { + path: op.path, + action: op.action, + message: e.message, + }); + } + } + let _ = on_progress.send(ide_vfs::DirectorySyncProgress { done: total, total, path: String::new() }); + Ok(failures) }) - }) - .await + .await; + host.end_request(request); + result } /// Files of a deleted folder snapshotted in Local History. @@ -186,26 +252,27 @@ pub async fn fs_delete_with_undo(host: &Host, window: &str, path: PathBuf) -> Id async fn delete_with_history(host: &Host, window: &str, path: PathBuf, undoable: bool) -> IdeResult { let project = if undoable { Some(host.project(window)?) } else { host.project(window).ok() }; - host.blocking(move || { - let paths = ide_workspace::file_ops::deletion_paths(&path)?; - let mut undo = DeletionUndo::default(); - if let Some(p) = &project { - if undoable { - undo = p.history.capture_deletion_undo(&paths, DELETE_SNAPSHOT_LIMIT); - } else { - for pth in &paths { - p.history.record_deletion(pth, DELETE_SNAPSHOT_LIMIT); - } + host.blocking(move || delete_recorded(project.as_deref(), &path, undoable)).await +} + +fn delete_recorded(project: Option<&Project>, path: &Path, undoable: bool) -> IdeResult { + let paths = ide_workspace::file_ops::deletion_paths(path)?; + let mut undo = DeletionUndo::default(); + if let Some(p) = project { + if undoable { + undo = p.history.capture_deletion_undo(&paths, DELETE_SNAPSHOT_LIMIT); + } else { + for pth in &paths { + p.history.record_deletion(pth, DELETE_SNAPSHOT_LIMIT); } } - ide_workspace::file_ops::delete(&path)?; - // A checkout backend opens the paths for delete; Git's hook is a no-op. - if let Some(p) = project { - let _ = p.with_backend_of(&path, |r| r.files_deleted(&paths)); - } - Ok(undo) - }) - .await + } + ide_workspace::file_ops::delete(path)?; + // A checkout backend opens the paths for delete; Git's hook is a no-op. + if let Some(p) = project { + let _ = p.with_backend_of(path, |r| r.files_deleted(&paths)); + } + Ok(undo) } #[command(trust = always)] @@ -317,5 +384,6 @@ ide_command::domain!( fs_read_text, fs_rename, fs_set_writable, + fs_synchronize_directories, fs_undo_delete, ); diff --git a/crates/ide-host/tests/directory_sync.rs b/crates/ide-host/tests/directory_sync.rs new file mode 100644 index 000000000..0cb73c0cd --- /dev/null +++ b/crates/ide-host/tests/directory_sync.rs @@ -0,0 +1,112 @@ +use ide_core::{NullSink, RequestId}; +use ide_host::{ + Host, HostConfig, + ops::{Channel, fs::fs_synchronize_directories}, +}; +use ide_vfs::{DirectorySyncAction as Action, DirectorySyncOperation, DirectorySyncProgress}; +use parking_lot::Mutex; +use std::{fs, path::Path, sync::Arc}; + +fn put(root: &Path, path: &str, content: &str) { + let path = root.join(path); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, content).unwrap(); +} + +fn op(path: &str, action: Action, overwrite: bool) -> DirectorySyncOperation { + DirectorySyncOperation { path: path.into(), action, overwrite } +} + +fn host(base: &Path) -> Host { + Host::new(HostConfig { + config_dir: base.join("config"), + data_dir: base.join("data"), + local_data_dir: base.join("data"), + languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()), + syntax: Arc::default(), + sink_for: Box::new(|_| Arc::new(NullSink)), + owner: |w| w, + runtime: tokio::runtime::Handle::current(), + project_environment: false, + }) +} + +#[tokio::test(flavor = "multi_thread")] +async fn runs_every_operation_reports_failures_and_stops_when_cancelled() { + let temp = tempfile::tempdir().unwrap(); + let base = dunce::canonicalize(temp.path()).unwrap(); + let root = base.join("project"); + let (left, right) = (root.join("left"), root.join("right")); + put(&left, "only-left/deep/nested/a.txt", "nested"); + put(&left, "changed.txt", "left"); + put(&right, "changed.txt", "right"); + put(&left, "kept.txt", "left"); + put(&right, "kept.txt", "right"); + put(&right, "shared/new.txt", "right"); + fs::create_dir_all(left.join("shared")).unwrap(); + let host = host(&base); + host.trust.decide(&root, true, false).unwrap(); + host.open_project("main", &root).unwrap(); + + let progress = Arc::new(Mutex::new(Vec::::new())); + let seen = progress.clone(); + let channel = Channel::new(move |p| seen.lock().push(p)); + let failures = fs_synchronize_directories( + &host, + "main", + left.clone(), + right.clone(), + vec![ + op("only-left", Action::CopyToRight, false), + // Not confirmed: the destination exists, so this one fails and the rest still run. + op("kept.txt", Action::CopyToRight, false), + op("changed.txt", Action::CopyToLeft, true), + op("shared", Action::CopyToLeft, false), + // A real delete would go to this machine's Trash; a missing entry still fails the same way. + op("missing.txt", Action::DeleteLeft, false), + ], + RequestId::next(), + channel.clone(), + ) + .await + .unwrap(); + assert_eq!(fs::read_to_string(right.join("only-left/deep/nested/a.txt")).unwrap(), "nested"); + assert_eq!(fs::read_to_string(right.join("kept.txt")).unwrap(), "right"); + assert_eq!(fs::read_to_string(left.join("changed.txt")).unwrap(), "right"); + assert_eq!(fs::read_to_string(left.join("shared/new.txt")).unwrap(), "right"); + let failed: Vec<_> = failures.iter().map(|f| (f.path.as_str(), f.action)).collect(); + assert_eq!(failed, [("kept.txt", Action::CopyToRight), ("missing.txt", Action::DeleteLeft)]); + let done: Vec<_> = progress.lock().iter().map(|p| (p.done, p.total)).collect(); + assert_eq!(done, (0..=5).map(|d| (d, 5)).collect::>()); + + // A path outside the roots rejects the whole batch before anything runs. + let error = fs_synchronize_directories( + &host, + "main", + left.clone(), + right.clone(), + vec![op("kept.txt", Action::CopyToRight, true), op("../escape", Action::DeleteLeft, false)], + RequestId::next(), + channel.clone(), + ) + .await + .unwrap_err(); + assert_eq!(error.kind, ide_core::error::ErrorKind::InvalidInput); + assert_eq!(fs::read_to_string(right.join("kept.txt")).unwrap(), "right"); + + let request = RequestId::next(); + host.cancel_request(request); + let error = fs_synchronize_directories( + &host, + "main", + left.clone(), + right.clone(), + vec![op("kept.txt", Action::CopyToRight, true)], + request, + channel, + ) + .await + .unwrap_err(); + assert_eq!(error.kind, ide_core::error::ErrorKind::Cancelled); + assert_eq!(fs::read_to_string(right.join("kept.txt")).unwrap(), "right"); +} diff --git a/crates/ide-vfs/src/compare.rs b/crates/ide-vfs/src/compare.rs index 309b09805..3b815797c 100644 --- a/crates/ide-vfs/src/compare.rs +++ b/crates/ide-vfs/src/compare.rs @@ -63,6 +63,42 @@ pub struct DirectoryCompareProgress { pub path: String, } +/// One row's synchronisation, applied by [`DirectorySyncOperation`] batches. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub enum DirectorySyncAction { + CopyToLeft, + CopyToRight, + DeleteLeft, + DeleteRight, +} + +#[derive(Clone, Debug, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct DirectorySyncOperation { + /// Relative to both comparison roots. + pub path: String, + pub action: DirectorySyncAction, + /// A copy may replace what is already at the destination (confirmed by the user). + pub overwrite: bool, +} + +#[derive(Clone, Debug, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct DirectorySyncFailure { + pub path: String, + pub action: DirectorySyncAction, + pub message: String, +} + +#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct DirectorySyncProgress { + pub done: u32, + pub total: u32, + pub path: String, +} + struct Entry { kind: EntryKind, size: u64, diff --git a/crates/ide-vfs/src/lib.rs b/crates/ide-vfs/src/lib.rs index cec968f58..61eea7e2b 100644 --- a/crates/ide-vfs/src/lib.rs +++ b/crates/ide-vfs/src/lib.rs @@ -27,8 +27,8 @@ pub use bytes::{ read_data_url, read_range, same_share, }; pub use compare::{ - DirectoryCompareEntry, DirectoryCompareMode, DirectoryCompareProgress, DirectoryCompareStatus, compare_directories, - copy_merge, + DirectoryCompareEntry, DirectoryCompareMode, DirectoryCompareProgress, DirectoryCompareStatus, DirectorySyncAction, + DirectorySyncFailure, DirectorySyncOperation, DirectorySyncProgress, compare_directories, copy_merge, }; use encoding::SNIFF_LEN; pub use encoding::{ diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index 21fa81dfa..065a6eaa5 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -283,6 +283,7 @@ fs_read_text always project_host bin fs_rename always project_host bindings async fs_resolve_reference always project_host bindings async fs_set_writable always project_host bindings sync +fs_synchronize_directories always project_host bindings async fs_undo_delete always project_host bindings async gh_account_repos trusted desktop bindings async gh_api trusted desktop bindings async diff --git a/src/bindings.ts b/src/bindings.ts index 153b8024f..842232f69 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -698,6 +698,11 @@ export const commands = { * state). Returns whether the file is read-only now. */ fsSetWritable: (path: string, writable: boolean) => typedError(__TAURI_INVOKE("fs_set_writable", { path, writable })), + /** + * Runs Compare Directories' synchronisation operations in order. A failed operation is + * reported and the rest still run; cancellation stops before the next one. + */ + fsSynchronizeDirectories: (left: string, right: string, operations: DirectorySyncOperation[], request: RequestId, onProgress: Channel) => typedError(__TAURI_INVOKE("fs_synchronize_directories", { left, right, operations, request, onProgress })), fsUndoDelete: (undo: DeletionUndo) => typedError(__TAURI_INVOKE("fs_undo_delete", { undo })), /** The repositories of the account gh is signed in to ("Get from Version Control" › GitHub); needs no project. */ ghAccountRepos: () => typedError(__TAURI_INVOKE("gh_account_repos")), @@ -5367,6 +5372,29 @@ export type DirectoryHistory_Serialize = { deleted: IpcPath[], }; +/** One row's synchronisation, applied by [`DirectorySyncOperation`] batches. */ +export type DirectorySyncAction = "copyToLeft" | "copyToRight" | "deleteLeft" | "deleteRight"; + +export type DirectorySyncFailure = { + path: string, + action: DirectorySyncAction, + message: string, +}; + +export type DirectorySyncOperation = { + /** Relative to both comparison roots. */ + path: string, + action: DirectorySyncAction, + /** A copy may replace what is already at the destination (confirmed by the user). */ + overwrite: boolean, +}; + +export type DirectorySyncProgress = { + done: number, + total: number, + path: string, +}; + /** See [`IdeEvent::Direnv`]. */ export type DirenvStatus = /** `direnv` is not installed (on the search path). */ diff --git a/src/features/vcs/DirectoryCompare.module.css b/src/features/vcs/DirectoryCompare.module.css index 3d26362ad..af70ba746 100644 --- a/src/features/vcs/DirectoryCompare.module.css +++ b/src/features/vcs/DirectoryCompare.module.css @@ -204,3 +204,24 @@ height: var(--h-control-small); font-size: var(--fs-small); } +.sync { + display: inline-flex; + align-items: center; + justify-content: center; + width: 20px; + height: 20px; + border-radius: var(--radius-small); + color: inherit; + opacity: 0.7; +} +.sync.planned { + opacity: 1; + --icon-color: var(--accent); +} +.sync:not(:disabled):hover { + background: var(--bg-toolbar-hover); + opacity: 1; +} +.sync:disabled { + cursor: default; +} diff --git a/src/features/vcs/DirectoryCompare.tsx b/src/features/vcs/DirectoryCompare.tsx index 717176bd4..e9be62256 100644 --- a/src/features/vcs/DirectoryCompare.tsx +++ b/src/features/vcs/DirectoryCompare.tsx @@ -6,8 +6,11 @@ import type { DirectoryCompareMode, DirectoryCompareProgress, DirectoryCompareStatus, + DirectorySyncAction, + DirectorySyncOperation, + DirectorySyncProgress, } from "@/bindings"; -import { call, commands, emitLocalIdeEvent, IpcError, isCancelled, nextRequestId } from "@/platform/ipc"; +import { call, commands, emitLocalIdeEvent, isCancelled, nextRequestId } from "@/platform/ipc"; import { notifyFileOperation } from "@/platform/fileOps"; import { tx, useTx } from "@/platform/i18n"; import { @@ -51,11 +54,6 @@ const FILTERS: { status: DirectoryCompareStatus; title: string; icon: IconName } { status: "equal", title: "Show identical files", icon: "check" }, { status: "rightOnly", title: "Show files only on right", icon: "diff-arrow-left" }, ]; -const MARKER: Partial> = { - leftOnly: "diff-arrow-right", - rightOnly: "diff-arrow-left", - different: "diff", -}; /** IDEA's "Compare by" choices; the last one picked is kept for the next comparison. */ export const COMPARE_MODES: ReadonlyArray<{ value: DirectoryCompareMode; label: string }> = [ { value: "content", label: "Binary content" }, @@ -79,6 +77,44 @@ function saveMode(mode: DirectoryCompareMode) { // ignore } } +/** A row's synchronisation (IDEA's "*" column); `none` leaves the entry alone. */ +export type SyncAction = DirectorySyncAction | "none"; +const SYNC_ICON: Record = { + copyToRight: "diff-arrow-right", + copyToLeft: "diff-arrow-left", + deleteLeft: "trash", + deleteRight: "trash", +}; +const SYNC_LABEL: Record = { + copyToRight: "Copy to Right", + copyToLeft: "Copy to Left", + deleteLeft: "Delete", + deleteRight: "Delete", + none: "Do nothing", +}; + +/** The operations a row cycles through with Space or a click, its default first. */ +export function syncChoices(e: DirectoryCompareEntry): SyncAction[] { + if (!e.rightKind) return ["copyToRight", "deleteLeft", "none"]; + if (!e.leftKind) return ["copyToLeft", "deleteRight", "none"]; + return ["none", "copyToRight", "copyToLeft"]; +} + +/** The batch for these rows, skipping `none`; a copy onto an existing entry overwrites it. */ +export function syncOperations( + entries: readonly DirectoryCompareEntry[], + actionOf: (e: DirectoryCompareEntry) => SyncAction, +): DirectorySyncOperation[] { + const ops: DirectorySyncOperation[] = []; + for (const e of entries) { + const action = actionOf(e); + if (action === "none") continue; + const target = action === "copyToRight" ? e.rightKind : action === "copyToLeft" ? e.leftKind : null; + ops.push({ path: e.path, action, overwrite: !!target }); + } + return ops; +} + const DEFAULT_SHOWN: ReadonlySet = new Set(["leftOnly", "rightOnly", "different"]); const join = (root: string, path: string) => `${root.replace(/\/$/, "")}/${path}`; @@ -199,6 +235,45 @@ function Side({ entry, side, folder }: { entry: DirectoryCompareEntry; side: "le )); } +/** The status marker, and a button that changes the row's operation (IDEA's "*" column). */ +function SyncCell({ + entry, + action, + disabled, + onCycle, +}: { + entry: DirectoryCompareEntry; + action: SyncAction; + disabled: boolean; + onCycle: () => void; +}) { + const t = useTx(); + // Rows left alone keep only the "differ" marker, so a skipped one-sided row shows no arrow. + const icon = action !== "none" ? SYNC_ICON[action] : entry.status === "different" ? "diff" : null; + const label = `${t(STATUS[entry.status])}: ${t(SYNC_LABEL[action])}`; + return ( + + + + ); +} + export function DirectoryCompare({ left, right }: { left: string; right: string }) { const rowHeight = useRowHeight(22); const t = useTx(); @@ -207,6 +282,7 @@ export function DirectoryCompare({ left, right }: { left: string; right: string const [shown, setShown] = useState>(DEFAULT_SHOWN); const [filter, setFilter] = useState(""); const [mode, setMode] = useState(loadMode); + const [actions, setActions] = useState>(new Map()); const [generation, setGeneration] = useState(0); const [busy, setBusy] = useState(true); const [operating, setOperating] = useState(false); @@ -249,6 +325,7 @@ export function DirectoryCompare({ left, right }: { left: string; right: string .then((rows) => { if (!alive) return; setEntries(rows); + setActions(new Map()); setCurrent((prev) => rows.find((e) => e.path === prev?.path) ?? null); }) .catch((e) => { @@ -292,57 +369,91 @@ export function DirectoryCompare({ left, right }: { left: string; right: string if (data) void openVcsDiff(data); }; - const operate = async (side: "left" | "right" | "delete") => { - if (!selected || busy || operating) return; + const actionOf = (e: DirectoryCompareEntry) => actions.get(e.path) ?? syncChoices(e)[0]!; + const cycle = (e: DirectoryCompareEntry) => { + if (busy || operating) return; + const choices = syncChoices(e); + const next = choices[(choices.indexOf(actionOf(e)) + 1) % choices.length]!; + setActions((m) => new Map(m).set(e.path, next)); + }; + const visible = rows.flatMap((r) => ("entry" in r ? [r.entry] : [])); + + const synchronize = async (targets: readonly DirectoryCompareEntry[]) => { + const ops = syncOperations(targets, actionOf); + if (!ops.length || busy || operating) return; + const deletes = ops.filter((o) => o.action === "deleteLeft" || o.action === "deleteRight").length; + const overwrites = ops.filter((o) => o.overwrite).length; + const count = ops.length; + if ( + (deletes || overwrites) && + !(await confirmDialog({ + title: "Synchronize", + message: tx`Synchronize ${count} entries? ${deletes} will be deleted and ${overwrites} overwritten.`, + okLabel: "Synchronize", + danger: true, + })) + ) + return; setOperating(true); setOperationError(null); - let attempted = false; - const targetRoot = side === "left" ? left : right; + const request = nextRequestId(); + const task = { + id: `directory-sync-${request}`, + title: tx("Synchronizing directories"), + message: null as string | null, + fraction: null as number | null, + cancel: () => { + void commands.cancelRequest(request); + }, + }; + upsertTask({ ...task, done: false }); + const channel = new Channel(); + channel.onmessage = (p) => { + task.message = p.path; + task.fraction = p.total ? p.done / p.total : null; + upsertTask({ ...task, done: false }); + }; try { - if (side === "delete") { - if (!!selected.leftKind === !!selected.rightKind) return; - const path = join(selected.leftKind ? left : right, selected.path); - if (!(await confirmDialog({ title: "Delete", message: tx`Delete ${path}?`, okLabel: "Delete", danger: true }))) - return; - attempted = true; - await call(commands.fsDelete(path)); - notifyFileOperation({ kind: "deleted", paths: [path] }); - emitLocalIdeEvent({ type: "fsChanged", created: [], modified: [], removed: [path] }); - } else { - const sourceRoot = side === "left" ? right : left; - const to = join(targetRoot, selected.path); - try { - attempted = true; - await call(commands.fsCopyMerge(sourceRoot, targetRoot, selected.path, false)); - } catch (e) { - if (!(e instanceof IpcError) || e.kind !== "alreadyExists") throw e; - if ( - !(await confirmDialog({ - title: "Overwrite files?", - message: tx`Copy to ${to} and overwrite existing files?`, - okLabel: "Overwrite", - danger: true, - })) - ) - return; - await call(commands.fsCopyMerge(sourceRoot, targetRoot, selected.path, true)); - } - notifyFileOperation({ kind: "created", paths: [to] }); - emitLocalIdeEvent({ type: "fsChanged", created: [to], modified: [to], removed: [] }); + const failures = await call(commands.fsSynchronizeDirectories(left, right, ops, request, channel)); + const failed = new Set(failures.map((f) => f.path)); + const created: string[] = []; + const removed: string[] = []; + for (const o of ops) { + if (failed.has(o.path)) continue; + if (o.action === "copyToLeft") created.push(join(left, o.path)); + else if (o.action === "copyToRight") created.push(join(right, o.path)); + else removed.push(join(o.action === "deleteLeft" ? left : right, o.path)); } + if (created.length) notifyFileOperation({ kind: "created", paths: created }); + if (removed.length) notifyFileOperation({ kind: "deleted", paths: removed }); + if (created.length || removed.length) + emitLocalIdeEvent({ type: "fsChanged", created, modified: created, removed }); + if (failures.length && mounted.current) + setOperationError(failures.map((f) => `${f.path}: ${tx(f.message)}`).join("\n")); } catch (e) { - if (mounted.current) setOperationError(e instanceof Error ? e.message : String(e)); + if (mounted.current && !isCancelled(e)) setOperationError(e instanceof Error ? e.message : String(e)); } finally { + upsertTask({ ...task, done: true }); if (mounted.current) { setOperating(false); - if (attempted) refresh(); + refresh(); } } }; const idle = !busy && !operating; const table = ( -
+
{ + if (e.key !== " " || !selected) return; + e.preventDefault(); + cycle(selected); + }} + >
@@ -388,14 +499,7 @@ export function DirectoryCompare({ left, right }: { left: string; right: string onDoubleClick={() => open(r.entry)} > - - {MARKER[r.entry.status] && } - + cycle(r.entry)} />
) @@ -434,18 +538,19 @@ export function DirectoryCompare({ left, right }: { left: string; right: string ))}
- -
({ compare: vi.fn(), cancel: vi.fn(), - copy: vi.fn(), - remove: vi.fn(), + sync: vi.fn(), confirm: vi.fn(), open: vi.fn(), })); @@ -17,8 +16,7 @@ vi.mock("@/platform/ipc", async (original) => { commands: { ...real.commands, fsCompareDirectories: mocks.compare, - fsCopyMerge: mocks.copy, - fsDelete: mocks.remove, + fsSynchronizeDirectories: mocks.sync, cancelRequest: mocks.cancel, }, }; @@ -38,7 +36,14 @@ vi.mock("../diffInput", async (original) => ({ openDiff: mocks.open, openVcsDiff: mocks.open, })); -import { DirectoryCompare, directoryDiff, directoryRows } from "../DirectoryCompare"; +import { + DirectoryCompare, + directoryDiff, + directoryRows, + syncChoices, + syncOperations, + type SyncAction, +} from "../DirectoryCompare"; import { directoryCompareTitle } from "../directoryCompareKind"; const row = ( @@ -61,8 +66,7 @@ const setup = () => render() beforeEach(() => { vi.clearAllMocks(); mocks.compare.mockResolvedValue(ok(rows)); - mocks.copy.mockResolvedValue(ok()); - mocks.remove.mockResolvedValue(ok()); + mocks.sync.mockResolvedValue(ok([])); mocks.confirm.mockResolvedValue(true); }); afterEach(cleanup); @@ -76,8 +80,8 @@ describe("disk directory comparison", () => { expect(await screen.findAllByText("中文.txt")).toHaveLength(2); expect(screen.getAllByRole("columnheader", { name: "Size" })).toHaveLength(2); expect(screen.getByText("2.0 KB")).toBeInTheDocument(); - expect(screen.getAllByLabelText("Only on left")).toHaveLength(2); - expect(screen.getByLabelText("Only on right")).toBeInTheDocument(); + expect(screen.getAllByLabelText(/^Only on left:/)).toHaveLength(2); + expect(screen.getByLabelText("Only on right: Copy to Left")).toBeInTheDocument(); expect(screen.queryByText("same.txt")).toBeNull(); const identical = screen.getByRole("button", { name: "Show identical files" }); expect(identical).toHaveAttribute("aria-pressed", "false"); @@ -88,8 +92,6 @@ describe("disk directory comparison", () => { fireEvent.change(screen.getByRole("textbox", { name: "Filter by name" }), { target: { value: "中文" } }); expect(screen.queryByText("same.txt")).toBeNull(); expect(screen.getAllByText("nested")).toHaveLength(2); - fireEvent.mouseDown(screen.getAllByText("nested")[0]!, { button: 0 }); - expect(screen.getByRole("button", { name: "Copy to Right" })).toBeEnabled(); }); it("groups files under their folder and keeps one-sided folders whole", () => { @@ -154,61 +156,66 @@ describe("disk directory comparison", () => { }); }); - it.each(["Copy to Left", "Copy to Right"])( - "confirms before overwriting, refreshes and restores selection after %s", - async (label) => { - mocks.copy - .mockResolvedValueOnce({ status: "error", error: { kind: "alreadyExists", message: "exists" } }) - .mockResolvedValueOnce(ok()); - setup(); - fireEvent.mouseDown((await screen.findAllByText("中文.txt"))[0]!, { button: 0 }); - fireEvent.click(screen.getByRole("button", { name: label })); - await waitFor(() => - expect(mocks.confirm).toHaveBeenCalledWith(expect.objectContaining({ title: "Overwrite files?" })), - ); - await waitFor(() => expect(mocks.compare).toHaveBeenCalledTimes(2)); - expect(mocks.copy.mock.calls[0]![3]).toBe(false); - expect(mocks.copy.mock.calls[1]![3]).toBe(true); - expect(mocks.copy.mock.calls[0]!.slice(0, 3)).toEqual( - label === "Copy to Left" - ? ["/p/right", "/p/left", "nested/中文.txt"] - : ["/p/left", "/p/right", "nested/中文.txt"], - ); - expect(await screen.findByTestId("diff")).toBeInTheDocument(); - }, - ); - - it("does not overwrite when confirmation is declined and reports operation errors", async () => { - mocks.copy.mockResolvedValue({ status: "error", error: { kind: "alreadyExists", message: "exists" } }); - mocks.confirm.mockResolvedValue(false); - setup(); - fireEvent.mouseDown((await screen.findAllByText("中文.txt"))[0]!, { button: 0 }); - fireEvent.click(screen.getByRole("button", { name: "Copy to Right" })); - await waitFor(() => expect(mocks.compare).toHaveBeenCalledTimes(2)); - expect(mocks.copy).toHaveBeenCalledTimes(1); - mocks.copy.mockResolvedValue({ status: "error", error: { kind: "permissionDenied", message: "Cannot write" } }); - fireEvent.click(screen.getByRole("button", { name: "Copy to Right" })); - expect(await screen.findByRole("alert")).toHaveTextContent("Cannot write"); + it("defaults, cycles and batches per-row operations", () => { + const entries = [rows[0]!, rows[1]!, rows[2]!, rows[3]!, rows[4]!]; + expect(entries.map((e) => syncChoices(e)[0])).toEqual(["none", "none", "copyToRight", "copyToLeft", "none"]); + expect(syncChoices(rows[2]!)).toEqual(["copyToRight", "deleteLeft", "none"]); + expect(syncChoices(rows[3]!)).toEqual(["copyToLeft", "deleteRight", "none"]); + const chosen: Record = { "nested/中文.txt": "copyToLeft", "only-right.txt": "deleteRight" }; + expect(syncOperations(entries, (e) => chosen[e.path] ?? syncChoices(e)[0]!)).toEqual([ + { path: "nested/中文.txt", action: "copyToLeft", overwrite: true }, + { path: "only-left.txt", action: "copyToRight", overwrite: false }, + { path: "only-right.txt", action: "deleteRight", overwrite: false }, + ]); }); - it("copies empty and nonempty subdirectories and confirms deletion only for one-sided entries", async () => { + it("synchronizes the selected row or all rows after one confirmation, then refreshes", async () => { setup(); - fireEvent.mouseDown((await screen.findAllByText("nested"))[0]!, { button: 0 }); - expect(screen.getByRole("button", { name: "Delete" })).toBeDisabled(); - fireEvent.click(screen.getByRole("button", { name: "Copy to Right" })); - await waitFor(() => expect(mocks.copy).toHaveBeenCalledWith("/p/left", "/p/right", "nested", false)); + const marker = async (name: string) => (await screen.findAllByRole("button", { name }))[0]!; + // Space on the selected row and a click on its marker change the operation. + fireEvent.mouseDown((await screen.findAllByText("中文.txt"))[0]!, { button: 0 }); + expect(screen.getByRole("button", { name: "Synchronize Selected" })).toBeDisabled(); + fireEvent.keyDown(screen.getByRole("grid"), { key: " " }); + expect(await marker("Contents differ: Copy to Right")).toBeInTheDocument(); + fireEvent.click(await marker("Contents differ: Copy to Right")); + expect(await marker("Contents differ: Copy to Left")).toBeInTheDocument(); + fireEvent.click(screen.getByRole("button", { name: "Synchronize Selected" })); + await waitFor(() => expect(mocks.confirm).toHaveBeenCalledTimes(1)); + expect(mocks.confirm.mock.calls[0]![0].message).toBe("Synchronize 1 entries? 0 will be deleted and 1 overwritten."); await waitFor(() => expect(mocks.compare).toHaveBeenCalledTimes(2)); - fireEvent.mouseDown(screen.getByText("empty"), { button: 0 }); - fireEvent.click(screen.getByRole("button", { name: "Copy to Right" })); - await waitFor(() => expect(mocks.copy).toHaveBeenCalledWith("/p/left", "/p/right", "empty", false)); - await waitFor(() => expect(mocks.compare).toHaveBeenCalledTimes(3)); - fireEvent.mouseDown(screen.getByText("only-left.txt"), { button: 0 }); + expect(mocks.sync.mock.calls[0]!.slice(0, 3)).toEqual([ + "/p/left", + "/p/right", + [{ path: "nested/中文.txt", action: "copyToLeft", overwrite: true }], + ]); + // A refresh resets the operations; only-left copies and the other one-sided row is deleted. + fireEvent.click(await marker("Only on right: Copy to Left")); + fireEvent.click(screen.getByRole("button", { name: "Synchronize All" })); + await waitFor(() => expect(mocks.sync).toHaveBeenCalledTimes(2)); + expect(mocks.confirm.mock.calls[1]![0].message).toBe("Synchronize 3 entries? 1 will be deleted and 0 overwritten."); + expect(mocks.sync.mock.calls[1]![2]).toEqual([ + { path: "empty", action: "copyToRight", overwrite: false }, + { path: "only-left.txt", action: "copyToRight", overwrite: false }, + { path: "only-right.txt", action: "deleteRight", overwrite: false }, + ]); + }); + + it("asks nothing for plain copies, keeps the batch when confirmation is declined and reports failures", async () => { mocks.confirm.mockResolvedValueOnce(false); - fireEvent.click(screen.getByRole("button", { name: "Delete" })); - await waitFor(() => expect(mocks.confirm).toHaveBeenCalled()); - expect(mocks.remove).not.toHaveBeenCalled(); - fireEvent.click(screen.getByRole("button", { name: "Delete" })); - await waitFor(() => expect(mocks.remove).toHaveBeenCalledWith("/p/left/only-left.txt")); + setup(); + fireEvent.click((await screen.findAllByRole("button", { name: "Only on right: Copy to Left" }))[0]!); + fireEvent.click(screen.getByRole("button", { name: "Synchronize All" })); + await waitFor(() => expect(mocks.confirm).toHaveBeenCalledTimes(1)); + expect(mocks.sync).not.toHaveBeenCalled(); + fireEvent.click(screen.getByRole("button", { name: "Only on right: Delete" })); + fireEvent.click(screen.getByRole("button", { name: "Only on right: Do nothing" })); + mocks.sync.mockResolvedValueOnce( + ok([{ path: "only-left.txt", action: "copyToRight", message: "Permission denied" }]), + ); + fireEvent.click(screen.getByRole("button", { name: "Synchronize All" })); + expect(await screen.findByRole("alert")).toHaveTextContent("only-left.txt: Permission denied"); + expect(mocks.confirm).toHaveBeenCalledTimes(1); + await waitFor(() => expect(mocks.compare).toHaveBeenCalledTimes(2)); }); it("compares by the chosen mode, recomparing and remembering it", async () => { diff --git a/src/platform/locales/text/es.json b/src/platform/locales/text/es.json index c803d07b8..8990e530b 100644 --- a/src/platform/locales/text/es.json +++ b/src/platform/locales/text/es.json @@ -5513,15 +5513,12 @@ "Compared files": "Archivos comparados", "Comparison cancelled": "Comparación cancelada", "No matching differences": "No hay diferencias coincidentes", - "Overwrite files?": "¿Sobrescribir archivos?", - "Copy to {to} and overwrite existing files?": "¿Copiar a {to} y sobrescribir los archivos existentes?", "Left: {left}": "Izquierda: {left}", "Right: {right}": "Derecha: {right}", "Compared {compared} of {total} entries": "Se compararon {compared} de {total} entradas", "Scanned {scanned} entries": "Se escanearon {scanned} entradas", "Binary content": "Contenido binario", "Binary files cannot be shown as text": "Los archivos binarios no se pueden mostrar como texto", - "Delete {path}?": "¿Eliminar {path}?", "copy requires an absolute path": "la copia requiere una ruta absoluta", "missing file name": "falta el nombre del archivo", "copy requires absolute paths": "la copia requiere rutas absolutas", diff --git a/src/platform/locales/text/fr.json b/src/platform/locales/text/fr.json index d324251b7..b7e3faec1 100644 --- a/src/platform/locales/text/fr.json +++ b/src/platform/locales/text/fr.json @@ -5339,15 +5339,12 @@ "Compared files": "Fichiers comparés", "Comparison cancelled": "Comparaison annulée", "No matching differences": "Aucune différence correspondante", - "Overwrite files?": "Écraser les fichiers ?", - "Copy to {to} and overwrite existing files?": "Copier vers {to} et écraser les fichiers existants ?", "Left: {left}": "Gauche : {left}", "Right: {right}": "Droite : {right}", "Compared {compared} of {total} entries": "{compared} entrées comparées sur {total}", "Scanned {scanned} entries": "{scanned} entrées analysées", "Binary content": "Contenu binaire", "Binary files cannot be shown as text": "Les fichiers binaires ne peuvent pas être affichés en texte", - "Delete {path}?": "Supprimer {path} ?", "copy requires an absolute path": "la copie nécessite un chemin absolu", "missing file name": "nom de fichier manquant", "copy requires absolute paths": "la copie nécessite des chemins absolus", diff --git a/src/platform/locales/text/ko.json b/src/platform/locales/text/ko.json index 3d4f5c29a..08f97131a 100644 --- a/src/platform/locales/text/ko.json +++ b/src/platform/locales/text/ko.json @@ -5581,15 +5581,12 @@ "Compared files": "비교된 파일", "Comparison cancelled": "비교가 취소되었습니다", "No matching differences": "일치하는 차이점이 없습니다", - "Overwrite files?": "파일을 덮어쓰시겠습니까?", - "Copy to {to} and overwrite existing files?": "{to}(으)로 복사하고 기존 파일을 덮어쓰시겠습니까?", "Left: {left}": "왼쪽: {left}", "Right: {right}": "오른쪽: {right}", "Compared {compared} of {total} entries": "항목 {total}개 중 {compared}개 비교됨", "Scanned {scanned} entries": "항목 {scanned}개 스캔됨", "Binary content": "바이너리 내용", "Binary files cannot be shown as text": "바이너리 파일은 텍스트로 표시할 수 없습니다", - "Delete {path}?": "{path}을(를) 삭제하시겠습니까?", "copy requires an absolute path": "복사하려면 절대 경로가 필요합니다", "missing file name": "파일 이름이 없습니다", "copy requires absolute paths": "복사하려면 절대 경로가 필요합니다", diff --git a/src/platform/locales/text/pl.json b/src/platform/locales/text/pl.json index 355b3846d..935882b18 100644 --- a/src/platform/locales/text/pl.json +++ b/src/platform/locales/text/pl.json @@ -5465,15 +5465,12 @@ "Compared files": "Porównywane pliki", "Comparison cancelled": "Porównywanie anulowane", "No matching differences": "Brak pasujących różnic", - "Overwrite files?": "Nadpisać pliki?", - "Copy to {to} and overwrite existing files?": "Skopiować do {to} i nadpisać istniejące pliki?", "Left: {left}": "Lewa strona: {left}", "Right: {right}": "Prawa strona: {right}", "Compared {compared} of {total} entries": "Porównano {compared} z {total} wpisów", "Scanned {scanned} entries": "Przeskanowano wpisy ({scanned})", "Binary content": "Zawartość binarna", "Binary files cannot be shown as text": "Pliki binarne nie mogą być wyświetlane jako tekst", - "Delete {path}?": "Usunąć {path}?", "copy requires an absolute path": "kopiowanie wymaga ścieżki bezwzględnej", "missing file name": "brakująca nazwa pliku", "copy requires absolute paths": "kopiowanie wymaga ścieżek bezwzględnych", diff --git a/src/platform/locales/text/pt.json b/src/platform/locales/text/pt.json index fbd0eb5e0..029d3eb2a 100644 --- a/src/platform/locales/text/pt.json +++ b/src/platform/locales/text/pt.json @@ -5479,15 +5479,12 @@ "Compared files": "Arquivos comparados", "Comparison cancelled": "Comparação cancelada", "No matching differences": "Nenhuma diferença correspondente", - "Overwrite files?": "Sobrescrever arquivos?", - "Copy to {to} and overwrite existing files?": "Copiar para {to} e sobrescrever os arquivos existentes?", "Left: {left}": "Esquerda: {left}", "Right: {right}": "Direita: {right}", "Compared {compared} of {total} entries": "{compared} de {total} entradas comparadas", "Scanned {scanned} entries": "{scanned} entradas verificadas", "Binary content": "Conteúdo binário", "Binary files cannot be shown as text": "Arquivos binários não podem ser exibidos como texto", - "Delete {path}?": "Excluir {path}?", "copy requires an absolute path": "a cópia requer um caminho absoluto", "missing file name": "nome de arquivo ausente", "copy requires absolute paths": "a cópia requer caminhos absolutos", diff --git a/src/platform/locales/text/tr.json b/src/platform/locales/text/tr.json index e34d5f280..2e4627513 100644 --- a/src/platform/locales/text/tr.json +++ b/src/platform/locales/text/tr.json @@ -8185,15 +8185,12 @@ "Compared files": "Karşılaştırılan dosyalar", "Comparison cancelled": "Karşılaştırma iptal edildi", "No matching differences": "Eşleşen fark yok", - "Overwrite files?": "Dosyaların üzerine yazılsın mı?", - "Copy to {to} and overwrite existing files?": "{to} konumuna kopyalanıp mevcut dosyaların üzerine yazılsın mı?", "Left: {left}": "Sol: {left}", "Right: {right}": "Sağ: {right}", "Compared {compared} of {total} entries": "{total} öğenin {compared} tanesi karşılaştırıldı", "Scanned {scanned} entries": "{scanned} öğe tarandı", "Binary content": "İkili içerik", "Binary files cannot be shown as text": "İkili dosyalar metin olarak gösterilemez", - "Delete {path}?": "{path} silinsin mi?", "copy requires an absolute path": "kopyalama için mutlak yol gerekli", "missing file name": "dosya adı eksik", "copy requires absolute paths": "kopyalama için mutlak yollar gerekli", diff --git a/src/platform/locales/text/zh-TW.json b/src/platform/locales/text/zh-TW.json index 840e06405..45fa03f08 100644 --- a/src/platform/locales/text/zh-TW.json +++ b/src/platform/locales/text/zh-TW.json @@ -6510,15 +6510,12 @@ "Compared files": "比較的檔案", "Comparison cancelled": "已取消比較", "No matching differences": "沒有符合的差異", - "Overwrite files?": "覆蓋檔案?", - "Copy to {to} and overwrite existing files?": "複製到 {to} 並覆蓋已有檔案?", "Left: {left}": "左側:{left}", "Right: {right}": "右側:{right}", "Compared {compared} of {total} entries": "已比較 {compared} / {total} 個條目", "Scanned {scanned} entries": "已掃描 {scanned} 個條目", "Binary content": "二進位制內容", "Binary files cannot be shown as text": "二進位制檔案無法以文字形式顯示", - "Delete {path}?": "刪除 {path}?", "copy requires an absolute path": "複製需要絕對路徑", "missing file name": "缺少檔名", "copy requires absolute paths": "複製需要絕對路徑", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 2da6faca8..ebbcb9ba4 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -6547,15 +6547,12 @@ "Compared files": "比较的文件", "Comparison cancelled": "已取消比较", "No matching differences": "没有匹配的差异", - "Overwrite files?": "覆盖文件?", - "Copy to {to} and overwrite existing files?": "复制到 {to} 并覆盖已有文件?", "Left: {left}": "左侧:{left}", "Right: {right}": "右侧:{right}", "Compared {compared} of {total} entries": "已比较 {compared} / {total} 个条目", "Scanned {scanned} entries": "已扫描 {scanned} 个条目", "Binary content": "二进制内容", "Binary files cannot be shown as text": "二进制文件无法以文本形式显示", - "Delete {path}?": "删除 {path}?", "copy requires an absolute path": "复制需要绝对路径", "missing file name": "缺少文件名", "copy requires absolute paths": "复制需要绝对路径", @@ -6748,6 +6745,9 @@ "Size and Timestamp": "大小和时间戳", "Binary Content": "二进制内容", "Synchronize Selected": "同步所选文件", + "Synchronize": "同步", + "Synchronize {count} entries? {deletes} will be deleted and {overwrites} overwritten.": "同步 {count} 个条目?其中 {deletes} 个将被删除,{overwrites} 个将被覆盖。", + "Synchronizing directories": "正在同步目录", "Stop content comparison": "停止内容比较", "Filter:": "筛选:", "Local files": "本地文件",