From af2e515d0f66753d4da4ea8b2d7bf34bac176f34 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Thu, 3 Dec 2026 05:43:01 +0800 Subject: [PATCH] fix(svn): file history diffs, annotation details and new-file confirmation (#7606) SVN annotation menu named the right system; single-revision history and cross-working-copy log diffs use each path's own previous revision and read paths outside the checkout from the repository; annotation details look up the requested revision; new SVN files follow the When files are created confirmation setting. Refs #7433. --- crates/ide-host/src/ops/fs.rs | 30 +-- crates/ide-host/src/ops/svn.rs | 22 +++ crates/ide-host/tests/svn.rs | 30 ++- crates/ide-svn/src/backend.rs | 187 ++++++++++++------ crates/ide-svn/src/ops.rs | 2 +- crates/ide-svn/src/workspace.rs | 70 ++++++- crates/ide-svn/tests/feedback.rs | 96 +++++++++ src-tauri/tests/commands.snap | 1 + src/bindings.ts | 2 + src/features/vcs/BlamePopup.tsx | 9 +- src/features/vcs/__tests__/blame.test.tsx | 50 ++++- .../vcs/__tests__/confirmations.test.ts | 23 +++ .../vcs/__tests__/logPreviewTab.test.tsx | 93 ++++++++- src/features/vcs/actions.tsx | 5 +- src/features/vcs/blame.ts | 10 +- src/features/vcs/confirmations.tsx | 45 +++-- src/features/vcs/diffInput.ts | 11 +- src/features/vcs/log/CommitDetails.tsx | 9 +- src/features/vcs/logChanges.ts | 4 +- src/features/vcs/logStore.ts | 8 +- src/features/vcs/unityMetadata.ts | 1 + src/features/vcs/vcsKind.ts | 4 + src/platform/locales/text/en.json | 6 + src/platform/locales/text/zh.json | 6 + 24 files changed, 602 insertions(+), 122 deletions(-) create mode 100644 crates/ide-svn/tests/feedback.rs diff --git a/crates/ide-host/src/ops/fs.rs b/crates/ide-host/src/ops/fs.rs index 2ed4a6242..45d9ea308 100644 --- a/crates/ide-host/src/ops/fs.rs +++ b/crates/ide-host/src/ops/fs.rs @@ -230,6 +230,18 @@ pub async fn fs_read_dir(host: &Host, window: &str, path: PathBuf) -> IdeResult< .await } +fn notify_vcs_of_created_file(project: &Project, path: &Path) { + let paths = &[path.to_path_buf()]; + let result = project.with_backend_of(path, |backend| match super::svn::as_svn(backend) { + // New SVN paths go through the same frontend confirmation as Git's. + Some(wc) => wc.restore_recreated_files(paths), + None => backend.files_added(paths), + }); + if let Err(e) = result { + tracing::debug!("vcs files_added for {}: {e}", path.display()); + } +} + /// Creates an empty file; inside a project, honours the EditorConfig /// `charset` (writes the BOM for `utf-8-bom` / UTF-16). #[command(trust = always)] @@ -248,10 +260,7 @@ pub fn fs_create_file(host: &Host, window: &str, path: PathBuf) -> IdeResult<()> if empty && !bom.is_empty() { std::fs::write(&path, bom)?; } - // A checkout backend opens the file for add; Git's hook is a no-op. - if let Err(e) = p.with_backend_of(&path, |r| r.files_added(std::slice::from_ref(&path))) { - tracing::debug!("vcs files_added for {}: {e}", path.display()); - } + notify_vcs_of_created_file(&p, &path); Ok(()) } Err(_) => ide_vfs::create_file(&path), @@ -263,10 +272,8 @@ pub async fn fs_create_file_bytes(host: &Host, window: &str, path: PathBuf, data let project = host.project(window).ok(); host.blocking(move || { ide_vfs::create_file_bytes(&path, &data)?; - if let Some(p) = project - && let Err(e) = p.with_backend_of(&path, |r| r.files_added(std::slice::from_ref(&path))) - { - tracing::debug!("vcs files_added for {}: {e}", path.display()); + if let Some(p) = project { + notify_vcs_of_created_file(&p, &path); } Ok(()) }) @@ -399,11 +406,8 @@ pub async fn fs_copy(host: &Host, window: &str, from: PathBuf, to: PathBuf) -> I let project = host.project(window).ok(); host.blocking(move || { ide_workspace::file_ops::copy(&from, &to)?; - // A copy is an add at the destination; Git's hook is a no-op. - if let Some(p) = project - && let Err(e) = p.with_backend_of(&to, |r| r.files_added(std::slice::from_ref(&to))) - { - tracing::debug!("vcs files_added for {}: {e}", to.display()); + if let Some(p) = project { + notify_vcs_of_created_file(&p, &to); } Ok(()) }) diff --git a/crates/ide-host/src/ops/svn.rs b/crates/ide-host/src/ops/svn.rs index 73d095c26..c598b52ed 100644 --- a/crates/ide-host/src/ops/svn.rs +++ b/crates/ide-host/src/ops/svn.rs @@ -196,6 +196,27 @@ pub async fn svn_repository_info(host: &Host, window: &str, repo: Option IdeResult> { + let project = host.project(window)?; + blocking(move || { + with_working_copy(&project, Some(&repo), |wc| { + wc.repository_text_at(&path, &revision, |bytes| { + let display_path = wc.root().join(path.trim_start_matches('/')); + project.staged_file_encoding(&display_path, bytes) + }) + }) + }) + .await +} + /// VCS › Subversion › Relocate: the same repository at a new URL (another host or scheme). #[command(trust = trusted)] pub async fn svn_relocate(host: &Host, window: &str, repo: Option, url: String) -> IdeResult<()> { @@ -480,6 +501,7 @@ ide_command::domain!( svn_merge_sources, svn_properties, svn_relocate, + svn_repository_file_at, svn_repository_info, svn_revert_revision, svn_set_property, diff --git a/crates/ide-host/tests/svn.rs b/crates/ide-host/tests/svn.rs index 10f8d0e38..3baf6523e 100644 --- a/crates/ide-host/tests/svn.rs +++ b/crates/ide-host/tests/svn.rs @@ -5,7 +5,7 @@ mod common; use ide_core::CancellationToken; use ide_host::Host; -use ide_host::ops::{svn, vcs}; +use ide_host::ops::{fs, svn, vcs}; use ide_vcs::{ChangeKind, CommitOptions, FileStatus, LogQuery, VcsKind}; use std::path::{Path, PathBuf}; use std::process::Command; @@ -138,6 +138,34 @@ fn commit_options(paths: &[PathBuf]) -> CommitOptions { CommitOptions { stage: paths.iter().cloned().map(Into::into).collect(), ..Default::default() } } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn creating_and_copying_files_waits_for_version_control_confirmation() { + let Some(fx) = fixture() else { return }; + let root = fx.checkout("wc"); + let original = root.join("tracked.txt"); + std::fs::write(&original, "before").unwrap(); + fx.svn(&root, &["add", "-q", "tracked.txt"]); + fx.svn(&root, &["commit", "-q", "-m", "tracked"]); + let (host, _) = open(&fx.base, &root).await; + let empty = root.join("empty.txt"); + let content = root.join("content.txt"); + let copy = root.join("copy.txt"); + fs::fs_create_file(&host, "main", empty.clone()).unwrap(); + fs::fs_create_file_bytes(&host, "main", content.clone(), b"text".to_vec().into()).await.unwrap(); + fs::fs_copy(&host, "main", original.clone(), copy.clone()).await.unwrap(); + let rows = kinds(&vcs::vcs_status(&host, "main").await.unwrap()); + assert_eq!(rows, ["content.txt", "copy.txt", "empty.txt"].map(|path| (path.to_owned(), ChangeKind::Untracked)),); + vcs::vcs_stage(&host, "main", vec![empty, content, copy]).await.unwrap(); + let rows = kinds(&vcs::vcs_status(&host, "main").await.unwrap()); + assert_eq!(rows, ["content.txt", "copy.txt", "empty.txt"].map(|path| (path.to_owned(), ChangeKind::Added))); + + fx.svn(&root, &["delete", "-q", "tracked.txt"]); + fs::fs_create_file_bytes(&host, "main", original, b"after".to_vec().into()).await.unwrap(); + assert!( + kinds(&vcs::vcs_status(&host, "main").await.unwrap()).contains(&("tracked.txt".into(), ChangeKind::Modified)) + ); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn a_working_copy_through_the_shared_commands() { let Some(fx) = fixture() else { return }; diff --git a/crates/ide-svn/src/backend.rs b/crates/ide-svn/src/backend.rs index ed52437e5..57b2105bc 100644 --- a/crates/ide-svn/src/backend.rs +++ b/crates/ide-svn/src/backend.rs @@ -7,7 +7,7 @@ //! the chosen paths. use crate::cli::{args, is_absent, target, url_target}; -use crate::workspace::{BATCH, Layout, Rev, WorkingCopy, decode, normalize}; +use crate::workspace::{BATCH, Layout, Rev, WorkingCopy, decode, normalize, unescape_url}; use crate::xml::{self, LogEntry, StatusEntry}; use ide_core::{CancellationToken, IdeError, IdeResult, error::ErrorKind}; use ide_vcs::changelists::DEFAULT_ID; @@ -395,6 +395,58 @@ fn revision_number(id: &str) -> IdeResult { } impl WorkingCopy { + /// Restore the schedule of recreated tracked files. New paths are handled by VCS confirmation. + pub fn restore_recreated_files(&self, paths: &[PathBuf]) -> IdeResult<()> { + self.update_created_paths(paths, false) + } + + fn update_created_paths(&self, paths: &[PathBuf], add: bool) -> IdeResult<()> { + // Its svn commands and the file steps between them run as one write. + self.exclusively(|| { + // A file deleted and created again (the IDE's overwrite: Delete, then a new file of that + // name): the deletion is taken back, keeping the new content, instead of a replacement. + let mut paths = outermost(self.inside(paths)); + let deleted: Vec = self + .entries_of(&paths)? + .into_iter() + .filter(|e| e.item == "deleted" && e.moved_to.is_none() && Path::new(&e.path).is_file()) + .map(|e| PathBuf::from(e.path)) + .collect(); + if !deleted.is_empty() { + // The new files are parked on disk while svn reverts (put back if it fails), then + // take the place of the base svn put back. + let mut parked = Leftovers::default(); + parked.carry.extend(deleted.iter().map(|p| (p.clone(), p.clone()))); + parked.stash_away(self.wc_root())?; + parked.reverting(|| { + for chunk in deleted.chunks(BATCH) { + self.run( + &[args(["revert", "--depth", "empty"]), chunk.iter().map(|p| target(p)).collect()].concat(), + )?; + } + Ok(()) + })?; + for path in &deleted { + remove(path); + } + parked.clean_up(); + } + if !add { + return Ok(()); + } + paths.retain(|p| !deleted.contains(p)); + // `svn add` of a named path adds it even where `svn:ignore` covers it (a build folder). + let mut kept = Vec::with_capacity(paths.len()); + for path in paths.drain(..) { + if !self.is_ignored(&path)? { + kept.push(path); + } + } + self.add(&kept)?; + Ok(()) + }) + } + /// Changes as the Changes view shows them. Folders are left out when /// their files are listed (an added or deleted folder); an unversioned /// folder is one entry, as `svn status` reports it. @@ -498,11 +550,11 @@ impl WorkingCopy { /// Log messages of `revisions`, read in one `svn log -c` per batch. fn messages(&self, revisions: &[u64]) -> IdeResult> { - self.log_entries(revisions, false) + self.log_entries(revisions, false, None) } fn revision_entry(&self, revision: u64) -> IdeResult { - self.log_entries(&[revision], true)? + self.log_entries(&[revision], true, None)? .remove(&revision) .ok_or_else(|| IdeError::not_found(format!("revision {revision} does not exist"))) } @@ -511,7 +563,12 @@ impl WorkingCopy { /// first: a server that authorizes by path may refuse the repository root (E175013) to a /// user who can read the project. Revisions it does not list (a change outside the working /// copy's history) are asked of the root. A failure is told only when nothing was read. - fn log_entries(&self, revisions: &[u64], verbose: bool) -> IdeResult> { + fn log_entries( + &self, + revisions: &[u64], + verbose: bool, + cancel: Option<&CancellationToken>, + ) -> IdeResult> { let repository = self.current_repository(); let mut urls = vec![repository.url]; if repository.root_url != urls[0] { @@ -528,7 +585,7 @@ impl WorkingCopy { argv.push("-v".into()); } argv.push(url_target(&url)); - match self.remote(&argv, None).and_then(|log| xml::log(&log)) { + match self.remote(&argv, cancel).and_then(|log| xml::log(&log)) { Ok(entries) => out.extend(entries.into_iter().map(|e| (e.revision, e))), Err(e) => { failure.get_or_insert(e); @@ -579,6 +636,24 @@ impl WorkingCopy { out } + /// Last changes to the named paths as they existed immediately before a commit. + fn last_changed_revisions(&self, paths: &[(String, u64)]) -> HashMap<(String, u64), u64> { + let repository = self.current_repository(); + let mut revisions = HashMap::new(); + for chunk in paths.chunks(BATCH) { + let mut argv = args(["info", "--xml"]); + argv.extend(chunk.iter().map(|(path, revision)| repository.revision_target(path, *revision))); + // A server may hide some paths. The caller can still use the known peg revision. + if let Ok(entries) = self.remote(&argv, None).and_then(|out| xml::info(&out)) { + revisions.extend(entries.into_iter().filter_map(|info| { + let path = unescape_url(info.relative_url.strip_prefix('^')?); + Some(((path, info.revision?), info.last_changed_revision?)) + })); + } + } + revisions + } + fn commit_of(entry: &LogEntry, older: Option) -> Commit { let id = entry.revision.to_string(); let message = entry.message.trim_end().to_owned(); @@ -1583,6 +1658,14 @@ impl Backend for WorkingCopy { } fn log(&self, query: &LogQuery, cancel: &CancellationToken) -> IdeResult> { + // Direct lookups by revision (for example, the annotation popup) must not return HEAD. + if query.path.is_none() + && query.paths.is_empty() + && let Some(revision) = query.branch.as_deref().and_then(|id| revision_number(id).ok()) + { + let entries = self.log_entries(&[revision], false, Some(cancel))?; + return Ok(entries.values().skip(query.skip as usize).map(|entry| Self::commit_of(entry, None)).collect()); + } let mut paths: Vec = query.paths.iter().map(|p| p.0.clone()).collect(); paths.extend(query.path.iter().map(|p| p.0.clone())); let paths = self.inside(&paths); @@ -1669,9 +1752,34 @@ impl Backend for WorkingCopy { numbers.dedup(); // Oldest first, so a file touched by several revisions spans the first before and the last after. let mut spans: Vec = Vec::new(); + let repository = self.current_repository(); for number in numbers { - for file in self.revision_files(&self.revision_entry(number)?) { - let before = (file.kind != ChangeKind::Added).then(|| (number - 1).to_string()); + let entry = self.revision_entry(number)?; + let files = self.revision_files(&entry); + let previous: HashMap<_, _> = files + .iter() + .filter(|file| file.kind != ChangeKind::Added && !spans.iter().any(|span| span.path == file.path)) + .map(|file| { + let path = repository.path_of_relative(file.old_path.as_deref().unwrap_or(&file.path)); + // A file edited under a copied directory was at the source before the copy. + let ancestor = entry + .paths + .iter() + .filter_map(|p| { + let suffix = path.strip_prefix(&p.path)?.strip_prefix('/')?; + p.copy_from.as_ref().map(|source| (p.path.len(), suffix, source)) + }) + .max_by_key(|(len, _, _)| *len); + let target = match ancestor { + Some((_, suffix, (source, revision))) => (format!("{source}/{suffix}"), *revision), + None => (path, number.saturating_sub(1)), + }; + (file.path.clone(), target) + }) + .collect(); + let targets: Vec<_> = previous.values().cloned().collect(); + let last_changed = self.last_changed_revisions(&targets); + for file in files { let after = (file.kind != ChangeKind::Deleted).then(|| number.to_string()); match spans.iter_mut().find(|s| s.path == file.path) { Some(span) => { @@ -1683,14 +1791,21 @@ impl Backend for WorkingCopy { (true, true) => ChangeKind::Modified, }; } - None => spans.push(RevisionChange { - path: file.path, - kind: file.kind, - old_path: file.old_path, - before, - after, - link: None, - }), + None => { + let target = previous.get(&file.path); + let before = + target.map(|target| last_changed.get(target).copied().unwrap_or(target.1).to_string()); + let old_path = + target.map(|(path, _)| self.rel_of_repo_path(path)).filter(|path| path != &file.path); + spans.push(RevisionChange { + path: file.path, + kind: file.kind, + old_path, + before, + after, + link: None, + }); + } } } } @@ -1822,47 +1937,7 @@ impl Backend for WorkingCopy { } fn files_added(&self, paths: &[PathBuf]) -> IdeResult<()> { - // Its svn commands and the file steps between them run as one write. - self.exclusively(|| { - // A file deleted and created again (the IDE's overwrite: Delete, then a new file of that - // name): the deletion is taken back, keeping the new content, instead of a replacement. - let mut paths = outermost(self.inside(paths)); - let deleted: Vec = self - .entries_of(&paths)? - .into_iter() - .filter(|e| e.item == "deleted" && e.moved_to.is_none() && Path::new(&e.path).is_file()) - .map(|e| PathBuf::from(e.path)) - .collect(); - if !deleted.is_empty() { - // The new files are parked on disk while svn reverts (put back if it fails), then - // take the place of the base svn put back. - let mut parked = Leftovers::default(); - parked.carry.extend(deleted.iter().map(|p| (p.clone(), p.clone()))); - parked.stash_away(self.wc_root())?; - parked.reverting(|| { - for chunk in deleted.chunks(BATCH) { - self.run( - &[args(["revert", "--depth", "empty"]), chunk.iter().map(|p| target(p)).collect()].concat(), - )?; - } - Ok(()) - })?; - for path in &deleted { - remove(path); - } - parked.clean_up(); - } - paths.retain(|p| !deleted.contains(p)); - // `svn add` of a named path adds it even where `svn:ignore` covers it (a build folder). - let mut kept = Vec::with_capacity(paths.len()); - for path in paths.drain(..) { - if !self.is_ignored(&path)? { - kept.push(path); - } - } - self.add(&kept)?; - Ok(()) - }) + self.update_created_paths(paths, true) } fn files_deleted(&self, paths: &[PathBuf]) -> IdeResult<()> { diff --git a/crates/ide-svn/src/ops.rs b/crates/ide-svn/src/ops.rs index d6be9123c..0e9164f99 100644 --- a/crates/ide-svn/src/ops.rs +++ b/crates/ide-svn/src/ops.rs @@ -891,7 +891,7 @@ const LINES_FRESH: std::time::Duration = std::time::Duration::from_secs(60); /// A repository path (as svn prints it, unescaped) for a URL: `/branches/a%20b` names the /// folder `a%20b`, so `%`, spaces and non-ASCII bytes are escaped; `/` separates. -fn escape_path(path: &str) -> String { +pub(crate) fn escape_path(path: &str) -> String { let mut out = String::with_capacity(path.len()); for byte in path.bytes() { match byte { diff --git a/crates/ide-svn/src/workspace.rs b/crates/ide-svn/src/workspace.rs index 01a5340de..91c720c44 100644 --- a/crates/ide-svn/src/workspace.rs +++ b/crates/ide-svn/src/workspace.rs @@ -2,6 +2,7 @@ //! status entries, repository paths, file content at a revision. use crate::cli::{LOCAL, REMOTE, Svn, SvnContext, args, is_absent, pegged, target}; +use crate::ops::escape_path; use crate::xml::{self, StatusEntry}; use ide_core::error::ErrorKind; use ide_core::{CancellationToken, IdeError, IdeResult}; @@ -517,17 +518,40 @@ impl WorkingCopy { Rev::Base => self.run(&[args(head), args(["-r", "BASE"]), vec![target(path)]].concat()), Rev::Other(rev) => self.pegged_at(&head, path, rev, None), }; - let mut properties = match result { - Ok(out) => xml::properties(&out)?, - Err(e) if is_absent(&e) => return Ok(None), + match result { + Ok(out) => Ok(Some(property_text(&out)?)), + Err(e) if is_absent(&e) => Ok(None), + Err(e) => Err(e), + } + } + + /// Reads a historical path from this repository even when it belongs to another checkout. + pub fn repository_text_at( + &self, + path: &str, + revision: &str, + encoding: impl FnOnce(&[u8]) -> TextEncoding, + ) -> IdeResult> { + let path = path + .strip_prefix('/') + .filter(|p| p.is_empty() || p.split('/').all(|part| !matches!(part, "" | "." | ".."))) + .ok_or_else(|| IdeError::invalid("invalid Subversion repository path"))?; + let revision = revision.parse::().map_err(|_| IdeError::invalid("invalid Subversion revision"))?; + let target = self.current_repository().revision_target(&format!("/{path}"), revision); + let info = self.remote(&[args(["info", "--xml"]), vec![target.clone()]].concat(), None); + let Some(info) = (match info { + Ok(out) => xml::info(&out)?.into_iter().next(), + Err(e) if is_absent(&e) => None, Err(e) => return Err(e), + }) else { + return Ok(None); }; - properties.sort(); - let text: String = properties - .into_iter() - .map(|(name, value)| format!("{name} = {}\n", value.strip_suffix('\n').unwrap_or(&value))) - .collect(); - Ok(Some(text.into_bytes())) + if info.kind == "dir" { + let out = self.remote(&[args(["proplist", "-v", "--xml"]), vec![target]].concat(), None)?; + return Ok(Some(String::from_utf8_lossy(&property_text(&out)?).into_owned())); + } + let bytes = self.remote(&[args(["cat"]), vec![target]].concat(), None)?; + Ok(Some(decode(&bytes, encoding(&bytes)))) } /// `command -r rev path`, which follows the file back through renames from @@ -612,6 +636,32 @@ impl WorkingCopy { } } +impl Repository { + pub(crate) fn revision_target(&self, path: &str, revision: u64) -> OsString { + format!("{}{}@{revision}", self.root_url.trim_end_matches('/'), escape_path(path)).into() + } + + pub(crate) fn path_of_relative(&self, path: &str) -> String { + if path.starts_with('/') { + path.to_owned() + } else if path.is_empty() { + self.path.clone() + } else { + format!("{}/{path}", self.path.trim_end_matches('/')) + } + } +} + +fn property_text(out: &[u8]) -> IdeResult> { + let mut properties = xml::properties(out)?; + properties.sort(); + let text: String = properties + .into_iter() + .map(|(name, value)| format!("{name} = {}\n", value.strip_suffix('\n').unwrap_or(&value))) + .collect(); + Ok(text.into_bytes()) +} + fn repository(info: &xml::Info) -> Repository { let path = info.relative_url.strip_prefix('^').unwrap_or(&info.relative_url); Repository { @@ -626,7 +676,7 @@ fn repository(info: &xml::Info) -> Repository { } /// `%20` and other escapes of a URL path, as log paths spell it unescaped. -fn unescape_url(path: &str) -> String { +pub(crate) fn unescape_url(path: &str) -> String { let bytes = path.as_bytes(); let mut out = Vec::with_capacity(bytes.len()); let mut i = 0; diff --git a/crates/ide-svn/tests/feedback.rs b/crates/ide-svn/tests/feedback.rs new file mode 100644 index 000000000..8e7e67b4e --- /dev/null +++ b/crates/ide-svn/tests/feedback.rs @@ -0,0 +1,96 @@ +mod common; + +use common::*; +use ide_core::CancellationToken; +use ide_vcs::{Backend, LogQuery}; + +fn workspace(repo: &Repo) -> (ide_svn::WorkingCopy, ide_svn::WorkingCopy) { + let all = repo.base.join("all"); + repo.svn(&repo.base, &["checkout", "-q", &repo.url, all.to_str().unwrap()]); + let a = all.join("trunk/projA/MainA.java"); + let b = all.join("trunk/projB/MainB.java"); + for (path, text) in [(&a, "class A { int x = 1; }\n"), (&b, "class B { int x = 1; }\n// B\n")] { + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, text).unwrap(); + } + repo.svn(&all, &["add", "-q", "trunk/projA", "trunk/projB"]); + repo.svn(&all, &["commit", "-q", "--username", "alice", "-m", "add the projects"]); + std::fs::write(&b, "class B { int x = 2; }\n// B\n").unwrap(); + repo.svn(&all, &["commit", "-q", "-m", "change only B"]); + repo.svn(&all, &["mkdir", "-q", "-m", "unrelated", &format!("{}/tags", repo.url)]); + std::fs::write(&a, "class A { int x = 2; }\n").unwrap(); + std::fs::write(&b, "class B { int x = 3; }\n// B\n").unwrap(); + repo.svn(&all, &["commit", "-q", "--username", "bob", "-m", "change both projects"]); + + let checkout = |name: &str| { + let local = repo.base.join(name); + repo.svn(&repo.base, &["checkout", "-q", &format!("{}/trunk/{name}", repo.url), local.to_str().unwrap()]); + ide_svn::WorkingCopy::discover(&local, ctx()).unwrap().unwrap() + }; + (checkout("projA"), checkout("projB")) +} + +#[test] +fn annotation_details_look_up_the_older_revision_by_id() { + let Some(repo) = repo() else { return }; + let (_, b) = workspace(&repo); + let lines = b.blame(&b.root().join("MainB.java"), None, None, utf8()).unwrap(); + assert_eq!(lines.iter().map(|line| line.commit.as_str()).collect::>(), ["5", "2"]); + let lookup = |revision: &str| { + b.log(&LogQuery { branch: Some(revision.into()), limit: 1, ..Default::default() }, &CancellationToken::new()) + .unwrap() + .remove(0) + }; + let older = lookup("2"); + let latest = lookup("5"); + assert_eq!((older.id.as_str(), older.author.as_str(), older.message.as_str()), ("2", "alice", "add the projects")); + assert_eq!((latest.author.as_str(), latest.message.as_str()), ("bob", "change both projects")); + assert!(latest.time_ms > older.time_ms); + assert_eq!(latest.time_ms, lines[0].time_ms); + assert_eq!( + (older.author.as_str(), older.time_ms, older.summary.as_str()), + (lines[1].author.as_str(), lines[1].time_ms, lines[1].summary.as_str()), + ); +} + +#[test] +fn file_history_diff_has_both_sides_of_the_one_character_change() { + let Some(repo) = repo() else { return }; + let (a, _) = workspace(&repo); + let path = a.root().join("MainA.java"); + let revisions = log(&a, LogQuery { path: Some(path.clone().into()), ..Default::default() }); + assert_eq!(revisions, ["5", "2"]); + let changes = a.commits_changes(&revisions[..1]).unwrap(); + let change = changes.iter().find(|c| c.path == "MainA.java").unwrap(); + assert_eq!(change.before.as_deref(), Some("2")); + assert_eq!(change.after.as_deref(), Some("5")); + assert_eq!( + a.file_at(&path, change.before.as_deref(), utf8()).unwrap().as_deref(), + Some("class A { int x = 1; }\n") + ); + assert_eq!(a.file_at(&path, change.after.as_deref(), utf8()).unwrap().as_deref(), Some("class A { int x = 2; }\n")); +} + +#[test] +fn project_log_uses_each_files_previous_revision_across_working_copies() { + let Some(repo) = repo() else { return }; + let (_, proj_b) = workspace(&repo); + let revisions = log(&proj_b, LogQuery::default()); + let changes = proj_b.commits_changes(&revisions[..1]).unwrap(); + let a = changes.iter().find(|c| c.path == "/trunk/projA/MainA.java").unwrap(); + let b = changes.iter().find(|c| c.path == "MainB.java").unwrap(); + assert_eq!((a.before.as_deref(), a.after.as_deref()), (Some("2"), Some("5"))); + assert_eq!((b.before.as_deref(), b.after.as_deref()), (Some("3"), Some("5"))); + for (revision, text) in + [(a.before.as_deref().unwrap(), "class A { int x = 1; }\n"), ("5", "class A { int x = 2; }\n")] + { + assert_eq!(proj_b.repository_text_at(&a.path, revision, |_| utf8()).unwrap().as_deref(), Some(text)); + } + let path = proj_b.root().join(&b.path); + for (revision, text) in [ + (b.before.as_deref(), "class B { int x = 2; }\n// B\n"), + (b.after.as_deref(), "class B { int x = 3; }\n// B\n"), + ] { + assert_eq!(proj_b.file_at(&path, revision, utf8()).unwrap().as_deref(), Some(text)); + } +} diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index b59919003..3d2bc488b 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -794,6 +794,7 @@ svn_merge trusted project_host bin svn_merge_sources trusted project_host bindings async svn_properties trusted project_host bindings async svn_relocate trusted project_host bindings async +svn_repository_file_at always project_host bindings async svn_repository_info trusted project_host bindings async svn_revert_revision trusted project_host bindings async svn_set_property trusted project_host bindings async diff --git a/src/bindings.ts b/src/bindings.ts index 4f3f6af3d..d9e918cbb 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -2386,6 +2386,8 @@ export const commands = { svnProperties: (path: string) => typedError(__TAURI_INVOKE("svn_properties", { path })), /** VCS › Subversion › Relocate: the same repository at a new URL (another host or scheme). */ svnRelocate: (repo: string | null, url: string) => typedError(__TAURI_INVOKE("svn_relocate", { repo, url })), + /** Reads a changed path at a fixed revision without requiring a checkout of that path. */ + svnRepositoryFileAt: (repo: string, path: string, revision: string) => typedError(__TAURI_INVOKE("svn_repository_file_at", { repo, path, revision })), svnRepositoryInfo: (repo: string | null) => typedError(__TAURI_INVOKE("svn_repository_info", { repo })), /** Subversion Log › Reverse Merge Revision (`svn merge -c -REV`). */ svnRevertRevision: (repo: string | null, request: RequestId, revision: number, onOutput: Channel) => typedError(__TAURI_INVOKE("svn_revert_revision", { repo, request, revision, onOutput })), diff --git a/src/features/vcs/BlamePopup.tsx b/src/features/vcs/BlamePopup.tsx index bf0765333..672becfdf 100644 --- a/src/features/vcs/BlamePopup.tsx +++ b/src/features/vcs/BlamePopup.tsx @@ -9,7 +9,8 @@ import { call, commands } from "@/platform/ipc"; import { Popup } from "@/ui"; import { IssueText } from "./issueLinks"; import { formatTime } from "./model"; -import { repoOf } from "./store"; +import { repoOf, vcsKindOf } from "./store"; +import { showCommitInLogLabel } from "./vcsKind"; import styles from "./BlamePopup.module.css"; interface BlamePopupState { @@ -40,7 +41,7 @@ function loadCommit(repo: string | null, commitId: string): Promise commits[0] ?? null, + (commits) => commits.find((commit) => commit.id === commitId) ?? null, () => null, ); if (commitCache.size >= 200) commitCache.delete(commitCache.keys().next().value!); @@ -160,10 +161,10 @@ function BlamePopupView({ state }: { state: BlamePopupState }) {