diff --git a/crates/ide-host/src/ops/svn.rs b/crates/ide-host/src/ops/svn.rs index b622d2e513..c70a3b47a3 100644 --- a/crates/ide-host/src/ops/svn.rs +++ b/crates/ide-host/src/ops/svn.rs @@ -137,6 +137,28 @@ pub async fn svn_cleanup(host: &Host, window: &str, repo: Option) -> Id .await } +/// Working Copies Information › Format › Change: `svn upgrade` of the working copy at `repo` +/// to the format `version` (`1.8`, `1.15`). +#[command(trust = trusted)] +pub async fn svn_upgrade( + host: &Host, + window: &str, + request: ide_core::RequestId, + repo: PathBuf, + version: String, +) -> IdeResult<()> { + let project = host.project(window)?; + let cancel = host.begin_request(request); + let result = blocking(move || { + with_working_copy(&project, Some(&repo), |wc| wc.upgrade(&version, &cancel))?; + project.vcs_changed(); + Ok(()) + }) + .await; + host.end_request(request); + result +} + /// VCS › Subversion › Lock: `svn lock` with a comment; `steal` takes a lock someone else holds. #[command(trust = trusted)] pub async fn svn_lock(host: &Host, window: &str, paths: Vec, comment: String, steal: bool) -> IdeResult<()> { @@ -702,7 +724,7 @@ impl From for SvnIncomingChange { } /// Working copy metadata returned by `svn_working_copy_info`. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] pub struct SvnWorkingCopyInfo { pub root: String, @@ -716,6 +738,14 @@ pub struct SvnWorkingCopyInfo { pub depth: String, pub format: Option, pub is_switched: bool, + /// `root` is the root of its working copy (IntelliJ's "Working copy root"). + pub is_wc_root: bool, + /// A working copy of its own inside another one: an `svn:externals` definition. + pub is_external: bool, + /// Why the working copy could not be read; the other fields are then empty. + pub error: Option, + /// The formats the configured svn can convert it to (Format › Change), oldest first. + pub formats: Vec, } impl From for SvnWorkingCopyInfo { @@ -731,7 +761,9 @@ impl From for SvnWorkingCopyInfo { last_changed_time_ms: w.last_changed_time_ms, depth: w.depth, format: w.format, + is_wc_root: w.is_wc_root, is_switched: w.is_switched, + ..Self::default() } } } @@ -789,6 +821,123 @@ pub async fn svn_incoming( result } +/// A revision committed after a working copy's BASE: a row of the Incoming tab. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct SvnIncomingRevision { + /// The working copy it is incoming to. + pub root: String, + pub revision: u32, + pub author: String, + pub time_ms: f64, + pub message: String, + pub paths: Vec, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct SvnIncomingPath { + /// `A`, `D`, `M` or `R`. + pub action: String, + /// Repository path: `/trunk/a.txt`. + pub path: String, + /// The file in the working copy, for a path under the working copy's URL. + pub local: Option, + pub kind: String, +} + +/// The Incoming tab's revisions of every Subversion working copy, and the working copies that +/// could not be read. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct SvnIncomingRevisions { + pub revisions: Vec, + pub errors: Vec, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct SvnWorkingCopyError { + pub root: String, + pub message: String, +} + +fn incoming_revision(root: &str, r: ide_svn::IncomingRevision) -> SvnIncomingRevision { + SvnIncomingRevision { + root: root.to_owned(), + revision: u32::try_from(r.revision).unwrap_or(u32::MAX), + author: r.author, + time_ms: r.time_ms, + message: r.message, + paths: r + .paths + .into_iter() + .map(|p| SvnIncomingPath { + action: p.action, + path: p.path, + local: p.local.map(|l| l.display().to_string()), + kind: p.kind, + }) + .collect(), + } +} + +/// Update Info › Group by Changelist: the revisions `from` to `to` of the working copy at `repo`, +/// newest first, with their files. +#[command(trust = trusted)] +pub async fn svn_revisions_between( + host: &Host, + window: &str, + request: ide_core::RequestId, + repo: PathBuf, + from: u32, + to: u32, +) -> IdeResult> { + let project = host.project(window)?; + project.require_trust()?; + let cancel = host.begin_request(request); + let result = blocking(move || { + with_working_copy(&project, Some(&repo), |wc| { + let root = wc.root().display().to_string(); + let found = wc.revisions_between(u64::from(from), u64::from(to), &cancel)?; + Ok(found.into_iter().map(|r| incoming_revision(&root, r)).collect()) + }) + }) + .await; + host.end_request(request); + result +} + +/// Incoming: for each Subversion working copy, the revisions committed to its URL after its +/// BASE revision, from BASE+1 to HEAD, as IntelliJ's Incoming tab lists them. +#[command(trust = trusted)] +pub async fn svn_incoming_revisions( + host: &Host, + window: &str, + request: ide_core::RequestId, +) -> IdeResult { + let project = host.project(window)?; + project.require_trust()?; + let cancel = host.begin_request(request); + let result = blocking(move || { + let mut out = SvnIncomingRevisions::default(); + for backend in project.backends() { + let Some(wc) = as_svn(backend.as_ref()) else { continue }; + let root = wc.root().display().to_string(); + match wc.incoming_revisions(&cancel) { + Ok(found) => out.revisions.extend(found.into_iter().map(|r| incoming_revision(&root, r))), + Err(e) if cancel.is_cancelled() => return Err(e), + Err(e) => out.errors.push(SvnWorkingCopyError { root, message: e.message }), + } + } + out.revisions.sort_by(|a, b| b.time_ms.total_cmp(&a.time_ms).then(b.revision.cmp(&a.revision))); + Ok(out) + }) + .await; + host.end_request(request); + result +} + /// Reads metadata for one Subversion working copy (`repo = Some`) or all Subversion working copies in the project. #[command(trust = trusted)] pub async fn svn_working_copy_info( @@ -805,16 +954,40 @@ pub async fn svn_working_copy_info( let mut infos: Vec = Vec::new(); for backend in project.backends() { if let Some(wc) = as_svn(backend.as_ref()) { - infos.extend(wc.working_copy_infos()?.into_iter().map(Into::into)); + // One working copy that cannot be read shows its error; the others still show. + match wc.working_copy_infos() { + Ok(found) => { + let formats = wc.supported_formats(); + infos.extend( + found.into_iter().map(|w| SvnWorkingCopyInfo { formats: formats.clone(), ..w.into() }), + ); + } + Err(e) => infos.push(SvnWorkingCopyInfo { + root: wc.root().display().to_string(), + error: Some(e.message), + ..SvnWorkingCopyInfo::default() + }), + } } } infos.sort_by(|a, b| a.root.cmp(&b.root)); infos.dedup_by(|a, b| a.root == b.root); + mark_externals(&mut infos); Ok(infos) }) .await } +/// A working copy root inside another listed working copy is an external of it: svn checks +/// `svn:externals` definitions out as working copies of their own, which the IDE finds as roots. +fn mark_externals(infos: &mut [SvnWorkingCopyInfo]) { + let roots: Vec = infos.iter().filter(|i| i.is_wc_root).map(|i| PathBuf::from(&i.root)).collect(); + for info in infos.iter_mut().filter(|i| i.is_wc_root) { + let path = PathBuf::from(&info.root); + info.is_external = roots.iter().any(|outer| outer != &path && path.starts_with(outer)); + } +} + /// Lists configured or standard-layout branches and tags for a Subversion working copy. #[command(trust = trusted)] pub async fn svn_branch_layout( @@ -1122,6 +1295,8 @@ ide_command::domain!( svn_eligible_revisions, svn_export, svn_incoming, + svn_incoming_revisions, + svn_revisions_between, svn_list_url, svn_ignore_pattern, svn_item_url, @@ -1142,6 +1317,7 @@ ide_command::domain!( svn_set_property_options, svn_switch_url, svn_unlock, + svn_upgrade, svn_update_options, svn_version, svn_working_copy_info, diff --git a/crates/ide-host/src/ops/vcs/commands.rs b/crates/ide-host/src/ops/vcs/commands.rs index c5356f5f30..be576b57e4 100644 --- a/crates/ide-host/src/ops/vcs/commands.rs +++ b/crates/ide-host/src/ops/vcs/commands.rs @@ -359,6 +359,23 @@ pub enum RemoteOpReport { pub struct UpdateReport { /// Files and folders added, deleted, changed or merged. pub updated_files: u32, + /// Each file or folder the update touched (Update Info's tree). + #[serde(default)] + pub items: Vec, + /// The working copy's revision before and after the update. + #[serde(default)] + pub from_revision: Option, + #[serde(default)] + pub to_revision: Option, +} + +/// One file or folder of an [`UpdateReport`]: `action` is svn's four status columns as it +/// prints them (`U `, ` U `, `C `, ` C`), or `restored` / `skipped`. +#[derive(Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct UpdatedItemReport { + pub path: PathBuf, + pub action: String, } #[derive(Serialize, Deserialize, Type)] @@ -2020,9 +2037,16 @@ pub async fn vcs_remote( { let result = with_shelf_batch(&project, shelf_batch, || { project.with_backend_recorded(repo.as_deref(), Some("Update"), |b| { - b.update(paths, &cancel, &out).map(|changed| { + b.update(paths, &cancel, &out).map(|summary| { Some(RemoteOpReport::Update(UpdateReport { - updated_files: u32::try_from(changed).unwrap_or(u32::MAX), + updated_files: u32::try_from(summary.changed).unwrap_or(u32::MAX), + items: summary + .items + .into_iter() + .map(|i| UpdatedItemReport { path: i.path, action: i.action }) + .collect(), + from_revision: summary.from_revision, + to_revision: summary.to_revision, })) }) }) diff --git a/crates/ide-host/tests/svn.rs b/crates/ide-host/tests/svn.rs index 22ef18d49d..37310b6fbe 100644 --- a/crates/ide-host/tests/svn.rs +++ b/crates/ide-host/tests/svn.rs @@ -1615,3 +1615,100 @@ async fn update_output_of_two_working_copies() { assert!(lines.last().is_some_and(|l| l.starts_with("Updated to revision ")), "{name}: {lines:?}"); } } + +/// Update Info (issue #7433): an update's report keeps what svn did to each file, as IntelliJ's +/// Update Info tree groups it (updated, created, deleted, merged, merged with conflicts), and the +/// revisions before and after. +#[tokio::test] +async fn update_report_keeps_each_files_action() { + let Some(fx) = fixture() else { return }; + let seed = fx.checkout("seed"); + for name in ["a.txt", "gone.txt", "merge.txt", "conflict.txt"] { + std::fs::write(seed.join(name), "one\ntwo\nthree\n").unwrap(); + } + fx.svn(&seed, &["add", "-q", "a.txt", "gone.txt", "merge.txt", "conflict.txt"]); + fx.svn(&seed, &["commit", "-q", "-m", "seed"]); + let root = fx.checkout("project"); + // Local edits: one that merges, one that conflicts. + std::fs::write(root.join("merge.txt"), "ONE\ntwo\nthree\n").unwrap(); + std::fs::write(root.join("conflict.txt"), "one\nmine\nthree\n").unwrap(); + std::fs::write(seed.join("a.txt"), "one\ntwo\nthree\nfour\n").unwrap(); + std::fs::write(seed.join("new.txt"), "new\n").unwrap(); + std::fs::write(seed.join("merge.txt"), "one\ntwo\nTHREE\n").unwrap(); + std::fs::write(seed.join("conflict.txt"), "one\ntheirs\nthree\n").unwrap(); + fx.svn(&seed, &["add", "-q", "new.txt"]); + fx.svn(&seed, &["rm", "-q", "gone.txt"]); + fx.svn(&seed, &["commit", "-q", "-m", "two"]); + + let (host, _project) = open(&fx.base, &root).await; + let channel = ide_host::ops::Channel::new(|_: String| {}); + let op = vcs::RemoteOp::UpdateProjectBranch { rebase: false }; + let report = vcs::vcs_remote(&host, "main", None, ide_core::RequestId::next(), op, channel, None).await.unwrap(); + let Some(vcs::RemoteOpReport::Update(report)) = report else { panic!("no update report") }; + let mut items: Vec<(String, String)> = report + .items + .iter() + .map(|i| (i.path.strip_prefix(&root).unwrap().display().to_string(), i.action.clone())) + .collect(); + items.sort(); + assert_eq!( + items, + [ + ("a.txt".to_owned(), "U ".to_owned()), + ("conflict.txt".to_owned(), "C ".to_owned()), + ("gone.txt".to_owned(), "D ".to_owned()), + ("merge.txt".to_owned(), "G ".to_owned()), + ("new.txt".to_owned(), "A ".to_owned()), + ] + ); + assert_eq!(report.updated_files, 5); + assert_eq!((report.from_revision.as_deref(), report.to_revision.as_deref()), (Some("2"), Some("3"))); +} + +/// Incoming (issue #7433): every working copy's revisions from BASE+1 to HEAD, newest first, +/// with their files where they are in that working copy; an updated copy has none left. +#[tokio::test] +async fn incoming_revisions_of_two_working_copies() { + let Some(fx) = fixture() else { return }; + let seed = fx.checkout("seed"); + std::fs::write(seed.join("a.txt"), "one\n").unwrap(); + fx.svn(&seed, &["add", "-q", "a.txt"]); + fx.svn(&seed, &["commit", "-q", "-m", "seed"]); + let project_root = fx.base.join("project"); + std::fs::create_dir(&project_root).unwrap(); + let trunk = format!("{}/trunk", fx.url); + for name in ["boot", "antd"] { + fx.svn(&fx.base, &["checkout", "-q", &trunk, project_root.join(name).to_str().unwrap()]); + } + std::fs::write(seed.join("a.txt"), "two\n").unwrap(); + fx.svn(&seed, &["commit", "-q", "-m", "change a"]); + std::fs::write(seed.join("b.txt"), "new\n").unwrap(); + fx.svn(&seed, &["add", "-q", "b.txt"]); + fx.svn(&seed, &["commit", "-q", "-m", "add b"]); + + let host = Host::new(common::host_config(&fx.base)).with_subversion(false); + host.trust.decide(&project_root, true, false).unwrap(); + let project = host.open_project("main", &project_root).unwrap(); + until("both working copies", || project.backends().len() == 2).await; + let incoming = || svn::svn_incoming_revisions(&host, "main", ide_core::RequestId::next()); + let found = incoming().await.unwrap(); + assert!(found.errors.is_empty(), "{:?}", found.errors); + for name in ["boot", "antd"] { + let root = project_root.join(name); + let mine: Vec<_> = found.revisions.iter().filter(|r| r.root == root.display().to_string()).collect(); + assert_eq!( + mine.iter().map(|r| (r.revision, r.message.as_str())).collect::>(), + [(4, "add b"), (3, "change a")] + ); + let b = &mine[0].paths[0]; + assert_eq!((b.action.as_str(), b.path.as_str()), ("A", "/trunk/b.txt")); + assert_eq!(b.local.as_deref(), Some(root.join("b.txt").display().to_string().as_str())); + } + + // Updated, boot has nothing incoming; antd still has both revisions. + fx.svn(&project_root.join("boot"), &["update", "-q"]); + let after = incoming().await.unwrap(); + let roots: Vec<_> = after.revisions.iter().map(|r| (r.root.clone(), r.revision)).collect(); + let antd = project_root.join("antd").display().to_string(); + assert_eq!(roots, [(antd.clone(), 4), (antd, 3)]); +} diff --git a/crates/ide-host/tests/vcs_backends.rs b/crates/ide-host/tests/vcs_backends.rs index 32dd6b90be..2b5fbe1309 100644 --- a/crates/ide-host/tests/vcs_backends.rs +++ b/crates/ide-host/tests/vcs_backends.rs @@ -44,10 +44,15 @@ impl Backend for Fake { fn head_label(&self) -> Option { Some(self.head.lock().clone()) } - fn update(&self, _: &[PathBuf], _: &CancellationToken, output: &dyn Fn(String)) -> IdeResult { + fn update( + &self, + _: &[PathBuf], + _: &CancellationToken, + output: &dyn Fn(String), + ) -> IdeResult { std::fs::write(self.root.join("a.txt"), "updated\n")?; output("Updated to revision 8.".into()); - Ok(1) + Ok(ide_vcs::UpdateSummary { changed: 1, ..Default::default() }) } fn branches(&self) -> IdeResult> { let head = self.head.lock().clone(); @@ -347,7 +352,7 @@ async fn a_working_copy_answers_the_shared_vcs_commands() { let channel = ide_host::ops::Channel::new(move |line: String| lines.lock().push(line)); let op = vcs::RemoteOp::UpdateProjectBranch { rebase: false }; let report = vcs::vcs_remote(&host, "main", None, ide_core::RequestId::next(), op, channel, None).await.unwrap(); - assert!(matches!(report, Some(vcs::RemoteOpReport::Update(vcs::UpdateReport { updated_files: 1 })))); + assert!(matches!(report, Some(vcs::RemoteOpReport::Update(vcs::UpdateReport { updated_files: 1, .. })))); assert_eq!(*output.lock(), ["Updated to revision 8."]); assert_eq!(std::fs::read_to_string(&file).unwrap(), "updated\n"); let labels: Vec = project.history.list(&file).unwrap().into_iter().map(|e| e.label).collect(); diff --git a/crates/ide-svn/src/backend.rs b/crates/ide-svn/src/backend.rs index a0dc7545d4..5fcb2c5b38 100644 --- a/crates/ide-svn/src/backend.rs +++ b/crates/ide-svn/src/backend.rs @@ -1349,8 +1349,13 @@ impl Backend for WorkingCopy { /// Update Project, Update File / Update Directory: `svn update` of the whole working copy /// or of `paths`, its output (the files it changed, the revision reached) sent to `output`. /// Conflicts stay for the merge editor. - fn update(&self, paths: &[PathBuf], cancel: &CancellationToken, output: &dyn Fn(String)) -> IdeResult { - WorkingCopy::update_reporting(self, paths, None, cancel, output).map(|(_, changed)| changed) + fn update( + &self, + paths: &[PathBuf], + cancel: &CancellationToken, + output: &dyn Fn(String), + ) -> IdeResult { + WorkingCopy::update_reporting(self, paths, None, cancel, output).map(|(_, summary)| summary) } fn branches(&self) -> IdeResult> { diff --git a/crates/ide-svn/src/lib.rs b/crates/ide-svn/src/lib.rs index 69cc4a89de..cb4a1d1996 100644 --- a/crates/ide-svn/src/lib.rs +++ b/crates/ide-svn/src/lib.rs @@ -18,8 +18,9 @@ pub use cli::{ }; pub use ops::{ BranchCompareEntry, BranchEntry, BranchLayout, CleanupOptions, Depth, EligibleRevision, EligibleRevisionsPage, - IncomingChange, MergeOptions, MergeResult, PropertyDiff, RemoteEntry, ResolveAccept, UpdateOptions, UpdateResult, - WorkingCopyInfo, cat_url, export_url, list_url, remote_copy, remote_delete, remote_log, remote_mkdir, + IncomingChange, IncomingPath, IncomingRevision, MergeOptions, MergeResult, PropertyDiff, RemoteEntry, + ResolveAccept, UpdateOptions, UpdateResult, WorkingCopyInfo, cat_url, export_url, list_url, remote_copy, + remote_delete, remote_log, remote_mkdir, }; pub use workspace::{Layout, Repository, WorkingCopy}; pub use xml::{Lock, StatusEntry}; diff --git a/crates/ide-svn/src/ops.rs b/crates/ide-svn/src/ops.rs index 4b302b82f3..214f0a9ec8 100644 --- a/crates/ide-svn/src/ops.rs +++ b/crates/ide-svn/src/ops.rs @@ -190,6 +190,31 @@ impl Depth { /// The items an `svn update` changed: its lines of four status columns (contents, /// properties, lock, tree conflict) and a path, as `U a.txt`, ` U dir`, ` C b.txt`. /// A broken lock alone (` B a.txt`) changes nothing in the working copy. +/// The files and folders `svn update` printed, with their action (see [`ide_vcs::UpdatedItem`]): +/// its status lines, `Restored 'x'` and `Skipped 'x'`. A relative path is under `root`. +pub(crate) fn update_items(output: &str, root: &Path) -> Vec { + let path_of = |p: &str| { + let p = PathBuf::from(p.trim()); + if p.is_absolute() { p } else { root.join(p) } + }; + let quoted = |rest: &str| rest.split('\'').nth(1).map(str::to_owned); + output + .lines() + .filter_map(|line| { + if let Some(path) = line.strip_prefix("Restored ").and_then(quoted) { + return Some(ide_vcs::UpdatedItem { path: path_of(&path), action: "restored".into() }); + } + if line.starts_with("Skipped") { + return quoted(line).map(|p| ide_vcs::UpdatedItem { path: path_of(&p), action: "skipped".into() }); + } + if updated_items(line) == 1 { + return Some(ide_vcs::UpdatedItem { path: path_of(&line[5..]), action: line[..4].to_owned() }); + } + None + }) + .collect() +} + pub(crate) fn updated_items(output: &str) -> usize { output .lines() @@ -375,7 +400,7 @@ impl WorkingCopy { revision: Option<&str>, cancel: &CancellationToken, ) -> IdeResult<(u64, usize)> { - self.update_reporting(paths, revision, cancel, &|_| {}) + self.update_reporting(paths, revision, cancel, &|_| {}).map(|(revision, summary)| (revision, summary.changed)) } /// [`update_counted`](Self::update_counted), with each line svn prints (`Updating '.':`, @@ -386,14 +411,21 @@ impl WorkingCopy { revision: Option<&str>, cancel: &CancellationToken, on_line: &dyn Fn(String), - ) -> IdeResult<(u64, usize)> { + ) -> IdeResult<(u64, ide_vcs::UpdateSummary)> { + let from = self.current_repository().revision; let mut argv = args(["update", "--accept", "postpone", "-r", revision.unwrap_or("HEAD")]); argv.extend(targets(&self.paths_or_root(paths)?)); let out = String::from_utf8_lossy(&self.remote_streaming(&argv, Some(cancel), on_line)?).into_owned(); let _ = self.refresh(); let reached = reached_revision(&out) .ok_or_else(|| IdeError::internal(format!("unexpected `svn update` output: {out}")))?; - Ok((reached, updated_items(&out))) + let summary = ide_vcs::UpdateSummary { + changed: updated_items(&out), + items: update_items(&out, self.root()), + from_revision: from.map(|r| r.to_string()), + to_revision: Some(reached.to_string()), + }; + Ok((reached, summary)) } /// `svn update` with IDEA Update Directory options (revision, depth, set-depth, ignore-externals) @@ -1343,11 +1375,92 @@ impl WorkingCopy { last_changed_time_ms: info.last_changed_date_ms, depth: info.depth, format, + is_wc_root: path == self.wc_root(), is_switched, }) } /// Reads structured working copy metadata (`svn info --xml`) for Working Copies Info view. + /// The revisions committed to the working copy's URL after its BASE revision, newest first, + /// with their files (`svn log -v` from BASE+1 to HEAD): IntelliJ's Incoming changes. + pub fn incoming_revisions(&self, cancel: &CancellationToken) -> IdeResult> { + let repo = self.current_repository(); + let base = match repo.revision { + Some(base) => base, + None => return Ok(Vec::new()), + }; + let head_argv = [args(["info", "--show-item", "revision", "-r", "HEAD", "--"]), vec![url_target(&repo.url)]]; + let head = String::from_utf8_lossy(&self.remote(&head_argv.concat(), Some(cancel))?).trim().parse::(); + let head = head.map_err(|_| IdeError::internal("unexpected `svn info` output for HEAD"))?; + if head <= base { + return Ok(Vec::new()); + } + self.revisions_between(base + 1, head, cancel) + } + + /// The revisions `from` to `to` committed to the working copy's URL, newest first, with their + /// files (`svn log -v`): Incoming, and Update Info grouped by changelist. + pub fn revisions_between( + &self, + from: u64, + to: u64, + cancel: &CancellationToken, + ) -> IdeResult> { + if from > to { + return Ok(Vec::new()); + } + let repo = self.current_repository(); + let range = format!("{from}:{to}"); + let argv = [args(["log", "--xml", "-v", "-r", &range, "--"]), vec![url_target(&repo.url)]].concat(); + let entries = xml::log(&self.remote(&argv, Some(cancel))?)?; + // The working copy root's repository path: `/trunk`, percent-decoded as log paths are. + let prefix = repo.path.trim_end_matches('/').to_owned(); + let local = |path: &str| -> Option { + let rest = if prefix.is_empty() { Some(path) } else { path.strip_prefix(&prefix) }?; + if !(rest.is_empty() || rest.starts_with('/')) { + return None; + } + let rel = rest.trim_start_matches('/'); + Some(if rel.is_empty() { self.root().to_path_buf() } else { self.root().join(rel) }) + }; + let mut out: Vec = entries + .into_iter() + .map(|e| IncomingRevision { + revision: e.revision, + author: e.author, + time_ms: e.time_ms, + message: e.message, + paths: e + .paths + .into_iter() + .map(|p| IncomingPath { local: local(&p.path), action: p.action, path: p.path, kind: p.kind }) + .collect(), + }) + .collect(); + out.sort_by_key(|a| std::cmp::Reverse(a.revision)); + Ok(out) + } + + /// The working copy formats the configured svn writes, oldest first (IntelliJ's Change Format + /// choices): `1.8`, and `1.15` from svn 1.15 on. + pub fn supported_formats(&self) -> Vec { + match self.context().version() { + Ok(version) if version >= (1, 15) => vec!["1.8".to_owned(), "1.15".to_owned()], + Ok(_) => vec!["1.8".to_owned()], + Err(_) => Vec::new(), + } + } + + /// Working Copies Information › Format › Change: `svn upgrade` of the working copy to the + /// format `version` (`--compatible-version`). + pub fn upgrade(&self, version: &str, cancel: &CancellationToken) -> IdeResult<()> { + if !version.chars().all(|c| c.is_ascii_digit() || c == '.') || version.is_empty() { + return Err(IdeError::invalid(format!("invalid working copy format: {version}"))); + } + let argv = [args(["upgrade", "--compatible-version", version, "--"]), vec![target(self.wc_root())]].concat(); + self.remote(&argv, Some(cancel)).map(|_| ()) + } + pub fn working_copy_info(&self) -> IdeResult { self.working_copy_info_for(self.root()) } @@ -1597,6 +1710,29 @@ pub struct IncomingChange { pub locked_by: Option, } +/// A revision committed after a working copy's BASE (IntelliJ's Incoming changes): its files +/// as repository paths, and where they are in the working copy. +#[derive(Clone, Debug, PartialEq)] +pub struct IncomingRevision { + pub revision: u64, + pub author: String, + pub time_ms: f64, + pub message: String, + pub paths: Vec, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct IncomingPath { + /// `A`, `D`, `M` or `R`. + pub action: String, + /// Repository path: `/trunk/a.txt`. + pub path: String, + /// The file in the working copy, for a path under the working copy's URL. + pub local: Option, + /// `file`, `dir`, or empty from old servers. + pub kind: String, +} + /// Working copy metadata returned by [`WorkingCopy::working_copy_info`]. #[derive(Clone, Debug, PartialEq)] pub struct WorkingCopyInfo { @@ -1611,6 +1747,8 @@ pub struct WorkingCopyInfo { pub depth: String, pub format: Option, pub is_switched: bool, + /// `root` is the root of its working copy, not a switched folder in it. + pub is_wc_root: bool, } /// One discovered branch or tag folder returned inside [`BranchLayout`]. diff --git a/crates/ide-vcs/src/backend.rs b/crates/ide-vcs/src/backend.rs index 576dd15d05..7eec9e186d 100644 --- a/crates/ide-vcs/src/backend.rs +++ b/crates/ide-vcs/src/backend.rs @@ -34,6 +34,26 @@ use std::any::Any; use std::path::{Path, PathBuf}; use std::sync::Arc; +/// What an update of a working copy changed ([`Backend::update`]): IntelliJ's Update Info. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct UpdateSummary { + /// Files and folders added, deleted, changed or merged. + pub changed: usize, + /// Each file or folder the update touched, with its action. + pub items: Vec, + /// The working copy's revision before and after the update. + pub from_revision: Option, + pub to_revision: Option, +} + +/// One file or folder of an [`UpdateSummary`]: `action` is svn's four status columns as it +/// prints them (`U `, ` U `, `C `, ` C`), or `restored` / `skipped`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct UpdatedItem { + pub path: PathBuf, + pub action: String, +} + /// Finds the working copies of one non-Git version control system. Registered /// once at host startup; the host asks it about the project root and each /// content root of a trusted project only, because answering may run the @@ -220,7 +240,12 @@ pub trait Backend: Send + Sync + Any { /// limits it to those files and folders (Update File / Update Directory); empty /// is the whole working copy. Returns how many files and folders it changed. /// Git's pull stays on [`Repo`]. - fn update(&self, _paths: &[PathBuf], _cancel: &CancellationToken, _output: &dyn Fn(String)) -> IdeResult { + fn update( + &self, + _paths: &[PathBuf], + _cancel: &CancellationToken, + _output: &dyn Fn(String), + ) -> IdeResult { Err(IdeError::unavailable("this version control system cannot update the working copy")) } diff --git a/crates/ide-vcs/src/lib.rs b/crates/ide-vcs/src/lib.rs index fd248c8262..57aaffc1cf 100644 --- a/crates/ide-vcs/src/lib.rs +++ b/crates/ide-vcs/src/lib.rs @@ -1084,7 +1084,7 @@ pub use submodules::SubmoduleRollbackSource; mod text_encoding; mod write; -pub use backend::{Backend, BackendProvider}; +pub use backend::{Backend, BackendProvider, UpdateSummary, UpdatedItem}; pub use cherry_pick_plan::CherryPickOptions; pub use cli::{ GitCommandObserver, askpass_env, detected_git_executable, filter_overrides_from, git_version, restrict, diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index 7667a69832..3d1873e05d 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -820,6 +820,7 @@ svn_eligible_revisions trusted project_host bin svn_export outside_restricted project_host bindings async svn_ignore_pattern trusted project_host bindings async svn_incoming trusted project_host bindings async +svn_incoming_revisions trusted project_host bindings async svn_item_url trusted project_host bindings async svn_list_url outside_restricted project_host bindings async svn_lock trusted project_host bindings async @@ -835,11 +836,13 @@ svn_remote_mkdir trusted project_host bin svn_repository_file_at trusted project_host bindings async svn_repository_info trusted project_host bindings async svn_revert_revision trusted project_host bindings async +svn_revisions_between trusted project_host bindings async svn_set_property trusted project_host bindings async svn_set_property_options trusted project_host bindings async svn_switch_url trusted project_host bindings async svn_unlock trusted project_host bindings async svn_update_options trusted project_host bindings async +svn_upgrade trusted project_host bindings async svn_version always project_host bindings async svn_working_copy_info trusted project_host bindings async syntax_errors always project_host bindings async diff --git a/src/bindings.ts b/src/bindings.ts index 95014a7b6b..39272ec744 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -2507,6 +2507,11 @@ export const commands = { svnIgnorePattern: (path: string, pattern: string) => typedError(__TAURI_INVOKE("svn_ignore_pattern", { path, pattern })), /** Lists incoming remote updates for a Subversion working copy (`svn status -u --xml`). */ svnIncoming: (request: RequestId, repo: string | null) => typedError(__TAURI_INVOKE("svn_incoming", { request, repo })), + /** + * Incoming: for each Subversion working copy, the revisions committed to its URL after its + * BASE revision, from BASE+1 to HEAD, as IntelliJ's Incoming tab lists them. + */ + svnIncomingRevisions: (request: RequestId) => typedError(__TAURI_INVOKE("svn_incoming_revisions", { request })), /** Repository URL of `path` inside a Subversion working copy. */ svnItemUrl: (path: string) => typedError(__TAURI_INVOKE("svn_item_url", { path })), /** Lists direct child entries of a remote repository URL (`svn list --xml`). */ @@ -2536,6 +2541,11 @@ export const commands = { 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 })), + /** + * Update Info › Group by Changelist: the revisions `from` to `to` of the working copy at `repo`, + * newest first, with their files. + */ + svnRevisionsBetween: (request: RequestId, repo: string, from: number, to: number) => typedError(__TAURI_INVOKE("svn_revisions_between", { request, repo, from, to })), /** Sets property `name` of `path`, or deletes it when `value` is `None`. */ svnSetProperty: (path: string, name: string, value: string | null) => typedError(__TAURI_INVOKE("svn_set_property", { path, name, value })), /** Sets or deletes property `name` of `path`, optionally recursively (`-R`). */ @@ -2549,6 +2559,11 @@ export const commands = { svnUnlock: (paths: string[], force: boolean) => typedError(__TAURI_INVOKE("svn_unlock", { paths, force })), /** VCS › Subversion › Update Directory… with explicit revision, depth, set-depth, and ignore-externals. */ svnUpdateOptions: (repo: string | null, request: RequestId, paths: string[], options: SvnUpdateOptions, onOutput: Channel) => typedError(__TAURI_INVOKE("svn_update_options", { repo, request, paths, options, onOutput })), + /** + * Working Copies Information › Format › Change: `svn upgrade` of the working copy at `repo` + * to the format `version` (`1.8`, `1.15`). + */ + svnUpgrade: (request: RequestId, repo: string, version: string) => typedError(__TAURI_INVOKE("svn_upgrade", { request, repo, version })), /** * Settings › Subversion › Test. Auto-detection runs anywhere; a path of the user's or the * project's choosing runs only in a trusted project (as Git's Test does). @@ -17909,6 +17924,36 @@ export type SvnIncomingChange = { lockedBy: string | null, }; +export type SvnIncomingPath = { + /** `A`, `D`, `M` or `R`. */ + action: string, + /** Repository path: `/trunk/a.txt`. */ + path: string, + /** The file in the working copy, for a path under the working copy's URL. */ + local: string | null, + kind: string, +}; + +/** A revision committed after a working copy's BASE: a row of the Incoming tab. */ +export type SvnIncomingRevision = { + /** The working copy it is incoming to. */ + root: string, + revision: number, + author: string, + timeMs: number | null, + message: string, + paths: SvnIncomingPath[], +}; + +/** + * The Incoming tab's revisions of every Subversion working copy, and the working copies that + * could not be read. + */ +export type SvnIncomingRevisions = { + revisions: SvnIncomingRevision[], + errors: SvnWorkingCopyError[], +}; + /** Options sent from the Subversion Merge From… dialog. */ export type SvnMergeOptions = { sourceUrl: string, @@ -18018,6 +18063,11 @@ export type SvnVersion = { error: string | null, }; +export type SvnWorkingCopyError = { + root: string, + message: string, +}; + /** Working copy metadata returned by `svn_working_copy_info`. */ export type SvnWorkingCopyInfo = { root: string, @@ -18031,6 +18081,14 @@ export type SvnWorkingCopyInfo = { depth: string, format: string | null, isSwitched: boolean, + /** `root` is the root of its working copy (IntelliJ's "Working copy root"). */ + isWcRoot: boolean, + /** A working copy of its own inside another one: an `svn:externals` definition. */ + isExternal: boolean, + /** Why the working copy could not be read; the other fields are then empty. */ + error: string | null, + /** The formats the configured svn can convert it to (Format › Change), oldest first. */ + formats: string[], }; export type SwiftSettings = { @@ -18835,6 +18893,11 @@ export type UpdateProgress = export type UpdateReport = { /** Files and folders added, deleted, changed or merged. */ updatedFiles: number, + /** Each file or folder the update touched (Update Info's tree). */ + items?: UpdatedItemReport[], + /** The working copy's revision before and after the update. */ + fromRevision?: string | null, + toRevision?: string | null, }; export type UpdateSource = "github" | "cnb"; @@ -18845,6 +18908,15 @@ export type UpdateStatus = { checking: boolean, }; +/** + * One file or folder of an [`UpdateReport`]: `action` is svn's four status columns as it + * prints them (`U `, ` U `, `C `, ` C`), or `restored` / `skipped`. + */ +export type UpdatedItemReport = { + path: string, + action: string, +}; + export type UpstreamTracking = { remote: string, branch: string, diff --git a/src/features/vcs/GitLog.tsx b/src/features/vcs/GitLog.tsx index 2ca3954bc3..41aac3ab84 100644 --- a/src/features/vcs/GitLog.tsx +++ b/src/features/vcs/GitLog.tsx @@ -22,6 +22,13 @@ import { LocalChangesView, StashContent, tabItems, useStashTabCounts } from "./C import styles from "./GitLog.module.css"; import { WorktreesPanel } from "./WorktreesPanel"; import { SvnIncomingPanel, SvnWorkingCopiesPanel } from "./svnPanels"; +import { closeSvnUpdate, isSvnUpdateTab, SvnUpdateInfo, useSvnUpdates } from "./svnUpdateInfo"; + +/** Closes a Subversion update's Update Info tab, showing the Log if it was shown. */ +function closeSvnUpdateTab(id: string) { + if (useGitLog.getState().tab === id) selectGitTab("log"); + closeSvnUpdate(id); +} import { gitTabs, shownTab } from "./gitTabs"; import { BranchesPanel } from "./log/BranchesPanel"; import { CommitDetails, useDiffLocation } from "./log/CommitDetails"; @@ -60,7 +67,18 @@ function useGitTabs() { const tab = useGitLog((s) => s.tab); const logTabs = useGitLog((s) => s.logTabs); const counts = useStashTabCounts(available && modal); - const tabs = gitTabs({ modal, combine, tab, logTabs, ...counts, noGit: !anyGit, workingCopies: hasSvn, hasSvn }); + const svnUpdates = useSvnUpdates((s) => s.updates); + const tabs = gitTabs({ + modal, + combine, + tab, + logTabs, + ...counts, + noGit: !anyGit, + workingCopies: hasSvn, + hasSvn, + svnUpdates, + }); return { tabs, shown: shownTab(tab, tabs, combine) }; } @@ -76,7 +94,7 @@ export function GitTabs() { className={styles.headerTabs} activeId={shown} onSelect={selectGitTab} - onClose={closeLogTab} + onClose={(id) => (isSvnUpdateTab(id) ? closeSvnUpdateTab(id) : closeLogTab(id))} aria-label="Git" panelIdPrefix="openidea-git" items={tabItems(tabs)} @@ -127,6 +145,8 @@ export function GitToolWindow() { ) : shown === "svnInfo" ? ( + ) : isSvnUpdateTab(shown) ? ( + ) : null} {keptLog && (
@@ -389,8 +409,18 @@ export function LogView() { // --------------------------------------------------------------------------- // Console +/** The systems whose commands the console shows: the project's roots' (IntelliJ's console names none). */ +function useConsoleSystem(): "git" | "subversion" | "mixed" { + return useVcs((s) => { + const kinds = new Set(s.roots.map((root) => s.kinds[root] ?? "git")); + if (kinds.size > 1) return "mixed"; + return kinds.has("subversion") ? "subversion" : kinds.has("git") || !kinds.size ? "git" : "mixed"; + }); +} + function ConsoleView() { const lines = useVcsConsole((s) => s.lines); + const system = useConsoleSystem(); const ref = useRef(null); const stick = useRef(true); useLayoutEffect(() => { @@ -408,7 +438,13 @@ function ConsoleView() { tabIndex={0} role="log" onKeyDown={copySelectionOnKeyDown} - aria-label={tx("Git console")} + aria-label={ + system === "git" + ? tx("Git console") + : system === "subversion" + ? tx("Subversion console") + : tx("Version control console") + } onScroll={(e) => { const el = e.currentTarget; stick.current = el.scrollTop + el.clientHeight >= el.scrollHeight - 8; @@ -416,7 +452,13 @@ function ConsoleView() { > {!lines.length && (
- Git commands run by the IDE appear here. + {system === "git" ? ( + Git commands run by the IDE appear here. + ) : system === "subversion" ? ( + Subversion commands run by the IDE appear here. + ) : ( + Version control commands run by the IDE appear here. + )}
)} {lines.map((l) => ( diff --git a/src/features/vcs/__tests__/commitMode.test.ts b/src/features/vcs/__tests__/commitMode.test.ts index 90d8f4b61f..906fda22a9 100644 --- a/src/features/vcs/__tests__/commitMode.test.ts +++ b/src/features/vcs/__tests__/commitMode.test.ts @@ -50,7 +50,15 @@ describe("Git and Commit tool window tabs", () => { it("puts Local Changes, Shelf and Stash into the Git window only with the modal commit interface", () => { expect(ids(gitTabs({ ...base, modal: false }))).toEqual(["log", "console", "worktrees"]); expect(ids(gitTabs({ ...base, modal: true }))).toEqual(["changes", "stashes", "log", "console", "worktrees"]); - expect(ids(gitTabs({ ...base, modal: false, noGit: true, hasSvn: true }))).toEqual(["log", "incoming", "console"]); + // IntelliJ's weights: Incoming (30) before Shelf (40) and Log (50). + expect(ids(gitTabs({ ...base, modal: false, noGit: true, hasSvn: true }))).toEqual(["incoming", "log", "console"]); + expect(ids(gitTabs({ ...base, modal: true, noGit: true, hasSvn: true, shelfCount: 1 }))).toEqual([ + "changes", + "incoming", + "shelf", + "log", + "console", + ]); expect(ids(gitTabs({ ...base, modal: true, shelfCount: 2 }))).toEqual([ "changes", "shelf", diff --git a/src/features/vcs/__tests__/svnPanels.test.tsx b/src/features/vcs/__tests__/svnPanels.test.tsx index 22167fd7f2..925f0bca38 100644 --- a/src/features/vcs/__tests__/svnPanels.test.tsx +++ b/src/features/vcs/__tests__/svnPanels.test.tsx @@ -1,6 +1,6 @@ import { act, fireEvent, render, screen, waitFor } from "@testing-library/react"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import type { SvnBranchCompareEntry, SvnBranchLayout, SvnIncomingChange, SvnWorkingCopyInfo } from "@/bindings"; +import type { SvnBranchCompareEntry, SvnBranchLayout, SvnWorkingCopyInfo } from "@/bindings"; const mocks = vi.hoisted(() => ({ svnIncoming: vi.fn(), @@ -78,12 +78,10 @@ vi.mock("../store", async (importOriginal) => { }); import { gitTabs } from "../gitTabs"; -import { useGitLog } from "../logStore"; -import { notifySvnProjectUpdated, useVcs } from "../store"; +import { useVcs } from "../store"; import { SvnCompareWithBranchDialog, SvnConfigureBranchesDialog, - SvnIncomingPanel, SvnSwitchUrlDialog, SvnWorkingCopiesPanel, } from "../svnPanels"; @@ -91,20 +89,6 @@ import { const WC_ROOT = "/work/svn-app"; const REPO_ROOT = "https://svn.example.com/repos/app"; -const INCOMING_ITEMS: SvnIncomingChange[] = [ - { - path: `${WC_ROOT}/src/main.rs`, - relPath: "src/main.rs", - item: "modified", - props: "none", - revision: 42, - author: "alice", - timeMs: 1_700_000_000_000, - hasLocalChange: true, - lockedBy: "bob", - }, -]; - const WC_INFO: SvnWorkingCopyInfo = { root: WC_ROOT, url: `${REPO_ROOT}/trunk`, @@ -117,6 +101,10 @@ const WC_INFO: SvnWorkingCopyInfo = { depth: "infinity", format: "1.15", isSwitched: false, + isWcRoot: true, + isExternal: false, + error: null, + formats: ["1.8", "1.15"], }; const BRANCH_LAYOUT: SvnBranchLayout = { @@ -147,7 +135,6 @@ beforeEach(() => { kinds: { [WC_ROOT]: "subversion" }, repo: WC_ROOT, }); - mocks.svnIncoming.mockResolvedValue({ status: "ok", data: INCOMING_ITEMS }); mocks.svnWorkingCopyInfo.mockResolvedValue({ status: "ok", data: [WC_INFO] }); mocks.svnBranchLayout.mockResolvedValue({ status: "ok", data: BRANCH_LAYOUT }); mocks.svnCompareWithUrl.mockResolvedValue({ status: "ok", data: COMPARE_ENTRIES }); @@ -164,44 +151,7 @@ afterEach(() => { vi.clearAllMocks(); }); -describe("Subversion Incoming, Working Copies Info, Branches, Compare, and Switch URL", () => { - it("renders incoming remote changes, refreshes after Update Project notification, and triggers Update Project", async () => { - render(); - - expect(await screen.findByText("src/main.rs")).toBeTruthy(); - expect(screen.getByText("Local edits")).toBeTruthy(); - expect(screen.getByText("r42")).toBeTruthy(); - expect(screen.getByText("alice")).toBeTruthy(); - - fireEvent.click(screen.getByRole("button", { name: "Update Project…" })); - expect(mocks.executeAction).toHaveBeenCalledWith("vcs.update"); - - mocks.svnIncoming.mockResolvedValueOnce({ status: "ok", data: [] }); - await act(async () => { - notifySvnProjectUpdated(); - }); - expect(await screen.findByText("No incoming changes")).toBeTruthy(); - }); - - it("renders working copy info cards and triggers cleanup action", async () => { - render(); - - expect(await screen.findByText(`${REPO_ROOT}/trunk`)).toBeTruthy(); - expect(screen.getByText("r41")).toBeTruthy(); - expect(screen.getByText("Format 1.15")).toBeTruthy(); - - await act(async () => { - fireEvent.click(screen.getByRole("button", { name: "Cleanup" })); - }); - expect(mocks.svnCleanup).toHaveBeenCalledWith(WC_ROOT); - - fireEvent.click(screen.getByRole("button", { name: "Update Project…" })); - expect(mocks.executeAction).toHaveBeenCalledWith("vcs.update", { repo: WC_ROOT }); - fireEvent.click(screen.getByRole("button", { name: "Show Log" })); - expect(useGitLog.getState().filters.repositories).toEqual([WC_ROOT]); - expect(useGitLog.getState().tab).toBe("log"); - }); - +describe("Subversion Working Copies tab, Branches, Compare, and Switch URL", () => { it("is a tab of the version control tool window when the project has a working copy", () => { const base = { modal: false, combine: false, logTabs: [], shelfCount: 0, stashCount: 0, tab: "log", noGit: true }; expect(gitTabs(base).map((t) => t.id)).toEqual(["log", "console"]); diff --git a/src/features/vcs/__tests__/svnToolWindowParity.test.tsx b/src/features/vcs/__tests__/svnToolWindowParity.test.tsx new file mode 100644 index 0000000000..7917e6a065 --- /dev/null +++ b/src/features/vcs/__tests__/svnToolWindowParity.test.tsx @@ -0,0 +1,561 @@ +/** + * Issue #7433: the Subversion tabs of the version control tool window as IntelliJ has them — + * Working Copies Information (`WorkingCopyInfoPanel`), Update Info (`UpdateInfoTree`), Incoming + * (`CommittedChangesTreeBrowser`), the Show Working Copies action and the Console's wording. + */ +import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { SvnIncomingRevision, SvnWorkingCopyInfo, VcsKind } from "@/bindings"; + +const mocks = vi.hoisted(() => ({ + svnWorkingCopyInfo: vi.fn(), + svnUpdateOptions: vi.fn(), + svnUpgrade: vi.fn(), + svnIncomingRevisions: vi.fn(), + svnRevisionsBetween: vi.fn(), + fsProbe: vi.fn(), + notify: vi.fn(), + expire: vi.fn(), + openFile: vi.fn(), + showToolWindow: vi.fn(), + confirmDialog: vi.fn(), + openVcsDiff: vi.fn(), + contextMenu: vi.fn(), + executeAction: vi.fn(), + writeClipboardText: vi.fn(), + svnCleanup: vi.fn(), +})); + +vi.mock("@/platform/ipc", async (importOriginal) => { + const real = await importOriginal(); + const ok = (data: unknown) => ({ status: "ok", data }); + return { + ...real, + nextRequestId: () => 7300, + commands: { + ...real.commands, + svnWorkingCopyInfo: (...args: unknown[]) => mocks.svnWorkingCopyInfo(...args), + svnUpdateOptions: async (...args: unknown[]) => ok(mocks.svnUpdateOptions(...args)), + svnUpgrade: async (...args: unknown[]) => ok(mocks.svnUpgrade(...args)), + svnIncomingRevisions: (...args: unknown[]) => mocks.svnIncomingRevisions(...args), + svnRevisionsBetween: (...args: unknown[]) => mocks.svnRevisionsBetween(...args), + fsProbe: (...args: unknown[]) => mocks.fsProbe(...args), + }, + }; +}); + +vi.mock("@tauri-apps/api/core", async (importOriginal) => ({ + ...(await importOriginal()), + Channel: class { + onmessage: ((line: string) => void) | null = null; + }, +})); + +vi.mock("@/workbench/contributions", async (importOriginal) => ({ + ...(await importOriginal()), + notifications: () => ({ notify: mocks.notify, expire: mocks.expire }), + editorService: () => ({ openFile: mocks.openFile }), + toolWindowService: () => ({ show: mocks.showToolWindow }), +})); + +vi.mock("@/ui", async (importOriginal) => ({ + ...(await importOriginal()), + showContextMenu: (...args: unknown[]) => mocks.contextMenu(...args), +})); + +vi.mock("@/platform/actions", async (importOriginal) => { + const real = await importOriginal(); + return { + ...real, + executeAction: (id: string, arg?: unknown) => + id === "svn.showWorkingCopies" ? real.executeAction(id, arg) : mocks.executeAction(id, arg), + }; +}); + +vi.mock("@/platform/clipboard", () => ({ writeClipboardText: (t: string) => mocks.writeClipboardText(t) })); + +vi.mock("../dialogs", async (importOriginal) => ({ + ...(await importOriginal()), + confirmDialog: (...args: unknown[]) => mocks.confirmDialog(...args), +})); + +vi.mock("../diffInput", async (importOriginal) => ({ + ...(await importOriginal()), + openVcsDiff: (...args: unknown[]) => mocks.openVcsDiff(...args), +})); + +vi.mock("../svn", async (importOriginal) => ({ + ...(await importOriginal()), + svnCleanup: (...args: unknown[]) => mocks.svnCleanup(...args), +})); + +import { getAction } from "@/platform/actions"; +import { registerVcsActions } from "../actions"; +import { VcsDialogHost } from "../dialogs"; +import { GitToolWindow } from "../GitLog"; +import { useGitLog } from "../logStore"; +import { notifyUpdated } from "../ops"; +import { useVcs } from "../store"; +import { dateGroup, incomingTree, SvnIncomingPanel } from "../svnIncoming"; +import { + addSvnUpdate, + SvnUpdateInfo, + updateGroupOf, + updateTree, + useSvnUpdates, + type UpdateNode, +} from "../svnUpdateInfo"; +import { formatVersion, newerFormats, SvnWorkingCopiesPanel } from "../svnWorkingCopies"; + +const A = "/w/app"; +const B = "/w/lib"; + +beforeEach(() => { + useVcs.setState({ + available: true, + root: "/w", + roots: [A, B], + kinds: { [A]: "subversion", [B]: "subversion" }, + repo: A, + }); + mocks.fsProbe.mockResolvedValue({ status: "ok", data: { size: 1, binary: false, tooLarge: false } }); + mocks.confirmDialog.mockResolvedValue(true); +}); + +afterEach(() => { + vi.clearAllMocks(); + useSvnUpdates.setState({ updates: [] }); + useGitLog.setState({ tab: "log" }); +}); + +const lastMenu = () => + (mocks.contextMenu.mock.calls.at(-1)![1] as { label?: string; run?: () => void }[]).filter((i) => i.label); + +// --------------------------------------------------------------------------- + +describe("the tool window and its tabs", () => { + it("has Show Working Copies, which shows the Working Copies Information tab", async () => { + const off = registerVcsActions(); + try { + await getAction("svn.showWorkingCopies")!.run({ arg: undefined, ctx: {} }); + expect(useGitLog.getState().tab).toBe("svnInfo"); + expect(mocks.showToolWindow).toHaveBeenCalledWith("git", true); + } finally { + off(); + } + }); + + it.each<[Record, string, string]>([ + [{ [A]: "subversion", [B]: "subversion" }, "Subversion commands run by the IDE appear here.", "Subversion console"], + [ + { [A]: "git", [B]: "subversion" }, + "Version control commands run by the IDE appear here.", + "Version control console", + ], + [{ [A]: "git", [B]: "git" }, "Git commands run by the IDE appear here.", "Git console"], + ])("names the console after the project's systems (%o)", (kinds, empty, name) => { + useVcs.setState({ kinds }); + useGitLog.setState({ tab: "console" }); + render(); + expect(screen.getByText(empty)).toBeInTheDocument(); + expect(screen.getByRole("log", { name })).toBeInTheDocument(); + }); +}); + +// --------------------------------------------------------------------------- + +const info = (over: Partial): SvnWorkingCopyInfo => ({ + root: A, + url: "https://svn.example.com/repos/app/trunk", + repositoryRoot: "https://svn.example.com/repos/app", + uuid: "u", + revision: 12, + lastChangedRev: 11, + lastChangedAuthor: "alice", + lastChangedTimeMs: 0, + depth: "infinity", + format: "31", + isSwitched: false, + isWcRoot: true, + isExternal: false, + error: null, + formats: ["1.8", "1.15"], + ...over, +}); + +describe("Subversion Working Copies Information", () => { + it("names formats as IntelliJ does and offers Change only for a newer one", () => { + expect(["4", "10", "29", "31", "32", "1.8", "99", null].map((f) => formatVersion(f))).toEqual([ + "1.3", + "1.6", + "1.7", + "1.8", + "1.15", + "1.8", + null, + null, + ]); + expect(newerFormats(info({ format: "31" }))).toEqual(["1.15"]); + expect(newerFormats(info({ format: "32" }))).toEqual([]); + expect(newerFormats(info({ format: "31", formats: ["1.8"] }))).toEqual([]); + }); + + it("lists the copies by path with IntelliJ's rows and links, an error in red without links", async () => { + mocks.svnWorkingCopyInfo.mockResolvedValue({ + status: "ok", + data: [ + info({ root: B, error: "E155036: upgrade required", url: "", format: null, depth: "" }), + info({ url: "https://svn.example.com/repos/app/my%20trunk", depth: "immediates" }), + info({ root: `${A}/vendor`, isExternal: true, format: "32" }), + info({ root: `${A}/feature`, isSwitched: true, isWcRoot: false }), + ], + }); + render(); + await screen.findByRole("region", { name: A }); + expect(screen.getAllByRole("region").map((r) => r.getAttribute("aria-label"))).toEqual([ + A, + `${A}/feature`, + `${A}/vendor`, + B, + ]); + const app = within(screen.getByRole("region", { name: A })); + expect(app.getByText("https://svn.example.com/repos/app/my trunk")).toBeInTheDocument(); + expect(app.getByText("1.8")).toBeInTheDocument(); + expect(app.getByRole("button", { name: "Change" })).toBeInTheDocument(); + expect(app.getByText("immediates")).toBeInTheDocument(); + expect(app.getByRole("button", { name: "Fix" })).toBeInTheDocument(); + expect(app.getByText("Working copy root")).toBeInTheDocument(); + expect( + app + .getAllByRole("button") + .map((b) => b.textContent) + .slice(2, 5), + ).toEqual(["Cleanup", "Configure Branches", "Merge From…"]); + expect(app.getByRole("button", { name: "Merge From…" }).className).toMatch(/boldLink/); + expect(within(screen.getByRole("region", { name: `${A}/vendor` })).getByText("External")).toBeInTheDocument(); + const feature = within(screen.getByRole("region", { name: `${A}/feature` })); + expect(feature.getByText("Switched")).toBeInTheDocument(); + expect(feature.queryByText("Working copy root")).toBeNull(); + const broken = within(screen.getByRole("region", { name: B })); + expect(broken.getByRole("alert")).toHaveTextContent("E155036: upgrade required"); + expect(broken.queryByRole("button", { name: "Cleanup" })).toBeNull(); + // IntelliJ's "Svn Roots Detection Errors" balloon, its Fix it showing this tab. + expect(mocks.notify).toHaveBeenCalledWith( + expect.objectContaining({ title: "Errors found while detecting Subversion working copies.", sticky: true }), + ); + const fixIt = (mocks.notify.mock.calls.at(-1)![0] as { actions: { label: string; run: () => void }[] }).actions[0]!; + expect(fixIt.label).toBe("Fix it"); + // The toolbar has Refresh only, at the left. + const toolbar = screen.getByRole("toolbar", { name: "Working Copies" }); + expect(toolbar).toHaveAttribute("aria-orientation", "vertical"); + expect( + within(toolbar) + .getAllByRole("button") + .map((b) => b.getAttribute("aria-label")), + ).toEqual(["Refresh"]); + }); + + it("fixes the depth after IntelliJ's confirmation and changes the format", async () => { + mocks.svnWorkingCopyInfo.mockResolvedValue({ status: "ok", data: [info({ depth: "files" })] }); + render( + <> + + + , + ); + const fix = await screen.findByRole("button", { name: "Fix" }); + await act(async () => fireEvent.click(fix)); + expect(mocks.confirmDialog).toHaveBeenCalledWith( + expect.objectContaining({ title: "Set Working Copy Infinity Depth" }), + ); + await waitFor(() => + expect(mocks.svnUpdateOptions).toHaveBeenCalledWith( + A, + 7300, + [A], + { revision: "HEAD", depth: "infinity", setDepth: true }, + expect.anything(), + ), + ); + + fireEvent.click(screen.getByRole("button", { name: "Change" })); + const dialog = await screen.findByRole("dialog", { name: "Convert Working Copy Format" }); + fireEvent.click(within(dialog).getByLabelText("1.15 format")); + await act(async () => fireEvent.click(within(dialog).getByRole("button", { name: "OK" }))); + await waitFor(() => expect(mocks.svnUpgrade).toHaveBeenCalledWith(7300, A, "1.15")); + }); +}); + +// --------------------------------------------------------------------------- + +const labels = (node: UpdateNode): string[] => [node.label, ...(node.children ?? []).flatMap(labels)]; + +describe("Update Info of a Subversion update", () => { + it("files svn's letters into IntelliJ's groups", () => { + expect( + [ + "U ", + " U ", + "A ", + "D ", + "G ", + " G ", + "C ", + " C ", + " C", + "AC ", + "R ", + "E ", + "restored", + "skipped", + ].map(updateGroupOf), + ).toEqual([ + "updated", + "updated", + "created", + "deleted", + "merged", + "merged", + "conflicts", + "propertyConflicts", + "treeConflicts", + "conflicts", + "notInRepository", + null, + "restored", + "skipped", + ]); + }); + + it("builds IntelliJ's tree: Updated from server first, empty groups left out, a re-added file Replaced", () => { + const f = (path: string, action: string) => ({ path: `${A}/${path}`, action, root: A }); + const tree = updateTree([ + f("b.txt", "U "), + f("A.txt", "U "), + f("new.txt", "A "), + f("gone.txt", "D "), + f("swap.txt", "D "), + f("swap.txt", "A "), + f("c.txt", "C "), + f("m.txt", "G "), + ]); + expect(labels(tree)).toEqual([ + // swap.txt, deleted and added again, is one item. + "Update Project (7 items)", + "Updated from server (4 items)", + "Updated (2 items)", + `${A}/A.txt`, + `${A}/b.txt`, + "Created (1 item)", + `${A}/new.txt`, + "Deleted (1 item)", + `${A}/gone.txt`, + "Merged with conflicts (1 item)", + `${A}/c.txt`, + "Merged (1 item)", + `${A}/m.txt`, + "Replaced (1 item)", + `${A}/swap.txt`, + ]); + // Group by Packages: folders under each group. + expect(labels(updateTree([f("src/a.ts", "U ")], true))).toEqual([ + "Update Project (1 item)", + "Updated from server (1 item)", + "Updated (1 item)", + `${A}/src`, + "a.ts", + ]); + }); + + it("opens from the balloon's View, with IntelliJ's toolbar, menu, double-click and diff", async () => { + await notifyUpdated([], "vcs.remote", 2, [ + { + root: A, + files: [ + { path: `${A}/a.txt`, action: "U " }, + { path: `${A}/new.txt`, action: "A " }, + ], + from: "4", + to: "6", + }, + ]); + const balloon = mocks.notify.mock.calls.at(-1)![0] as { + title: string; + actions: { label: string; run: () => void }[]; + }; + expect(balloon.title).toBe("2 Files Updated"); + expect(balloon.actions.map((a) => a.label)).toEqual(["View"]); + const [update] = useSvnUpdates.getState().updates; + // IntelliJ adds the tab without selecting it; View selects it. + expect(useGitLog.getState().tab).toBe("log"); + act(() => balloon.actions[0]!.run()); + await waitFor(() => expect(useGitLog.getState().tab).toBe(update!.id)); + + render(); + const toolbar = screen.getByRole("toolbar", { name: "Update Info" }); + expect( + within(toolbar) + .getAllByRole("button") + .map((b) => b.getAttribute("aria-label")), + ).toEqual([ + "Group by Packages", + "Group by Changelist", + "Scope Filter", + "Expand All", + "Collapse All", + "Show Diff", + "Close", + ]); + fireEvent.click(within(toolbar).getByRole("button", { name: "Expand All" })); + const file = await screen.findByText(`${A}/a.txt`); + fireEvent.doubleClick(file); + await waitFor(() => expect(mocks.openFile).toHaveBeenCalledWith(`${A}/a.txt`, { focus: true })); + mocks.fsProbe.mockResolvedValueOnce({ status: "error", error: { kind: "notFound", message: "gone" } }); + fireEvent.doubleClick(screen.getByText(`${A}/new.txt`)); + await waitFor(() => + expect(mocks.notify).toHaveBeenCalledWith(expect.objectContaining({ title: `${A}/new.txt no longer exists` })), + ); + + fireEvent.mouseDown(screen.getByText(`${A}/a.txt`), { button: 0 }); + fireEvent.contextMenu(screen.getByText(`${A}/a.txt`)); + expect(lastMenu().map((i) => i.label)).toEqual(["Jump to Source", "Delete", "Show Diff"]); + act(() => lastMenu()[2]!.run!()); + const [diff] = mocks.openVcsDiff.mock.calls.at(-1)! as [ + { path: string; left: unknown; right: unknown; chain: unknown[] }, + ]; + expect(diff).toMatchObject({ + path: `${A}/a.txt`, + left: { type: "rev", rev: "4", label: "Before update" }, + right: { type: "rev", rev: "6", label: "After update" }, + }); + expect(diff.chain).toHaveLength(2); + }); + + it("groups by changelist after reading the update's revisions", async () => { + let resolve!: (value: unknown) => void; + mocks.svnRevisionsBetween.mockReturnValue(new Promise((r) => (resolve = r))); + const id = addSvnUpdate([{ root: A, files: [{ path: `${A}/a.txt`, action: "U " }], from: "4", to: "6" }])!; + render(); + fireEvent.click(screen.getByRole("button", { name: "Group by Changelist" })); + expect(screen.getByText("Loading changelists…")).toBeInTheDocument(); + expect(mocks.svnRevisionsBetween).toHaveBeenCalledWith(7300, A, 5, 6); + await act(async () => + resolve({ + status: "ok", + data: [ + { + root: A, + revision: 6, + author: "bob", + timeMs: 0, + message: "Tune a\nmore", + paths: [{ action: "M", path: "/trunk/a.txt", local: `${A}/a.txt`, kind: "file" }], + }, + ], + }), + ); + expect(await screen.findByText("#6 Tune a")).toBeInTheDocument(); + expect(screen.queryByText("Loading changelists…")).toBeNull(); + }); +}); + +// --------------------------------------------------------------------------- + +const DAY = 24 * 3600 * 1000; +// Wednesday, 2026-12-09 10:00 local time. +const NOW = new Date(2026, 11, 9, 10, 0).getTime(); + +const revision = ( + root: string, + n: number, + timeMs: number, + author = "alice", + message = `change ${n}`, +): SvnIncomingRevision => ({ + root, + revision: n, + author, + timeMs, + message, + paths: [{ action: n % 2 ? "M" : "A", path: `/trunk/f${n}.txt`, local: `${root}/f${n}.txt`, kind: "file" }], +}); + +describe("Incoming", () => { + it("groups revisions by date as IntelliJ does", () => { + expect( + [ + NOW, + NOW - DAY, // Tuesday + NOW - 3 * DAY, // Sunday, this week + NOW - 4 * DAY, // Saturday: last week + NOW - 10 * DAY, // Sunday of last week + NOW - 20 * DAY, + new Date(2025, 11, 20).getTime(), + ].map((t) => dateGroup(t, NOW)), + ).toEqual(["Today", "Tuesday", "Sunday", "Last Week", "Last Week", "November", "December 2025"]); + const byUser = incomingTree([revision(A, 3, NOW), revision(B, 2, NOW - DAY, "bob")], "user", NOW); + expect(byUser.map((g) => [g.label, g.children!.map((c) => c.label)])).toEqual([ + ["alice", ["#3"]], + ["bob", ["#2"]], + ]); + }); + + it("shows every working copy's revisions in one tree with IntelliJ's toolbar, menu and diffs", async () => { + mocks.svnIncomingRevisions.mockResolvedValue({ + status: "ok", + data: { + revisions: [revision(A, 7, Date.now(), "alice", "Fix\nthe build"), revision(B, 4, Date.now(), "bob")], + errors: [{ root: "/w/broken", message: "E170013: unable to connect" }], + }, + }); + render(); + expect(await screen.findByText("Fix // the build")).toBeInTheDocument(); + expect(screen.getByText("change 4")).toBeInTheDocument(); + expect(screen.getByText("Today")).toBeInTheDocument(); + expect(screen.getByRole("alert")).toHaveTextContent("broken: E170013: unable to connect"); + const toolbar = screen.getByRole("toolbar", { name: "Incoming" }); + expect( + within(toolbar) + .getAllByRole("button") + .map((b) => b.getAttribute("aria-label")), + ).toEqual([ + "Refresh", + "Show Details", + "Update Project", + "Filter by", + "Group by", + "Expand All", + "Collapse All", + "Copy Revision Number", + ]); + expect(screen.queryByText(/incoming change/)).toBeNull(); + + fireEvent.mouseDown(screen.getByText("Fix // the build"), { button: 0 }); + const changes = screen.getByRole("listbox", { name: "Changed files" }); + expect(within(changes).getByText("/trunk/f7.txt")).toBeInTheDocument(); + fireEvent.doubleClick(within(changes).getByText("/trunk/f7.txt")); + expect(mocks.openVcsDiff.mock.calls.at(-1)![0]).toMatchObject({ + path: `${A}/f7.txt`, + left: { type: "rev", rev: "6" }, + right: { type: "rev", rev: "7" }, + }); + + fireEvent.click(within(toolbar).getByRole("button", { name: "Copy Revision Number" })); + expect(mocks.writeClipboardText).toHaveBeenCalledWith("7"); + fireEvent.contextMenu(screen.getByText("Fix // the build")); + expect(lastMenu().map((i) => i.label)).toEqual([ + "Refresh", + "Show Details", + "Update Project", + "Copy Revision Number", + ]); + act(() => lastMenu()[2]!.run!()); + expect(mocks.executeAction).toHaveBeenCalledWith("vcs.update", undefined); + }); + + it("says there are no incoming changes", async () => { + mocks.svnIncomingRevisions.mockResolvedValue({ status: "ok", data: { revisions: [], errors: [] } }); + render(); + expect(await screen.findByText("There are no incoming changes")).toBeInTheDocument(); + }); +}); diff --git a/src/features/vcs/__tests__/svnUpdateFiles.test.ts b/src/features/vcs/__tests__/svnUpdateFiles.test.ts index 6fccd1b61e..3c9b441bf5 100644 --- a/src/features/vcs/__tests__/svnUpdateFiles.test.ts +++ b/src/features/vcs/__tests__/svnUpdateFiles.test.ts @@ -91,7 +91,8 @@ describe("Subversion › Update File / Update Directory", () => { it("reports the files the updates changed, across working copies", async () => { Object.assign(changed, { [boot]: 2, [antd]: 1 }); await svnUpdateFiles([`${boot}/a.txt`, `${boot}/src`, `${antd}/b.txt`]); - expect(notified.at(-1)).toBe("3 files updated"); + // IntelliJ's balloon: "N Files Updated" (`update.notification.title.count.files.updated`). + expect(notified.at(-1)).toBe("3 Files Updated"); }); it("says the files are up to date when an update changed none", async () => { diff --git a/src/features/vcs/__tests__/vcsIdentity.test.tsx b/src/features/vcs/__tests__/vcsIdentity.test.tsx index caeec17b61..5d8159e3f5 100644 --- a/src/features/vcs/__tests__/vcsIdentity.test.tsx +++ b/src/features/vcs/__tests__/vcsIdentity.test.tsx @@ -19,7 +19,8 @@ describe("which version control system a root is", () => { const content = window().component; // A mixed project follows the selected root. useVcs.setState({ repo: "/p/wc" }); - expect([window().title, window().icon]).toEqual(["SVN", "subversion"]); + // IntelliJ's stripe has the version control icon for every system. + expect([window().title, window().icon]).toEqual(["SVN", "toolwindow-git"]); expect(window().component).toBe(content); useVcs.setState({ repo: "/p/app" }); expect([window().title, window().icon]).toEqual(["Git", "toolwindow-git"]); diff --git a/src/features/vcs/actions.tsx b/src/features/vcs/actions.tsx index 355f540d86..b46d6c4dbe 100644 --- a/src/features/vcs/actions.tsx +++ b/src/features/vcs/actions.tsx @@ -1428,6 +1428,19 @@ export function registerVcsActions(): () => void { keywords: ["svn", "branches", "trunk", "tags"], run: ({ arg }) => openSvnConfigureBranchesDialog(rootOfKind(operationRepo(arg), "subversion")), }, + { + // Version Control › Show Tool Window Tab › Show Working Copies (`Svn.Show.Working.Copies`). + id: "svn.showWorkingCopies", + title: "Show Working Copies", + category: "Subversion", + when: `${VCS} && ${SUBVERSION}`, + visibleWhen: SUBVERSION, + keywords: ["svn", "working copies information"], + run: () => { + selectGitTab("svnInfo"); + showGitWindow(); + }, + }, { id: "svn.cleanup", title: "Cleanup", diff --git a/src/features/vcs/gitTabs.ts b/src/features/vcs/gitTabs.ts index 0baa8f4d78..b418f69707 100644 --- a/src/features/vcs/gitTabs.ts +++ b/src/features/vcs/gitTabs.ts @@ -57,16 +57,29 @@ export interface GitTabsInput extends StashTabsInput { workingCopies?: boolean; /** Project contains at least one Subversion working copy (shows the Incoming tab). */ hasSvn?: boolean; + /** Update Info tabs of Subversion updates (their file trees), after the Git ones. */ + svnUpdates?: readonly { id: string; time: string }[]; } +/** The tab title of an update's Update Info, as the Git ones are named. */ +function updateInfoLabel(target: string): string { + return tx`Update Info: ${target}`; +} + +/** + * In IntelliJ's order (`ChangesViewContentManager` weights): Local Changes, Incoming, Shelf, + * Log, Console, Worktrees; Subversion's working copies after them. + */ export function gitTabs(input: GitTabsInput): ContentTab[] { return [ - ...(input.modal ? [{ id: "changes", label: "Local Changes" }, ...stashTabs(input)] : []), + ...(input.modal ? [{ id: "changes", label: "Local Changes" }] : []), + ...(input.hasSvn ? [{ id: "incoming", label: "Incoming" }] : []), + ...(input.modal ? stashTabs(input) : []), { id: "log", label: "Log" }, ...input.logTabs .filter((t) => t.location !== "editor") .map((t) => ({ id: t.id, label: logTabLabel(t), closable: true })), - ...(input.hasSvn ? [{ id: "incoming", label: "Incoming" }] : []), + ...(input.svnUpdates ?? []).map((u) => ({ id: u.id, label: updateInfoLabel(u.time), closable: true })), { id: "console", label: "Console" }, ...(input.noGit ? [] : [{ id: "worktrees", label: "Worktrees" }]), ...(input.workingCopies ? [{ id: "svnInfo", label: "Subversion Working Copies Information" }] : []), diff --git a/src/features/vcs/ops.ts b/src/features/vcs/ops.ts index 4b0fa9a9f0..190b6665a8 100644 --- a/src/features/vcs/ops.ts +++ b/src/features/vcs/ops.ts @@ -369,6 +369,8 @@ export async function runRemoteRound( const updated: UpdatedRange[] = []; // Files an update of a non-Git working copy (`svn update`) changed; it has no commit range. let workingCopyFiles = 0; + // Their files and revisions: the update's Update Info tab (IntelliJ's UpdateInfoTree). + const workingCopyUpdates: WorkingCopyUpdate[] = []; const pushed: RepoPushOutcome[] = []; const fetched: Array = []; let hasFetchReport = false; @@ -492,8 +494,16 @@ export async function runRemoteRound( const firstError = errors[0]; if (firstError) throw new IpcError({ ...firstError, message: errors.map(({ message }) => message).join("\n") }); - } else if (report && "updatedFiles" in report) workingCopyFiles += report.updatedFiles; - else if (report) recordPush(root, describePush(report)); + } else if (report && "updatedFiles" in report) { + workingCopyFiles += report.updatedFiles; + if (root) + workingCopyUpdates.push({ + root, + files: report.items ?? [], + from: report.fromRevision ?? null, + to: report.toRevision ?? null, + }); + } else if (report) recordPush(root, describePush(report)); else if (isPush(op)) { const fallback = op.op === "pushTag" ? tx`Pushed tag ${op.tag} to ${op.remote}` : tx("Push successful"); recordPush(root, [legacyPush ?? fallback]); @@ -602,7 +612,7 @@ export async function runRemoteRound( }); } if (!reported && isUpdate(first) && (updated.length || workingCopyFiles)) - await notifyUpdated(updated, "vcs.remote.updated", workingCopyFiles); + await notifyUpdated(updated, "vcs.remote.updated", workingCopyFiles, workingCopyUpdates); return failures; } if (restoreError !== null) { @@ -613,7 +623,7 @@ export async function runRemoteRound( lastRemoteError = null; if (detached === targets.length) notify({ level: "info", key: "vcs.remote", title: "Nothing to update" }); else if (isUpdate(first)) { - await notifyUpdated(updated, "vcs.remote", workingCopyFiles); + await notifyUpdated(updated, "vcs.remote", workingCopyFiles, workingCopyUpdates); // An update that leaves conflicts and still succeeds (`svn update --accept postpone`; a // conflicted Git pull fails instead, above) opens the conflicts as a pull does. if (targets.some(({ repo }) => vcsKindOf(repo ?? primary) !== "git")) await refreshNow(); @@ -816,11 +826,51 @@ async function openUpdateInfo(updated: readonly UpdatedRange[]) { toolWindowService().show("git", true); } +/** What an update of a working copy of another system (`svn update`) changed. */ +export interface WorkingCopyUpdate { + root: string; + files: { path: string; action: string }[]; + from: string | null; + to: string | null; +} + +/** IntelliJ's balloon of an update of working copies: "N Files Updated" with View, its Update Info tab. */ +async function notifyWorkingCopiesUpdated(key: string, files: number, updates: readonly WorkingCopyUpdate[]) { + const { addSvnUpdate } = await import("./svnUpdateInfo"); + const tab = addSvnUpdate(updates); + notify({ + level: "info", + key, + title: files === 1 ? tx("1 File Updated") : tx`${files} Files Updated`, + actions: tab + ? [ + { + label: "View", + run: () => { + selectGitTabLazily(tab); + toolWindowService().show("git", true); + }, + }, + ] + : undefined, + }); +} + +function selectGitTabLazily(id: string) { + void import("./logStore").then(({ selectGitTab }) => selectGitTab(id)); +} + /** - * Update Project's result: "N files updated in M commits" with View Commits, or "N files - * updated" for working copies of other systems (`workingCopyFiles`), which have no commit range. + * Update Project's result: "N files updated in M commits" with View Commits, or IntelliJ's + * "N Files Updated" with View for working copies of other systems (`workingCopyFiles`), which + * have no commit range: their files open in an Update Info tab. */ -export async function notifyUpdated(updated: readonly UpdatedRange[], key = "vcs.remote", workingCopyFiles = 0) { +export async function notifyUpdated( + updated: readonly UpdatedRange[], + key = "vcs.remote", + workingCopyFiles = 0, + workingCopyUpdates: readonly WorkingCopyUpdate[] = [], +) { const project = useProject.getState().project; if (!updated.length && !workingCopyFiles) { notify({ level: "info", key, title: "All files are up-to-date" }); @@ -850,9 +900,11 @@ export async function notifyUpdated(updated: readonly UpdatedRange[], key = "vcs ); if (useProject.getState().project !== project) return; if (!updated.length) { - notify({ level: "info", key, title: `${filesText(files)} updated` }); + await notifyWorkingCopiesUpdated(key, files, workingCopyUpdates); return; } + // Working copies of another system updated as well: their files get an Update Info tab too. + if (workingCopyUpdates.length) void import("./svnUpdateInfo").then((m) => m.addSvnUpdate(workingCopyUpdates)); notify({ level: "info", key, diff --git a/src/features/vcs/svnIncoming.tsx b/src/features/vcs/svnIncoming.tsx new file mode 100644 index 0000000000..5c85a1ddfc --- /dev/null +++ b/src/features/vcs/svnIncoming.tsx @@ -0,0 +1,394 @@ +/** + * Incoming, as IntelliJ's Incoming changes view (`IncomingChangesViewProvider`, + * `CommittedChangesTreeBrowser`): the revisions committed after each working copy's BASE, of + * every working copy in one tree grouped by date (`DateChangeListGroupingStrategy`), with the + * selected revisions' files at the right (30%). A file's diff is the change its revision made. + */ +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import type { SvnIncomingPath, SvnIncomingRevision, SvnIncomingRevisions } from "@/bindings"; +import { executeAction } from "@/platform/actions"; +import { writeClipboardText } from "@/platform/clipboard"; +import { tx, useI18n } from "@/platform/i18n"; +import { call, commands, nextRequestId } from "@/platform/ipc"; +import { + IconButton, + Select, + showContextMenu, + Spinner, + SplitGroup, + SplitHandle, + SplitPanel, + T, + Tree, + type TreeHandle, +} from "@/ui"; +import { openVcsDiff, withChain, type DiffData } from "./diffInput"; +import { formatTime } from "./model"; +import { errorMessage } from "./ops"; +import { repoName, useSvnPanelRefresh, useVcs } from "./store"; +import commonStyles from "./common.module.css"; +import styles from "./svnToolWindow.module.css"; + +// --------------------------------------------------------------------------- +// Grouping (DateChangeListGroupingStrategy, and Group by User) + +/** The start (local midnight) of the Sunday-first week of `d`, as Java's English calendar counts weeks. */ +const weekStart = (d: Date) => new Date(d.getFullYear(), d.getMonth(), d.getDate() - d.getDay()).getTime(); + +/** + * IntelliJ's date group of a revision: Today, a weekday of this week, Last Week, a month of this + * year, or "Month yyyy" before that; names in the UI's language. + */ +export function dateGroup(timeMs: number, now = Date.now()): string { + const date = new Date(timeMs); + const today = new Date(now); + const locale = useI18n.getState().locale; + if (date.toDateString() === today.toDateString()) return tx("Today"); + const week = weekStart(today); + if (weekStart(date) === week) return date.toLocaleDateString(locale, { weekday: "long" }); + if (weekStart(date) === weekStart(new Date(week - 1))) return tx("Last Week"); + if (date.getFullYear() === today.getFullYear()) return date.toLocaleDateString(locale, { month: "long" }); + return date.toLocaleDateString(locale, { month: "long", year: "numeric" }); +} + +export type IncomingGroupBy = "date" | "user"; + +export interface IncomingNode { + key: string; + label: string; + revision?: SvnIncomingRevision; + children?: IncomingNode[]; +} + +const revisionKey = (r: SvnIncomingRevision) => `rev:${r.root}:${r.revision}`; + +/** The revision tree: groups (by date or by user) in the order their newest revision comes. */ +export function incomingTree(revisions: readonly SvnIncomingRevision[], by: IncomingGroupBy, now = Date.now()) { + const groups = new Map(); + const sorted = [...revisions].sort((a, b) => (b.timeMs ?? 0) - (a.timeMs ?? 0) || b.revision - a.revision); + for (const r of sorted) { + const label = by === "date" ? dateGroup(r.timeMs ?? 0, now) : r.author || tx(""); + let group = groups.get(label); + if (!group) { + group = { key: `group:${label}`, label, children: [] }; + groups.set(label, group); + } + group.children!.push({ key: revisionKey(r), label: `#${r.revision}`, revision: r }); + } + return [...groups.values()]; +} + +/** A revision's comment on one line, as IntelliJ's renderer shows it. */ +export const oneLine = (message: string) => message.trim().replace(/\r?\n/g, " // "); + +// --------------------------------------------------------------------------- +// A file's diff: the change its revision made + +/** The diff of `path` as revision `r` changed it: before (r - 1) and at r. */ +export function incomingDiff(r: SvnIncomingRevision, path: SvnIncomingPath): DiffData | null { + if (!path.local) return null; + const before = String(r.revision - 1); + const at = String(r.revision); + const absent = (label: string) => ({ type: "text" as const, text: "", label, absent: true }); + return { + path: path.local, + left: path.action === "A" ? absent(tx`r${before}`) : { type: "rev", rev: before, label: `r${before}` }, + right: path.action === "D" ? absent(tx`r${at}`) : { type: "rev", rev: at, label: `r${at}` }, + }; +} + +/** Show Diff of `path` with the other files of the revisions shown as its chain. */ +function showIncomingDiff(rows: readonly ChangeRow[], at: ChangeRow) { + const diffs = rows.flatMap((row) => { + const d = incomingDiff(row.revision, row.path); + return d ? [{ row, d }] : []; + }); + const index = diffs.findIndex((x) => x.row === at); + if (index < 0) return; + void openVcsDiff( + withChain( + diffs.map((x) => x.d), + index, + ), + { preview: true }, + ); +} + +interface ChangeRow { + key: string; + revision: SvnIncomingRevision; + path: SvnIncomingPath; +} + +const ACTION_CLASS: Record = { + A: styles.added, + D: styles.deleted, + M: styles.modified, + R: styles.modified, +}; + +// --------------------------------------------------------------------------- +// The view + +export function SvnIncomingPanel() { + const roots = useVcs((s) => s.roots); + const kinds = useVcs((s) => s.kinds); + const incomingVersion = useSvnPanelRefresh((s) => s.incomingVersion); + const svnRoots = useMemo(() => roots.filter((r) => kinds[r] === "subversion"), [roots, kinds]); + const [tick, setTick] = useState(0); + const [state, setState] = useState<{ key: string; data: SvnIncomingRevisions | null; error: string | null }>({ + key: "", + data: null, + error: null, + }); + const fetchKey = svnRoots.length ? `${svnRoots.join("\0")}::${tick}::${incomingVersion}` : ""; + const loading = !!fetchKey && state.key !== fetchKey; + const data = state.data; + + useEffect(() => { + if (!fetchKey) return; + let alive = true; + void call(commands.svnIncomingRevisions(nextRequestId())) + .then((res) => alive && setState({ key: fetchKey, data: res, error: null })) + .catch((e) => alive && setState({ key: fetchKey, data: null, error: errorMessage(e) })); + return () => { + alive = false; + }; + }, [fetchKey]); + const refresh = useCallback(() => setTick((t) => t + 1), []); + + const [groupBy, setGroupBy] = useState("date"); + const [filterBy, setFilterBy] = useState<"none" | "user">("none"); + const [users, setUsers] = useState>(() => new Set()); + const [details, setDetails] = useState(false); + const [selected, setSelected] = useState>(() => new Set()); + const [expanded, setExpanded] = useState | null>(null); + const tree = useRef(null); + + const revisions = useMemo(() => data?.revisions ?? [], [data]); + const authors = useMemo(() => [...new Set(revisions.map((r) => r.author))].sort(), [revisions]); + const shown = useMemo( + () => (filterBy === "user" && users.size ? revisions.filter((r) => users.has(r.author)) : revisions), + [revisions, filterBy, users], + ); + const nodes = useMemo(() => incomingTree(shown, groupBy), [shown, groupBy]); + const groupKeys = useMemo(() => nodes.map((n) => n.key), [nodes]); + // IntelliJ's tree shows every group open. + const open = expanded ?? new Set(groupKeys); + const chosen = useMemo( + () => shown.filter((r) => selected.has(revisionKey(r))).sort((a, b) => b.revision - a.revision), + [shown, selected], + ); + const changes = useMemo( + () => + chosen.flatMap((revision) => + revision.paths.map((path) => ({ key: `${revisionKey(revision)}:${path.path}`, revision, path })), + ), + [chosen], + ); + const [changeKey, setChangeKey] = useState(null); + + const copyRevisions = () => { + if (chosen.length) void writeClipboardText(chosen.map((r) => String(r.revision)).join(", ")); + }; + const updateProject = () => void executeAction("vcs.update"); + const menu = (e: { clientX: number; clientY: number }) => + showContextMenu({ x: e.clientX, y: e.clientY }, [ + { label: "Refresh", icon: "refresh", run: refresh }, + { label: "Show Details", checked: details, run: () => setDetails((d) => !d) }, + { label: "Update Project", run: updateProject }, + { label: "Copy Revision Number", icon: "copy", disabled: !chosen.length, run: copyRevisions }, + ]); + + if (!svnRoots.length) { + return ( +
+ No Subversion working copies detected in the project +
+ ); + } + + const errors = + state.key === fetchKey + ? [...(state.error ? [state.error] : []), ...(data?.errors ?? []).map((e) => `${repoName(e.root)}: ${e.message}`)] + : []; + + return ( + + +
+
+ + setDetails((d) => !d)} + /> + + + + setExpanded(new Set(groupKeys))} + /> + setExpanded(new Set())} /> + +
+ {errors.map((message) => ( +
+ {message} +
+ ))} +
+ {filterBy === "user" && ( +
+ {authors.map((author) => ( +
+ setUsers((s) => { + const next = new Set(s); + if (next.has(author)) next.delete(author); + else next.add(author); + return next; + }) + } + > + {author || tx("")} +
+ ))} +
+ )} + {loading && !data ? ( +
+ +
+ ) : !shown.length ? ( +
+ There are no incoming changes +
+ ) : ( + + handleRef={tree} + className={styles.revisionTree} + aria-label={tx("Incoming revisions")} + roots={nodes} + getKey={(n) => n.key} + getLabel={(n) => (n.revision ? `#${n.revision.revision} ${oneLine(n.revision.message)}` : n.label)} + getChildren={(n) => n.children} + isExpandable={(n) => !!n.children} + expanded={open} + onExpandedChange={(next) => setExpanded(next)} + selected={selected} + onSelectionChange={(next) => setSelected(next)} + multiSelect + speedSearch + renderNode={(n) => + n.revision ? : {n.label} + } + onContextMenu={(_n, _s, e) => menu(e)} + /> + )} +
+
+
+ + +
+ {details && chosen.length > 0 && ( +
+ {chosen.map((r) => ( +
+
+ {tx`Revision ${r.revision}`} · {r.author} · {formatTime(r.timeMs)} · {repoName(r.root)} +
+
{r.message.trim() || tx("")}
+
+ ))} +
+ )} +
{ + const at = changes.find((c) => c.key === changeKey); + if (at && (e.key === "Enter" || ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "d"))) { + e.preventDefault(); + showIncomingDiff(changes, at); + } + }} + > + {changes.map((c) => ( +
setChangeKey(c.key)} + onDoubleClick={() => showIncomingDiff(changes, c)} + > + {c.path.action} + {c.path.path} +
+ ))} +
+
+
+
+ ); +} + +function RevisionRow({ r }: { r: SvnIncomingRevision }) { + const message = oneLine(r.message); + return ( + + #{r.revision} + {message || tx("")} + {r.author} + , {formatTime(r.timeMs)} + + ); +} diff --git a/src/features/vcs/svnPanels.tsx b/src/features/vcs/svnPanels.tsx index 84f2415eeb..89b3a2f126 100644 --- a/src/features/vcs/svnPanels.tsx +++ b/src/features/vcs/svnPanels.tsx @@ -6,39 +6,19 @@ * - Compare with Branch dialog (`SvnCompareWithBranchDialog`) * - Switch to URL dialog (`SvnSwitchUrlDialog`) */ -import { useCallback, useEffect, useMemo, useState } from "react"; -import type { - SvnBranchCompareEntry, - SvnBranchLayout, - SvnDepth, - SvnIncomingChange, - SvnWorkingCopyInfo, -} from "@/bindings"; +import { useEffect, useMemo, useState } from "react"; +import type { SvnBranchCompareEntry, SvnBranchLayout, SvnDepth, SvnWorkingCopyInfo } from "@/bindings"; import clsx from "clsx"; -import { executeAction } from "@/platform/actions"; import { writeClipboardText } from "@/platform/clipboard"; import { tx } from "@/platform/i18n"; import { call, commands, nextRequestId } from "@/platform/ipc"; import { useWorkflowSettings, workflowSettings, type SvnBranchConfigValid } from "@/platform/workflowSettings"; -import { Button, Checkbox, Dialog, Icon, IconButton, Input, Select, Spinner, T, type SelectOption } from "@/ui"; +import { Button, Checkbox, Dialog, IconButton, Input, Select, T, type SelectOption } from "@/ui"; import { notifications } from "@/workbench/contributions"; import { openDialog } from "./dialogs"; -import { selectGitTab, setLogFilters } from "./logStore"; -import { formatTime } from "./model"; import { errorMessage, logConsole } from "./ops"; import { saveVcsSettingOrThrow } from "./settingsUi"; -import { - notifySvnProjectUpdated, - notifySvnWorkingCopiesChanged, - otherSystemLines, - refreshNow, - repoName, - repoOf, - rootOfKind, - useSvnPanelRefresh, - useVcs, -} from "./store"; -import { svnCleanup, svnRelocate } from "./svn"; +import { notifySvnProjectUpdated, otherSystemLines, refreshNow, repoName, repoOf, rootOfKind } from "./store"; import commonStyles from "./common.module.css"; import styles from "./svn.module.css"; @@ -193,282 +173,11 @@ export function openSvnSwitchUrlDialog(repo?: string | null, initialUrl?: string // --------------------------------------------------------------------------- // Incoming Panel -export function SvnIncomingPanel() { - const roots = useVcs((s) => s.roots); - const kinds = useVcs((s) => s.kinds); - const selectedRepo = useVcs((s) => s.repo); - const incomingVersion = useSvnPanelRefresh((s) => s.incomingVersion); - const svnRoots = useMemo(() => roots.filter((r) => kinds[r] === "subversion"), [roots, kinds]); - const defaultRepo = - (selectedRepo && kinds[selectedRepo] === "subversion" ? selectedRepo : null) ?? svnRoots[0] ?? null; +// Incoming: `svnIncoming.tsx`. +export { SvnIncomingPanel } from "./svnIncoming"; - const [pickedRepo, setPickedRepo] = useState(null); - const repo = pickedRepo && svnRoots.includes(pickedRepo) ? pickedRepo : defaultRepo; - - const [tick, setTick] = useState(0); - const [state, setState] = useState<{ key: string; changes: SvnIncomingChange[]; error: string | null }>({ - key: "", - changes: [], - error: null, - }); - - const fetchKey = repo ? `${repo}::${tick}::${incomingVersion}` : ""; - const loading = !!fetchKey && state.key !== fetchKey; - const changes = useMemo(() => (state.key === fetchKey ? state.changes : []), [state, fetchKey]); - const error = state.key === fetchKey ? state.error : null; - - useEffect(() => { - if (!repo || !fetchKey) return; - let alive = true; - logConsole("cmd", `svn status -u --xml ${repo}`); - void call(commands.svnIncoming(nextRequestId(), repo)) - .then((res) => { - if (alive) setState({ key: fetchKey, changes: res, error: null }); - }) - .catch((e) => { - if (alive) setState({ key: fetchKey, changes: [], error: errorMessage(e) }); - }); - return () => { - alive = false; - }; - }, [repo, fetchKey]); - - const reload = useCallback(() => setTick((t) => t + 1), []); - - if (!svnRoots.length) { - return ( -
- No Subversion working copies detected in the project -
- ); - } - - return ( -
-
- {svnRoots.length > 1 && ( -