дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-05 17:47:08 +02:00
feat(svn): rework the Subversion tool window tabs: Incoming, Update Info and Working Copies (#8212)
Reworks the Subversion tabs of the bottom version control tool window:
- Incoming lists the revisions committed after the working copy's BASE (new svn_incoming_revisions command, svn log -v BASE+1:HEAD per working copy) in one tree grouped by date or user, with the selected revisions' files beside it, an icon toolbar (Refresh, Show Details, Update Project, Filter by, Group by, Expand/Collapse All, Copy Revision Number), a context menu and per-file diffs between N-1 and N. It is now the first tab.
- After an SVN update, a "{n} Files Updated" balloon with View opens an "Update Info: {time}" tab: Update Project > Updated from server > Updated / Created / Deleted / Restored, then Skipped, conflicts, Merged, Not in repository, Replaced, parsed from svn update's file lines, with group-by-package and by-changelist, Jump to Source, Delete and before/after-update diffs.
- Subversion Working Copies Information: vertical Refresh toolbar, copies sorted by path, decoded URLs, the format shown as its release with Change running svn upgrade --compatible-version (new svn_upgrade command), Depth Fix running svn update --set-depth infinity, External/Switched/Working copy root markers, Cleanup / Configure Branches / Merge From... links, and a detection-error balloon with Fix it. A new Show Working Copies action selects the tab.
- The console's empty state names Subversion in an SVN-only project, the stripe uses the version control icon for every VCS, and new strings are in en and zh.
Refs #7433
Co-authored-by: wildcatDownstairs <[email protected]>
Цей коміт міститься в:
1 джерело
b4148e2f39
коміт
65545d3563
29 files changed
+2770
-415
No files matched your search
@@ -137,6 +137,28 @@ pub async fn svn_cleanup(host: &Host, window: &str, repo: Option<PathBuf>) -> 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<PathBuf>, comment: String, steal: bool) -> IdeResult<()> {
|
||||
@@ -702,7 +724,7 @@ impl From<ide_svn::IncomingChange> 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<String>,
|
||||
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<String>,
|
||||
/// The formats the configured svn can convert it to (Format › Change), oldest first.
|
||||
pub formats: Vec<String>,
|
||||
}
|
||||
|
||||
impl From<ide_svn::WorkingCopyInfo> for SvnWorkingCopyInfo {
|
||||
@@ -731,7 +761,9 @@ impl From<ide_svn::WorkingCopyInfo> 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<SvnIncomingPath>,
|
||||
}
|
||||
|
||||
#[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<String>,
|
||||
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<SvnIncomingRevision>,
|
||||
pub errors: Vec<SvnWorkingCopyError>,
|
||||
}
|
||||
|
||||
#[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<Vec<SvnIncomingRevision>> {
|
||||
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<SvnIncomingRevisions> {
|
||||
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<SvnWorkingCopyInfo> = 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<PathBuf> = 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,
|
||||
|
||||
@@ -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<UpdatedItemReport>,
|
||||
/// The working copy's revision before and after the update.
|
||||
#[serde(default)]
|
||||
pub from_revision: Option<String>,
|
||||
#[serde(default)]
|
||||
pub to_revision: Option<String>,
|
||||
}
|
||||
|
||||
/// 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,
|
||||
}))
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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::<Vec<_>>(),
|
||||
[(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)]);
|
||||
}
|
||||
@@ -44,10 +44,15 @@ impl Backend for Fake {
|
||||
fn head_label(&self) -> Option<String> {
|
||||
Some(self.head.lock().clone())
|
||||
}
|
||||
fn update(&self, _: &[PathBuf], _: &CancellationToken, output: &dyn Fn(String)) -> IdeResult<usize> {
|
||||
fn update(
|
||||
&self,
|
||||
_: &[PathBuf],
|
||||
_: &CancellationToken,
|
||||
output: &dyn Fn(String),
|
||||
) -> IdeResult<ide_vcs::UpdateSummary> {
|
||||
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<Vec<Branch>> {
|
||||
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<String> = project.history.list(&file).unwrap().into_iter().map(|e| e.label).collect();
|
||||
|
||||
@@ -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<usize> {
|
||||
WorkingCopy::update_reporting(self, paths, None, cancel, output).map(|(_, changed)| changed)
|
||||
fn update(
|
||||
&self,
|
||||
paths: &[PathBuf],
|
||||
cancel: &CancellationToken,
|
||||
output: &dyn Fn(String),
|
||||
) -> IdeResult<ide_vcs::UpdateSummary> {
|
||||
WorkingCopy::update_reporting(self, paths, None, cancel, output).map(|(_, summary)| summary)
|
||||
}
|
||||
|
||||
fn branches(&self) -> IdeResult<Vec<Branch>> {
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -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<ide_vcs::UpdatedItem> {
|
||||
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<Vec<IncomingRevision>> {
|
||||
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::<u64>();
|
||||
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<Vec<IncomingRevision>> {
|
||||
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<PathBuf> {
|
||||
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<IncomingRevision> = 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<String> {
|
||||
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<WorkingCopyInfo> {
|
||||
self.working_copy_info_for(self.root())
|
||||
}
|
||||
@@ -1597,6 +1710,29 @@ pub struct IncomingChange {
|
||||
pub locked_by: Option<String>,
|
||||
}
|
||||
|
||||
/// 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<IncomingPath>,
|
||||
}
|
||||
|
||||
#[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<PathBuf>,
|
||||
/// `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<String>,
|
||||
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`].
|
||||
|
||||
@@ -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<UpdatedItem>,
|
||||
/// The working copy's revision before and after the update.
|
||||
pub from_revision: Option<String>,
|
||||
pub to_revision: Option<String>,
|
||||
}
|
||||
|
||||
/// 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<usize> {
|
||||
fn update(
|
||||
&self,
|
||||
_paths: &[PathBuf],
|
||||
_cancel: &CancellationToken,
|
||||
_output: &dyn Fn(String),
|
||||
) -> IdeResult<UpdateSummary> {
|
||||
Err(IdeError::unavailable("this version control system cannot update the working copy"))
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -2507,6 +2507,11 @@ export const commands = {
|
||||
svnIgnorePattern: (path: string, pattern: string) => typedError<null, IdeError>(__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<SvnIncomingChange[], IdeError>(__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<SvnIncomingRevisions, IdeError>(__TAURI_INVOKE("svn_incoming_revisions", { request })),
|
||||
/** Repository URL of `path` inside a Subversion working copy. */
|
||||
svnItemUrl: (path: string) => typedError<string, IdeError>(__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<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 })),
|
||||
/**
|
||||
* 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<SvnIncomingRevision[], IdeError>(__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<null, IdeError>(__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<null, IdeError>(__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<string>) => typedError<SvnUpdateResult, IdeError>(__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<null, IdeError>(__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,
|
||||
|
||||
@@ -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() {
|
||||
<WorktreesPanel className={styles.worktrees} listClassName={styles.worktreeList} />
|
||||
) : shown === "svnInfo" ? (
|
||||
<SvnWorkingCopiesPanel />
|
||||
) : isSvnUpdateTab(shown) ? (
|
||||
<SvnUpdateInfo id={shown} />
|
||||
) : null}
|
||||
{keptLog && (
|
||||
<div ref={logHost} className={clsx(styles.logHost, !logShown && styles.logHidden)} inert={!logShown}>
|
||||
@@ -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<HTMLDivElement>(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 && (
|
||||
<div className={styles.muted}>
|
||||
<T>Git commands run by the IDE appear here.</T>
|
||||
{system === "git" ? (
|
||||
<T>Git commands run by the IDE appear here.</T>
|
||||
) : system === "subversion" ? (
|
||||
<T>Subversion commands run by the IDE appear here.</T>
|
||||
) : (
|
||||
<T>Version control commands run by the IDE appear here.</T>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{lines.map((l) => (
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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(<SvnIncomingPanel />);
|
||||
|
||||
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(<SvnWorkingCopiesPanel />);
|
||||
|
||||
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"]);
|
||||
|
||||
@@ -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<typeof import("@/platform/ipc")>();
|
||||
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<typeof import("@tauri-apps/api/core")>()),
|
||||
Channel: class {
|
||||
onmessage: ((line: string) => void) | null = null;
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/workbench/contributions", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@/workbench/contributions")>()),
|
||||
notifications: () => ({ notify: mocks.notify, expire: mocks.expire }),
|
||||
editorService: () => ({ openFile: mocks.openFile }),
|
||||
toolWindowService: () => ({ show: mocks.showToolWindow }),
|
||||
}));
|
||||
|
||||
vi.mock("@/ui", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@/ui")>()),
|
||||
showContextMenu: (...args: unknown[]) => mocks.contextMenu(...args),
|
||||
}));
|
||||
|
||||
vi.mock("@/platform/actions", async (importOriginal) => {
|
||||
const real = await importOriginal<typeof import("@/platform/actions")>();
|
||||
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<typeof import("../dialogs")>()),
|
||||
confirmDialog: (...args: unknown[]) => mocks.confirmDialog(...args),
|
||||
}));
|
||||
|
||||
vi.mock("../diffInput", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("../diffInput")>()),
|
||||
openVcsDiff: (...args: unknown[]) => mocks.openVcsDiff(...args),
|
||||
}));
|
||||
|
||||
vi.mock("../svn", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("../svn")>()),
|
||||
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, VcsKind>, 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(<GitToolWindow />);
|
||||
expect(screen.getByText(empty)).toBeInTheDocument();
|
||||
expect(screen.getByRole("log", { name })).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const info = (over: Partial<SvnWorkingCopyInfo>): 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(<SvnWorkingCopiesPanel />);
|
||||
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(
|
||||
<>
|
||||
<VcsDialogHost />
|
||||
<SvnWorkingCopiesPanel />
|
||||
</>,
|
||||
);
|
||||
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(<SvnUpdateInfo id={update!.id} />);
|
||||
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(<SvnUpdateInfo id={id} />);
|
||||
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(<SvnIncomingPanel />);
|
||||
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(<SvnIncomingPanel />);
|
||||
expect(await screen.findByText("There are no incoming changes")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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"]);
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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" }] : []),
|
||||
|
||||
@@ -369,6 +369,8 @@ export async function runRemoteRound<Op extends RemoteOp>(
|
||||
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<FetchRemoteResult & { destination: string }> = [];
|
||||
let hasFetchReport = false;
|
||||
@@ -492,8 +494,16 @@ export async function runRemoteRound<Op extends RemoteOp>(
|
||||
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<Op extends RemoteOp>(
|
||||
});
|
||||
}
|
||||
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<Op extends RemoteOp>(
|
||||
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,
|
||||
|
||||
@@ -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<string, IncomingNode>();
|
||||
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("<no author>");
|
||||
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<string, string | undefined> = {
|
||||
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<IncomingGroupBy>("date");
|
||||
const [filterBy, setFilterBy] = useState<"none" | "user">("none");
|
||||
const [users, setUsers] = useState<ReadonlySet<string>>(() => new Set());
|
||||
const [details, setDetails] = useState(false);
|
||||
const [selected, setSelected] = useState<ReadonlySet<string>>(() => new Set());
|
||||
const [expanded, setExpanded] = useState<ReadonlySet<string> | null>(null);
|
||||
const tree = useRef<TreeHandle>(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<ChangeRow[]>(
|
||||
() =>
|
||||
chosen.flatMap((revision) =>
|
||||
revision.paths.map((path) => ({ key: `${revisionKey(revision)}:${path.path}`, revision, path })),
|
||||
),
|
||||
[chosen],
|
||||
);
|
||||
const [changeKey, setChangeKey] = useState<string | null>(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 (
|
||||
<div className={styles.empty}>
|
||||
<T>No Subversion working copies detected in the project</T>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const errors =
|
||||
state.key === fetchKey
|
||||
? [...(state.error ? [state.error] : []), ...(data?.errors ?? []).map((e) => `${repoName(e.root)}: ${e.message}`)]
|
||||
: [];
|
||||
|
||||
return (
|
||||
<SplitGroup orientation="horizontal" className={styles.incoming} storageKey="openidea.svn.incomingSplit">
|
||||
<SplitPanel id="revisions" defaultSize="70%" minSize="30%">
|
||||
<div className={styles.column}>
|
||||
<div className={styles.topToolbar} role="toolbar" aria-label={tx("Incoming")}>
|
||||
<IconButton icon="refresh" title="Refresh" size="small" disabled={loading} onClick={refresh} />
|
||||
<IconButton
|
||||
icon="preview-details"
|
||||
title="Show Details"
|
||||
size="small"
|
||||
pressed={details}
|
||||
onClick={() => setDetails((d) => !d)}
|
||||
/>
|
||||
<IconButton icon="git-pull" title="Update Project" size="small" onClick={updateProject} />
|
||||
<span className={styles.toolbarSeparator} aria-hidden />
|
||||
<label className={styles.toolbarSelect}>
|
||||
<T>Filter by</T>
|
||||
<Select
|
||||
aria-label={tx("Filter by")}
|
||||
variant="ghost"
|
||||
value={filterBy}
|
||||
options={[
|
||||
{ value: "none", label: "None" },
|
||||
{ value: "user", label: "User" },
|
||||
]}
|
||||
onChange={(v) => setFilterBy(v === "user" ? "user" : "none")}
|
||||
/>
|
||||
</label>
|
||||
<label className={styles.toolbarSelect}>
|
||||
<T>Group by</T>
|
||||
<Select
|
||||
aria-label={tx("Group by")}
|
||||
variant="ghost"
|
||||
value={groupBy}
|
||||
options={[
|
||||
{ value: "date", label: "Date" },
|
||||
{ value: "user", label: "User" },
|
||||
]}
|
||||
onChange={(v) => setGroupBy(v === "user" ? "user" : "date")}
|
||||
/>
|
||||
</label>
|
||||
<IconButton
|
||||
icon="expand-all"
|
||||
title="Expand All"
|
||||
size="small"
|
||||
onClick={() => setExpanded(new Set(groupKeys))}
|
||||
/>
|
||||
<IconButton icon="collapse-all" title="Collapse All" size="small" onClick={() => setExpanded(new Set())} />
|
||||
<IconButton
|
||||
icon="copy"
|
||||
title="Copy Revision Number"
|
||||
size="small"
|
||||
disabled={!chosen.length}
|
||||
onClick={copyRevisions}
|
||||
/>
|
||||
</div>
|
||||
{errors.map((message) => (
|
||||
<div key={message} className={commonStyles.error} role="alert">
|
||||
{message}
|
||||
</div>
|
||||
))}
|
||||
<div className={styles.revisionsArea}>
|
||||
{filterBy === "user" && (
|
||||
<div className={styles.userFilter} role="listbox" aria-label={tx("User")} aria-multiselectable>
|
||||
{authors.map((author) => (
|
||||
<div
|
||||
key={author}
|
||||
role="option"
|
||||
aria-selected={users.has(author)}
|
||||
className={styles.userRow}
|
||||
data-selected={users.has(author) || undefined}
|
||||
onClick={() =>
|
||||
setUsers((s) => {
|
||||
const next = new Set(s);
|
||||
if (next.has(author)) next.delete(author);
|
||||
else next.add(author);
|
||||
return next;
|
||||
})
|
||||
}
|
||||
>
|
||||
{author || tx("<no author>")}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{loading && !data ? (
|
||||
<div className={styles.empty}>
|
||||
<Spinner />
|
||||
</div>
|
||||
) : !shown.length ? (
|
||||
<div className={styles.empty}>
|
||||
<T>There are no incoming changes</T>
|
||||
</div>
|
||||
) : (
|
||||
<Tree<IncomingNode>
|
||||
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 ? <RevisionRow r={n.revision} /> : <span className={styles.groupRow}>{n.label}</span>
|
||||
}
|
||||
onContextMenu={(_n, _s, e) => menu(e)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</SplitPanel>
|
||||
<SplitHandle />
|
||||
<SplitPanel id="changes" defaultSize="30%" minSize="15%">
|
||||
<div className={styles.column}>
|
||||
{details && chosen.length > 0 && (
|
||||
<div className={styles.details}>
|
||||
{chosen.map((r) => (
|
||||
<div key={revisionKey(r)}>
|
||||
<div className={styles.detailsTitle}>
|
||||
{tx`Revision ${r.revision}`} · {r.author} · {formatTime(r.timeMs)} · {repoName(r.root)}
|
||||
</div>
|
||||
<pre className={styles.detailsMessage}>{r.message.trim() || tx("<no comment>")}</pre>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div
|
||||
className={styles.changeList}
|
||||
role="listbox"
|
||||
aria-label={tx("Changed files")}
|
||||
tabIndex={0}
|
||||
onKeyDown={(e) => {
|
||||
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) => (
|
||||
<div
|
||||
key={c.key}
|
||||
role="option"
|
||||
aria-selected={changeKey === c.key}
|
||||
className={styles.changeRow}
|
||||
data-selected={changeKey === c.key || undefined}
|
||||
title={c.path.path}
|
||||
onClick={() => setChangeKey(c.key)}
|
||||
onDoubleClick={() => showIncomingDiff(changes, c)}
|
||||
>
|
||||
<span className={ACTION_CLASS[c.path.action] ?? styles.modified}>{c.path.action}</span>
|
||||
<span className={styles.changePath}>{c.path.path}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</SplitPanel>
|
||||
</SplitGroup>
|
||||
);
|
||||
}
|
||||
|
||||
function RevisionRow({ r }: { r: SvnIncomingRevision }) {
|
||||
const message = oneLine(r.message);
|
||||
return (
|
||||
<span className={styles.revisionRow}>
|
||||
<span className={styles.revisionNumber}>#{r.revision}</span>
|
||||
<span className={message ? styles.revisionMessage : styles.noComment}>{message || tx("<no comment>")}</span>
|
||||
<span className={styles.revisionAuthor}>{r.author}</span>
|
||||
<span className={styles.revisionDate}>, {formatTime(r.timeMs)}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -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<string | null>(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 (
|
||||
<div className={styles.panelEmpty}>
|
||||
<T>No Subversion working copies detected in the project</T>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={styles.panelWrap}>
|
||||
<div className={styles.panelToolbar}>
|
||||
{svnRoots.length > 1 && (
|
||||
<Select
|
||||
aria-label={tx("Working copy")}
|
||||
value={repo ?? ""}
|
||||
onChange={(v) => setPickedRepo(v || null)}
|
||||
options={svnRoots.map((r) => ({ value: r, label: repoName(r) }))}
|
||||
/>
|
||||
)}
|
||||
<Button onClick={reload} disabled={loading || !repo}>
|
||||
<Icon name="refresh" />
|
||||
<T>Refresh</T>
|
||||
</Button>
|
||||
<Button onClick={() => void executeAction("vcs.update")} disabled={!repo}>
|
||||
<T>Update Project…</T>
|
||||
</Button>
|
||||
<span className={styles.toolbarCount}>
|
||||
{loading ? tx("Checking remote changes…") : tx`${changes.length} incoming change(s)`}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{error && <div className={commonStyles.error}>{error}</div>}
|
||||
|
||||
{loading && changes.length === 0 ? (
|
||||
<div className={styles.panelEmpty}>
|
||||
<Spinner />
|
||||
</div>
|
||||
) : !error && changes.length === 0 ? (
|
||||
<div className={styles.panelEmpty}>
|
||||
<T>No incoming changes</T>
|
||||
</div>
|
||||
) : (
|
||||
<div className={styles.panelList}>
|
||||
{changes.map((c) => {
|
||||
const badge = statusBadge(c.item, c.props);
|
||||
return (
|
||||
<div key={c.path} className={styles.panelRow}>
|
||||
<span className={compareKindClass(c.item) ?? styles.statusBadge}>{badge}</span>
|
||||
<span className={styles.path} title={c.path}>
|
||||
{c.relPath}
|
||||
</span>
|
||||
{c.hasLocalChange && (
|
||||
<span className={styles.conflictTag}>
|
||||
<T>Local edits</T>
|
||||
</span>
|
||||
)}
|
||||
{c.lockedBy && (
|
||||
<span className={styles.metaCell} title={c.lockedBy}>
|
||||
{tx`Locked by ${c.lockedBy}`}
|
||||
</span>
|
||||
)}
|
||||
{c.revision !== null && <span className={styles.revBadge}>r{c.revision}</span>}
|
||||
{c.author && <span className={styles.metaCell}>{c.author}</span>}
|
||||
{(c.timeMs ?? 0) > 0 && <span className={styles.metaCell}>{formatTime(c.timeMs)}</span>}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Working Copies Information Panel
|
||||
|
||||
export function SvnWorkingCopiesPanel() {
|
||||
const roots = useVcs((s) => s.roots);
|
||||
const kinds = useVcs((s) => s.kinds);
|
||||
const heads = useVcs((s) => s.heads);
|
||||
const wcInfoVersion = useSvnPanelRefresh((s) => s.wcInfoVersion);
|
||||
const svnRoots = useMemo(() => roots.filter((r) => kinds[r] === "subversion"), [roots, kinds]);
|
||||
const headSignature = useMemo(
|
||||
() => svnRoots.map((r) => `${r}=${heads[r]?.head ?? ""}@${heads[r]?.headCommit ?? ""}`).join("\0"),
|
||||
[svnRoots, heads],
|
||||
);
|
||||
const [tick, setTick] = useState(0);
|
||||
const [state, setState] = useState<{ key: string; infos: SvnWorkingCopyInfo[]; error: string | null }>({
|
||||
key: "",
|
||||
infos: [],
|
||||
error: null,
|
||||
});
|
||||
|
||||
const fetchKey = svnRoots.length ? `${svnRoots.join("\0")}::${headSignature}::${tick}::${wcInfoVersion}` : "";
|
||||
const loading = !!fetchKey && state.key !== fetchKey;
|
||||
const infos = state.key === fetchKey ? state.infos : [];
|
||||
const error = state.key === fetchKey ? state.error : null;
|
||||
|
||||
useEffect(() => {
|
||||
if (!fetchKey) return;
|
||||
let alive = true;
|
||||
void call(commands.svnWorkingCopyInfo(null))
|
||||
.then((res) => {
|
||||
if (alive) setState({ key: fetchKey, infos: res, error: null });
|
||||
})
|
||||
.catch((e) => {
|
||||
if (alive) setState({ key: fetchKey, infos: [], error: errorMessage(e) });
|
||||
});
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, [fetchKey]);
|
||||
|
||||
const reload = useCallback(() => setTick((t) => t + 1), []);
|
||||
|
||||
if (!svnRoots.length) {
|
||||
return (
|
||||
<div className={styles.panelEmpty}>
|
||||
<T>No Subversion working copies detected in the project</T>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={styles.panelWrap}>
|
||||
<div className={styles.panelToolbar}>
|
||||
<Button onClick={reload} disabled={loading}>
|
||||
<Icon name="refresh" />
|
||||
<T>Refresh</T>
|
||||
</Button>
|
||||
<Button onClick={() => openSvnConfigureBranchesDialog(svnRoots[0])}>
|
||||
<T>Configure Branches…</T>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{error && <div className={commonStyles.error}>{error}</div>}
|
||||
|
||||
{loading && infos.length === 0 ? (
|
||||
<div className={styles.panelEmpty}>
|
||||
<Spinner />
|
||||
</div>
|
||||
) : (
|
||||
<div className={styles.panelList}>
|
||||
{infos.map((info) => (
|
||||
<div key={info.root} className={styles.wcCard}>
|
||||
<div className={styles.wcHeader}>
|
||||
<span className={styles.wcTitle}>{repoName(info.root)}</span>
|
||||
<span className={styles.branchesPaneUrl} title={info.root}>
|
||||
{info.root}
|
||||
</span>
|
||||
{info.revision !== null && <span className={styles.revBadge}>r{info.revision}</span>}
|
||||
{info.format && <span className={styles.metaCell}>{tx`Format ${info.format}`}</span>}
|
||||
{info.depth && <span className={styles.metaCell}>{tx`Depth: ${info.depth}`}</span>}
|
||||
{info.isSwitched && (
|
||||
<span className={styles.conflictTag}>
|
||||
<T>Switched</T>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className={styles.wcMetaLine}>
|
||||
<span className={styles.metaLabel}>
|
||||
<T>URL:</T>
|
||||
</span>
|
||||
<span className={styles.branchesPaneUrl} title={info.url}>
|
||||
{info.url}
|
||||
</span>
|
||||
</div>
|
||||
<div className={styles.wcActions}>
|
||||
<button
|
||||
type="button"
|
||||
className={commonStyles.linkButton}
|
||||
onClick={() => {
|
||||
setLogFilters({ repositories: [resolveSvnRepo(info.root) ?? info.root] });
|
||||
selectGitTab("log");
|
||||
}}
|
||||
>
|
||||
<T>Show Log</T>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={commonStyles.linkButton}
|
||||
onClick={() => void executeAction("vcs.update", { repo: resolveSvnRepo(info.root) ?? info.root })}
|
||||
>
|
||||
<T>Update Project…</T>
|
||||
</button>
|
||||
<button type="button" className={commonStyles.linkButton} onClick={() => svnCleanup(info.root)}>
|
||||
<T>Cleanup</T>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={commonStyles.linkButton}
|
||||
onClick={() =>
|
||||
void svnRelocate(info.root).then(() => {
|
||||
reload();
|
||||
notifySvnWorkingCopiesChanged();
|
||||
})
|
||||
}
|
||||
>
|
||||
<T>Relocate…</T>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={commonStyles.linkButton}
|
||||
onClick={() => openSvnSwitchUrlDialog(info.root, info.url)}
|
||||
>
|
||||
<T>Switch to URL…</T>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={commonStyles.linkButton}
|
||||
onClick={() =>
|
||||
openSvnCompareWithBranchDialog(
|
||||
resolveSvnRepo(info.root) ?? info.root,
|
||||
info.isSwitched ? info.root : null,
|
||||
)
|
||||
}
|
||||
>
|
||||
<T>Compare with Branch…</T>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={commonStyles.linkButton}
|
||||
onClick={() => openSvnConfigureBranchesDialog(resolveSvnRepo(info.root) ?? info.root)}
|
||||
>
|
||||
<T>Configure Branches…</T>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
// Working Copies Information: `svnWorkingCopies.tsx`.
|
||||
export { SvnWorkingCopiesPanel } from "./svnWorkingCopies";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Configure Branches Dialog
|
||||
|
||||
@@ -0,0 +1,230 @@
|
||||
/* The Subversion tabs of the version control tool window, laid out as IntelliJ's panels. */
|
||||
.empty {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex: 1 1 0;
|
||||
padding: var(--space-4);
|
||||
color: var(--fg-secondary);
|
||||
}
|
||||
/* A panel with IntelliJ's vertical toolbar at its left. */
|
||||
.withSideToolbar {
|
||||
display: flex;
|
||||
flex: 1 1 0;
|
||||
min-height: 0;
|
||||
min-width: 0;
|
||||
}
|
||||
.sideToolbar {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: var(--space-0-5);
|
||||
padding: var(--space-1);
|
||||
border-right: 1px solid var(--border);
|
||||
}
|
||||
.copies {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-4);
|
||||
flex: 1 1 0;
|
||||
min-width: 0;
|
||||
overflow: auto;
|
||||
padding: var(--space-3) var(--space-4);
|
||||
}
|
||||
/* WorkingCopyInfoPanel: label, value and link columns. */
|
||||
.copy {
|
||||
display: grid;
|
||||
grid-template-columns: max-content minmax(0, max-content) max-content;
|
||||
align-items: baseline;
|
||||
gap: var(--space-1) var(--space-3);
|
||||
}
|
||||
.copyPath {
|
||||
grid-column: 1 / -1;
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: var(--space-2);
|
||||
font-weight: 600;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.revision {
|
||||
font-weight: 400;
|
||||
color: var(--fg-secondary);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
.label {
|
||||
color: var(--fg-secondary);
|
||||
}
|
||||
.value {
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.copyError {
|
||||
min-width: 0;
|
||||
color: var(--danger);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.italicRow {
|
||||
grid-column: 1 / -1;
|
||||
font-style: italic;
|
||||
}
|
||||
.links {
|
||||
grid-column: 1 / -1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: var(--space-1);
|
||||
}
|
||||
.boldLink {
|
||||
border: 0;
|
||||
padding: 0;
|
||||
background: none;
|
||||
color: var(--link);
|
||||
font: inherit;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
}
|
||||
.boldLink:hover {
|
||||
color: var(--link-hover);
|
||||
text-decoration: underline;
|
||||
}
|
||||
.boldLink:focus-visible {
|
||||
outline: 2px solid var(--focus-ring);
|
||||
outline-offset: 1px;
|
||||
}
|
||||
/* Incoming (CommittedChangesTreeBrowser): revisions at the left, their files at the right. */
|
||||
.incoming {
|
||||
flex: 1 1 0;
|
||||
min-height: 0;
|
||||
}
|
||||
.column {
|
||||
display: flex;
|
||||
flex: 1 1 0;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
min-height: 0;
|
||||
min-width: 0;
|
||||
}
|
||||
.topToolbar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--space-0-5);
|
||||
padding: var(--space-1) var(--space-2);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.toolbarSeparator {
|
||||
width: 1px;
|
||||
height: 16px;
|
||||
margin: 0 var(--space-1);
|
||||
background: var(--border-strong);
|
||||
}
|
||||
.toolbarSelect {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
margin-inline: var(--space-1);
|
||||
color: var(--fg-secondary);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
.revisionsArea {
|
||||
display: flex;
|
||||
flex: 1 1 0;
|
||||
min-height: 0;
|
||||
}
|
||||
.userFilter {
|
||||
flex: 0 0 160px;
|
||||
overflow: auto;
|
||||
padding: var(--space-1);
|
||||
border-right: 1px solid var(--border);
|
||||
}
|
||||
.userRow,
|
||||
.changeRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
padding: 2px var(--space-2);
|
||||
border-radius: var(--radius-small);
|
||||
cursor: default;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.userRow:hover,
|
||||
.changeRow:hover {
|
||||
background: var(--bg-hover);
|
||||
}
|
||||
.userRow[data-selected],
|
||||
.changeRow[data-selected] {
|
||||
background: var(--bg-list-selected);
|
||||
}
|
||||
.revisionTree {
|
||||
flex: 1 1 0;
|
||||
min-width: 0;
|
||||
}
|
||||
.groupRow {
|
||||
font-weight: 600;
|
||||
}
|
||||
.revisionRow {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: var(--space-2);
|
||||
min-width: 0;
|
||||
}
|
||||
.revisionNumber,
|
||||
.revisionDate,
|
||||
.noComment {
|
||||
color: var(--fg-secondary);
|
||||
}
|
||||
.revisionMessage {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
min-width: 0;
|
||||
}
|
||||
.revisionAuthor {
|
||||
font-weight: 600;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.revisionDate {
|
||||
margin-left: calc(-1 * var(--space-2));
|
||||
white-space: nowrap;
|
||||
}
|
||||
.details {
|
||||
max-height: 40%;
|
||||
overflow: auto;
|
||||
padding: var(--space-2);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
.detailsTitle {
|
||||
color: var(--fg-secondary);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
.detailsMessage {
|
||||
margin: var(--space-1) 0 var(--space-2);
|
||||
white-space: pre-wrap;
|
||||
font: inherit;
|
||||
}
|
||||
.changeList {
|
||||
flex: 1 1 0;
|
||||
overflow: auto;
|
||||
padding: var(--space-1);
|
||||
}
|
||||
.changePath {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.added {
|
||||
color: var(--vcs-added);
|
||||
font-family: var(--font-mono);
|
||||
}
|
||||
.deleted {
|
||||
color: var(--vcs-deleted);
|
||||
font-family: var(--font-mono);
|
||||
}
|
||||
.modified {
|
||||
color: var(--vcs-modified);
|
||||
font-family: var(--font-mono);
|
||||
}
|
||||
.treeStatus {
|
||||
padding: var(--space-1) var(--space-2);
|
||||
border-top: 1px solid var(--border);
|
||||
color: var(--fg-secondary);
|
||||
}
|
||||
@@ -0,0 +1,434 @@
|
||||
/**
|
||||
* Update Info of a Subversion update, as IntelliJ's `UpdateInfoTree`: the files svn changed,
|
||||
* grouped as IntelliJ's `UpdatedFiles` groups them (Updated from server › Updated / Created /
|
||||
* Deleted / Restored, Skipped, Merged with conflicts…), under "Update Project (N items)". The
|
||||
* toolbar at the left groups by folder or by changelist, expands, collapses, shows the diff
|
||||
* (the file before and after the update) and closes the tab.
|
||||
*/
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { create } from "zustand";
|
||||
import type { SvnIncomingRevision } from "@/bindings";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { call, commands, nextRequestId } from "@/platform/ipc";
|
||||
import { fileIconName, IconButton, showContextMenu, T, Tree, type TreeHandle } from "@/ui";
|
||||
import { editorService, notifications } from "@/workbench/contributions";
|
||||
import { openVcsDiff, withChain, type DiffData } from "./diffInput";
|
||||
import { selectGitTab } from "./logStore";
|
||||
import { errorMessage } from "./ops";
|
||||
import commonStyles from "./common.module.css";
|
||||
import styles from "./svnToolWindow.module.css";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Groups (IntelliJ's UpdatedFiles, and svn4idea's UpdateEventHandler)
|
||||
|
||||
export type UpdateGroupId =
|
||||
| "updated"
|
||||
| "created"
|
||||
| "deleted"
|
||||
| "restored"
|
||||
| "skipped"
|
||||
| "conflicts"
|
||||
| "treeConflicts"
|
||||
| "propertyConflicts"
|
||||
| "merged"
|
||||
| "notInRepository"
|
||||
| "replaced";
|
||||
|
||||
/** The group of a file svn printed with `action` (its status columns, `restored`, `skipped`). */
|
||||
export function updateGroupOf(action: string): UpdateGroupId | null {
|
||||
if (action === "restored") return "restored";
|
||||
if (action === "skipped") return "skipped";
|
||||
const [text = " ", props = " ", , tree = " "] = action;
|
||||
if (tree === "C") return "treeConflicts";
|
||||
if (text === "C" || (text === "A" && props === "C")) return "conflicts";
|
||||
if (text === "A") return "created";
|
||||
if (text === "D") return "deleted";
|
||||
if (props === "C") return "propertyConflicts";
|
||||
if (text === "U" || props === "U") return "updated";
|
||||
if (text === "G" || props === "G") return "merged";
|
||||
// IntelliJ files svn's `R` of an update under Not in repository, and shows no `E`.
|
||||
if (text === "R") return "notInRepository";
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* IntelliJ's group names (`update.group.name.*`) with their size, in its order; the first four are
|
||||
* under "Updated from server". Whole templates, so each name gets its own translation.
|
||||
*/
|
||||
const GROUP_LABELS: Record<UpdateGroupId, (count: string) => string> = {
|
||||
updated: (count) => tx`Updated (${count})`,
|
||||
created: (count) => tx`Created (${count})`,
|
||||
deleted: (count) => tx`Deleted (${count})`,
|
||||
restored: (count) => tx`Restored (${count})`,
|
||||
skipped: (count) => tx`Skipped (${count})`,
|
||||
conflicts: (count) => tx`Merged with conflicts (${count})`,
|
||||
treeConflicts: (count) => tx`Merged with tree conflicts (${count})`,
|
||||
propertyConflicts: (count) => tx`Merged with property conflicts (${count})`,
|
||||
merged: (count) => tx`Merged (${count})`,
|
||||
notInRepository: (count) => tx`Not in repository (${count})`,
|
||||
replaced: (count) => tx`Replaced (${count})`,
|
||||
};
|
||||
const FROM_SERVER: UpdateGroupId[] = ["updated", "created", "deleted", "restored"];
|
||||
const TOP_GROUPS: UpdateGroupId[] = [
|
||||
"skipped",
|
||||
"conflicts",
|
||||
"treeConflicts",
|
||||
"propertyConflicts",
|
||||
"merged",
|
||||
"notInRepository",
|
||||
"replaced",
|
||||
];
|
||||
|
||||
export interface UpdatedFile {
|
||||
path: string;
|
||||
action: string;
|
||||
/** The working copy it belongs to. */
|
||||
root: string;
|
||||
}
|
||||
|
||||
const rootLabel = (count: string) => tx`Update Project (${count})`;
|
||||
const fromServerLabel = (count: string) => tx`Updated from server (${count})`;
|
||||
|
||||
/** "3 items", as IntelliJ's `update.tree.node.size.statistics`. */
|
||||
export function itemCount(n: number): string {
|
||||
return n === 0 ? tx("no items") : n === 1 ? tx("1 item") : tx`${n} items`;
|
||||
}
|
||||
|
||||
export interface UpdateNode {
|
||||
key: string;
|
||||
label: string;
|
||||
file?: UpdatedFile;
|
||||
/** A folder (Group by Packages): its path. */
|
||||
folder?: string;
|
||||
revision?: SvnIncomingRevision;
|
||||
children?: UpdateNode[];
|
||||
}
|
||||
|
||||
const byPath = (a: UpdatedFile, b: UpdatedFile) => a.path.toLowerCase().localeCompare(b.path.toLowerCase());
|
||||
const dirOf = (path: string) => path.slice(0, Math.max(0, path.replace(/\\/g, "/").lastIndexOf("/")));
|
||||
const nameOf = (path: string) => path.replace(/\\/g, "/").split("/").pop() ?? path;
|
||||
|
||||
function fileNodes(files: readonly UpdatedFile[], byFolder: boolean, scope: string): UpdateNode[] {
|
||||
const sorted = [...files].sort(byPath);
|
||||
const leaf = (f: UpdatedFile): UpdateNode => ({
|
||||
key: `${scope}:file:${f.path}`,
|
||||
label: byFolder ? nameOf(f.path) : f.path,
|
||||
file: f,
|
||||
});
|
||||
if (!byFolder) return sorted.map(leaf);
|
||||
const folders = new Map<string, UpdateNode>();
|
||||
for (const f of sorted) {
|
||||
const dir = dirOf(f.path);
|
||||
let folder = folders.get(dir);
|
||||
if (!folder) {
|
||||
folder = { key: `${scope}:dir:${dir}`, label: dir, folder: dir, children: [] };
|
||||
folders.set(dir, folder);
|
||||
}
|
||||
folder.children!.push(leaf(f));
|
||||
}
|
||||
return [...folders.values()].sort((a, b) => a.label.toLowerCase().localeCompare(b.label.toLowerCase()));
|
||||
}
|
||||
|
||||
/**
|
||||
* The tree of an update's files: "Update Project (N items)", then IntelliJ's groups in its order,
|
||||
* empty ones left out. A file added where one was deleted is Replaced, as svn4idea files it.
|
||||
*/
|
||||
export function updateTree(files: readonly UpdatedFile[], byFolder = false): UpdateNode {
|
||||
const groups = new Map<UpdateGroupId, UpdatedFile[]>();
|
||||
for (const f of files) {
|
||||
const id = updateGroupOf(f.action);
|
||||
if (id) groups.set(id, [...(groups.get(id) ?? []), f]);
|
||||
}
|
||||
const deleted = new Set((groups.get("deleted") ?? []).map((f) => f.path));
|
||||
const created = groups.get("created") ?? [];
|
||||
const replaced = created.filter((f) => deleted.has(f.path));
|
||||
if (replaced.length) {
|
||||
groups.set(
|
||||
"created",
|
||||
created.filter((f) => !deleted.has(f.path)),
|
||||
);
|
||||
groups.set(
|
||||
"deleted",
|
||||
(groups.get("deleted") ?? []).filter((f) => !replaced.some((r) => r.path === f.path)),
|
||||
);
|
||||
groups.set("replaced", replaced);
|
||||
}
|
||||
const group = (id: UpdateGroupId): UpdateNode | null => {
|
||||
const own = groups.get(id) ?? [];
|
||||
return own.length
|
||||
? { key: `group:${id}`, label: GROUP_LABELS[id](itemCount(own.length)), children: fileNodes(own, byFolder, id) }
|
||||
: null;
|
||||
};
|
||||
const fromServer = FROM_SERVER.map(group).filter((g): g is UpdateNode => !!g);
|
||||
const serverCount = FROM_SERVER.reduce((n, id) => n + (groups.get(id)?.length ?? 0), 0);
|
||||
const children = [
|
||||
...(fromServer.length
|
||||
? [{ key: "group:fromServer", label: fromServerLabel(itemCount(serverCount)), children: fromServer }]
|
||||
: []),
|
||||
...TOP_GROUPS.map(group).filter((g): g is UpdateNode => !!g),
|
||||
];
|
||||
const total = [...groups.values()].reduce((n, g) => n + g.length, 0);
|
||||
return { key: "root", label: rootLabel(itemCount(total)), children };
|
||||
}
|
||||
|
||||
/** Group by Changelist: each revision of the update with the files it changed, newest first. */
|
||||
export function changelistTree(files: readonly UpdatedFile[], revisions: readonly SvnIncomingRevision[]): UpdateNode {
|
||||
const byLocal = new Map(files.map((f) => [f.path, f]));
|
||||
const children = revisions
|
||||
.map((r): UpdateNode => {
|
||||
const own = r.paths.flatMap((p) => {
|
||||
const f = p.local ? byLocal.get(p.local) : undefined;
|
||||
return f ? [f] : [];
|
||||
});
|
||||
const message = r.message.trim().split(/\r?\n/)[0] ?? "";
|
||||
return {
|
||||
key: `rev:${r.root}:${r.revision}`,
|
||||
label: `#${r.revision} ${message}`,
|
||||
revision: r,
|
||||
children: fileNodes(own, false, `rev${r.revision}`),
|
||||
};
|
||||
})
|
||||
.filter((n) => n.children!.length);
|
||||
return { key: "root", label: rootLabel(itemCount(files.length)), children };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tabs
|
||||
|
||||
export interface SvnUpdate {
|
||||
id: string;
|
||||
/** When it ran: the tab says "Update Info: <time>". */
|
||||
time: string;
|
||||
files: UpdatedFile[];
|
||||
/** Per working copy, its revision before and after the update. */
|
||||
ranges: Record<string, { from: string | null; to: string | null }>;
|
||||
}
|
||||
|
||||
export const useSvnUpdates = create<{ updates: SvnUpdate[] }>(() => ({ updates: [] }));
|
||||
let updateSeq = 0;
|
||||
|
||||
/** Keeps an update's files as an Update Info tab (not selected, as IntelliJ adds it). */
|
||||
export function addSvnUpdate(
|
||||
reports: readonly {
|
||||
root: string;
|
||||
files: { path: string; action: string }[];
|
||||
from: string | null;
|
||||
to: string | null;
|
||||
}[],
|
||||
): string | null {
|
||||
const files = reports.flatMap((r) => r.files.map((f) => ({ ...f, root: r.root })));
|
||||
if (!files.length) return null;
|
||||
const id = `svnUpdate:${++updateSeq}`;
|
||||
const time = new Date().toLocaleString([], { dateStyle: "short", timeStyle: "short" });
|
||||
const ranges = Object.fromEntries(reports.map((r) => [r.root, { from: r.from, to: r.to }]));
|
||||
useSvnUpdates.setState((s) => ({ updates: [...s.updates, { id, time, files, ranges }] }));
|
||||
return id;
|
||||
}
|
||||
|
||||
export function closeSvnUpdate(id: string) {
|
||||
useSvnUpdates.setState((s) => ({ updates: s.updates.filter((u) => u.id !== id) }));
|
||||
}
|
||||
|
||||
export const isSvnUpdateTab = (id: string) => id.startsWith("svnUpdate:");
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// The tab's view
|
||||
|
||||
/** The diff of `file` between before and after the update, as IntelliJ's labels name them. */
|
||||
export function updatedFileDiff(file: UpdatedFile, range: { from: string | null; to: string | null }): DiffData | null {
|
||||
const group = updateGroupOf(file.action);
|
||||
if (!range.from || !range.to || group === "skipped" || group === "restored") return null;
|
||||
const absent = (label: string) => ({ type: "text" as const, text: "", label, absent: true });
|
||||
return {
|
||||
path: file.path,
|
||||
left:
|
||||
group === "created" ? absent(tx("Before update")) : { type: "rev", rev: range.from, label: tx("Before update") },
|
||||
right: group === "deleted" ? absent(tx("After update")) : { type: "rev", rev: range.to, label: tx("After update") },
|
||||
};
|
||||
}
|
||||
|
||||
function filesOf(node: UpdateNode): UpdatedFile[] {
|
||||
return node.file ? [node.file] : (node.children ?? []).flatMap(filesOf);
|
||||
}
|
||||
|
||||
export function SvnUpdateInfo({ id }: { id: string }) {
|
||||
const update = useSvnUpdates((s) => s.updates.find((u) => u.id === id));
|
||||
const [byFolder, setByFolder] = useState(false);
|
||||
const [byChangelist, setByChangelist] = useState(false);
|
||||
const [revisions, setRevisions] = useState<SvnIncomingRevision[] | null>(null);
|
||||
const [revisionsError, setRevisionsError] = useState<string | null>(null);
|
||||
const [expanded, setExpanded] = useState<ReadonlySet<string> | null>(null);
|
||||
const [selected, setSelected] = useState<ReadonlySet<string>>(() => new Set());
|
||||
const tree = useRef<TreeHandle>(null);
|
||||
|
||||
// Group by Changelist reads the revisions of the update once ("Loading changelists…").
|
||||
useEffect(() => {
|
||||
if (!byChangelist || revisions || !update) return;
|
||||
let alive = true;
|
||||
const ranges = Object.entries(update.ranges).filter(([, r]) => r.from && r.to && Number(r.from) < Number(r.to));
|
||||
void Promise.all(
|
||||
ranges.map(([root, r]) =>
|
||||
call(commands.svnRevisionsBetween(nextRequestId(), root, Number(r.from) + 1, Number(r.to))),
|
||||
),
|
||||
)
|
||||
.then((lists) => alive && setRevisions(lists.flat().sort((a, b) => b.revision - a.revision)))
|
||||
.catch((e) => alive && setRevisionsError(errorMessage(e)));
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, [byChangelist, revisions, update]);
|
||||
|
||||
const root = useMemo(() => {
|
||||
if (!update) return null;
|
||||
return byChangelist && revisions ? changelistTree(update.files, revisions) : updateTree(update.files, byFolder);
|
||||
}, [update, byChangelist, revisions, byFolder]);
|
||||
const allKeys = useMemo(() => {
|
||||
const keys: string[] = [];
|
||||
const walk = (n: UpdateNode) => {
|
||||
if (n.children) keys.push(n.key);
|
||||
n.children?.forEach(walk);
|
||||
};
|
||||
if (root) walk(root);
|
||||
return keys;
|
||||
}, [root]);
|
||||
// The root open, and a single group under it, as IntelliJ's `expandRootChildren`.
|
||||
const initial = useMemo(
|
||||
() => new Set(root ? [root.key, ...(root.children?.length === 1 ? [root.children[0]!.key] : [])] : []),
|
||||
[root],
|
||||
);
|
||||
const open = expanded ?? initial;
|
||||
if (!update || !root) return null;
|
||||
|
||||
const files = filesOf(root);
|
||||
const nodeByKey = new Map<string, UpdateNode>();
|
||||
const index = (n: UpdateNode) => {
|
||||
nodeByKey.set(n.key, n);
|
||||
n.children?.forEach(index);
|
||||
};
|
||||
index(root);
|
||||
const selectedFiles = [...selected].flatMap((k) => {
|
||||
const n = nodeByKey.get(k);
|
||||
return n ? filesOf(n) : [];
|
||||
});
|
||||
|
||||
const showDiff = (at?: UpdatedFile) => {
|
||||
const target = at ?? selectedFiles[0];
|
||||
if (!target) return;
|
||||
const diffs = files.flatMap((f) => {
|
||||
const range = update.ranges[f.root];
|
||||
const d = range ? updatedFileDiff(f, range) : null;
|
||||
return d ? [{ f, d }] : [];
|
||||
});
|
||||
const i = diffs.findIndex((x) => x.f === target);
|
||||
if (i < 0) return;
|
||||
void openVcsDiff(
|
||||
withChain(
|
||||
diffs.map((x) => x.d),
|
||||
i,
|
||||
),
|
||||
{ preview: true },
|
||||
);
|
||||
};
|
||||
const jumpToSource = async (file: UpdatedFile) => {
|
||||
const exists = await call(commands.fsProbe(file.path)).then(
|
||||
() => true,
|
||||
() => false,
|
||||
);
|
||||
if (exists) void editorService().openFile(file.path, { focus: true });
|
||||
else notifications().notify({ group: "vcs", level: "warning", title: tx`${file.path} no longer exists` });
|
||||
};
|
||||
const menu = (e: { clientX: number; clientY: number }) => {
|
||||
const file = selectedFiles[0];
|
||||
showContextMenu({ x: e.clientX, y: e.clientY }, [
|
||||
{ label: "Jump to Source", icon: "edit", disabled: !file, run: () => file && void jumpToSource(file) },
|
||||
{
|
||||
label: "Delete",
|
||||
icon: "trash",
|
||||
disabled: !selectedFiles.length,
|
||||
run: () =>
|
||||
void executeAction(
|
||||
"project.delete",
|
||||
selectedFiles.map((f) => f.path),
|
||||
),
|
||||
},
|
||||
{ label: "Show Diff", icon: "diff", disabled: !file, run: () => showDiff() },
|
||||
]);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={styles.withSideToolbar}>
|
||||
<div className={styles.sideToolbar} role="toolbar" aria-orientation="vertical" aria-label={tx("Update Info")}>
|
||||
<IconButton
|
||||
icon="folder"
|
||||
title="Group by Packages"
|
||||
size="small"
|
||||
pressed={byFolder}
|
||||
disabled={byChangelist}
|
||||
onClick={() => setByFolder((v) => !v)}
|
||||
/>
|
||||
<IconButton
|
||||
icon="changelist"
|
||||
title="Group by Changelist"
|
||||
size="small"
|
||||
pressed={byChangelist}
|
||||
onClick={() => setByChangelist((v) => !v)}
|
||||
/>
|
||||
<IconButton icon="filter" title="Scope Filter" size="small" disabled pressed={false} onClick={() => {}} />
|
||||
<IconButton icon="expand-all" title="Expand All" size="small" onClick={() => setExpanded(new Set(allKeys))} />
|
||||
<IconButton icon="collapse-all" title="Collapse All" size="small" onClick={() => setExpanded(new Set())} />
|
||||
<IconButton
|
||||
icon="diff"
|
||||
title="Show Diff"
|
||||
size="small"
|
||||
disabled={!selectedFiles.length}
|
||||
onClick={() => showDiff()}
|
||||
/>
|
||||
<IconButton
|
||||
icon="close"
|
||||
title="Close"
|
||||
size="small"
|
||||
onClick={() => {
|
||||
closeSvnUpdate(id);
|
||||
selectGitTab("log");
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.column}>
|
||||
<Tree<UpdateNode>
|
||||
handleRef={tree}
|
||||
className={styles.revisionTree}
|
||||
aria-label={tx("Update Info")}
|
||||
roots={[root]}
|
||||
getKey={(n) => n.key}
|
||||
getLabel={(n) => n.label}
|
||||
getChildren={(n) => n.children}
|
||||
isExpandable={(n) => !!n.children}
|
||||
getIcon={(n, isOpen) =>
|
||||
n.file
|
||||
? fileIconName(nameOf(n.file.path), n.file.path)
|
||||
: n.folder !== undefined
|
||||
? isOpen
|
||||
? "folder-open"
|
||||
: "folder"
|
||||
: undefined
|
||||
}
|
||||
expanded={open}
|
||||
onExpandedChange={(next) => setExpanded(next)}
|
||||
selected={selected}
|
||||
onSelectionChange={(next) => setSelected(next)}
|
||||
multiSelect
|
||||
speedSearch
|
||||
onActivate={(n) => n.file && void jumpToSource(n.file)}
|
||||
onContextMenu={(_n, _s, e) => menu(e)}
|
||||
/>
|
||||
{byChangelist && !revisions && !revisionsError && (
|
||||
<div className={styles.treeStatus}>
|
||||
<T>Loading changelists…</T>
|
||||
</div>
|
||||
)}
|
||||
{revisionsError && <div className={commonStyles.error}>{revisionsError}</div>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
/**
|
||||
* Subversion Working Copies Information, as IntelliJ's `CopiesPanel` / `WorkingCopyInfoPanel`:
|
||||
* a Refresh toolbar at the left; per working copy, sorted by path, its path in bold, then URL,
|
||||
* Format (with Change), Depth (with Fix), External / Switched and Working copy root, and the
|
||||
* links Cleanup, Configure Branches and Merge From…, one per row. OpenIDEA's own links follow.
|
||||
*/
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { Channel } from "@tauri-apps/api/core";
|
||||
import type { SvnWorkingCopyInfo } from "@/bindings";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { call, commands, nextRequestId } from "@/platform/ipc";
|
||||
import { Dialog, IconButton, Radio, Spinner, T } from "@/ui";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import { confirmDialog, openDialog } from "./dialogs";
|
||||
import { selectGitTab, setLogFilters } from "./logStore";
|
||||
import { errorMessage, runOp } from "./ops";
|
||||
import { notifySvnWorkingCopiesChanged, useSvnPanelRefresh, useVcs } from "./store";
|
||||
import { svnCleanup, svnRelocate } from "./svn";
|
||||
import { openSvnMergeDialog } from "./svnMerge";
|
||||
import { openSvnCompareWithBranchDialog, openSvnConfigureBranchesDialog, openSvnSwitchUrlDialog } from "./svnPanels";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import commonStyles from "./common.module.css";
|
||||
import styles from "./svnToolWindow.module.css";
|
||||
|
||||
/** `a` is an older format than `b` (`1.8` < `1.15`). */
|
||||
export function olderFormat(a: string, b: string): boolean {
|
||||
const [am = 0, an = 0] = a.split(".").map(Number);
|
||||
const [bm = 0, bn = 0] = b.split(".").map(Number);
|
||||
return am < bm || (am === bm && an < bn);
|
||||
}
|
||||
|
||||
/** svn's working copy format numbers, as IntelliJ's `WorkingCopyFormat` names them (and 1.15's). */
|
||||
const FORMAT_VERSIONS: Record<string, string> = {
|
||||
"4": "1.3",
|
||||
"8": "1.4",
|
||||
"9": "1.5",
|
||||
"10": "1.6",
|
||||
"29": "1.7",
|
||||
"31": "1.8",
|
||||
"32": "1.15",
|
||||
};
|
||||
|
||||
/** The Format row's value: the release a copy's format is named after (`31` → `1.8`), or null. */
|
||||
export function formatVersion(format: string | null): string | null {
|
||||
if (!format) return null;
|
||||
return format.includes(".") ? format : (FORMAT_VERSIONS[format] ?? null);
|
||||
}
|
||||
|
||||
/** Change: the formats the configured svn writes that are newer than the copy's. */
|
||||
export function newerFormats(info: Pick<SvnWorkingCopyInfo, "format" | "formats">): string[] {
|
||||
const current = formatVersion(info.format);
|
||||
return current ? info.formats.filter((f) => olderFormat(current, f)) : [];
|
||||
}
|
||||
|
||||
/** IntelliJ's sort of working copies: by path, as strings. */
|
||||
export function sortedCopies(infos: readonly SvnWorkingCopyInfo[]): SvnWorkingCopyInfo[] {
|
||||
return [...infos].sort((a, b) => (a.root < b.root ? -1 : a.root > b.root ? 1 : 0));
|
||||
}
|
||||
|
||||
function decodedUrl(url: string): string {
|
||||
try {
|
||||
return decodeURI(url);
|
||||
} catch {
|
||||
return url;
|
||||
}
|
||||
}
|
||||
|
||||
const DETECTION_ERRORS = "svn.workingCopies.detectionErrors";
|
||||
|
||||
/**
|
||||
* IntelliJ's "Svn Roots Detection Errors" balloon: shown while a working copy cannot be read,
|
||||
* its Fix it shows this tab; gone once the copies read again.
|
||||
*/
|
||||
function reportDetectionErrors(failed: boolean) {
|
||||
const service = notifications();
|
||||
if (!failed) {
|
||||
service.expire?.(DETECTION_ERRORS);
|
||||
return;
|
||||
}
|
||||
service.notify({
|
||||
group: "vcs",
|
||||
key: DETECTION_ERRORS,
|
||||
level: "error",
|
||||
title: tx("Errors found while detecting Subversion working copies."),
|
||||
sticky: true,
|
||||
actions: [
|
||||
{
|
||||
label: tx("Fix it"),
|
||||
run: () => {
|
||||
service.expire?.(DETECTION_ERRORS);
|
||||
void executeAction("svn.showWorkingCopies");
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
export function SvnWorkingCopiesPanel() {
|
||||
const roots = useVcs((s) => s.roots);
|
||||
const kinds = useVcs((s) => s.kinds);
|
||||
const heads = useVcs((s) => s.heads);
|
||||
const wcInfoVersion = useSvnPanelRefresh((s) => s.wcInfoVersion);
|
||||
const svnRoots = useMemo(() => roots.filter((r) => kinds[r] === "subversion"), [roots, kinds]);
|
||||
const headSignature = useMemo(
|
||||
() => svnRoots.map((r) => `${r}=${heads[r]?.head ?? ""}@${heads[r]?.headCommit ?? ""}`).join("\0"),
|
||||
[svnRoots, heads],
|
||||
);
|
||||
const [tick, setTick] = useState(0);
|
||||
const [state, setState] = useState<{ key: string; infos: SvnWorkingCopyInfo[]; error: string | null }>({
|
||||
key: "",
|
||||
infos: [],
|
||||
error: null,
|
||||
});
|
||||
const fetchKey = svnRoots.length ? `${svnRoots.join("\0")}::${headSignature}::${tick}::${wcInfoVersion}` : "";
|
||||
const loading = !!fetchKey && state.key !== fetchKey;
|
||||
const infos = useMemo(() => (state.key === fetchKey ? sortedCopies(state.infos) : []), [state, fetchKey]);
|
||||
const error = state.key === fetchKey ? state.error : null;
|
||||
|
||||
useEffect(() => {
|
||||
if (!fetchKey) return;
|
||||
let alive = true;
|
||||
void call(commands.svnWorkingCopyInfo(null))
|
||||
.then((res) => {
|
||||
if (!alive) return;
|
||||
setState({ key: fetchKey, infos: res, error: null });
|
||||
reportDetectionErrors(res.some((info) => !!info.error));
|
||||
})
|
||||
.catch((e) => {
|
||||
if (alive) setState({ key: fetchKey, infos: [], error: errorMessage(e) });
|
||||
});
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, [fetchKey]);
|
||||
|
||||
const reload = useCallback(() => setTick((t) => t + 1), []);
|
||||
|
||||
if (!svnRoots.length) {
|
||||
return (
|
||||
<div className={styles.empty}>
|
||||
<T>No Subversion working copies detected in the project</T>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={styles.withSideToolbar}>
|
||||
<div className={styles.sideToolbar} role="toolbar" aria-orientation="vertical" aria-label={tx("Working Copies")}>
|
||||
<IconButton icon="refresh" title="Refresh" size="small" disabled={loading} onClick={reload} />
|
||||
</div>
|
||||
<div className={styles.copies}>
|
||||
{error && <div className={commonStyles.error}>{error}</div>}
|
||||
{loading && !infos.length ? (
|
||||
<div className={styles.empty}>
|
||||
<Spinner />
|
||||
</div>
|
||||
) : (
|
||||
infos.map((info) => <WorkingCopyInfoView key={info.root} info={info} onChanged={reload} />)
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function WorkingCopyInfoView({ info, onChanged }: { info: SvnWorkingCopyInfo; onChanged: () => void }) {
|
||||
const failed = !!info.error;
|
||||
const formats = newerFormats(info);
|
||||
const version = formatVersion(info.format);
|
||||
const changed = () => {
|
||||
onChanged();
|
||||
notifySvnWorkingCopiesChanged();
|
||||
};
|
||||
const link = (label: string, run: () => void, bold = false) => (
|
||||
<button type="button" className={bold ? styles.boldLink : commonStyles.linkButton} onClick={run}>
|
||||
<T>{label}</T>
|
||||
</button>
|
||||
);
|
||||
return (
|
||||
<section className={styles.copy} aria-label={info.root}>
|
||||
<div className={styles.copyPath}>
|
||||
{info.root}
|
||||
{info.revision !== null && <span className={styles.revision}>r{info.revision}</span>}
|
||||
</div>
|
||||
<span className={styles.label}>
|
||||
<T>URL:</T>
|
||||
</span>
|
||||
{failed ? (
|
||||
<span className={styles.copyError} role="alert">
|
||||
{info.error}
|
||||
</span>
|
||||
) : (
|
||||
<span className={styles.value} title={info.url}>
|
||||
{decodedUrl(info.url)}
|
||||
</span>
|
||||
)}
|
||||
<span />
|
||||
<span className={styles.label}>
|
||||
<T>Format:</T>
|
||||
</span>
|
||||
<span className={styles.value}>{version ?? tx("unknown")}</span>
|
||||
<span>{!failed && formats.length > 0 && link("Change", () => changeFormat(info, changed))}</span>
|
||||
<span className={styles.label}>
|
||||
<T>Depth:</T>
|
||||
</span>
|
||||
<span className={styles.value}>{info.depth || tx("unknown")}</span>
|
||||
<span>
|
||||
{!failed && info.depth && info.depth !== "infinity" && link("Fix", () => void fixDepth(info, changed))}
|
||||
</span>
|
||||
{(info.isExternal || info.isSwitched) && (
|
||||
<span className={styles.italicRow}>
|
||||
<T>{info.isExternal ? "External" : "Switched"}</T>
|
||||
</span>
|
||||
)}
|
||||
{info.isWcRoot && (
|
||||
<span className={styles.italicRow}>
|
||||
<T>Working copy root</T>
|
||||
</span>
|
||||
)}
|
||||
{!failed && (
|
||||
<div className={styles.links}>
|
||||
{(!version || !olderFormat(version, "1.7")) && link("Cleanup", () => void svnCleanup(info.root))}
|
||||
{link("Configure Branches", () => openSvnConfigureBranchesDialog(info.root))}
|
||||
{link("Merge From…", () => openSvnMergeDialog(info.root), true)}
|
||||
{link("Show Log", () => {
|
||||
setLogFilters({ repositories: [info.root] });
|
||||
selectGitTab("log");
|
||||
})}
|
||||
{link("Update Project…", () => void executeAction("vcs.update", { repo: info.root }))}
|
||||
{link("Relocate…", () => void svnRelocate(info.root).then(changed))}
|
||||
{link("Switch to URL…", () => openSvnSwitchUrlDialog(info.root, info.url))}
|
||||
{link("Compare with Branch…", () =>
|
||||
openSvnCompareWithBranchDialog(info.root, info.isSwitched ? info.root : null),
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
/** Depth › Fix: IntelliJ's confirmation, then the copy at infinity depth and HEAD. */
|
||||
async function fixDepth(info: SvnWorkingCopyInfo, done: () => void) {
|
||||
const ok = await confirmDialog({
|
||||
title: "Set Working Copy Infinity Depth",
|
||||
message: tx`You are going to checkout into '${info.root}' with 'infinity' depth.\nThis will update your working copy to HEAD revision as well.`,
|
||||
okLabel: "OK",
|
||||
danger: true,
|
||||
});
|
||||
if (!ok) return;
|
||||
await runOp(tx("Set Working Copy Infinity Depth"), () =>
|
||||
call(
|
||||
commands.svnUpdateOptions(
|
||||
info.root,
|
||||
nextRequestId(),
|
||||
[info.root],
|
||||
{ revision: "HEAD", depth: "infinity", setDepth: true },
|
||||
new Channel<string>(),
|
||||
),
|
||||
),
|
||||
);
|
||||
done();
|
||||
}
|
||||
|
||||
/** Format › Change: IntelliJ's Convert Working Copy Format dialog, then `svn upgrade`. */
|
||||
function changeFormat(info: SvnWorkingCopyInfo, done: () => void) {
|
||||
openDialog((close) => <ChangeFormatDialog info={info} onClose={close} onDone={done} />);
|
||||
}
|
||||
|
||||
function ChangeFormatDialog({
|
||||
info,
|
||||
onClose,
|
||||
onDone,
|
||||
}: {
|
||||
info: SvnWorkingCopyInfo;
|
||||
onClose: () => void;
|
||||
onDone: () => void;
|
||||
}) {
|
||||
const current = formatVersion(info.format);
|
||||
const choices = useMemo(() => [...new Set([current ?? "", ...info.formats])].filter(Boolean), [current, info]);
|
||||
const [chosen, setChosen] = useState(current ?? choices[0] ?? "");
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
title="Convert Working Copy Format"
|
||||
onClose={onClose}
|
||||
width={440}
|
||||
buttons={[
|
||||
{
|
||||
label: "OK",
|
||||
role: "default",
|
||||
disabled: !chosen || chosen === current,
|
||||
onClick: () => {
|
||||
onClose();
|
||||
void runOp(tx("Convert Working Copy Format"), () =>
|
||||
call(commands.svnUpgrade(nextRequestId(), info.root, chosen)),
|
||||
).then(onDone);
|
||||
},
|
||||
},
|
||||
{ label: "Cancel", role: "cancel" },
|
||||
]}
|
||||
>
|
||||
<div className={commonStyles.form} role="radiogroup" aria-label={tx("Format")}>
|
||||
<span>{tx`Change working copy '${info.root}' format to:`}</span>
|
||||
{choices.map((format) => (
|
||||
<Radio
|
||||
key={format}
|
||||
name="svn-format"
|
||||
checked={chosen === format}
|
||||
onChange={() => setChosen(format)}
|
||||
label={tx`${format} format`}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -151,7 +151,8 @@ export function gateByVcsKind(actions: Action[]): Action[] {
|
||||
/**
|
||||
* How a root's version control system shows itself. A Subversion root has its own icon (a
|
||||
* central repository with two working copies) wherever the system is shown: the branch
|
||||
* widget, the tool window stripe, repository lists, Directory Mappings; Git keeps its icons.
|
||||
* widget, repository lists, Directory Mappings; Git keeps its icons. The tool window stripe
|
||||
* has the version control icon for every system, as IntelliJ's.
|
||||
*/
|
||||
export function vcsIcon(kind: VcsKind): "subversion" | null {
|
||||
return kind === "subversion" ? "subversion" : null;
|
||||
@@ -169,7 +170,7 @@ 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";
|
||||
/** The tool window's stripe icon: the version control one for every system, as IntelliJ's. */
|
||||
export function vcsToolWindowIcon(_kind: VcsKind): string {
|
||||
return "toolwindow-git";
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* The version control tool window (Log, Console…). Its title and stripe icon name the
|
||||
* selected root's system: "Git" with the VCS icon, or "SVN" with Subversion's icon. In a
|
||||
* project with both, they follow the selected root, as the actions do.
|
||||
* The version control tool window (Log, Console…). Its title names the selected root's
|
||||
* system, "Git" or "SVN", under the version control icon. In a project with both, it
|
||||
* follows the selected root, as the actions do.
|
||||
*/
|
||||
import { lazyComponent } from "@/ui";
|
||||
import { registerToolWindow } from "@/workbench/contributions";
|
||||
|
||||
@@ -5712,14 +5712,6 @@
|
||||
"Incoming": "Incoming",
|
||||
"trunk ({trunkUrl})": "trunk ({trunkUrl})",
|
||||
"No Subversion working copies detected in the project": "No Subversion working copies detected in the project",
|
||||
"Working copy": "Working copy",
|
||||
"Checking remote changes…": "Checking remote changes…",
|
||||
"{length} incoming change(s)": "{length} incoming change(s)",
|
||||
"No incoming changes": "No incoming changes",
|
||||
"Local edits": "Local edits",
|
||||
"Locked by {lockedBy}": "Locked by {lockedBy}",
|
||||
"Format {format}": "Format {format}",
|
||||
"Depth: {depth}": "Depth: {depth}",
|
||||
"Switched": "Switched",
|
||||
"Saved Subversion branch configuration for {repo}": "Saved Subversion branch configuration for {repo}",
|
||||
"Configure Subversion Branches ({repo})": "Configure Subversion Branches ({repo})",
|
||||
@@ -5858,5 +5850,56 @@
|
||||
"{imageCount} images": "{imageCount} images",
|
||||
"{title} actions": "{title} actions",
|
||||
"{n}/{count} files": "{n}/{count} files",
|
||||
"… {count} lines not shown …": "… {count} lines not shown …"
|
||||
"… {count} lines not shown …": "… {count} lines not shown …",
|
||||
"1 File Updated": "1 File Updated",
|
||||
"{files} Files Updated": "{files} Files Updated",
|
||||
"1 item": "1 item",
|
||||
"no items": "no items",
|
||||
"<no author>": "<no author>",
|
||||
"<no comment>": "<no comment>",
|
||||
"Before update": "Before update",
|
||||
"After update": "After update",
|
||||
"Change working copy '{root}' format to:": "Change working copy '{root}' format to:",
|
||||
"Convert Working Copy Format": "Convert Working Copy Format",
|
||||
"Update Project ({count})": "Update Project ({count})",
|
||||
"Updated from server ({count})": "Updated from server ({count})",
|
||||
"Updated ({count})": "Updated ({count})",
|
||||
"Created ({count})": "Created ({count})",
|
||||
"Deleted ({count})": "Deleted ({count})",
|
||||
"Restored ({count})": "Restored ({count})",
|
||||
"Skipped ({count})": "Skipped ({count})",
|
||||
"Merged ({count})": "Merged ({count})",
|
||||
"Merged with conflicts ({count})": "Merged with conflicts ({count})",
|
||||
"Merged with property conflicts ({count})": "Merged with property conflicts ({count})",
|
||||
"Merged with tree conflicts ({count})": "Merged with tree conflicts ({count})",
|
||||
"Not in repository ({count})": "Not in repository ({count})",
|
||||
"Replaced ({count})": "Replaced ({count})",
|
||||
"Errors found while detecting Subversion working copies.": "Errors found while detecting Subversion working copies.",
|
||||
"Fix it": "Fix it",
|
||||
"External": "External",
|
||||
"Working copy root": "Working copy root",
|
||||
"Change": "Change",
|
||||
"Configure Branches": "Configure Branches",
|
||||
"unknown": "unknown",
|
||||
"{format} format": "{format} format",
|
||||
"Set Working Copy Infinity Depth": "Set Working Copy Infinity Depth",
|
||||
"You are going to checkout into '{root}' with 'infinity' depth.\nThis will update your working copy to HEAD revision as well.": "You are going to checkout into '{root}' with 'infinity' depth.\nThis will update your working copy to HEAD revision as well.",
|
||||
"Working Copies": "Working Copies",
|
||||
"Show Working Copies": "Show Working Copies",
|
||||
"Filter by": "Filter by",
|
||||
"Group by": "Group by",
|
||||
"Group by Changelist": "Group by Changelist",
|
||||
"Group by Packages": "Group by Packages",
|
||||
"Scope Filter": "Scope Filter",
|
||||
"Loading changelists…": "Loading changelists…",
|
||||
"Update Info": "Update Info",
|
||||
"{path} no longer exists": "{path} no longer exists",
|
||||
"Incoming revisions": "Incoming revisions",
|
||||
"Revision {revision}": "Revision {revision}",
|
||||
"Last Week": "Last Week",
|
||||
"There are no incoming changes": "There are no incoming changes",
|
||||
"Subversion console": "Subversion console",
|
||||
"Version control console": "Version control console",
|
||||
"Subversion commands run by the IDE appear here.": "Subversion commands run by the IDE appear here.",
|
||||
"Version control commands run by the IDE appear here.": "Version control commands run by the IDE appear here."
|
||||
}
|
||||
@@ -5794,7 +5794,6 @@
|
||||
"Label '{value}' added to Local History": "已将标签 '{value}' 添加到本地历史记录",
|
||||
"{doneTitle} successful": "{doneTitle}成功",
|
||||
"{file} updated in {commit}": "已在 {commit}中更新 {file}",
|
||||
"{file} updated": "已更新 {file}",
|
||||
"Shelved {length} file": "已搁置 {length} 个文件",
|
||||
"Shelved {length} files": "已搁置 {length} 个文件",
|
||||
"{what}: {length} file with conflicts": "{what}:{length} 个文件存在冲突",
|
||||
@@ -12612,14 +12611,6 @@
|
||||
"Incoming": "传入",
|
||||
"trunk ({trunkUrl})": "主干({trunkUrl})",
|
||||
"No Subversion working copies detected in the project": "项目中未检测到 Subversion 工作副本",
|
||||
"Working copy": "工作副本",
|
||||
"Checking remote changes…": "正在检查远程更改…",
|
||||
"{length} incoming change(s)": "{length} 项传入更改",
|
||||
"No incoming changes": "没有传入更改",
|
||||
"Local edits": "本地修改",
|
||||
"Locked by {lockedBy}": "已被 {lockedBy} 锁定",
|
||||
"Format {format}": "格式 {format}",
|
||||
"Depth: {depth}": "深度:{depth}",
|
||||
"Switched": "已切换",
|
||||
"Saved Subversion branch configuration for {repo}": "已保存 {repo} 的 Subversion 分支配置",
|
||||
"Configure Subversion Branches ({repo})": "配置 Subversion 分支({repo})",
|
||||
@@ -12748,5 +12739,56 @@
|
||||
"{imageCount} images": "{imageCount} 张图片",
|
||||
"{title} actions": "{title} 操作",
|
||||
"{n}/{count} files": "{n}/{count} 个文件",
|
||||
"… {count} lines not shown …": "… {count} 行未显示 …"
|
||||
"… {count} lines not shown …": "… {count} 行未显示 …",
|
||||
"1 File Updated": "1 个文件已更新",
|
||||
"{files} Files Updated": "{files} 个文件已更新",
|
||||
"1 item": "1 项",
|
||||
"no items": "无项目",
|
||||
"<no author>": "<无作者>",
|
||||
"<no comment>": "<无注释>",
|
||||
"Before update": "更新前",
|
||||
"After update": "更新后",
|
||||
"Change working copy '{root}' format to:": "将工作副本“{root}”的格式更改为:",
|
||||
"Convert Working Copy Format": "转换工作副本格式",
|
||||
"Update Project ({count})": "更新项目 ({count})",
|
||||
"Updated from server ({count})": "已从服务器更新 ({count})",
|
||||
"Updated ({count})": "已更新 ({count})",
|
||||
"Created ({count})": "已创建 ({count})",
|
||||
"Deleted ({count})": "已删除 ({count})",
|
||||
"Restored ({count})": "已还原 ({count})",
|
||||
"Skipped ({count})": "已跳过 ({count})",
|
||||
"Merged ({count})": "已合并 ({count})",
|
||||
"Merged with conflicts ({count})": "已合并,但存在冲突 ({count})",
|
||||
"Merged with property conflicts ({count})": "已合并,但存在属性冲突 ({count})",
|
||||
"Merged with tree conflicts ({count})": "已合并,但存在树冲突 ({count})",
|
||||
"Not in repository ({count})": "不在仓库中 ({count})",
|
||||
"Replaced ({count})": "已替换 ({count})",
|
||||
"Errors found while detecting Subversion working copies.": "检测 Subversion 工作副本时发现错误。",
|
||||
"Fix it": "修复",
|
||||
"External": "外部",
|
||||
"Working copy root": "工作副本根",
|
||||
"Change": "更改",
|
||||
"Configure Branches": "配置分支",
|
||||
"unknown": "未知",
|
||||
"{format} format": "{format} 格式",
|
||||
"Set Working Copy Infinity Depth": "设置工作副本无限深度",
|
||||
"You are going to checkout into '{root}' with 'infinity' depth.\nThis will update your working copy to HEAD revision as well.": "您将以“infinity”深度检出到“{root}”。\n这也会将您的工作副本更新到 HEAD 修订。",
|
||||
"Working Copies": "工作副本",
|
||||
"Show Working Copies": "显示工作副本",
|
||||
"Filter by": "筛选依据",
|
||||
"Group by": "分组依据",
|
||||
"Group by Changelist": "按更改列表分组",
|
||||
"Group by Packages": "按软件包分组",
|
||||
"Scope Filter": "范围筛选器",
|
||||
"Loading changelists…": "正在加载更改列表…",
|
||||
"Update Info": "更新信息",
|
||||
"{path} no longer exists": "{path} 已不存在",
|
||||
"Incoming revisions": "传入的修订",
|
||||
"Revision {revision}": "修订 {revision}",
|
||||
"Last Week": "上周",
|
||||
"There are no incoming changes": "没有传入的更改",
|
||||
"Subversion console": "Subversion 控制台",
|
||||
"Version control console": "版本控制控制台",
|
||||
"Subversion commands run by the IDE appear here.": "IDE 运行的 Subversion 命令会显示在这里。",
|
||||
"Version control commands run by the IDE appear here.": "IDE 运行的版本控制命令会显示在这里。"
|
||||
}
|
||||
Reference in new issue
Заблокувати користувача