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.
Цей коміт міститься в:
l0ng-ai authored and GitHub committed 2026-12-03 05:43:01 +08:00
1 джерело a1ed7af5cf
коміт af2e515d0f
24 files changed
+602 -122

No files matched your search

+17 -13
Переглянути файл
@@ -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(())
})
+22
Переглянути файл
@@ -196,6 +196,27 @@ pub async fn svn_repository_info(host: &Host, window: &str, repo: Option<PathBuf
.await
}
/// Reads a changed path at a fixed revision without requiring a checkout of that path.
#[command(trust = always)]
pub async fn svn_repository_file_at(
host: &Host,
window: &str,
repo: PathBuf,
path: String,
revision: String,
) -> IdeResult<Option<String>> {
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<PathBuf>, 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,
+29 -1
Переглянути файл
@@ -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 };
+131 -56
Переглянути файл
@@ -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<u64> {
}
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<PathBuf> = 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<HashMap<u64, LogEntry>> {
self.log_entries(revisions, false)
self.log_entries(revisions, false, None)
}
fn revision_entry(&self, revision: u64) -> IdeResult<LogEntry> {
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<HashMap<u64, LogEntry>> {
fn log_entries(
&self,
revisions: &[u64],
verbose: bool,
cancel: Option<&CancellationToken>,
) -> IdeResult<HashMap<u64, LogEntry>> {
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<u64>) -> 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<Vec<Commit>> {
// 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<PathBuf> = 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<RevisionChange> = 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<PathBuf> = 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<()> {
+1 -1
Переглянути файл
@@ -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 {
+60 -10
Переглянути файл
@@ -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<Option<String>> {
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::<u64>().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<Vec<u8>> {
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;
+96
Переглянути файл
@@ -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::<Vec<_>>(), ["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));
}
}
+1
Переглянути файл
@@ -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
+2
Переглянути файл
@@ -2386,6 +2386,8 @@ export const commands = {
svnProperties: (path: string) => typedError<SvnProperty[], IdeError>(__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<null, IdeError>(__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<string | null, IdeError>(__TAURI_INVOKE("svn_repository_file_at", { repo, path, revision })),
svnRepositoryInfo: (repo: string | null) => typedError<SvnRepositoryInfo, IdeError>(__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<string>) => typedError<SvnMergeResult, IdeError>(__TAURI_INVOKE("svn_revert_revision", { repo, request, revision, onOutput })),
+5 -4
Переглянути файл
@@ -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<Commit | nul
limit: 1,
}),
).then(
(commits) => 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 }) {
<button
type="button"
className={styles.hashLink}
title={tx("Show Commit in Git Log")}
title={tx(showCommitInLogLabel(vcsKindOf(repo)))}
onClick={() => {
closeBlamePopup();
void executeAction("vcs.showCommit", line.commit);
void executeAction("vcs.showCommit", { id: line.commit, path });
}}
>
{line.commit}
+48 -2
Переглянути файл
@@ -88,7 +88,7 @@ beforeEach(() => {
vi.clearAllMocks();
useI18n.setState({ locale: "en", texts: {} });
useProject.setState({ settings: {} });
useVcs.setState({ available: true, root: "/repo", repo: "/repo", roots: ["/repo"] });
useVcs.setState({ available: true, root: "/repo", repo: "/repo", roots: ["/repo"], kinds: {} });
mocks.blame.mockResolvedValue({ status: "ok", data: lines });
mocks.log.mockResolvedValue({ status: "ok", data: [fullCommit] });
});
@@ -101,6 +101,52 @@ afterEach(() => {
});
describe("git blame gutter and commit popup", () => {
it("opens the SVN log for the annotated file in a mixed workspace", async () => {
const path = "/workspace/projA/MainA.java";
useVcs.setState({
repo: "/workspace/git",
roots: ["/workspace/git", "/workspace/projA", "/workspace/projB"],
kinds: { "/workspace/projA": "subversion", "/workspace/projB": "subversion" },
});
mocks.blame.mockResolvedValue({ status: "ok", data: [{ ...lines[0], commit: "28" }] });
view = new EditorView({
parent: document.body,
state: EditorState.create({ doc: "line", extensions: [blameSlot()] }),
});
await toggleAnnotations(view, path);
fireEvent.contextMenu(view.dom.querySelector("[data-commit='28']")!);
const items = mocks.menu.mock.calls[0]![1] as { label?: string; run?: () => void }[];
const reveal = items.find((item) => item.label === "Show Revision in SVN Log");
expect(reveal).toBeDefined();
reveal!.run!();
expect(mocks.action).toHaveBeenCalledWith("vcs.showCommit", { id: "28", path });
});
it("keeps the older SVN line's metadata if the log returns a different revision", async () => {
const path = "/workspace/projB/MainB.java";
useVcs.setState({
repo: "/workspace/projB",
roots: ["/workspace/projB"],
kinds: { "/workspace/projB": "subversion" },
});
const older = { commit: "28", author: "Alice", timeMs: Date.UTC(2025, 10, 2), summary: "Initial version" };
mocks.blame.mockResolvedValue({ status: "ok", data: [older] });
mocks.log.mockResolvedValue({ status: "ok", data: [{ ...fullCommit, id: "35", author: "Bob" }] });
view = new EditorView({
parent: document.body,
state: EditorState.create({ doc: "line", extensions: [blameSlot()] }),
});
await toggleAnnotations(view, path);
fireEvent.mouseOver(view.dom.querySelector("[data-commit='28']")!);
await act(async () => {
await vi.advanceTimersByTimeAsync(260);
});
expect(mocks.log).toHaveBeenCalledWith("/workspace/projB", expect.objectContaining({ branch: "28" }));
expect(screen.getByText("Initial version")).toBeInTheDocument();
expect(screen.getByText("Author: Alice")).toBeInTheDocument();
expect(screen.queryByText(/Author: Bob/)).not.toBeInTheDocument();
});
it("opens no empty column for a file Git has no commit of", async () => {
const zero = "0".repeat(40);
mocks.blame.mockResolvedValue({
@@ -156,7 +202,7 @@ describe("git blame gutter and commit popup", () => {
await act(async () => {
fireEvent.click(screen.getByRole("button", { name: sha }));
});
expect(mocks.action).toHaveBeenCalledWith("vcs.showCommit", sha);
expect(mocks.action).toHaveBeenCalledWith("vcs.showCommit", { id: sha, path: "/repo/src/main.py" });
});
it.each([undefined, "/repo/src/original.py"])("shows the line's change from its origin %s", async (originPath) => {
+23
Переглянути файл
@@ -63,6 +63,7 @@ beforeEach(() => {
root: "/p",
roots: ["/p"],
repo: "/p",
kinds: {},
statusLoaded: true,
loading: false,
error: null,
@@ -72,6 +73,28 @@ beforeEach(() => {
});
afterEach(() => dispose());
describe("SVN new-file confirmation in an attached working copy", () => {
it.each([
{ mode: "ask", button: "ok", prompts: 1, adds: 1 },
{ mode: "ask", button: "cancel", prompts: 1, adds: 0 },
{ mode: "silently", button: "cancel", prompts: 0, adds: 1 },
{ mode: "never", button: "ok", prompts: 0, adds: 0 },
])("$mode with $button", async ({ mode, button, prompts, adds }) => {
const root = "/attached/projB";
const path = `${root}/MainB.java`;
useVcs.setState({ roots: ["/p", root], kinds: { [root]: "subversion" } });
publish(file(path));
mocks.mode = mode;
mocks.ask.mockResolvedValue({ button, checked: false });
createFile(path);
await settle();
expect(mocks.ask).toHaveBeenCalledTimes(prompts);
if (prompts) expect(mocks.ask).toHaveBeenCalledWith(expect.objectContaining({ title: "Add File to SVN" }));
expect(mocks.stage).toHaveBeenCalledTimes(adds);
if (adds) expect(mocks.stage).toHaveBeenCalledWith([path]);
});
});
describe("Unity new-file Git confirmations", () => {
it("includes existing metadata in the confirmation and stages both files", async () => {
publish(file(asset), file(meta));
+89 -4
Переглянути файл
@@ -3,6 +3,9 @@ import { act, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const vcsCommitFiles = vi.fn();
const vcsCommitsChanges = vi.fn();
const vcsFileAt = vi.fn();
const svnRepositoryFileAt = vi.fn();
vi.mock("@/platform/ipc", async (importOriginal) => {
const real = await importOriginal<typeof import("@/platform/ipc")>();
const ok = <T,>(data: T) => Promise.resolve({ status: "ok" as const, data });
@@ -11,6 +14,9 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
commands: {
...real.commands,
vcsCommitFiles: (repo: unknown, id: string) => vcsCommitFiles(repo, id),
vcsCommitsChanges: (repo: unknown, ids: string[]) => vcsCommitsChanges(repo, ids),
vcsFileAt: (path: string, rev: string) => vcsFileAt(path, rev),
svnRepositoryFileAt: (repo: string, path: string, rev: string) => svnRepositoryFileAt(repo, path, rev),
vcsTags: () => ok([]),
vcsLog: () => ok([]),
vcsConfigGet: () => ok(null),
@@ -19,12 +25,13 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
});
import { useProject } from "@/platform/project";
import { provideEditorService } from "@/workbench/contributions";
import { diffInput } from "../diffInput";
import { provideEditorService, type EditorInput } from "@/workbench/contributions";
import { diffInput, readDiffSide, type DiffData } from "../diffInput";
import { CommitDetails } from "../log/CommitDetails";
import { toLogChanges } from "../logChanges";
import { DEFAULT_LOG_OPTIONS, useLogOptions } from "../logOptions";
import { emptyFilters, useGitLog } from "../logStore";
import { commitKey } from "../multiRoot";
import { useVcs } from "../store";
const commit: Commit = {
@@ -46,7 +53,7 @@ const files: ChangedFile[] = [
/** The preview tab of the first file, as the editor would report it. */
const shownInput = diffInput(toLogChanges(files, commit, "/repo")[0]!.diff);
const openInput = vi.fn(async () => undefined);
const openInput = vi.fn(async (_input: EditorInput) => undefined);
const activeInput = vi.fn(() => shownInput);
provideEditorService({ activeInput, openInput } as never);
@@ -54,10 +61,13 @@ const diffAsEditorTab = (on: boolean) =>
useProject.setState({ settings: { vcs: { diffAsEditorTab: on } } as Settings });
beforeEach(() => {
useVcs.setState({ root: "/repo", repo: "/repo", roots: ["/repo"], available: true, branchesLoaded: true });
useVcs.setState({ root: "/repo", repo: "/repo", roots: ["/repo"], kinds: {}, available: true, branchesLoaded: true });
useGitLog.setState({ commits: [commit], selected: commit.id, selection: [commit.id], filters: emptyFilters() });
useLogOptions.setState({ ...DEFAULT_LOG_OPTIONS });
vcsCommitFiles.mockReset().mockResolvedValue({ status: "ok", data: files });
vcsCommitsChanges.mockReset();
vcsFileAt.mockReset();
svnRepositoryFileAt.mockReset();
openInput.mockClear();
activeInput.mockClear();
});
@@ -82,6 +92,81 @@ async function selectSecondFile() {
}
describe("Git Log selection preview", () => {
it("compares a single SVN file history revision with the path's previous revision", async () => {
const path = "/repo/src/MainA.java";
const revision = { ...commit, id: "30", shortId: "30", parents: [], repo: "/repo" };
const selected = commitKey(revision);
useVcs.setState({ kinds: { "/repo": "subversion" } });
useGitLog.setState({
commits: [revision],
selected,
selection: [selected],
filters: { ...emptyFilters(), path },
});
vcsCommitsChanges.mockResolvedValue({
status: "ok",
data: [{ path: "src/MainA.java", kind: "modified", before: "29", after: "30" }],
});
diffAsEditorTab(true);
render(<CommitDetails commits={[revision]} />);
const row = await screen.findByText("MainA.java");
fireEvent.doubleClick(row);
expect(vcsCommitsChanges).toHaveBeenCalledWith("/repo", ["30"]);
expect(openInput).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({
path,
left: expect.objectContaining({ type: "rev", rev: "29" }),
right: expect.objectContaining({ type: "rev", rev: "30" }),
}),
}),
expect.anything(),
);
});
it("loads diffs for both files when the SVN log is scoped to one working copy", async () => {
const a = "/workspace/projA";
const b = "/workspace/projB";
const outside = "/trunk/projA/MainA.java";
const revision = { ...commit, id: "35", shortId: "35", parents: [], repo: b };
const selected = commitKey(revision);
useVcs.setState({ root: "/workspace", repo: b, roots: [a, b], kinds: { [a]: "subversion", [b]: "subversion" } });
useGitLog.setState({
commits: [revision],
selected,
selection: [selected],
filters: { ...emptyFilters(), repositories: [b] },
});
vcsCommitsChanges.mockResolvedValue({
status: "ok",
data: [
{ path: outside, kind: "modified", before: "30", after: "35" },
{ path: "MainB.java", kind: "modified", before: "33", after: "35" },
],
});
svnRepositoryFileAt.mockImplementation(async (_repo, _path, rev) => ({ status: "ok", data: `A r${rev}` }));
vcsFileAt.mockImplementation(async (_path, rev) => ({ status: "ok", data: `B r${rev}` }));
diffAsEditorTab(true);
render(<CommitDetails commits={[revision]} />);
const checkDiff = async (file: string, expected: string[]) => {
fireEvent.doubleClick(await screen.findByText(file));
const data = openInput.mock.lastCall![0].data as DiffData;
await expect(
Promise.all([readDiffSide(data.path, data.left), readDiffSide(data.path, data.right)]),
).resolves.toEqual(expected);
};
await checkDiff("MainA.java", ["A r30", "A r35"]);
await checkDiff("MainB.java", ["B r33", "B r35"]);
expect(svnRepositoryFileAt.mock.calls).toEqual([
[b, outside, "30"],
[b, outside, "35"],
]);
expect(vcsFileAt.mock.calls).toEqual([
[`${b}/MainB.java`, "33"],
[`${b}/MainB.java`, "35"],
]);
});
it("opens no preview tab when diffs open in a separate window", async () => {
diffAsEditorTab(false);
render(<CommitDetails commits={[commit]} />);
+3 -2
Переглянути файл
@@ -1267,8 +1267,9 @@ export function registerVcsActions(): () => void {
const commit = arg && typeof arg === "object" && "id" in arg ? (arg as import("@/bindings").Commit) : null;
const id = typeof arg === "string" ? arg : commit?.id;
if (!id) return;
const active = maybeEditorService()?.activePath();
const repo = commit ? commitRepo(commit) : ((active ? repoOf(active) : null) ?? currentRepo());
const path = typeof arg === "object" ? argPath(arg) : undefined;
const active = path ?? maybeEditorService()?.activePath();
const repo = commit && !path ? commitRepo(commit) : ((active ? repoOf(active) : null) ?? currentRepo());
showGitWindow();
void revealCommit(id, repo);
},
+6 -4
Переглянути файл
@@ -14,6 +14,7 @@ import { closeBlamePopup, scheduleCloseBlamePopup, scheduleOpenBlamePopup } from
import { formatPrettyDay } from "@/platform/dateFormat";
import { saveVcsSetting } from "./settingsUi";
import { repoOf, useVcs, vcsKindOf } from "./store";
import { showCommitInLogLabel } from "./vcsKind";
const ZERO = /^0+$/;
@@ -658,13 +659,14 @@ function blameExtension(lines: BlameLine[], source: BlameSource): Extension {
click(view, block) {
closeBlamePopup(view);
const l = lineAt(view, block.from);
if (l && !isUncommitted(l)) void executeAction("vcs.showCommit", l.commit);
if (l && !isUncommitted(l)) void executeAction("vcs.showCommit", { id: l.commit, path });
return true;
},
contextmenu(view, block, event) {
closeBlamePopup(view);
const l = lineAt(view, block.from);
const origin = l?.originPath ?? path;
const kind = vcsKindOf(repoOf(path));
event.preventDefault();
showContextMenu(event as MouseEvent, [
{ label: "Close Annotations", run: () => setAnnotations(view, null, source) },
@@ -705,12 +707,12 @@ function blameExtension(lines: BlameLine[], source: BlameSource): Extension {
void import("./annotateRevision").then((m) => m.annotatePreviousRevision(origin, l.commit)),
},
{
label: "Show Commit in Git Log",
label: showCommitInLogLabel(kind),
icon: "commit",
run: () => void executeAction("vcs.showCommit", l.commit),
run: () => void executeAction("vcs.showCommit", { id: l.commit, path }),
},
// Git's blame.ignoreRevsFile: svn has no list of revisions to skip.
...(vcsKindOf(repoOf(path)) === "git"
...(kind === "git"
? [
{
label: "Ignore This Commit",
+31 -14
Переглянути файл
@@ -1,6 +1,6 @@
/**
* Settings › Version Control › Confirmation: files created in the IDE are
* added to Git (ask / silently / never); tracked files deleted in the IDE have
* added to version control (ask / silently / never); tracked files deleted in the IDE have
* the deletion staged (`git rm`), with the same three choices.
*/
import { onFileOperation, type FileOperation } from "@/platform/fileOps";
@@ -10,7 +10,7 @@ import { ipcPath, isSameOrInside } from "@/platform/paths";
import { loadSettings } from "@/platform/project";
import { workflowSettings } from "@/platform/workflowSettings";
import { ask } from "@/workbench/messages";
import { effectiveKind, relTo, stripSlash } from "./model";
import { effectiveKind, relTo, rootOf, stripSlash } from "./model";
import { runOp } from "./ops";
import { refreshNow, useVcs } from "./store";
import { createUnityMetadataStaging } from "./unityMetadata";
@@ -40,23 +40,31 @@ export async function rememberSetting(key: string, value: unknown) {
}
}
async function confirmFiles(op: FileOperation["kind"], files: string[]): Promise<{ ok: boolean; remember: boolean }> {
const root = useVcs.getState().root ?? "";
async function confirmFiles(
op: FileOperation["kind"],
files: string[],
system: string,
): Promise<{ ok: boolean; remember: boolean }> {
const { root, roots } = useVcs.getState();
const add = op === "created";
const n = files.length;
const list = files
.slice(0, 10)
.map((f) => relTo(root, f))
.map((f) => relTo(rootOf(f, roots) ?? root ?? "", f))
.join("\n");
const question = add
? n === 1
? tx("Do you want to add the following file to Git?")
: tx`Do you want to add the following ${n} files to Git?`
? system === "Git"
? n === 1
? tx("Do you want to add the following file to Git?")
: tx`Do you want to add the following ${n} files to Git?`
: n === 1
? tx`Do you want to add the following file to ${system}?`
: tx`Do you want to add the following ${n} files to ${system}?`
: n === 1
? tx("Do you want to remove the following file from Git?")
: tx`Do you want to remove the following ${n} files from Git?`;
const r = await ask({
title: add ? "Add File to Git" : "Remove File from Git",
title: add ? (system === "Git" ? "Add File to Git" : tx`Add File to ${system}`) : "Remove File from Git",
body: `${question}\n${list}${n > 10 ? "\n…" : ""}`,
checkbox: "Don't ask again",
width: 480,
@@ -71,7 +79,9 @@ async function handle(op: FileOperation, metadata: ReturnType<typeof createUnity
const conf = workflowSettings().vcs.confirmation;
const mode = op.kind === "created" ? conf.onCreate : conf.onDelete;
if (mode === "never") return;
const paths = op.paths.map((p) => stripSlash(ipcPath(p))).filter((p) => isSameOrInside(p, vcs.root!));
const paths = op.paths
.map((p) => stripSlash(ipcPath(p)))
.filter((p) => rootOf(p, vcs.roots) || isSameOrInside(p, vcs.root!));
if (!paths.length) return;
const addition = metadata.begin(op.kind === "created" ? paths : []);
await refreshNow();
@@ -79,8 +89,11 @@ async function handle(op: FileOperation, metadata: ReturnType<typeof createUnity
const files = matching(paths, op.kind === "created" ? "untracked" : "deleted");
if (!files.length) return;
const confirmed = addition.include(files);
const { roots, kinds } = useVcs.getState();
const svn = (p: string) => kinds[rootOf(p, roots) ?? ""] === "subversion";
const system = confirmed.every(svn) ? "SVN" : confirmed.some(svn) ? tx("Version Control") : "Git";
if (mode === "ask") {
const { ok, remember } = await confirmFiles(op.kind, confirmed);
const { ok, remember } = await confirmFiles(op.kind, confirmed, system);
if (!addition.current()) return;
if (remember) {
const key = op.kind === "created" ? "vcs.confirmation.onCreate" : "vcs.confirmation.onDelete";
@@ -93,9 +106,13 @@ async function handle(op: FileOperation, metadata: ReturnType<typeof createUnity
const n = stageFiles.length;
const ok = await runOp(
op.kind === "created"
? n === 1
? tx("Add 1 file to Git")
: tx`Add ${n} files to Git`
? system === "Git"
? n === 1
? tx("Add 1 file to Git")
: tx`Add ${n} files to Git`
: n === 1
? tx`Add 1 file to ${system}`
: tx`Add ${n} files to ${system}`
: n === 1
? tx("Remove 1 file from Git")
: tx`Remove ${n} files from Git`,
+8 -3
Переглянути файл
@@ -17,7 +17,7 @@ import type { StagingRange } from "./stagingRange";
type GitDiffSide =
/** File content at a git revision (`HEAD`, `:0` = index, a commit id, `<id>^`). */
| { type: "rev"; rev: string; path?: string; label?: string }
| { type: "rev"; rev: string; path?: string; label?: string; svn?: { repo: string; path: string } }
/** The working file (unsaved editor buffer included). */
| { type: "worktree"; label?: string; labelDetail?: string };
@@ -107,7 +107,7 @@ export function oneSided(data: Pick<DiffData, "left" | "right">): boolean {
export function sideKey(s: DiffSide): string {
switch (s.type) {
case "rev":
return `rev:${s.rev}:${s.path ?? ""}`;
return s.svn ? `svn:${s.rev}:${s.svn.repo}:${s.svn.path}` : `rev:${s.rev}:${s.path ?? ""}`;
case "worktree":
return "wt";
case "file":
@@ -361,16 +361,19 @@ export function commitFileDiffData(
export function revisionChangeDiffData(change: RevisionChange, root = currentRepoRoot()): DiffData {
const path = joinRoot(change.path, root);
const { before, after } = change;
const svnPath = (path: string) =>
root && path.startsWith("/") && vcsKindOf(root) === "subversion" ? { svn: { repo: root, path } } : {};
const left: DiffSide = before
? {
type: "rev",
rev: before,
path: change.oldPath ? joinRoot(change.oldPath, root) : undefined,
label: before.slice(0, 8),
...svnPath(change.oldPath ?? change.path),
}
: { type: "text", text: "", label: "(does not exist)", absent: true };
const right: DiffSide = after
? { type: "rev", rev: after, label: after.slice(0, 8) }
? { type: "rev", rev: after, label: after.slice(0, 8), ...svnPath(change.path) }
: { type: "text", text: "", label: "(deleted)", absent: true };
return { path, left, right };
}
@@ -378,6 +381,7 @@ export function revisionChangeDiffData(change: RevisionChange, root = currentRep
export async function readDiffSide(path: string, side: DiffSide): Promise<string | null> {
switch (side.type) {
case "rev":
if (side.svn) return call(commands.svnRepositoryFileAt(side.svn.repo, side.svn.path, side.rev));
return call(commands.vcsFileAt(side.path ?? path, side.rev));
case "worktree": {
const text = await readWorkingText(path);
@@ -409,6 +413,7 @@ export async function loadSide(path: string, side: DiffSide): Promise<string> {
export async function loadSideMode(path: string, side: DiffSide): Promise<string | null> {
switch (side.type) {
case "rev":
if (side.svn) return null;
return call(commands.vcsFileMode(side.path ?? path, side.rev)).catch(() => null);
case "worktree":
return call(commands.vcsFileMode(path, "WT")).catch(() => null);
+5 -4
Переглянути файл
@@ -58,7 +58,7 @@ import { logOptions, useLogOptions } from "../logOptions";
import { openLogTab, updateLogOptions, useGitLog } from "../logStore";
import { KIND_COLOR, dirName, fileCount, renameFrom, type EffectiveKind } from "../model";
import { commitKey, commitRepo } from "../multiRoot";
import { currentRepo, repoName } from "../store";
import { currentRepo, repoName, useVcsKind } from "../store";
import { CommitMessage } from "./CommitMessage";
import { useDropdownMenu, useReadOnlyLog } from "./logHooks";
import { PANE_STYLE, toggle } from "./shared";
@@ -107,6 +107,7 @@ export function CommitDetails({ commits, fileHistory = false }: { commits: Commi
const many = chosen.length > 1;
const idsKey = chosen.map(commitKey).join(" ");
const commitRoot = commit ? commitRepo(commit) : null;
const kind = useVcsKind(commitRoot);
const [result, setResult] = useState<{
key: string;
files: LogChange[] | null;
@@ -124,7 +125,7 @@ export function CommitDetails({ commits, fileHistory = false }: { commits: Commi
const diffLocation = modal && savedLocation === "editor" ? "right" : savedLocation;
const showLineStats = useLogOptions((s) => s.showLineStats);
const filters = useGitLog((s) => s.filters);
const filesKey = JSON.stringify([idsKey, fromParents, parentIndex, commitRoot, showLineStats]);
const filesKey = JSON.stringify([idsKey, fromParents, parentIndex, commitRoot, kind, showLineStats]);
const files = result?.key === filesKey ? result.files : null;
const error = result?.key === filesKey ? result.error : null;
@@ -132,7 +133,7 @@ export function CommitDetails({ commits, fileHistory = false }: { commits: Commi
if (!idsKey) return;
let alive = true;
const load = (async () => {
if (many) {
if (many || kind === "subversion") {
const roots = [...new Set(chosen.map(commitRepo))];
return (
await Promise.all(
@@ -185,7 +186,7 @@ export function CommitDetails({ commits, fileHistory = false }: { commits: Commi
alive = false;
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [idsKey, fromParents, parentIndex, commitRoot, filesKey, many, readOnly, showLineStats]);
}, [idsKey, fromParents, parentIndex, commitRoot, filesKey, kind, many, readOnly, showLineStats]);
const groupByDirectory = useLogOptions((s) => s.groupByDirectory);
const [selectedKeys, setSelectedKeys] = useState<ReadonlySet<string>>(() => new Set());
+2 -2
Переглянути файл
@@ -23,7 +23,7 @@ import type { FileTreeNode } from "./fileTree";
import { baseName } from "./model";
import { readWorkingText, runOp, saveAll, writeFileText } from "./ops";
import { reportApply } from "./shelf";
import { currentRepoRoot, useVcs } from "./store";
import { currentRepoRoot, useVcs, vcsKindOf } from "./store";
import { commitRepo } from "./multiRoot";
import { repositoryPath } from "./repositoryPaths";
import { confirmDialog } from "./dialogs";
@@ -93,7 +93,7 @@ export function toLogChanges(
const r = f as RevisionChange;
return {
repo,
readOnly,
readOnly: readOnly || (r.path.startsWith("/") && vcsKindOf(repo) === "subversion"),
path: r.path,
oldPath: r.oldPath,
kind: r.kind,
+6 -2
Переглянути файл
@@ -19,7 +19,7 @@ import {
type LogOptions,
} from "./logOptions";
import { clearConsole, errorMessage } from "./ops";
import { currentRepo, currentRepoRoot, repoName, repoOf, useVcs } from "./store";
import { currentRepo, currentRepoRoot, repoName, repoOf, useVcs, vcsKindOf } from "./store";
import { chooseLogCommit } from "./CommitChooser";
import { presentLogGraph } from "./logPresentation";
import { toggleBookmark, updateBookmarks, useBookmarks } from "@/features/search/bookmarks/store";
@@ -1383,10 +1383,14 @@ export async function revealCommit(id: string, repo = currentRepo(), tab = "log"
state.selected === selected
);
};
const allowPrefix = vcsKindOf(repo) !== "subversion";
const find = () =>
useGitLog
.getState()
.commits.find((c) => (!repo || !commitRepo(c) || commitRepo(c) === repo) && (c.id === id || c.id.startsWith(id)));
.commits.find(
(c) =>
(!repo || !commitRepo(c) || commitRepo(c) === repo) && (c.id === id || (allowPrefix && c.id.startsWith(id))),
);
const waitReload = async () => {
await reloadLog();
// The log's first mount may replace this request with its own initial load.
+1
Переглянути файл
@@ -105,6 +105,7 @@ export function createUnityMetadataStaging() {
source &&
untracked(source) &&
repo &&
(vcs.kinds[repo] ?? "git") === "git" &&
rootOf(`${path}.meta`, vcs.roots) === repo
? [[path, repo] as const]
: [];
+4
Переглянути файл
@@ -165,6 +165,10 @@ export function vcsToolWindowTitle(kind: VcsKind): string {
return kind === "subversion" ? "SVN" : "Git";
}
export function showCommitInLogLabel(kind: VcsKind): string {
return kind === "subversion" ? "Show Revision in SVN Log" : "Show Commit in Git Log";
}
/** The tool window's stripe icon: Subversion's for a Subversion root, the VCS icon otherwise. */
export function vcsToolWindowIcon(kind: VcsKind): string {
return kind === "subversion" ? "subversion" : "toolwindow-git";
+6
Переглянути файл
@@ -1,4 +1,10 @@
{
"Add File to {system}": "Add File to {system}",
"Add 1 file to {system}": "Add 1 file to {system}",
"Add {n} files to {system}": "Add {n} files to {system}",
"Do you want to add the following file to {system}?": "Do you want to add the following file to {system}?",
"Do you want to add the following {n} files to {system}?": "Do you want to add the following {n} files to {system}?",
"Show Revision in SVN Log": "Show Revision in SVN Log",
"Large Files": "Large Files",
"Maximum file size for code insight": "Maximum file size for code insight",
"Reopen files to apply the new limit.": "Reopen files to apply the new limit.",
+6
Переглянути файл
@@ -1,4 +1,10 @@
{
"Add File to {system}": "将文件添加到 {system}",
"Add 1 file to {system}": "将 1 个文件添加到 {system}",
"Add {n} files to {system}": "将 {n} 个文件添加到 {system}",
"Do you want to add the following file to {system}?": "是否将以下文件添加到 {system}?",
"Do you want to add the following {n} files to {system}?": "是否将以下 {n} 个文件添加到 {system}?",
"Show Revision in SVN Log": "在 SVN 日志中显示修订",
"Not verified": "未验证",
"No loaded code at this line yet. If it stays unbound after its module loads, the debug info may record this file under another path (through a symlink, or /tmp for /private/tmp): set a source map from that path to this one": "此行的代码尚未加载。如果模块加载后仍未绑定,调试信息可能以另一条路径记录了此文件(经过符号链接,或以 /tmp 代替 /private/tmp):请设置从该路径到此路径的源映射",
"Large Files": "大文件",