feat(plugins): Project view panes and Git branch menu commands (API 1.21) (#7980)

Plugins can add panes to the Project tool window and commands to the Git branch menus:

- `[[contributes.projectViewPanes]]` with the `project-view-provider` export regroups a directory's native children under virtual folders. Existing nodes keep their icons, Git status and actions. `project-view.refresh` / `select-in` and `projectViewContext` menu items work against these panes. Requires `project.read`.
- `git.branches.popup` and `git.branch.context` menus. `invocation.git-action-context` gives the command the repository roots and the full ref of the clicked branch. Requires `vcs.read`.
- `views.open-revision-comparison` opens the IDE's comparison of two full commit IDs as a Compare tool window tab, the same one Compare Versions opens. The repository must be a mapped Git root of the invoking trusted project. Requires `vcs.read`.

All of this is part of plugin API 1.21. A project-view test fixture and host tests cover the provider, the branch menu context and the comparison call. The plugin components and bindings are rebuilt.

Co-authored-by: kirito1105 <[email protected]>
Цей коміт міститься в:
astesiaтаkirito1105 authored and GitHub committed 2026-12-05 12:24:10 +08:00
1 джерело 455e32ab76
коміт 05a88394fb
207 files changed
+4278 -307

No files matched your search

+77
Переглянути файл
@@ -161,6 +161,10 @@ pub trait PluginWorkspace: Send + Sync {
fn repositories(&self, _root: &Path) -> Result<ide_vcs::Repos, HostError> {
Err(HostError::NotFound("no open project repositories".into()))
}
/// The invoking window's project, mapped Git roots, and project-close token.
fn git_comparison_project(&self, _window: &str) -> Result<(PathBuf, ide_vcs::Repos, CancellationToken), HostError> {
Err(HostError::NotFound("no open project repositories".into()))
}
/// The git executable of the project at `root` (see [`crate::Project::git_executable`]).
fn git_executable(&self, _root: &Path) -> Option<PathBuf> {
None
@@ -1364,6 +1368,14 @@ impl PluginApi {
self.pkg.id()
}
fn project_view_pane(&self, view: &str, allow_project: bool) -> Result<(), HostError> {
let panes = self.shared.ui.items(super::ui_points::PROJECT_VIEW_PANES, Some(self.id()));
if (allow_project && view == "project" && !panes.is_empty()) || panes.iter().any(|pane| pane.key == view) {
return Ok(());
}
Err(HostError::NotFound(format!("the plugin declares no project view pane {view:?}")))
}
/// The storage directory, after moving a `storage.json` written by an
/// older version into it.
fn storage(&self) -> Result<PathBuf, HostError> {
@@ -2278,6 +2290,15 @@ impl HostApi for PluginApi {
self.shared.sink.emit(Some(client), PluginEvent::OpenDiff { plugin_id: self.id().into(), diff, file_name });
Ok(())
}
fn open_revision_comparison(
&self,
invocation: &ide_plugin::Invocation,
comparison: ide_plugin::RevisionComparison,
cancel: &CancellationToken,
timeout: Duration,
) -> Result<(), HostError> {
self.open_git_comparison(invocation, comparison, cancel, timeout)
}
fn reply_content_tab(
&self,
client: &str,
@@ -3963,6 +3984,50 @@ impl HostApi for PluginApi {
.emit(None, PluginEvent::ViewChanged { plugin_id: self.id().to_owned(), view: view.to_owned() });
}
fn refresh_project_view(
&self,
client: Option<&str>,
root: Option<&Path>,
view: &str,
directory: Option<String>,
) -> Result<(), HostError> {
self.project_view_pane(view, false)?;
let directory = directory
.map(|directory| {
let root = root.ok_or_else(|| HostError::NotFound("the invoking project is closed".into()))?;
let path = super::project_view::resolve_path(root, &directory)?;
if !path.is_dir() {
return Err(HostError::Invalid("project view refresh requires a directory".into()));
}
Ok(path.into())
})
.transpose()?;
self.shared.sink.emit(
client,
PluginEvent::ProjectViewRefresh { plugin_id: self.id().into(), view_id: view.into(), directory },
);
Ok(())
}
fn select_in_project_view(&self, client: &str, view: &str, path: String, focus: bool) -> Result<(), HostError> {
self.project_view_pane(view, true)?;
let root = self
.shared
.project_of(client)
.ok_or_else(|| HostError::NotFound("the window's project is closed".into()))?;
let path = super::project_view::resolve_path(&root, &path)?;
self.shared.sink.emit(
Some(client),
PluginEvent::ProjectViewSelect {
plugin_id: self.id().into(),
view_id: view.into(),
path: path.into(),
focus,
},
);
Ok(())
}
fn post_view_message(&self, view: &str, message: String) -> Result<(), HostError> {
let declared = super::ui_points::WEB_POINTS
.iter()
@@ -4561,6 +4626,18 @@ impl PluginWorkspace for HostWorkspace {
.repos())
}
fn git_comparison_project(&self, window: &str) -> Result<(PathBuf, ide_vcs::Repos, CancellationToken), HostError> {
let host = self.0.upgrade().ok_or(HostError::Cancelled)?;
let project = host.project(window).map_err(|error| HostError::NotFound(error.message))?;
if !project.is_trusted() {
return Err(HostError::Denied("the project is not trusted".into()));
}
if !project.git_enabled() {
return Err(HostError::NotFound("Git integration is disabled".into()));
}
Ok((project.root.clone(), project.repos(), project.closed.clone()))
}
fn git_executable(&self, root: &Path) -> Option<PathBuf> {
HostWorkspace::project_covering(self, root)?.git_executable()
}
+68 -1
Переглянути файл
@@ -9,7 +9,7 @@ use crate::Host;
use crate::ops::blocking;
use ide_command::command;
use ide_core::{DocId, IdeError, IdeResult, Range, RequestId};
use ide_plugin::{Invocation, ProviderDocument, SyntaxDecorationBatch, SyntaxNodeSnapshot};
use ide_plugin::{GitActionContext, Invocation, ProviderDocument, SyntaxDecorationBatch, SyntaxNodeSnapshot};
use ide_workspace::settings::SettingsScope;
use std::collections::BTreeMap;
use std::path::PathBuf;
@@ -79,6 +79,7 @@ pub async fn plugin_run_command(
editor: editor.map(PluginEditor::context),
selected_paths: paths.unwrap_or_default(),
global_settings: matches!(settings_scope, Some(SettingsScope::Global)),
git_action: None,
};
let cancel = request.map(|id| host.begin_project_read_request(window, id));
let result = host
@@ -92,6 +93,70 @@ pub async fn plugin_run_command(
result
}
/// Runs a declared Git menu command with the menu's repository and branch snapshot.
#[command(trust = trusted)]
pub async fn plugin_run_git_command(
host: &Host,
plugins: &Arc<PluginHost>,
window: &str,
plugin_id: String,
command_id: String,
context: GitActionContext,
editor: Option<PluginEditor>,
) -> IdeResult<Option<String>> {
let project = host.project(window)?;
let plugins = plugins.clone();
let invocation = Invocation {
client: Some(window.to_owned()),
workspace_root: Some(project.root.clone()),
editor: editor.map(PluginEditor::context),
..Default::default()
};
host.blocking(move || {
if !project.git_enabled() {
return Err(IdeError::not_found("Git integration is disabled"));
}
plugins.run_git_command(&plugin_id, &command_id, invocation, context, &project.repos())
})
.await
}
/// Rearranges native children for one plugin-owned Project pane.
#[allow(clippy::too_many_arguments)]
#[command(trust = trusted)]
pub async fn plugin_project_view_modify(
host: &Host,
plugins: &Arc<PluginHost>,
window: &str,
plugin_id: String,
view_id: String,
parent: ide_plugin::ProjectViewNativeNode,
children: Vec<ide_plugin::ProjectViewNativeNode>,
settings: String,
request: Option<RequestId>,
) -> IdeResult<Option<Vec<ide_plugin::ProjectViewProjectionNode>>> {
let root = host.project(window)?.root.clone();
let invocation = Invocation { workspace_root: Some(root), client: Some(window.to_owned()), ..Default::default() };
let input = Arc::new(super::project_view::ModifyProjectView { view: view_id, parent, children, settings });
let plugins = plugins.clone();
let cancel = request.map(|id| host.begin_project_read_request(window, id)).unwrap_or_default();
let work_cancel = cancel.clone();
let result = tokio::select! {
_ = cancel.cancelled() => Err(IdeError::cancelled()),
result = tokio::time::timeout(super::project_view::CALL_BUDGET, host.blocking(move || {
plugins.modify_project_view(&plugin_id, invocation, input, &work_cancel)
})) => match result {
Ok(result) => result,
Err(_) => Err(IdeError::new(ide_core::error::ErrorKind::TimedOut, "project view provider timed out")),
},
};
cancel.cancel();
if let Some(request) = request {
host.end_request(request);
}
result
}
/// Run Anything entries of the plugin declaring `prefix` for the field's `text` (API 1.18).
#[command(trust = trusted)]
pub async fn plugin_run_anything_suggest(
@@ -534,11 +599,13 @@ ide_command::domain!(
plugin_parse_test_results,
plugin_post_events,
plugin_prepare_debug_run,
plugin_project_view_modify,
plugin_program,
plugin_run_anything_run,
plugin_run_anything_suggest,
plugin_run_command,
plugin_run_configuration_complete,
plugin_run_git_command,
plugin_run_log_tail,
plugin_select_tests,
plugin_set_active_file,
+18 -2
Переглянути файл
@@ -246,13 +246,24 @@ impl PluginApi {
request: WindowRequest,
cancel: &CancellationToken,
timeout: Duration,
) -> Result<Option<String>, HostError> {
self.window_request_until(client, request, cancel, timeout, || false)
}
pub(super) fn window_request_until(
&self,
client: &str,
request: WindowRequest,
cancel: &CancellationToken,
timeout: Duration,
project_closed: impl Fn() -> bool,
) -> Result<Option<String>, HostError> {
let id = self.shared.next_prompt.fetch_add(1, Ordering::Relaxed);
let (tx, rx) = std::sync::mpsc::sync_channel(1);
{
let closed = self.shared.closed_clients.lock();
let blocked = self.shared.prompts_blocked.lock();
if closed.contains(client) || blocked.contains(self.pkg.id()) {
if closed.contains(client) || blocked.contains(self.pkg.id()) || project_closed() {
return Err(HostError::Cancelled);
}
self.shared.prompts.lock().insert(
@@ -266,7 +277,12 @@ impl PluginApi {
);
let deadline = Instant::now() + timeout;
loop {
match rx.recv_timeout(Duration::from_millis(20)) {
let answer = rx.recv_timeout(Duration::from_millis(20));
if project_closed() {
self.shared.prompts.lock().remove(&id);
return Err(HostError::Cancelled);
}
match answer {
Ok(CommandAnswer::Value(value)) => return Ok(value),
Ok(CommandAnswer::NotFound) => return Err(HostError::NotFound("window service unavailable".into())),
Ok(CommandAnswer::Failed(error)) => return Err(HostError::Failed(error)),
+313
Переглянути файл
@@ -0,0 +1,313 @@
//! Git context menu invocations and native revision comparisons for plugins.
use super::api::PluginApi;
use super::ui_points::{GIT_BRANCH_CONTEXT_MENU, GIT_BRANCHES_POPUP_MENU, MENUS};
use super::{PluginHost, WindowRequest};
use ide_core::{CancellationToken, IdeError, IdeResult, ipc_path::to_ipc};
use ide_plugin::{GitActionBranch, GitActionContext, HostError, Invocation, RevisionComparison};
use ide_vcs::{Repo, Repos};
use std::{collections::HashSet, path::Path, time::Duration};
fn repository<'a>(repos: &'a Repos, path: &str) -> Option<&'a Repo> {
let path = Path::new(path);
if !path.is_absolute() {
return None;
}
repos.at_root(path).filter(|repo| !repo.is_stale()).map(AsRef::as_ref)
}
fn valid_branch(branch: &GitActionBranch) -> bool {
let namespace = if branch.remote { "refs/remotes/" } else { "refs/heads/" };
!branch.name.is_empty()
&& branch.full_ref.len() <= 4096
&& branch.full_ref.strip_prefix(namespace) == Some(branch.name.as_str())
&& ide_vcs::is_valid_reference_name(&branch.full_ref)
}
fn validated_context(mut context: GitActionContext, repos: &Repos) -> IdeResult<GitActionContext> {
if context.repositories.is_empty() || context.branch.as_ref().is_some_and(|branch| !valid_branch(branch)) {
return Err(IdeError::invalid("invalid Git menu context"));
}
let mut seen = HashSet::new();
let mut repositories = Vec::with_capacity(context.repositories.len());
for path in &context.repositories {
let repo =
repository(repos, path).ok_or_else(|| IdeError::not_found("Git repository is outside this project"))?;
let root = to_ipc(repo.root());
if seen.insert(root.clone()) {
repositories.push(root);
}
}
context.repositories = repositories;
Ok(context)
}
impl PluginHost {
pub(super) fn run_git_command(
&self,
plugin: &str,
command: &str,
mut invocation: Invocation,
context: GitActionContext,
repos: &Repos,
) -> IdeResult<Option<String>> {
let menu = if context.branch.is_some() { GIT_BRANCH_CONTEXT_MENU } else { GIT_BRANCHES_POPUP_MENU };
let key = format!("{menu}/{command}");
if !self.ui.items(MENUS, Some(plugin)).iter().any(|item| item.key == key) {
return Err(IdeError::not_found("the plugin does not declare this Git menu command"));
}
invocation.git_action = Some(validated_context(context, repos)?);
self.run_command(plugin, command, None, invocation)
}
}
fn validated_comparison(mut comparison: RevisionComparison, repos: &Repos) -> Result<RevisionComparison, HostError> {
for id in [&mut comparison.left, &mut comparison.right] {
if !ide_vcs::is_full_commit_id(id) {
return Err(HostError::Invalid("expected full Git commit object IDs".into()));
}
id.make_ascii_lowercase();
}
for label in [&comparison.left_label, &comparison.right_label].into_iter().flatten() {
super::execution::label(label, 256)?;
}
let repo = repository(repos, &comparison.repository)
.ok_or_else(|| HostError::NotFound("Git repository is outside this project".into()))?;
for id in [&comparison.left, &comparison.right] {
if !repo.contains_commit_id(id).map_err(|error| HostError::Failed(error.message))? {
return Err(HostError::NotFound(format!("commit {id} is not in this repository")));
}
}
comparison.repository = to_ipc(repo.root());
Ok(comparison)
}
impl PluginApi {
pub(super) fn open_git_comparison(
&self,
invocation: &Invocation,
comparison: RevisionComparison,
cancel: &CancellationToken,
timeout: Duration,
) -> Result<(), HostError> {
let workspace = self.shared.workspace().ok_or_else(|| HostError::NotFound("window project".into()))?;
let client = invocation.client.as_deref().ok_or_else(|| HostError::NotFound("invoking window".into()))?;
let (root, repos, closed) = workspace.git_comparison_project(client)?;
// The window has opened another project since the plugin was invoked.
if invocation.workspace_root.as_deref() != Some(&root) {
return Err(HostError::Cancelled);
}
let comparison = validated_comparison(comparison, &repos)?;
let request = WindowRequest::RevisionComparison { comparison, project: to_ipc(&root) };
self.window_request_until(client, request, cancel, timeout, || {
closed.is_cancelled() || workspace.project_of(client).as_deref() != Some(&root)
})
.map(|_| ())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::plugins::{CommandAnswer, HostWorkspace, PluginEvent, PluginWorkspace};
use std::sync::Arc;
fn git(root: &Path, args: &[&str]) -> String {
let output = std::process::Command::new("git").current_dir(root).args(args).output().unwrap();
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
String::from_utf8(output.stdout).unwrap().trim().into()
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn git_comparison_opens_in_the_invoking_window() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path().join("project");
std::fs::create_dir(&root).unwrap();
ide_vcs::init(&root).unwrap();
for subject in ["first", "second"] {
git(
&root,
&[
"-c",
"user.name=Test",
"-c",
"[email protected]",
"-c",
"commit.gpgsign=false",
"commit",
"--allow-empty",
"-qm",
subject,
],
);
}
let left = git(&root, &["rev-parse", "HEAD~1"]);
let right = git(&root, &["rev-parse", "HEAD"]);
let host = Arc::new(crate::Host::new(crate::HostConfig::for_test(temp.path())));
host.trust.decide(&root, true, false).unwrap();
let project = host.open_project("main", &root).unwrap();
project.refresh_repositories();
let (tx, rx) = std::sync::mpsc::channel();
let plugins = PluginHost::new(
temp.path().join("plugins"),
Arc::new(move |client: Option<&str>, event| {
if let PluginEvent::WindowRequest { request_id, request, .. } = event {
tx.send((client.map(str::to_owned), request_id, request)).unwrap();
}
}),
ide_plugin::Limits::default(),
)
.unwrap();
plugins.set_workspace(Some(Arc::new(HostWorkspace(Arc::downgrade(&host)))));
let manifest = ide_extension::Manifest::parse(
"id = \"test\"\nname = \"Test\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.21\"\n",
)
.unwrap();
let api =
PluginApi { pkg: ide_extension::Package::new(manifest, root.clone()), shared: plugins.shared.clone() };
let canonical_root = to_ipc(project.repos().primary().unwrap().root());
let invocation = Invocation {
client: Some("main".into()),
workspace_root: Some(project.root.clone()),
..Default::default()
};
let comparison = RevisionComparison {
repository: to_ipc(&root.join(".")),
left: left.to_ascii_uppercase(),
right: right.clone(),
left_label: Some("Base".into()),
right_label: None,
};
for answer in [CommandAnswer::Value(None), CommandAnswer::Failed("compare tool unavailable".into())] {
std::thread::scope(|scope| {
let request = comparison.clone();
let api = &api;
let invocation = &invocation;
let result = scope.spawn(move || {
api.open_git_comparison(invocation, request, &CancellationToken::new(), Duration::from_secs(10))
});
let (client, id, request) = rx.recv_timeout(Duration::from_secs(2)).unwrap();
assert_eq!(client.as_deref(), Some("main"));
assert_eq!(
request,
WindowRequest::RevisionComparison {
comparison: RevisionComparison {
repository: canonical_root.clone(),
left: left.clone(),
..comparison.clone()
},
project: to_ipc(&project.root),
},
);
assert!(!result.is_finished());
assert!(!plugins.answer_command("other", &id, CommandAnswer::Value(None)));
let expected = match &answer {
CommandAnswer::Failed(error) => Err(HostError::Failed(error.clone())),
_ => Ok(()),
};
assert!(plugins.answer_command("main", &id, answer));
assert_eq!(result.join().unwrap(), expected);
});
}
// The window has switched projects since the plugin was invoked.
let stale_invocation = Invocation { workspace_root: Some(temp.path().join("previous")), ..invocation.clone() };
assert!(matches!(
api.open_git_comparison(&stale_invocation, comparison.clone(), &CancellationToken::new(), Duration::ZERO),
Err(HostError::Cancelled)
));
assert!(rx.try_recv().is_err());
// Closing the project ends a request the window has not answered yet.
std::thread::scope(|scope| {
let (api, invocation, comparison) = (&api, &invocation, &comparison);
let waiting = scope.spawn(move || {
api.open_git_comparison(
invocation,
comparison.clone(),
&CancellationToken::new(),
Duration::from_secs(30),
)
});
let (_, id, _) = rx.recv_timeout(Duration::from_secs(10)).unwrap();
host.close_project("main");
let deadline = std::time::Instant::now() + Duration::from_secs(2);
while !waiting.is_finished() && std::time::Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(5));
}
assert!(waiting.is_finished());
assert_eq!(waiting.join().unwrap(), Err(HostError::Cancelled));
assert!(!plugins.answer_command("main", &id, CommandAnswer::Value(None)));
});
assert!(matches!(
api.open_git_comparison(&invocation, comparison, &CancellationToken::new(), Duration::ZERO),
Err(HostError::NotFound(_))
));
assert!(rx.try_recv().is_err());
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn git_comparison_repositories_follow_the_invoking_window_for_a_shared_member() {
let temp = tempfile::tempdir().unwrap();
let project = temp.path().join("project");
let member = temp.path().join("member");
let host = Arc::new(crate::Host::new(crate::HostConfig::for_test(temp.path())));
for root in [&project, &member] {
std::fs::create_dir(root).unwrap();
ide_vcs::init(root).unwrap();
host.trust.decide(root, true, false).unwrap();
}
host.open_project("group", &project).unwrap();
crate::ops::project::attach_workspace(&host, "group", &member).unwrap();
host.open_project("direct", &member).unwrap();
let workspace = HostWorkspace(Arc::downgrade(&host));
let (_, group, _) = workspace.git_comparison_project("group").unwrap();
let (_, direct, _) = workspace.git_comparison_project("direct").unwrap();
assert!(group.at_root(&project).is_some());
assert!(group.at_root(&member).is_some());
assert!(direct.at_root(&member).is_some());
assert!(direct.at_root(&project).is_none());
host.close_project("direct");
assert!(matches!(workspace.git_comparison_project("direct"), Err(HostError::NotFound(_))));
}
#[test]
fn git_action_context_keeps_the_full_ref_and_known_roots() {
let project = tempfile::tempdir().unwrap();
let outside = tempfile::tempdir().unwrap();
ide_vcs::init(project.path()).unwrap();
ide_vcs::init(outside.path()).unwrap();
let repos = Repos::discover(project.path(), &|_| false).unwrap();
let root = to_ipc(repos.primary().unwrap().root());
let mut context = GitActionContext {
repositories: vec![root.clone(), root.clone()],
branch: Some(GitActionBranch {
name: "origin/release".into(),
full_ref: "refs/remotes/origin/release".into(),
remote: true,
}),
};
let checked = validated_context(context.clone(), &repos).unwrap();
assert_eq!(checked.repositories, [root]);
assert_eq!(checked.branch, context.branch);
context.branch.as_mut().unwrap().full_ref = "refs/heads/origin/release".into();
assert!(validated_context(context, &repos).is_err());
let other = GitActionContext { repositories: vec![to_ipc(outside.path())], branch: None };
assert!(validated_context(other, &repos).is_err());
}
#[test]
fn git_comparisons_reject_refs_and_missing_objects() {
let project = tempfile::tempdir().unwrap();
ide_vcs::init(project.path()).unwrap();
let repos = Repos::discover(project.path(), &|_| false).unwrap();
let mut comparison = RevisionComparison {
repository: to_ipc(repos.primary().unwrap().root()),
left: "HEAD~1".into(),
right: "b".repeat(40),
left_label: None,
right_label: None,
};
assert!(matches!(validated_comparison(comparison.clone(), &repos), Err(HostError::Invalid(_))));
comparison.left = "a".repeat(40);
assert!(matches!(validated_comparison(comparison, &repos), Err(HostError::NotFound(_))));
}
}
+1
Переглянути файл
@@ -199,6 +199,7 @@ pub async fn plugin_navigation_index(
editor: None,
selected_paths: Vec::new(),
global_settings: false,
git_action: None,
},
Some(&cancel),
) {
+3
Переглянути файл
@@ -32,6 +32,7 @@ mod event_wake;
mod execution;
mod external_watch;
mod files_changed;
mod git_actions;
mod hover;
mod http_stream;
mod icon_extensions;
@@ -52,6 +53,7 @@ mod mcp;
pub mod navigation;
mod network_inbox;
mod points;
mod project_view;
mod providers;
pub mod remote;
pub mod remote_host;
@@ -2653,6 +2655,7 @@ impl PluginHost {
selected_paths: Vec::new(),
global_settings: false,
command_chain: Vec::new(),
git_action: None,
};
let kinds: BTreeSet<EventKind> = queue.events.iter().map(WorkbenchEvent::kind).collect();
let filesystem = kinds.contains(&EventKind::FilesChanged);
+61
Переглянути файл
@@ -96,6 +96,7 @@ pub fn register_builtin_points(
registry.register(Arc::new(UiPoint::new(p::STATUS_BAR, ui.clone(), p::status_item)))?;
registry.register(Arc::new(UiPoint::new(p::SETTINGS, ui.clone(), p::settings)))?;
registry.register(Arc::new(UiPoint::new(p::VIEWS, ui.clone(), p::view)))?;
registry.register(Arc::new(UiPoint::new(p::PROJECT_VIEW_PANES, ui.clone(), p::project_view_pane)))?;
registry.register(Arc::new(UiPoint::new(p::CUSTOM_EDITORS, ui.clone(), p::custom_editor)))?;
registry.register(Arc::new(UiPoint::new(p::EDITOR_PANELS, ui.clone(), p::editor_panel)))?;
registry.register(Arc::new(UiPoint::new(p::OVERLAYS, ui.clone(), p::overlay)))?;
@@ -111,3 +112,63 @@ pub fn register_builtin_points(
registry.register(Arc::new(UiPoint::new(ide_extension::LOCALES_POINT, ui.clone(), p::locales)))?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn registers_project_view_panes_as_native_ui_contributions() {
let registry = ExtensionRegistry::new();
let ui = Arc::new(UiStore::default());
register_builtin_points(
&registry,
&ui,
&Arc::default(),
&Arc::default(),
&Arc::default(),
&Arc::default(),
&Arc::default(),
&Arc::default(),
)
.unwrap();
let source = r#"
id = "go-folders"
name = "Go Folder Groups"
version = "0.1.0"
engines.openidea = "^1.21"
wasm = "plugin.wasm"
[capabilities]
required = ["project.read"]
[[contributes.projectViewPanes]]
id = "grouped"
title = "Go Folder Groups"
weight = 10
[[contributes.commands]]
id = "inspect"
title = "Inspect Node"
[[contributes.menus]]
menu = "projectView.context"
command = "inspect"
projectViewContext = true
"#;
let package =
|source: &str| Package::new(ide_extension::Manifest::parse(source).unwrap(), std::env::temp_dir());
registry.commit(registry.prepare(&package(source)).unwrap()).unwrap();
let panes = ui.items("projectViewPanes", Some("go-folders"));
assert_eq!(panes.len(), 1);
assert_eq!(panes[0].key, "grouped");
assert_eq!(panes[0].decl["weight"], 10);
assert_eq!(ui.items("menus", Some("go-folders"))[0].decl["projectViewContext"], true);
for (bad, expected) in [
(source.replace("^1.21", "^1.20"), "1.21"),
(source.replace("wasm = \"plugin.wasm\"", ""), "wasm"),
(source.replace("required = [\"project.read\"]", ""), "project.read"),
(source.replace("projectView.context", "editor.context"), "projectViewContext"),
(format!("{source}\n[[contributes.projectViewPanes]]\nid = 'grouped'\ntitle = 'Duplicate'\n"), "duplicate"),
] {
assert!(registry.prepare(&package(&bad)).err().unwrap().contains(expected));
}
}
}
+209
Переглянути файл
@@ -0,0 +1,209 @@
use super::{PluginHost, ui_points::PROJECT_VIEW_PANES};
use ide_core::{CancellationToken, IdeError, IdeResult};
use ide_extension::Capability;
use ide_plugin::{HostError, Invocation, ProjectViewNativeNode, ProjectViewNodeKind, ProjectViewProjectionNode};
use std::path::{Component, Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
pub(super) const CALL_BUDGET: Duration = Duration::from_secs(2);
const GUEST_BUDGET: Duration = Duration::from_millis(300);
const MAX_CHILDREN: usize = 4096;
const MAX_PATH: usize = 16 * 1024;
const MAX_ID: usize = 16 * 1024;
const MAX_BYTES: usize = 2 * 1024 * 1024;
pub(super) fn resolve_path(root: &Path, path: &str) -> Result<PathBuf, HostError> {
let requested = Path::new(path);
if path.is_empty()
|| path.len() > MAX_PATH
|| path.contains('\0')
|| requested.components().any(|part| matches!(part, Component::ParentDir))
{
return Err(HostError::Invalid("invalid project view path".into()));
}
let native_path = |base: &Path| {
// Validate the real target but keep the alias displayed in the Project tree.
let alias: PathBuf = base.join(requested).components().collect();
ide_plugin::resolve_in_root(base, &ide_core::ipc_path::to_ipc(&alias)).map(|_| alias)
};
native_path(root)
.or_else(|project_error| {
crate::project::workspace_member_roots(root)
.iter()
.find_map(|member| native_path(member).ok())
.ok_or(project_error)
})
.map_err(HostError::Invalid)
}
fn native_bytes(node: &ProjectViewNativeNode) -> usize {
node.id.len() + node.path.len() + node.label.len()
}
fn valid_request(parent: &ProjectViewNativeNode, children: &[ProjectViewNativeNode], settings: &str) -> bool {
let path = Path::new(&parent.path);
let valid = |node: &ProjectViewNativeNode| {
let p = Path::new(&node.path);
!node.id.is_empty()
&& node.id.len() <= MAX_ID
&& node.path.len() <= MAX_PATH
&& !node.path.contains('\0')
&& p.is_absolute()
&& p.components().all(|c| !matches!(c, Component::ParentDir))
};
parent.kind == ProjectViewNodeKind::Directory
&& valid(parent)
&& children.len() <= MAX_CHILDREN
&& settings.len() <= MAX_PATH
&& serde_json::from_str::<serde_json::Value>(settings).is_ok_and(|v| v.is_object())
&& children.iter().all(|n| valid(n) && Path::new(&n.path) != path && Path::new(&n.path).starts_with(path))
&& native_bytes(parent) + children.iter().map(native_bytes).sum::<usize>() <= MAX_BYTES
}
fn valid_result(nodes: &[ProjectViewProjectionNode]) -> bool {
let mut bytes = 0;
for node in nodes {
let (id, parent) = match node {
ProjectViewProjectionNode::ExistingNode { id, parent } => (id, parent),
ProjectViewProjectionNode::VirtualFolder { id, parent, label, icon } => {
if id.contains('\0')
|| label.trim().is_empty()
|| label.len() > 1024
|| label.chars().any(char::is_control)
|| icon.as_ref().is_some_and(|icon| icon.len() > 128)
{
return false;
}
bytes += label.len() + icon.as_ref().map_or(0, String::len);
(id, parent)
}
};
let parent_bytes = parent.as_ref().map_or(0, String::len);
if id.is_empty() || id.len() > MAX_ID || parent_bytes > MAX_ID {
return false;
}
bytes += id.len() + parent_bytes;
if bytes > MAX_BYTES {
return false;
}
}
true
}
pub(super) struct ModifyProjectView {
pub view: String,
pub parent: ProjectViewNativeNode,
pub children: Vec<ProjectViewNativeNode>,
pub settings: String,
}
impl PluginHost {
pub(super) fn modify_project_view(
self: &Arc<Self>,
plugin: &str,
invocation: Invocation,
input: Arc<ModifyProjectView>,
cancel: &CancellationToken,
) -> IdeResult<Option<Vec<ProjectViewProjectionNode>>> {
let loaded = self.get(plugin)?;
let Some(root) = invocation.workspace_root.as_deref() else { return Ok(None) };
let eligible = || {
let allowed = {
let meta = loaded.meta.lock();
meta.status.is_live() && meta.pending.is_empty() && meta.granted.contains(&Capability::ProjectRead)
};
allowed
&& loaded.dev_root.as_deref().is_none_or(|p| p == root)
&& self.shared.workspace().is_some_and(|w| w.trusted(root))
&& self.ui.items(PROJECT_VIEW_PANES, Some(plugin)).iter().any(|pane| pane.key == input.view)
&& self.plugins.read().get(plugin).is_some_and(|p| Arc::ptr_eq(p, &loaded))
};
if !valid_request(&input.parent, &input.children, &input.settings) || !eligible() {
return Ok(None);
}
if !resolve_path(root, &input.parent.path).is_ok_and(|p| p.is_dir()) {
return Ok(None);
}
let request = input.clone();
let expected_plugin = loaded.clone();
let dispatch_host = self.clone();
let plugin_id = plugin.to_owned();
let result = self.code_call_with_budget(
plugin,
invocation.clone(),
"grouping project view children",
Some(cancel),
Some(CALL_BUDGET),
move |runtime, context| {
let current =
dispatch_host.plugins.read().get(&plugin_id).is_some_and(|p| Arc::ptr_eq(p, &expected_plugin));
if !current {
return Ok(None);
}
runtime.modify_project_view_children(
&request.view,
&request.parent,
&request.children,
&request.settings,
context,
GUEST_BUDGET,
)
},
)?;
if !eligible() || cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
Ok(result.filter(|nodes| valid_result(nodes)))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn providers_only_receive_children_below_the_native_parent() {
let tmp = tempfile::tempdir().unwrap();
let parent = tmp.path().join("src");
let native = |path: PathBuf, kind| ProjectViewNativeNode {
id: ide_core::ipc_path::to_ipc(&path),
path: ide_core::ipc_path::to_ipc(&path),
label: path.file_name().unwrap().to_string_lossy().into_owned(),
kind,
};
let directory = native(parent.clone(), ProjectViewNodeKind::Directory);
let child = native(parent.join("main.go"), ProjectViewNodeKind::File);
assert!(valid_request(&directory, &[child], "{}"));
let sibling = native(tmp.path().join("main.go"), ProjectViewNodeKind::File);
assert!(!valid_request(&directory, &[sibling], "{}"));
let traversal = native(parent.join("../main.go"), ProjectViewNodeKind::File);
assert!(!valid_request(&directory, &[traversal], "{}"));
assert!(!valid_request(&directory, &[], "[]"));
}
#[test]
fn project_view_positions_use_paths_from_the_native_tree() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("src").join("main.go");
std::fs::create_dir(file.parent().unwrap()).unwrap();
std::fs::write(&file, "package main").unwrap();
assert_eq!(resolve_path(tmp.path(), "./src//main.go").unwrap(), file);
assert_eq!(resolve_path(tmp.path(), &ide_core::ipc_path::to_ipc(&file)).unwrap(), file);
}
#[cfg(unix)]
#[test]
fn project_view_paths_keep_native_aliases_within_workspace() {
let tmp = tempfile::tempdir().unwrap();
let target = tmp.path().join("original.go");
let alias = tmp.path().join("alias.go");
std::fs::write(&target, "package main").unwrap();
std::os::unix::fs::symlink(&target, &alias).unwrap();
assert_eq!(resolve_path(tmp.path(), "alias.go").unwrap(), alias);
let outside = tempfile::NamedTempFile::new().unwrap();
std::os::unix::fs::symlink(outside.path(), tmp.path().join("external.go")).unwrap();
assert!(resolve_path(tmp.path(), "external.go").is_err());
}
}
+2
Переглянути файл
@@ -159,6 +159,8 @@ pub fn forwarded(event: &PluginEvent) -> bool {
| PluginEvent::SubscriptionsChanged
| PluginEvent::WebsocketReady { .. }
| PluginEvent::ViewChanged { .. }
| PluginEvent::ProjectViewRefresh { .. }
| PluginEvent::ProjectViewSelect { .. }
| PluginEvent::ViewMessage { .. }
| PluginEvent::OpenTerminal { .. }
| PluginEvent::OpenLocation { .. }
+6
Переглянути файл
@@ -350,6 +350,10 @@ pub enum PluginEvent {
/// A view (or the custom editors) of a plugin must be rendered again.
#[serde(rename_all = "camelCase")]
ViewChanged { plugin_id: String, view: String },
#[serde(rename_all = "camelCase")]
ProjectViewRefresh { plugin_id: String, view_id: String, directory: Option<ide_core::IpcPath> },
#[serde(rename_all = "camelCase")]
ProjectViewSelect { plugin_id: String, view_id: String, path: ide_core::IpcPath, focus: bool },
/// For the script of a view's `html` body.
#[serde(rename_all = "camelCase")]
ViewMessage { plugin_id: String, view: String, message: String },
@@ -592,6 +596,8 @@ pub enum WindowRequest {
DatabaseConnect { id: String },
/// Open and acknowledge validation by the shared content editor.
ContentTab { tab: ide_plugin::ContentTab },
/// Open the native comparison of two commits in this window's Compare tool window.
RevisionComparison { comparison: ide_plugin::RevisionComparison, project: String },
#[serde(rename_all = "camelCase")]
Run { operation: String, config: Box<ide_run::RunConfig>, debug: bool },
#[serde(rename_all = "camelCase")]
+68 -1
Переглянути файл
@@ -104,6 +104,7 @@ pub const KEYMAPS: &str = "keymaps";
pub const STATUS_BAR: &str = "statusBar";
pub const SETTINGS: &str = "settings";
pub const VIEWS: &str = "views";
pub const PROJECT_VIEW_PANES: &str = "projectViewPanes";
pub const CUSTOM_EDITORS: &str = "customEditors";
pub const EDITOR_PANELS: &str = "editorPanels";
pub const OVERLAYS: &str = "overlays";
@@ -137,7 +138,9 @@ const DATABASE_SCHEMA_MENU: &str = "database.schema.context";
const DATABASE_COLUMN_MENU: &str = "database.column.context";
/// Toolbar of the Run and Debug consoles (API 1.21).
const RUN_CONSOLE_TOOLBAR_MENU: &str = "runConsole.toolbar";
const MENU_IDS: [&str; 18] = [
pub(super) const GIT_BRANCHES_POPUP_MENU: &str = "git.branches.popup";
pub(super) const GIT_BRANCH_CONTEXT_MENU: &str = "git.branch.context";
const MENU_IDS: [&str; 20] = [
"editor.context",
"projectView.context",
"editorTab.context",
@@ -156,6 +159,8 @@ const MENU_IDS: [&str; 18] = [
DATABASE_SCHEMA_MENU,
DATABASE_COLUMN_MENU,
RUN_CONSOLE_TOOLBAR_MENU,
GIT_BRANCHES_POPUP_MENU,
GIT_BRANCH_CONTEXT_MENU,
];
const MAX_TITLE: usize = 256;
const MAX_SETTINGS: usize = 200;
@@ -193,6 +198,39 @@ fn json<T: Serialize>(v: &T) -> Result<Value, String> {
serde_json::to_value(v).map_err(|e| e.to_string())
}
#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
struct ProjectViewPaneDecl {
id: String,
title: String,
#[serde(default)]
weight: i32,
}
pub(super) fn project_view_pane(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
let pane: ProjectViewPaneDecl = decode(PROJECT_VIEW_PANES, decl)?;
pkg.manifest.needs_api("contributes.projectViewPanes", 21)?;
validate_item_id(&pane.id, "project view pane id")?;
if pane.id == "project" {
return Err("contributes.projectViewPanes: `project` is the built-in pane id".into());
}
if pkg
.manifest
.declarations(PROJECT_VIEW_PANES)
.iter()
.filter(|value| value.get("id").and_then(toml::Value::as_str) == Some(&pane.id))
.nth(1)
.is_some()
{
return Err(format!("contributes.projectViewPanes: duplicate pane id {:?}", pane.id));
}
title(PROJECT_VIEW_PANES, &pane.title)?;
if pkg.manifest.wasm.is_none() || !pkg.manifest.declares(&ide_extension::Capability::ProjectRead) {
return Err("contributes.projectViewPanes needs `wasm` and the `project.read` capability".into());
}
Ok(UiDecl::new(pane.id.clone(), pane.title.clone(), json(&pane)?))
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
struct MenuDecl {
@@ -206,6 +244,8 @@ struct MenuDecl {
/// submenu under it.
#[serde(default, skip_serializing_if = "Option::is_none")]
submenu: Option<String>,
#[serde(rename = "projectViewContext", default, skip_serializing_if = "Option::is_none")]
project_view_context: Option<bool>,
}
pub(super) fn menu(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
@@ -213,6 +253,12 @@ pub(super) fn menu(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
if !MENU_IDS.contains(&d.menu.as_str()) {
return Err(format!("contributes.menus: unknown menu {:?} (one of {})", d.menu, MENU_IDS.join(", ")));
}
if d.project_view_context.is_some() {
if d.menu != "projectView.context" {
return Err("contributes.menus: projectViewContext only applies to projectView.context".into());
}
pkg.manifest.needs_api("contributes.menus.projectViewContext", 21)?;
}
declared_command(pkg, MENUS, &d.command)?;
if ["editor.title", "mainToolbar", "problems.context", "searchResults.context"].contains(&d.menu.as_str()) {
pkg.manifest.needs_api("contributes.menus: language workbench menus", 4)?;
@@ -226,6 +272,12 @@ pub(super) fn menu(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
if d.menu == DATABASE_TABLE_MENU {
pkg.manifest.needs_api(&format!("contributes.menus: {DATABASE_TABLE_MENU}"), 20)?;
}
if [GIT_BRANCHES_POPUP_MENU, GIT_BRANCH_CONTEXT_MENU].contains(&d.menu.as_str()) {
pkg.manifest.needs_api(&format!("contributes.menus: {}", d.menu), 21)?;
if d.submenu.is_some() {
return Err(format!("contributes.menus: `submenu` is not supported by {:?}", d.menu));
}
}
if [DATABASE_SOURCE_MENU, DATABASE_SCHEMA_MENU, DATABASE_COLUMN_MENU].contains(&d.menu.as_str()) {
pkg.manifest.needs_api(&format!("contributes.menus: {}", d.menu), 21)?;
}
@@ -1939,6 +1991,21 @@ pub(super) fn locales(pkg: &Package, _decl: toml::Value) -> Result<UiDecl, Strin
#[cfg(test)]
mod tests {
#[test]
fn git_menus_require_api21_and_accept_conditions_on_declared_commands() {
for (api, valid) in [("^1.20", false), ("^1.21", true)] {
let source = format!(
"id='comparison'\nname='Comparison'\nversion='1.0.0'\nengines.openidea='{api}'\n[[contributes.commands]]\nid='compare'\ntitle='Compare'"
);
let pkg = Package::new(ide_extension::Manifest::parse(&source).unwrap(), PathBuf::from("/unused"));
for location in [GIT_BRANCHES_POPUP_MENU, GIT_BRANCH_CONTEXT_MENU] {
let decl = format!("menu='{location}'\ncommand='compare'\nwhen='projectOpen'");
assert_eq!(menu(&pkg, toml::from_str(&decl).unwrap()).is_ok(), valid);
assert!(menu(&pkg, toml::from_str(&format!("{decl}\nsubmenu='Nested'")).unwrap()).is_err());
}
}
}
#[test]
fn database_table_menu_requires_api20_and_a_declared_command() {
use ide_extension::{Manifest, Package};
+1
Переглянути файл
@@ -65,6 +65,7 @@ fn inv() -> Invocation {
editor: None,
selected_paths: Vec::new(),
global_settings: false,
git_action: None,
}
}
+1
Переглянути файл
@@ -244,6 +244,7 @@ fn two_windows_of_same_root_keep_unsaved_snapshots_isolated() {
editor: None,
selected_paths: Vec::new(),
global_settings: false,
git_action: None,
},
)
.unwrap();
+108
Переглянути файл
@@ -0,0 +1,108 @@
//! API 1.21 Project view panes and Git branch menus, through the fixture plugin.
mod common;
use ide_core::ipc_path::to_ipc;
use ide_host::plugins::commands::{plugin_project_view_modify, plugin_run_git_command};
use ide_host::plugins::{Consent, HostWorkspace, PluginHost};
use ide_host::{Host, ops};
use ide_plugin::{
GitActionBranch, GitActionContext, Limits, ProjectViewNativeNode, ProjectViewNodeKind, ProjectViewProjectionNode,
};
use std::path::{Path, PathBuf};
use std::sync::Arc;
fn fixture() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR")).join("../ide-plugin/tests/fixtures/project-view")
}
fn node(path: &Path, kind: ProjectViewNodeKind) -> ProjectViewNativeNode {
ProjectViewNativeNode {
id: to_ipc(path),
path: to_ipc(path),
label: path.file_name().unwrap().to_string_lossy().into_owned(),
kind,
}
}
async fn setup(tmp: &Path) -> (Arc<Host>, Arc<PluginHost>, PathBuf) {
let root = dunce::canonicalize(tmp).unwrap().join("project");
std::fs::create_dir_all(root.join("src")).unwrap();
for file in ["mod_a.go", "mod_b.go", "main.go"] {
std::fs::write(root.join("src").join(file), "package main\n").unwrap();
}
ide_vcs::init(&root).unwrap();
let host = Arc::new(Host::new(common::host_config(tmp)));
host.open_project("main", &root).unwrap();
ops::project::project_trust_set(&host, root.clone(), true, false).await.unwrap();
host.project("main").unwrap().refresh_repositories();
let plugins =
Arc::new(PluginHost::new(tmp.join("plugins"), Arc::new(|_: Option<&str>, _| {}), Limits::default()).unwrap());
plugins.set_workspace(Some(Arc::new(HostWorkspace(Arc::downgrade(&host)))));
plugins.install_from_dir(&fixture(), &Consent::all()).unwrap();
(host, plugins, root)
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_pane_groups_native_children_under_a_virtual_folder() {
let tmp = tempfile::tempdir().unwrap();
let (host, plugins, root) = setup(tmp.path()).await;
let src = root.join("src");
let parent = node(&src, ProjectViewNodeKind::Directory);
let children: Vec<_> =
["mod_a.go", "mod_b.go", "main.go"].map(|file| node(&src.join(file), ProjectViewNodeKind::File)).into();
let modify = |view: &str, settings: &str| {
plugin_project_view_modify(
&host,
&plugins,
"main",
"test.project-view".into(),
view.into(),
parent.clone(),
children.clone(),
settings.into(),
None,
)
};
let nodes = modify("grouped", "{}").await.unwrap().expect("the pane rearranges the children");
assert_eq!(
nodes,
[
ProjectViewProjectionNode::VirtualFolder {
id: "mod".into(),
parent: None,
label: "mod".into(),
icon: None
},
ProjectViewProjectionNode::ExistingNode { id: children[0].id.clone(), parent: Some("mod".into()) },
ProjectViewProjectionNode::ExistingNode { id: children[1].id.clone(), parent: Some("mod".into()) },
]
);
assert_eq!(modify("grouped", r#"{"plain":true}"#).await.unwrap(), None, "the plugin keeps the native list");
assert_eq!(modify("other", "{}").await.unwrap(), None, "a pane the plugin does not declare");
assert_eq!(modify("grouped", "[]").await.unwrap(), None, "settings must be a JSON object");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_git_branch_menu_command_receives_the_repository_and_full_ref() {
let tmp = tempfile::tempdir().unwrap();
let (host, plugins, _root) = setup(tmp.path()).await;
let repo = to_ipc(host.project("main").unwrap().repos().primary().unwrap().root());
let context = |repositories: Vec<String>| GitActionContext {
repositories,
branch: Some(GitActionBranch { name: "main".into(), full_ref: "refs/heads/main".into(), remote: false }),
};
let run = |context: GitActionContext| {
plugin_run_git_command(&host, &plugins, "main", "test.project-view".into(), "branch".into(), context, None)
};
let answer = run(context(vec![repo.clone(), repo.clone()])).await.unwrap();
assert_eq!(answer.as_deref(), Some(format!("{repo}|refs/heads/main").as_str()));
let outside = tempfile::tempdir().unwrap();
ide_vcs::init(outside.path()).unwrap();
assert!(run(context(vec![to_ipc(outside.path())])).await.is_err(), "a repository outside the project");
let mut wrong_ref = context(vec![repo]);
wrong_ref.branch.as_mut().unwrap().full_ref = "refs/remotes/main".into();
assert!(run(wrong_ref).await.is_err(), "the full ref must name the branch");
}
+1
Переглянути файл
@@ -428,6 +428,7 @@ impl Fixture {
editor: None,
selected_paths: Vec::new(),
global_settings: false,
git_action: None,
}
}
+105 -1
Переглянути файл
@@ -22,6 +22,7 @@ use crate::wit_host::completion_resolve_bindings::exports::openidea::plugin::com
use crate::wit_host::hover_actions_bindings::exports::openidea::plugin::hover_actions as wit_hia;
use crate::wit_host::injections_bindings::exports::openidea::plugin::injections as wit_inj;
use crate::wit_host::language_features_bindings::exports::openidea::plugin::language_features as wit_lf;
use crate::wit_host::project_view_bindings::exports::openidea::plugin::project_view_provider as wit_pvp;
use crate::wit_host::rename_bindings::exports::openidea::plugin::rename_provider as wit_rename;
use crate::wit_host::run_anything_bindings::exports::openidea::plugin::run_anything_provider as wit_ra;
use crate::wit_host::run_config_completion_bindings::exports::openidea::plugin::run_configuration_completion as wit_rcc;
@@ -40,7 +41,7 @@ use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::{Duration, Instant};
use wasmtime::component::{Component, HasSelf, Linker, ResourceTable};
use wasmtime::component::{Component, HasSelf, Linker, Resource, ResourceTable};
use wasmtime::{Config, Engine, Store, StoreLimits, StoreLimitsBuilder, UpdateDeadline};
use wasmtime_wasi::p2::pipe::MemoryOutputPipe;
use wasmtime_wasi::{WasiCtx, WasiCtxView, WasiView};
@@ -51,6 +52,7 @@ use crate::wit_host::launch_configurations_bindings::exports::openidea::plugin::
use crate::wit_host::run_configurations_bindings::exports::openidea::plugin::run_configurations as wit_configs;
use crate::wit_host::test_results_bindings::exports::openidea::plugin::test_results as wit_tests;
use bindings::openidea::plugin::events as wit_events;
use bindings::openidea::plugin::project_view_types as wit_pv;
use bindings::openidea::plugin::run as wit_run;
use bindings::openidea::plugin::types as wit_types;
use commit_checks_bindings::exports::openidea::plugin::commit_checker as wit_cc;
@@ -361,6 +363,16 @@ pub trait HostApi: Send + Sync {
) -> Result<(), HostError>;
/// Opens a diff of two texts in the invoking window; a `None` side doesn't exist.
fn open_diff(&self, client: &str, diff: crate::FileDiff, file_name: Option<String>) -> Result<(), HostError>;
/// Opens the native comparison of two commits in the invoking window.
fn open_revision_comparison(
&self,
_invocation: &Invocation,
_comparison: crate::RevisionComparison,
_cancel: &CancellationToken,
_timeout: Duration,
) -> Result<(), HostError> {
Err(HostError::NotFound("revision comparison is unavailable on this host".into()))
}
/// Answers a content action in the invoking window.
fn reply_content_tab(&self, client: &str, request: &str, reply: crate::ContentTabReply) -> Result<(), HostError>;
/// The invoking window's editors.
@@ -713,6 +725,14 @@ pub trait HostApi: Send + Sync {
fn task_end(&self, id: u64);
/// The plugin's view (or custom editors) `view` must be rendered again.
fn refresh_view(&self, view: &str);
fn refresh_project_view(
&self,
client: Option<&str>,
root: Option<&Path>,
view: &str,
directory: Option<String>,
) -> Result<(), HostError>;
fn select_in_project_view(&self, client: &str, view: &str, path: String, focus: bool) -> Result<(), HostError>;
/// A message for the script of the `html` body of `view`.
fn post_view_message(&self, view: &str, message: String) -> Result<(), HostError>;
/// Opens a terminal in `client`'s window running the approved file of
@@ -1141,6 +1161,7 @@ struct Exports {
indexer: Option<wit_index::Guest>,
file_actions: Option<wit_fa::Guest>,
views: Option<wit_view::Guest>,
project_view: Option<wit_pvp::Guest>,
semantic: Option<wit_sem::Guest>,
details: Option<wit_detail::Guest>,
diagnostics: Option<crate::wit_host::diagnostics_bindings::exports::openidea::plugin::diagnostics_provider::Guest>,
@@ -1323,6 +1344,7 @@ impl Runtime {
let syntax_decoration_indices = wit_syn::GuestIndices::new(&pre).ok();
let endpoint_indices = wit_endpoints::GuestIndices::new(&pre).ok();
let search_indices = wit_search::GuestIndices::new(&pre).ok();
let project_view_indices = wit_pvp::GuestIndices::new(&pre).ok();
let hover_actions_indices = wit_hia::GuestIndices::new(&pre).ok();
let completion_list_indices = wit_cl::GuestIndices::new(&pre).ok();
let completion_resolve_indices = wit_cr::GuestIndices::new(&pre).ok();
@@ -1404,6 +1426,7 @@ impl Runtime {
None => None,
};
let search = search_indices.map(|i| i.load(&mut store, &instance)).transpose().map_err(api_hint)?;
let project_view = project_view_indices.map(|i| i.load(&mut store, &instance)).transpose().map_err(api_hint)?;
let hover_actions =
hover_actions_indices.map(|i| i.load(&mut store, &instance)).transpose().map_err(api_hint)?;
let completion_list =
@@ -1427,6 +1450,7 @@ impl Runtime {
syntax,
providers,
views,
project_view,
indexer,
semantic,
details,
@@ -2296,6 +2320,41 @@ impl Runtime {
.collect())
}
/// Project pane providers reuse native model ids and have no interactive host context.
pub fn modify_project_view_children(
&mut self,
view: &str,
parent: &crate::ProjectViewNativeNode,
children: &[crate::ProjectViewNativeNode],
settings: &str,
invocation: Invocation,
timeout: Duration,
) -> Result<Option<Vec<crate::ProjectViewProjectionNode>>, CallError> {
if !self.store.data().granted.iter().any(|grant| grant.covers(&Capability::ProjectRead)) {
return Ok(None);
}
if self.exports.project_view.is_none() {
return Err(CallError::missing_export("project-view-provider"));
}
let parent = project_view_node_to_wit(parent);
let children: Vec<_> = children.iter().map(project_view_node_to_wit).collect();
let result = self.call(invocation, timeout, |exports, store| {
let ctx = store.data_mut().new_invocation()?;
let result = exports.project_view.as_ref().expect("checked").call_modify_children(
&mut *store,
view,
&parent,
&children,
settings,
Resource::new_borrow(ctx.rep()),
);
store.data_mut().drop_invocation(ctx);
result
})?;
let Some(nodes) = result.filter(|nodes| nodes.len() <= MAX_PROVIDER_ITEMS) else { return Ok(None) };
Ok(Some(nodes.into_iter().map(project_view_node_from_wit).collect()))
}
pub fn activate(&mut self) -> Result<(), CallError> {
let data = self.store.data();
let ctx = wit_types::Context {
@@ -2603,6 +2662,29 @@ fn doc_to_wit(d: &ProviderDocument) -> wit_prov::Document {
wit_prov::Document { path: to_ipc(&d.path), language: d.language.clone(), version: d.version, text: d.text.clone() }
}
fn project_view_node_to_wit(node: &crate::ProjectViewNativeNode) -> wit_pv::NativeNode {
wit_pv::NativeNode {
id: node.id.clone(),
path: node.path.clone(),
label: node.label.clone(),
kind: match node.kind {
crate::ProjectViewNodeKind::File => wit_pv::NodeKind::File,
crate::ProjectViewNodeKind::Directory => wit_pv::NodeKind::Directory,
},
}
}
fn project_view_node_from_wit(node: wit_pv::ProjectionNode) -> crate::ProjectViewProjectionNode {
use crate::ProjectViewProjectionNode::{ExistingNode, VirtualFolder};
let wit_pv::ProjectionNode { id, parent, kind } = node;
match kind {
wit_pv::ProjectionKind::ExistingNode => ExistingNode { id, parent },
wit_pv::ProjectionKind::VirtualFolder(folder) => {
VirtualFolder { id, parent, label: folder.label, icon: folder.icon }
}
}
}
/// Resets the budgets for the next call: fuel, deadline, cancellation.
fn arm(store: &mut Store<StoreData>, limits: &Limits, timeout: Duration) -> wasmtime::Result<()> {
store.set_fuel(limits.fuel)?;
@@ -3463,6 +3545,28 @@ impl Runtime {
mod tests {
use super::*;
#[test]
fn the_revision_comparison_import_links() {
let engine = PluginEngine::new().unwrap();
let fixture = r#"(component
(import "openidea:plugin/[email protected]" (instance $types
(type $error (variant (case "denied" string) (case "stale")
(case "not-found" string) (case "invalid" string)
(case "cancelled") (case "failed" string)))
(export "error" (type (eq $error)))))
(alias export $types "error" (type $error))
(import "openidea:plugin/[email protected]" (instance
(export "error" (type $view-error (eq $error)))
(type $comparison (record (field "repository" string)
(field "left" string) (field "right" string)
(field "left-label" (option string)) (field "right-label" (option string))))
(export "revision-comparison" (type $view-comparison (eq $comparison)))
(export "open-revision-comparison" (func (param "comparison" $view-comparison)
(result (result (error $view-error))))))))"#;
let component = engine.compile_bytes(&wat::parse_str(fixture).unwrap()).unwrap();
engine.linker.instantiate_pre(&component).unwrap();
}
/// The second compile of the same component loads the cached one instead of compiling and
/// writing it again (a failed load deletes and rewrites the file).
#[test]
+48
Переглянути файл
@@ -36,6 +36,54 @@ pub struct Invocation {
pub editor: Option<EditorContext>,
/// Files and folders the command was run on.
pub selected_paths: Vec<PathBuf>,
/// Git menu selection captured by the invoking workbench.
pub git_action: Option<GitActionContext>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct GitActionBranch {
pub name: String,
pub full_ref: String,
pub remote: bool,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
pub struct GitActionContext {
pub repositories: Vec<String>,
pub branch: Option<GitActionBranch>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct RevisionComparison {
pub repository: String,
pub left: String,
pub right: String,
pub left_label: Option<String>,
pub right_label: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, specta::Type)]
#[serde(rename_all = "camelCase")]
pub enum ProjectViewNodeKind {
File,
Directory,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, specta::Type)]
pub struct ProjectViewNativeNode {
pub id: String,
pub path: String,
pub label: String,
pub kind: ProjectViewNodeKind,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, specta::Type)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum ProjectViewProjectionNode {
ExistingNode { id: String, parent: Option<String> },
VirtualFolder { id: String, parent: Option<String>, label: String, icon: Option<String> },
}
/// A failed host call, as the plugin sees it (WIT `types.error`).
+83
Переглянути файл
@@ -1496,6 +1496,25 @@ impl invocation::HostInvocation for StoreData {
Ok(self.invocation.selected_paths.iter().take(MAX_FIND as usize).map(|p| to_ipc(p)).collect())
}
fn git_action_context(
&mut self,
_this: Resource<InvocationRes>,
) -> wasmtime::Result<Option<invocation::GitActionContext>> {
if self.require(Capability::VcsRead).is_err()
|| self.host.require_api("invocation.git-action-context", 21).is_err()
{
return Ok(None);
}
Ok(self.invocation.git_action.as_ref().map(|context| invocation::GitActionContext {
repositories: context.repositories.clone(),
branch: context.branch.as_ref().map(|branch| invocation::GitActionBranch {
name: branch.name.clone(),
full_ref: branch.full_ref.clone(),
remote: branch.remote,
}),
}))
}
fn drop(&mut self, rep: Resource<InvocationRes>) -> wasmtime::Result<()> {
// Owned by the host for the duration of the call.
let _ = rep;
@@ -2446,6 +2465,30 @@ impl process::HostChild for StoreData {
}
impl StoreData {
fn request_revision_comparison(&self, comparison: views::RevisionComparison) -> Fallible<()> {
if let Err(e) = self.require_window().and_then(|()| self.require(Capability::VcsRead)) {
return Ok(Err(e));
}
if let Err(e) = self.host.require_api("views.open-revision-comparison", 21) {
return Ok(Err(to_wit(e)));
}
Ok(self
.host
.open_revision_comparison(
&self.invocation,
crate::RevisionComparison {
repository: comparison.repository,
left: comparison.left,
right: comparison.right,
left_label: comparison.left_label,
right_label: comparison.right_label,
},
&self.cancel.token(),
self.remaining(),
)
.map_err(to_wit))
}
fn open_keyed_terminal(
&mut self,
key: String,
@@ -2536,6 +2579,9 @@ impl views::Host for StoreData {
}
Ok(self.host.open_diff(self.invocation.client.as_deref().unwrap(), diff.into(), file_name).map_err(to_wit))
}
fn open_revision_comparison(&mut self, comparison: views::RevisionComparison) -> Fallible<()> {
self.request_revision_comparison(comparison)
}
fn reply_content_tab(&mut self, request_id: String, reply: views::ContentTabReply) -> Fallible<()> {
if let Err(e) = self.require_window() {
return Ok(Err(e));
@@ -2882,6 +2928,43 @@ pub(crate) mod search_bindings {
});
}
pub(crate) mod project_view_bindings {
wasmtime::component::bindgen!({
world: "project-view-exports", path: "../../wit",
with: {
"openidea:plugin/types": super::bindings::openidea::plugin::types,
"openidea:plugin/workspace": super::bindings::openidea::plugin::workspace,
"openidea:plugin/editor": super::bindings::openidea::plugin::editor,
"openidea:plugin/invocation": super::bindings::openidea::plugin::invocation,
"openidea:plugin/project-view-types": super::bindings::openidea::plugin::project_view_types,
},
});
}
impl bindings::openidea::plugin::project_view_types::Host for StoreData {}
impl bindings::openidea::plugin::project_view::Host for StoreData {
fn refresh(&mut self, view_id: String, directory: Option<String>) -> Fallible<()> {
if let Err(error) = self.require(Capability::ProjectRead).and_then(|_| self.require_interactive()) {
return Ok(Err(error));
}
Ok(self
.host
.refresh_project_view(self.client(), self.invocation.workspace_root.as_deref(), &view_id, directory)
.map_err(to_wit))
}
fn select_in(&mut self, view_id: String, path: String, focus: Option<bool>) -> Fallible<()> {
if let Err(error) = self.require(Capability::ProjectRead).and_then(|_| self.require_window()) {
return Ok(Err(error));
}
Ok(self
.host
.select_in_project_view(self.client().expect("checked"), &view_id, path, focus.unwrap_or(true))
.map_err(to_wit))
}
}
/// The optional `file-actions` export.
pub(crate) mod file_actions_bindings {
wasmtime::component::bindgen!({
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
fb42c489a763c38528faae4f7d46dfde6bbe192b6e6c3f6459b73869d9ccfea7
e1a347e0a46d2070ef47a0981cf1bfeff8fa18927761b783fc4398c100fa4c70
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
46a14028b6d2f23dd0142f5c181ad9a0c1cb5773fd668c3f7a768cdc431dca0c
e0ab3ccc8803f0ff237247af18470b2f2f2a8c7ae26773f03a5535c779e79ee5
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
ae96924ed394bbd54a53f083cf1e55c55f20c2f01ee8563685269478b1bee344
42060867cbd7f9ea386c51ff592945c325d859de0ffbd346d2fd44213b1bfd12
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
8ae340de9f7562d607b0de6477b8875dfc7849f0a462862883daf76d1c5abbd9
afc5796cc6a8d9e9c6cfc906cb4fe24718bdc0461ca0dd1270db291fdc87240e
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
ed8c0953d070e21aa426f1b9a897cf97a670c2b1b62e6adc716a0c9589a381d0
fed095032428deb380a5240716fd8d9269be025eec33233f23895002e84d3d6a
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
882ca569d56569a6110d525b76663bfc7ad35acc0004fa291265a5e02a4525a0
47b272d0697770654b4a262ca39a3613692d23c83906e522561c1d911e864ad0
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
bb50cdabd486309b3675424bf59f38340ae61cdd6bee974845bb181d428bb18a
73c2603e57ff568b281db2f80dbc9ee9a9c471c7dd51136fd0dadfb4ed89a736
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
eec563d70e0f026239573807bd9e7072d9f3c9a91d580a594b817edaeb4375fa
20702ddef376e762a3c5dba0a2eebf29ec8404a354fe387126646ffec870f667
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
62dd4fa287c01eb231e434303589faa1a73d22797fb255c8b0fd1c213a030d8b
e450fa53d1a68e7abf001405ba5e0dfa7451ee5e5c79495c13cee211d34b8e7f
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
07da400055a9ac7d262dd46ae93d11cc4da0f97bcb7d0984f20f68f03a97f3bf
13808d05b2fabec23fd1bf39e7cf0e61839e77e76a7ef4ed9d44e1a353e90a97
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
32a7e422fe6fc82e02f5ccb1e8c368c2ba34994fccb1039388bbbf1c0a4e30c0
c81cd4a68e4a3f560afd6cb1e486483c1c2baf997dd3f04a43ee4bbc1d55a29e
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
3554a3705a870165925c21ab732a9813bc3ee94d44f9c60b62cf0f76b9d1d44c
73067aa8f964a539388266ce606d6f678a9393f40583d672ead38a2e4c6fa64c
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
0f673811ac240ae6894eba412932f2962cc6b5671dc55eb0b039983ef39a02a8
2ccbcbafabfcbe853fe6aa3575f71af8483e516e09fab95428469bd8a7d5da02
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
37cf4ee118c1f46a831b852b12306a7fa3e3d919ddf1fdef01064293d97a1ba6
1bc694b2574304c694c0a85fc7e2083d5a9e01f8dcd07280c24eef88d00a4286
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
7aa7cd595054241777fe2f953b12e386ab58ade816c968ebc6cd0f4da1a00ecd
a2be66c49163955ea14abde1720a2f3624d225422978f1413f42ae64e86d231e
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
0ca98809772ef9609532dc7b8fd6904dfb3420a6947ab591417f177b9eee5dea
ecba604e70ed814fdfb38676a59cb119496279fd290faaf8ff3d3949bcf0cd91
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
ad590e2109c277ec256de9d682544f1ab5af8328f280dff96885bb94e04520c6
968165359ca514f4179305d6dc5c9c835dc2626d6f0bd4446909aa28299627e2
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
ced86a481cdab49a10c5035ef9b45c541adf04dd53d182a68df7a5a2f5c7555c
8815550ebdad8e5a85be73f10f2df0952aeaba0c83faf1f1ffec13e998cba7ef
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
772c5514b14a6510f24b44187ec639294aa0e92d797c08afffa7804b74e6849c
8c44243cffd802476787e4923f2d251eae028ca403476f51bfaacb2282332a06
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
69118ba53e95cd1ee4f7a76ec850a73382dbc92995910931756be84949ded88f
8c29696aafa860321fe48b608606c5d6754e32b65522adaa525c852ad51a0c85
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
47ffe9183dab375a63f2701740ff60b95d7876b0334b78aaba3ef764bfec6137
a4246103cecf529590c55a6f2c42b47ac226c476cc6ddda0c0ba1d79b6f50cab
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
5f4be603d2ab1f58a37fa956562bc074ad98de2fece895fd51be0c2ed4e09693
f738c392ff54a51dbfb40ad610c04104e217f171da80a071888ecdc6ba0d0eef
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
0a574cee59fba2ca8a56047b803f7b8dfda44eb89e40cad5cac7258a3aada6f4
42f710a4ce7021940954fd5a47507abc46b24cde43999ec7b65fcc89a38be69f
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
dcc6c63c6627b383ede8afd46f49d4e6ce2c72ffcf4965cf3aea9bf347e7ac28
1100040f719b68d4830af2a6258cf4d4c0c5a9b3c52f6a2227735836c7e589f4
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
4897e01ccc7bae20887c18f09768bb21f090ef9d6b3f5c753631c82b092fcdcd
fdd7dcaf1669f50b35fbc7416210571403834b8bd1b30646e1eb5ebe6ca29963
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
1c083813d241283b06162483c32d651845fee61a5510781a36f0a7222617e322
768d2248a14f87a97b20cd7911fcc135d12e5226e5e434a02e8b8c40596f3d36
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
251ed6c52e194bf765e3f5b142b67ef2cacadafb8a949c4a456ae9279a9c3390
07924e411a8870ba1937d61f304e962aeb6715360df414201f4ba43f92d939ae
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
7403453bb71817bffc0b09d39d0e2b8c3b50509d07ab28cdcc00c900b4ab665c
2204e040f617aa3fc1a47c18af96226574c60cd25b90a96fc3c327365a19a3dc
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
e0271196b348d9c463c86326f09223df4e7846a47666d4b88f570713981b1284
b2c4bf766c66afc72758f30803d91c3258fc4ff2d80e3a4f60f09876db5578a1
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
816ed04e60eaee776b2bd56d2f688138fb2b8260e46e9d4f2eaa86bdfc40141a
81daf9773437f80d42129fd000790074128f87a441bd3263d16d1c712b296395
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
207f46222a0032485f38b7433e2ac88c9d0dc4c89a9c9dff0a142e1f3c8c5f95
43ed5bf5c7bd2a64fab09fe1c32f9083066c00d735599e3104ed7b8d3f92ee54
+336
Переглянути файл
@@ -0,0 +1,336 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "anyhow"
version = "1.0.105"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2cb931c189b85683d69a5cfad41d4d418671e1ac413dd209f3f2fc31e3cfd902"
[[package]]
name = "bitflags"
version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]]
name = "equivalent"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
[[package]]
name = "foldhash"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
[[package]]
name = "hashbrown"
version = "0.17.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc"
dependencies = [
"foldhash",
]
[[package]]
name = "heck"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "id-arena"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "indexmap"
version = "2.14.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
dependencies = [
"equivalent",
"hashbrown",
"serde",
"serde_core",
]
[[package]]
name = "itoa"
version = "1.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
[[package]]
name = "leb128fmt"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
[[package]]
name = "log"
version = "0.4.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
[[package]]
name = "macro-string"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e7b3a5bbb2f63aaa223a671ea1bd0e7bc16bd30ce387324cf63995deaddbbd2"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "openidea-plugin"
version = "0.1.0"
dependencies = [
"serde",
"serde_json",
"wit-bindgen",
]
[[package]]
name = "openidea-test-project-view"
version = "0.1.0"
dependencies = [
"openidea-plugin",
]
[[package]]
name = "prettyplease"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0"
dependencies = [
"proc-macro2",
"syn",
]
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "semver"
version = "1.0.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
[[package]]
name = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.154"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "syn"
version = "3.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[[package]]
name = "wasm-encoder"
version = "0.262.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4495a6f85dd94c411c749303efcbc5defade0b0cbdbc0541495241ab917a9b5a"
dependencies = [
"leb128fmt",
"wasmparser",
]
[[package]]
name = "wasm-metadata"
version = "0.262.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c86ff6668190d9fb70372b306b4f9fe8930f0e2f57ce72e4922bf2f117900949"
dependencies = [
"anyhow",
"indexmap",
"wasm-encoder",
"wasmparser",
]
[[package]]
name = "wasmparser"
version = "0.262.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "974d643b125b272607e2fff8012ea14a8328acd7621e4bafa7afb32500052b1b"
dependencies = [
"bitflags",
"hashbrown",
"indexmap",
"semver",
]
[[package]]
name = "wit-bindgen"
version = "0.63.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b85a987ab61d365382d25c7d47e26edd48941b3bf6e3fbf76eff918bc71dab06"
dependencies = [
"bitflags",
"wit-bindgen-rust-macro",
]
[[package]]
name = "wit-bindgen-core"
version = "0.63.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "775e122e390603abfacd548027016cd0113a6e2bf2f8ce6bdd3658b013456ea8"
dependencies = [
"anyhow",
"heck",
"wit-parser",
]
[[package]]
name = "wit-bindgen-rust"
version = "0.63.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "84e26e13b9d972026778d2ffb7985736de116026fdc8d9464f966e12df2eb240"
dependencies = [
"anyhow",
"heck",
"indexmap",
"prettyplease",
"syn",
"wasm-metadata",
"wit-bindgen-core",
"wit-component",
]
[[package]]
name = "wit-bindgen-rust-macro"
version = "0.63.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "16a008a0d6b4840677326beb4edbeb210a2f1b7d0183fb7cc33f466b90fd7fb6"
dependencies = [
"anyhow",
"macro-string",
"prettyplease",
"proc-macro2",
"quote",
"syn",
"wit-bindgen-core",
"wit-bindgen-rust",
]
[[package]]
name = "wit-component"
version = "0.262.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "078def49fdb49cab405c3006e05793b3fdaf7069126ba6b9c97d01ec8c98fe4c"
dependencies = [
"anyhow",
"bitflags",
"indexmap",
"log",
"serde",
"serde_derive",
"serde_json",
"wasm-encoder",
"wasm-metadata",
"wasmparser",
"wit-parser",
]
[[package]]
name = "wit-parser"
version = "0.262.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00f0dc051466ffe46787721fca3d088536f158ae400be044f1b1c386ba9397ad"
dependencies = [
"anyhow",
"hashbrown",
"id-arena",
"indexmap",
"log",
"semver",
"serde",
"serde_derive",
"serde_json",
"unicode-ident",
"wasmparser",
]
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+20
Переглянути файл
@@ -0,0 +1,20 @@
[package]
name = "openidea-test-project-view"
version = "0.1.0"
edition = "2024"
publish = false
[workspace]
[lib]
crate-type = ["cdylib", "rlib"]
[dependencies]
openidea-plugin = { path = "../../../../../sdk/rust/openidea-plugin" }
[profile.release]
opt-level = "s"
lto = true
strip = true
codegen-units = 1
panic = "abort"
+7
Переглянути файл
@@ -0,0 +1,7 @@
# Project view fixture
Proves the `project-view-provider` export and the Git branch menu context. The
`grouped` pane puts every child named `mod_*` under a virtual `mod` folder and
leaves the rest unchanged; `{"plain": true}` settings keep the native children.
The `branch` command answers with the menu's repositories and full ref, and
`compare` opens `repository|left|right` with `views.open-revision-comparison`.
Бінарний файл не відображається.
+1
Переглянути файл
@@ -0,0 +1 @@
2fb3927fd769bf2edb8beabd7d3498f461d388cf85c5f6339c973d12bee0c9f8
+24
Переглянути файл
@@ -0,0 +1,24 @@
id = "test.project-view"
name = "Project view fixture"
version = "0.1.0"
engines.openidea = "^1.21"
wasm = "dist/plugin.wasm"
[capabilities]
required = ["project.read", "vcs.read"]
[[contributes.projectViewPanes]]
id = "grouped"
title = "Grouped"
[[contributes.commands]]
id = "branch"
title = "Show Branch"
[[contributes.commands]]
id = "compare"
title = "Compare Commits"
[[contributes.menus]]
menu = "git.branch.context"
command = "branch"
+56
Переглянути файл
@@ -0,0 +1,56 @@
use openidea_plugin::project_view::{NativeNode, ProjectViewProvider, ProjectionKind, ProjectionNode};
use openidea_plugin::{Error, Invocation, Plugin, RevisionComparison, host, register_plugin};
#[derive(Default)]
struct Fixture;
impl Plugin for Fixture {
fn run_command(&mut self, id: &str, ctx: &Invocation, arg: Option<&str>) -> Result<Option<String>, Error> {
if id == "compare" {
// `repository|left|right`
let mut parts = arg.unwrap_or_default().split('|').map(str::to_owned);
let (Some(repository), Some(left), Some(right)) = (parts.next(), parts.next(), parts.next()) else {
return Err(Error::Invalid("expected repository|left|right".into()));
};
let comparison =
RevisionComparison { repository, left, right, left_label: Some("Base".into()), right_label: None };
host::open_revision_comparison(&comparison)?;
return Ok(None);
}
if id != "branch" {
return Err(Error::NotFound(id.into()));
}
let context = ctx.git_action_context().ok_or_else(|| Error::NotFound("git menu context".into()))?;
let branch = context.branch.map(|branch| branch.full_ref).unwrap_or_default();
Ok(Some(format!("{}|{branch}", context.repositories.join(","))))
}
}
impl ProjectViewProvider for Fixture {
fn modify_children(
&mut self,
_view_id: &str,
_parent: &NativeNode,
children: &[NativeNode],
settings: &str,
_ctx: &Invocation<'_>,
) -> Option<Vec<ProjectionNode>> {
if settings.contains("\"plain\":true") {
return None;
}
let grouped: Vec<_> = children.iter().filter(|node| node.label.starts_with("mod_")).collect();
if grouped.is_empty() {
return None;
}
let folder = ProjectionKind::VirtualFolder { label: "mod".into(), icon: None };
let mut nodes = vec![ProjectionNode { id: "mod".into(), parent: None, kind: folder }];
nodes.extend(grouped.into_iter().map(|node| ProjectionNode {
id: node.id.clone(),
parent: Some("mod".into()),
kind: ProjectionKind::ExistingNode,
}));
Some(nodes)
}
}
register_plugin!(Fixture, project_view);
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
463d3fda155ee87f8ec95d9dc38da060da513fb6ade2305b45c067a73a6b34f1
c11ffdbdfd871a2f6ac7bbbfece97ac58b5162051351236e33049221cae6fb19
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
18333ac68547a277306b7bc4e33321423c417399dd63d046f20b50a9a37d0fdf
02f53d543c5f07c2c1afd54447c26bada486e36e4c560f6ed712e315ab898b40
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
e2cb367c7df57766676fcf7ecd34e6ee78d541662fb1ed80fc0c36140b12bf7e
501d55f3b0befb95d956f34b6334ef0b1aa5dcd851403644c68027eb83b74290
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
c4e910f2f4582d436851242fb4a0ecdfb3140262ee18e7dfbca064ac724b5388
88b0ed7663311accef6e2019ef1256bee191227d157ad4c6b70a23a30655d75d
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
ed38663014507490713c3b2161ec40b85b574309f34f8de8c8230f44e7b27e68
d9bc7c65f445c44f748d8578282311bc0e975a8379c1d2447591d69863c027dd
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
fd4b4702801cecf9ad5e7cb20a1a14e33bd47d1056e0b0599ffdc3e3c12d602a
b9ba467dac9a4d4d00548c142867148d54b69a4c6c5a4bac101e5ca804001659
Бінарний файл не відображається.
Loaded 100 of 207 files, more files were not shown because too many files have changed in this diff. Show more