feat(plugins): add plugin run targets and interpreter routing

Цей коміт міститься в:
l0ng-ai committed 2026-11-09 07:47:24 +08:00
1 джерело 7a9baac475
коміт adc252ccd4
131 files changed
+1401 -84

No files matched your search

+13
Переглянути файл
@@ -191,6 +191,19 @@ pub struct RunTarget {
pub image_user: bool,
}
/// A plugin-owned argv wrapper for project runs (API 1.4).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct PluginRunTarget {
pub id: String,
pub name: String,
pub program: String,
pub args: Vec<String>,
pub workdir_args: Vec<String>,
pub container_root: Option<String>,
pub commands: Vec<(String, Vec<String>)>,
}
#[cfg(test)]
mod deployment_tests {
use super::*;
+4
Переглянути файл
@@ -767,6 +767,8 @@ impl Default for PythonSettings {
pub struct PhpSettings {
/// `php` CLI executable; empty = the one on `PATH`.
pub interpreter: String,
/// Run PHP/Composer or Node/package-manager commands in this target; empty = project default, `local` = local.
pub run_target: String,
/// PHP version the language server checks the code against (`7.4`); empty = from
/// `composer.json` (`config.platform.php`, else the lowest version `require.php` allows).
pub language_level: String,
@@ -794,6 +796,8 @@ pub struct RubySettings {
pub struct NodeSettings {
/// `node` executable; empty = the one on `PATH`.
pub interpreter: String,
/// Run PHP/Composer or Node/package-manager commands in this target; empty = project default, `local` = local.
pub run_target: String,
/// `npm` | `pnpm` | `yarn`; empty = detect from the lock file / `packageManager`.
pub package_manager: String,
}
+9 -1
Переглянути файл
@@ -272,6 +272,8 @@ impl Default for PythonDebuggerSettings {
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(default, rename_all = "camelCase")]
pub struct RunSettings {
/// Target for configurations without an explicit target. Empty = local.
pub default_target: String,
pub confirm_rerun: bool,
/// Ask before closing a Run tab whose process is still running.
pub confirm_terminate: bool,
@@ -282,7 +284,13 @@ pub struct RunSettings {
impl Default for RunSettings {
fn default() -> Self {
Self { confirm_rerun: true, confirm_terminate: true, show_on_start: true, termination_timeout_ms: 3000 }
Self {
default_target: String::new(),
confirm_rerun: true,
confirm_terminate: true,
show_on_start: true,
termination_timeout_ms: 3000,
}
}
}
+5
Переглянути файл
@@ -249,6 +249,11 @@ impl Host {
self.cancel_request(request);
}
let project = self.projects.write().remove(window)?;
if self.windows_for_root(&project.root).is_empty()
&& let Some(plugins) = self.plugin_host()
{
plugins.withdraw_project_run_targets(&project.root);
}
project.files_events_active.store(false, std::sync::atomic::Ordering::Release);
project.plugin_diagnostics.close();
if let Some(plugins) = plugins::editor_plugin_host() {
+22
Переглянути файл
@@ -218,6 +218,9 @@ async fn start_inner(
) -> IdeResult<RunInfo> {
host.require_trust(window)?;
let project = host.project(window)?;
if config.extras.target.is_none() {
config.extras.target = ide_sdk::apply::run_target(&config, &project.settings.effective()).map(str::to_owned);
}
if config.detected
&& config.id.starts_with(ide_run::EXTERNAL_PREFIX)
&& let Some(plugins) = host.plugin_host()
@@ -250,6 +253,25 @@ async fn start_inner(
}
if let Some(id) = config.extras.target.as_deref().filter(|t| !t.is_empty()) {
let settings = project.settings.effective();
if id.starts_with("plugin-target:") {
let plugins =
host.plugin_host().ok_or_else(|| IdeError::not_found("plugin run target is no longer available"))?;
let root = project.root.clone();
let id = id.to_owned();
let config = host.blocking(move || plugins.prepare_run_target(&root, &id, &config)).await?;
project.require_trust()?;
return host.processes.start(
&project.root,
&config,
&StartOptions {
encoding: Some(settings.console.encoding).filter(|e| !e.trim().is_empty()),
python_paths: Vec::new(),
ruby_reporter: None,
},
sink,
Box::new(move |c| on_output(c)),
);
}
let target = ide_remote::service::run_target(&settings, id)?;
if target.kind != RunTargetKind::Ssh {
// A local run of the docker CLI: the command is resolved in the container, and
+11 -1
Переглянути файл
@@ -494,6 +494,7 @@ pub(super) struct Shared {
pub(super) prompts_blocked: Mutex<BTreeSet<String>>,
pub(super) next_prompt: AtomicU64,
pub(super) run_configurations: super::run_detectors::DynamicConfigurations,
pub(super) run_targets: Mutex<super::run_targets::Targets>,
pub(super) operations: Mutex<BTreeMap<String, super::execution::Operation>>,
pub(super) content_tabs: Mutex<BTreeMap<(String, String, String), ide_plugin::ContentTab>>,
pub(super) content_requests: Mutex<ContentRequests>,
@@ -560,6 +561,7 @@ impl Shared {
prompts_blocked: Mutex::default(),
next_prompt: AtomicU64::new(1),
run_configurations: Arc::default(),
run_targets: Mutex::default(),
operations: Mutex::default(),
content_tabs: Mutex::default(),
content_requests: Mutex::default(),
@@ -739,6 +741,7 @@ impl Shared {
/// Withdraws a plugin's run-time state (it stopped or failed). Its
/// subscriptions go only with `subscriptions`, as they survive restarts.
pub fn clear_plugin(&self, plugin: &str, subscriptions: bool) {
self.withdraw_run_targets(Some(plugin), None);
self.run_configurations.write().retain(|(p, _), _| p != plugin);
self.operations.lock().retain(|_, op| op.plugin != plugin);
self.content_tabs.lock().retain(|(p, _, _), _| p != plugin);
@@ -994,7 +997,7 @@ impl PluginApi {
self.approved_program_in_project(program, None)
}
fn approved_program_in_project(&self, program: &str, root: Option<&Path>) -> Result<PathBuf, HostError> {
pub(super) fn approved_program_in_project(&self, program: &str, root: Option<&Path>) -> Result<PathBuf, HostError> {
if let Some(pin) = root.and_then(|root| {
self.shared.project_pins.read().get(&(self.id().into(), format!("process:{program}"), root.into())).cloned()
}) {
@@ -1248,6 +1251,13 @@ fn failed(e: impl std::fmt::Display) -> HostError {
}
impl HostApi for PluginApi {
fn register_run_target(&self, root: &Path, target: ide_plugin::PluginRunTarget) -> Result<(), HostError> {
self.register_target(root, target)
}
fn unregister_run_target(&self, root: &Path, id: &str) {
self.unregister_target(root, id);
}
fn start_run(
&self,
client: &str,
+3
Переглянути файл
@@ -464,6 +464,9 @@ impl PluginHost {
if owned.debug_adapter.is_none() {
return Err(IdeError::invalid("this configuration has no debugger"));
}
if config.extras.target.is_none() {
config.extras.target = owned.extras.target.clone();
}
if config.extras.target.as_ref().is_some_and(|t| !t.is_empty()) {
return Err(IdeError::invalid("debugging this target is not supported"));
}
+2
Переглянути файл
@@ -40,6 +40,7 @@ mod providers;
pub mod remote;
pub mod remote_host;
mod run_detectors;
pub mod run_targets;
mod semantic_tokens;
mod theme;
mod types;
@@ -661,6 +662,7 @@ impl PluginHost {
/// Unloads the project plugins of `root` (the project became untrusted or closed).
pub fn restrict_project(&self, root: &Path) {
self.shared.withdraw_run_targets(None, Some(root));
let _guard = self.lifecycle.lock();
let ids: Vec<_> = self
.plugins
+17 -1
Переглянути файл
@@ -131,7 +131,8 @@ pub fn package_digest(dir: &Path, files: &[PathBuf]) -> IdeResult<String> {
pub fn forwarded(event: &PluginEvent) -> bool {
matches!(
event,
PluginEvent::WindowRequest { .. }
PluginEvent::RunTargetsChanged
| PluginEvent::WindowRequest { .. }
| PluginEvent::ContentTabReply { .. }
| PluginEvent::DecorationsChanged { .. }
| PluginEvent::EditorOpen { .. }
@@ -720,6 +721,21 @@ impl RemotePlugins {
let h = h.clone();
async move { super::index_ops::plugin_endpoints(&c.host, alive(&h)?, &c.window, c.arg("pluginId")?).await }
});
let h = host.clone();
d.add("plugin_run_targets", move |c| {
let h = h.clone();
async move { super::run_targets::list(&c.host, alive(&h)?.as_ref(), &c.window) }
});
let h = host.clone();
d.add("plugin_answer_run_target", move |c| {
let h = h.clone();
async move {
let plugins = alive(&h)?;
let id: String = c.arg("id")?;
let use_target = c.arg("useTarget")?;
blocking(move || super::run_targets::answer(&c.host, &plugins, &c.window, &id, use_target)).await
}
});
d.add("plugin_line_markers", |c| async move {
crate::ops::lsp::plugin_line_markers(&c.host, &c.window, c.arg("doc")?).await
});
+150
Переглянути файл
@@ -0,0 +1,150 @@
//! Project-owned registrations, retained across idle instance reclamation.
use super::api::{PluginApi, Shared};
use super::{PluginEvent, PluginHost};
use ide_core::{IdeError, IdeResult};
use ide_plugin::{HostError, PluginRunTarget};
use std::path::{Path, PathBuf};
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, specta::Type)]
#[serde(rename_all = "camelCase")]
pub struct RegisteredRunTarget {
/// Opaque selector id, namespaced by the host.
pub id: String,
pub plugin_id: String,
pub plugin_name: String,
pub target: PluginRunTarget,
pub prompt: bool,
}
pub(super) type Targets = std::collections::BTreeMap<(PathBuf, String), RegisteredRunTarget>;
fn selector(plugin: &str, id: &str) -> String {
format!("plugin-target:{}:{plugin}{id}", plugin.len())
}
impl Shared {
fn target_answer_file(&self, root: &Path, id: &str) -> PathBuf {
let key = format!("{}\0{id}", root.display());
self.data_dir.join(".run-target-answers").join(blake3::hash(key.as_bytes()).to_hex().as_str())
}
pub(super) fn withdraw_run_targets(&self, plugin: Option<&str>, root: Option<&Path>) {
let mut targets = self.run_targets.lock();
let before = targets.len();
targets.retain(|(r, _), t| !(plugin.is_none_or(|p| p == t.plugin_id) && root.is_none_or(|path| path == r)));
if before != targets.len() {
drop(targets);
self.sink.emit(None, PluginEvent::RunTargetsChanged);
}
}
}
impl PluginApi {
pub(super) fn register_target(&self, root: &Path, target: PluginRunTarget) -> Result<(), HostError> {
ide_remote::plugin_target::validate(&target).map_err(|e| HostError::Invalid(e.to_string()))?;
let workspace = self.shared.workspace().ok_or(HostError::Cancelled)?;
if !workspace.projects().iter().any(|r| r == root) {
return Err(HostError::NotFound("project is not open".into()));
}
if !workspace.trusted(root) {
return Err(HostError::Denied("project is not trusted".into()));
}
self.approved_program_in_project(&target.program, Some(root))?;
let blocked = self.shared.prompts_blocked.lock();
if blocked.contains(self.pkg.id()) {
return Err(HostError::Cancelled);
}
let id = selector(self.pkg.id(), &target.id);
let mut targets = self.shared.run_targets.lock();
if !targets.contains_key(&(root.into(), id.clone()))
&& targets.iter().filter(|((r, _), t)| r == root && t.plugin_id == self.pkg.id()).count() >= 32
{
return Err(HostError::Invalid("at most 32 targets per plugin and project".into()));
}
let prompt = !self.shared.target_answer_file(root, &id).exists();
targets.insert(
(root.into(), id.clone()),
RegisteredRunTarget {
id,
plugin_id: self.pkg.id().into(),
plugin_name: self.pkg.manifest.name.clone(),
target,
prompt,
},
);
drop(targets);
drop(blocked);
self.shared.sink.emit(None, PluginEvent::RunTargetsChanged);
Ok(())
}
pub(super) fn unregister_target(&self, root: &Path, id: &str) {
if self.shared.run_targets.lock().remove(&(root.into(), selector(self.pkg.id(), id))).is_some() {
self.shared.sink.emit(None, PluginEvent::RunTargetsChanged);
}
}
}
impl PluginHost {
/// Drops registrations when their project closes or loses trust.
pub fn withdraw_project_run_targets(&self, root: &Path) {
self.shared.withdraw_run_targets(None, Some(root));
}
pub fn run_targets(&self, root: &Path) -> Vec<RegisteredRunTarget> {
self.shared.run_targets.lock().iter().filter(|((r, _), _)| r == root).map(|(_, t)| t.clone()).collect()
}
pub fn prepare_run_target(
&self,
root: &Path,
id: &str,
config: &ide_run::RunConfig,
) -> IdeResult<ide_run::RunConfig> {
let target = self
.shared
.run_targets
.lock()
.get(&(root.into(), id.into()))
.cloned()
.ok_or_else(|| IdeError::not_found("plugin run target is no longer available"))?;
let program = self.program_for_project(&target.plugin_id, &target.target.program, Some(root))?;
ide_remote::plugin_target::prepare(root, &target.target, &program, config)
}
}
pub fn list(host: &crate::Host, plugins: &PluginHost, window: &str) -> IdeResult<Vec<RegisteredRunTarget>> {
Ok(plugins.run_targets(&host.project(window)?.root))
}
/// The first answer wins across the project's windows. Only Use changes settings.
pub fn answer(
host: &crate::Host,
plugins: &PluginHost,
window: &str,
id: &str,
use_target: bool,
) -> IdeResult<ide_core::settings::Settings> {
host.require_trust(window)?;
let project = host.project(window)?;
let mut targets = plugins.shared.run_targets.lock();
let target = targets
.get_mut(&(project.root.clone(), id.into()))
.ok_or_else(|| IdeError::not_found("plugin run target is no longer available"))?;
let file = plugins.shared.target_answer_file(&project.root, id);
if file.exists() {
target.prompt = false;
return Ok(project.settings.effective());
}
if use_target {
plugins.program_for_project(&target.plugin_id, &target.target.program, Some(&project.root))?;
let scope = ide_workspace::SettingsScope::Project;
for key in ["run.defaultTarget", "languages.php.runTarget", "languages.node.runTarget"] {
project.settings.set(scope, key, serde_json::json!(id))?;
for window in host.windows_for_root(&project.root) {
if let Ok(open) = host.project(&window) {
open.settings.reload();
open.sink.emit(ide_core::IdeEvent::SettingsChanged { key: key.into() });
}
}
}
}
std::fs::create_dir_all(file.parent().unwrap())?;
std::fs::write(file, if use_target { "use" } else { "not-now" })?;
target.prompt = false;
drop(targets);
plugins.shared.sink.emit(None, PluginEvent::RunTargetsChanged);
Ok(project.settings.effective())
}
+2
Переглянути файл
@@ -165,6 +165,8 @@ pub struct PluginUpdate {
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum PluginEvent {
/// Project target registrations or remembered prompt answers changed.
RunTargetsChanged,
/// A window-owned operation; an empty request id queues an asynchronous run.
#[serde(rename_all = "camelCase")]
WindowRequest { plugin_id: String, request_id: String, request: WindowRequest },
+3
Переглянути файл
@@ -146,6 +146,9 @@ impl crate::Host {
phpstan.interrupt();
}
if !trusted {
if let Some(plugins) = self.plugin_host() {
plugins.withdraw_project_run_targets(&project.root);
}
project.lsp.set_execution_allowed(false);
}
project.repos();
+123
Переглянути файл
@@ -229,3 +229,126 @@ async fn plugin_debug_uses_the_source_language_and_revalidates_its_owned_program
plugins.set_capability("execution", "process:execution-tool", false).unwrap();
assert!(plugins.prepare_debug_run("main", config).is_err());
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread")]
async fn plugin_run_targets_register_prompt_route_revalidate_and_withdraw() {
use ide_host::plugins::{Consent, PluginEvent, PluginHost, run_targets};
use ide_plugin::{Invocation, Limits};
use std::os::unix::fs::PermissionsExt;
let f = Harness::new();
f.host.set_project_trust(&f.root, true, false).await.unwrap();
let plugins = Arc::new(
PluginHost::new(
f._tmp.path().join("plugins"),
Arc::new(|_: Option<&str>, _: PluginEvent| {}),
Limits { idle_timeout: Some(std::time::Duration::from_millis(10)), ..Default::default() },
)
.unwrap(),
);
plugins.set_workspace(Some(Arc::new(f.workspace())));
f.host.set_plugin_host(&plugins);
let package = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../ide-plugin/tests/fixtures/execution");
plugins.install_from_dir(&package, &Consent::all()).unwrap();
let tool = f._tmp.path().join("wrapper");
std::fs::write(&tool, "#!/bin/sh\nprintf 'cwd=%s\\n' \"$PWD\"\nprintf '<%s>\\n' \"$@\"\n").unwrap();
std::fs::set_permissions(&tool, std::fs::Permissions::from_mode(0o755)).unwrap();
let invocation =
|| Invocation { client: Some("main".into()), workspace_root: Some(f.root.clone()), ..Default::default() };
assert!(plugins.run_command("execution", "target", None, invocation()).is_err());
plugins.choose_program("execution", "process:execution-tool", Some(&f.root), Some(&tool)).unwrap();
plugins.run_command("execution", "target", None, invocation()).unwrap();
tokio::time::sleep(std::time::Duration::from_millis(30)).await;
plugins.tick_at(std::time::Instant::now());
assert_eq!(plugins.info_of("execution").unwrap().status, ide_host::plugins::PluginStatus::Inactive);
let targets = run_targets::list(&f.host, &plugins, "main").unwrap();
assert_eq!(targets.len(), 1);
assert!(targets[0].prompt);
assert!(f.host.project("main").unwrap().settings.effective().run.default_target.is_empty());
let id = &targets[0].id;
let settings = run_targets::answer(&f.host, &plugins, "main", id, false).unwrap();
assert!(settings.run.default_target.is_empty());
// A stale prompt in a second window cannot change an answered selection.
assert!(run_targets::answer(&f.host, &plugins, "second", id, true).unwrap().run.default_target.is_empty());
plugins.run_command("execution", "untarget", None, invocation()).unwrap();
assert!(plugins.run_targets(&f.root).is_empty());
plugins.run_command("execution", "target", None, invocation()).unwrap();
assert!(!plugins.run_targets(&f.root)[0].prompt);
plugins.run_command("execution", "target", Some("preferred"), invocation()).unwrap();
let preferred = plugins.run_targets(&f.root).into_iter().find(|t| t.target.id == "preferred").unwrap();
let settings = run_targets::answer(&f.host, &plugins, "main", &preferred.id, true).unwrap();
assert_eq!(settings.run.default_target, preferred.id);
assert_eq!(settings.languages.php.run_target, preferred.id);
assert_eq!(settings.languages.node.run_target, preferred.id);
assert_eq!(f.host.project("second").unwrap().settings.effective().run.default_target, preferred.id);
std::fs::write(f.root.join("execution.marker"), "").unwrap();
std::fs::write(f.root.join("entry.py"), "print('test')\n").unwrap();
let mut detected =
plugins.run_detection().detect(&f.root).into_iter().find(|c| c.id == "plugin:execution:detected").unwrap();
detected.args = vec!["entry.py".into()];
ide_run::save_user_configs(&f.root, &[detected]).unwrap();
let mut debug = f.workspace().run_configuration("main", "execution", "detected").unwrap();
debug.extras.target = None;
let error = plugins.prepare_debug_run("main", debug).unwrap_err();
assert_eq!(error.kind, ide_core::error::ErrorKind::InvalidInput);
assert!(error.to_string().contains("target"));
assert!(plugins.run_command("execution", "debug", None, invocation()).unwrap_err().to_string().contains("target"));
let output = Arc::new(parking_lot::Mutex::new(String::new()));
let captured = output.clone();
let config = ide_run::RunConfig {
id: "php-target".into(),
name: "PHP target".into(),
kind: "php".into(),
command: "php".into(),
args: vec!["x.php".into(), "a b; $(touch forbidden)".into()],
cwd: None,
env: Default::default(),
detected: false,
is_test: false,
debug_adapter: None,
allow_parallel: false,
extras: Default::default(),
};
let run = ide_host::ops::run::start(
&f.host,
"main",
config.clone(),
Arc::new(move |chunk| {
if let ide_run::OutputChunk::Stdout { text } = chunk {
captured.lock().push_str(&text);
}
}),
)
.await
.unwrap();
for _ in 0..100 {
if f.host.processes.list().iter().any(|r| r.id == run.id && !r.running) {
break;
}
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
}
let text = output.lock().clone();
assert!(text.contains("<wrapped>\n<--cwd=/container>\n<php>\n<x.php>\n<a b; $(touch forbidden)>"), "{text}");
assert!(text.contains(&format!("cwd={}", f.root.display())), "{text}");
assert!(!f.root.join("forbidden").exists());
// Pin checks are repeated at launch, not only at registration.
std::fs::write(&tool, "#!/bin/sh\nexit 99\n").unwrap();
assert!(ide_host::ops::run::start(&f.host, "main", config.clone(), Arc::new(|_| {})).await.is_err());
plugins.set_capability("execution", "process:execution-tool", false).unwrap();
assert!(plugins.run_targets(&f.root).is_empty());
assert!(ide_host::ops::run::start(&f.host, "main", config, Arc::new(|_| {})).await.is_err());
plugins.choose_program("execution", "process:execution-tool", Some(&f.root), Some(&tool)).unwrap();
plugins.run_command("execution", "target", None, invocation()).unwrap();
f.host.set_project_trust(&f.root, false, false).await.unwrap();
assert!(plugins.run_targets(&f.root).is_empty());
assert!(
plugins.run_command("execution", "target", None, invocation()).unwrap_err().to_string().contains("trusted")
);
f.host.set_project_trust(&f.root, true, false).await.unwrap();
plugins.run_command("execution", "target", None, invocation()).unwrap();
f.host.close_project_detached("main");
assert_eq!(plugins.run_targets(&f.root).len(), 1);
f.host.close_project_detached("second");
assert!(plugins.run_targets(&f.root).is_empty());
plugins.shutdown();
}
+33 -1
Переглянути файл
@@ -477,7 +477,7 @@ async fn api14_stage3_remote_terminal_pins_and_exit_events_stay_on_the_execution
let bin = tmp.path().join("bin");
std::fs::create_dir(&bin).unwrap();
let executable = bin.join("execution-tool");
std::fs::write(&executable, "#!/bin/sh\nread line\nprintf '%s\\n' \"$line\"\n").unwrap();
std::fs::write(&executable, "#!/bin/sh\nif [ \"$1\" = wrapped ]; then printf '<%s>\\n' \"$@\" > \"$PWD/wrapped.txt\"; exit; fi\nread line\nprintf '%s\\n' \"$line\"\n").unwrap();
std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o755)).unwrap();
let path_var = {
let bin = bin.clone();
@@ -521,6 +521,38 @@ async fn api14_stage3_remote_terminal_pins_and_exit_events_stay_on_the_execution
invoke(&peer, "project_trust_set", json!({ "path": project, "trusted": true, "folder": false })).await.unwrap();
sync(&peer, &desktop, &[]).await;
assert!(sync(&peer, &desktop, &["execution"]).await.failed.is_empty());
invoke(
&peer,
"plugin_run_command",
json!({"pluginId":"execution", "commandId":"target", "arg":null, "editor":null}),
)
.await
.unwrap();
let targets = invoke(&peer, "plugin_run_targets", json!({})).await.unwrap();
assert_eq!(targets.as_array().unwrap().len(), 1);
assert_eq!(targets[0]["pluginId"], "execution");
assert!(desktop.run_targets(&project).is_empty());
let id = targets[0]["id"].as_str().unwrap();
let settings = invoke(&peer, "plugin_answer_run_target", json!({"id":id, "useTarget":false})).await.unwrap();
assert_eq!(settings["run"]["defaultTarget"], "");
let config = json!({"id":"wrapped-php", "name":"Wrapped PHP", "kind":"php", "command":"php", "args":["x.php", "literal ; $(touch bad)"], "env":{}, "detected":false, "isTest":false, "target":id});
invoke(&peer, "run_start", json!({"config":config, "onOutput":{"$channel":38}})).await.unwrap();
until("remote wrapped run", 5, || project.join("wrapped.txt").exists()).await;
assert_eq!(
std::fs::read_to_string(project.join("wrapped.txt")).unwrap(),
"<wrapped>\n<--cwd=/container>\n<php>\n<x.php>\n<literal ; $(touch bad)>\n"
);
assert!(!project.join("bad").exists());
invoke(
&peer,
"plugin_run_command",
json!({"pluginId":"execution", "commandId":"untarget", "arg":null, "editor":null}),
)
.await
.unwrap();
assert_eq!(invoke(&peer, "plugin_run_targets", json!({})).await.unwrap(), json!([]));
client.plugin_events.lock().clear();
client.events.lock().clear();
let runner = peer.clone();
let run = tokio::spawn(async move {
invoke(
+2
Переглянути файл
@@ -26,3 +26,5 @@ pub use wasmtime::component::Component;
mod execution;
pub use execution::*;
pub use ide_core::remote_settings::PluginRunTarget;
+10
Переглянути файл
@@ -64,6 +64,16 @@ pub const CANCELLED: &str = "was cancelled";
/// which routes notifications and status items to windows and edits to open
/// documents. Capabilities are already checked when these are called.
pub trait HostApi: Send + Sync {
/// Registers a project-scoped wrapper after validating its process grant and pin.
fn register_run_target(&self, root: &Path, target: crate::PluginRunTarget) -> Result<(), HostError> {
let _ = (root, target);
Err(HostError::Failed("run targets unavailable".into()))
}
/// Withdraws this plugin's target, preserving the user's remembered prompt answer.
fn unregister_run_target(&self, root: &Path, id: &str) {
let _ = (root, id);
}
/// Starts one of this plugin's configurations in a window.
fn start_run(
&self,
+33
Переглянути файл
@@ -1846,6 +1846,39 @@ impl From<bindings::openidea::plugin::views::ContentTabReply> for crate::Content
}
}
impl bindings::openidea::plugin::run_targets::Host for StoreData {
fn register(
&mut self,
project: Resource<ProjectRes>,
target: bindings::openidea::plugin::run_targets::RunTarget,
) -> Fallible<()> {
if let Err(e) = self.require(Capability::Process(target.program.clone())) {
return Ok(Err(e));
}
let root = self.table.get(&project)?.root.clone();
Ok(self
.host
.register_run_target(
&root,
crate::PluginRunTarget {
id: target.id,
name: target.name,
program: target.program,
args: target.args,
workdir_args: target.workdir_args,
container_root: target.container_root,
commands: target.commands,
},
)
.map_err(to_wit))
}
fn unregister(&mut self, project: Resource<ProjectRes>, id: String) -> wasmtime::Result<()> {
let root = self.table.get(&project)?.root.clone();
self.host.unregister_run_target(&root, &id);
Ok(())
}
}
impl bindings::openidea::plugin::run::Host for StoreData {
fn start(&mut self, config: String, args: Vec<String>, debug: bool) -> Fallible<String> {
if let Err(e) = self.require_window() {
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
fd49e1032cb7f21e8b2e75952cd0c55402a53879be5279c0a4edced2c0a28378
aca0cf50e9b7e9f66d62705ba040c7caee745f0cf97fe492cb39af86971aed22
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
31c908f292255eedff07d31e42ac951fcbdaa6ac18780c41680318519cca3eba
f3d07c243ae6e279f49cb4e1bd9fa67117ad4f7ebfb4c22dcfe1510701b56a71
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
73f5b3c6d12525aae266f1d8d29d1e626f97d16b2842e9a51367ec51bd0faa16
6134e5ad5b174fe75ee6ddba9604a30d5d30bd675ffabbaea1ad78831a21609a
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
958787ffaecf4fe99f4fdc30591d98f4d3d1492208db4a94b226839c1a4ba1fa
9f9b56b7044adac003648ca18d34ceffb58505918f550cf8ad187ac14a8845d7
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
f9f076f9b4b1670722b4bce2619492600cebae044e4ccf3fa4d66c9c5acb4d40
ed71c7f1ad8420439f58426f898b41d982ae97653916b1c56590705320dc66b1
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
3d09d87137b9e56b980dbfdb9ff04cef680576298f5ead117917ec296bd2bb4d
fc3b498f6f82197db683cd2aa9500593f883f962492ca11f0a6940233ad6c7f0
+7
Переглянути файл
@@ -43,3 +43,10 @@ title = "content"
[[contributes.commands]]
id = "events"
title = "events"
[[contributes.commands]]
id = "target"
title = "target"
[[contributes.commands]]
id = "untarget"
title = "untarget"
+21 -1
Переглянути файл
@@ -2,8 +2,28 @@ use openidea_plugin::{host, register_plugin, *};
#[derive(Default)]
struct Execution;
impl Plugin for Execution {
fn run_command(&mut self, id: &str, _ctx: &Invocation, arg: Option<&str>) -> Result<Option<String>, Error> {
fn run_command(&mut self, id: &str, ctx: &Invocation, arg: Option<&str>) -> Result<Option<String>, Error> {
match id {
"target" => {
let project = ctx.project().ok_or_else(|| Error::Invalid("no project".into()))?;
host::register_run_target(
&project,
&PluginRunTarget {
id: arg.unwrap_or("wrapper").into(),
name: "Execution target".into(),
program: "execution-tool".into(),
args: vec!["wrapped".into()],
workdir_args: vec!["--cwd={cwd}".into()],
container_root: Some("/container".into()),
commands: vec![("composer".into(), vec!["composer".into()])],
},
)?;
Ok(None)
}
"untarget" => {
host::unregister_run_target(&ctx.project().unwrap(), arg.unwrap_or("wrapper"));
Ok(None)
}
"run" | "debug" => {
host::start_run(arg.unwrap_or("detected"), &["appended".into()], id == "debug").map(Some)
}
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
fbcb5bd5df53955f023c2081837678ea2d591b503ae4b33282b9ed288c926f4d
131d45a3c7ef42f063e1100ab7f9d4e1e7b7fcf2095f27377f95eb59387756ee
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
8eeb6053d1ab0fca27eae8bd22b9e226cfdfe1a09b8abe5b93b130c6b2cb3a44
ea0612a1a1248e5410de7e55ff2dad7c4c1973cff690ce0e7f151e5d9395b209
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
0663bba12d8e91b11738a0a51380a393f5f9c28c10de52825bf11b9cc7ce31ff
99cbcce92580b3b292bb92ab34468a156554b1afa53df66320a85df92b37f936
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
f86f6b160823401e80462158d2cc7d1d52835d4487c3d71844f27f48ddf1bfd0
e7209fe969f00bb2ffb135e401aede7fa40a5b59ca865cc2c0f499d935b8d944
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
d139e628e3497f8fde3c56faa0f9e33315fc8c3daf89e1e8db1ab3f8ea5ed8e7
da1d956ebc383809fd44dd40fa37d9107bf71e2cf2328dcb4a9f4be9203fdff1
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
27c82fc8d8297f6f1d990227a07ca0b3b6351b768cae4cc117afb2cd1901fa89
9367abca6a02ab0867707450b0dad9a810b586ca14593f8b4ceecbdef67763cd
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
ab2f64512307cc51261d359b404a50371d5d5f248903ed9fc007c0699cd23e99
9d6498184eff25bfa053c5ab81f22ffc2ec817e83b26ce8496ab25e7f75c4811
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
354b750d92a13ba24f23d0b3b6baf74a5c94ab5494d45fa48e2b8b5299dd5ffa
caad529a0659e7b48763026f49025c29d78d1bc12702e4fed307d1f94d76556f
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
02749044dc9a4a1a8e586f2444b542c92aa1bbe57115649bebdb603117df41bf
867d6182eefeb902cfc500c3f7e9eaaf0e58483acfcc3dcac28c3f032d2a7628
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
bb2712ef88dbaffe93871aaf77a37afd4f0368343f1cb31edb45b91a726e74d7
663c709e7b9da5a97851383f2b47c41eda745b870dc4c770dca0fe092afad4e9
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
02c4b90c7e8f0c11b123c1c448331d5439d92e04d9672a88321fb7351ff1f2aa
18e0bfeacbd6d5b2cb4ec86ff42d0daf7d679134b2be70136abc24b6572b514b
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
87794561120d35a3168d34c3c90527c4d46c3387b6937b441425b11b479873d9
413693a2fbb1ad85f5443040bb15e6535572d2aac00cb9f6626dc059ac08137a
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
49cc9486316cb5ffbddb9d5bc93cd182c06e1a01a8dcd4c9d335170e4746955a
46541cd8169abd46eea69185feb2a5c00d6315f9ba22ff15bb357cf058ca0e68
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
36110599d633b5d5f6ba0e8cab87c6020d8961b37b1a09ab45601d6303bbee4f
a44ecdc63945e57ad99cd1a285b3b5cd7f82b6825dc110273fc9ddff943c9527
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
2f9da3991a052b07dfd5b43258c3356d4e037fd375fcacdf9c485ed3eac0e91c
c0d21fff65bd68e7cb827bdd3436961e5082d2eaa611022ce6ca9fb486e29e3e
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
68cad6550041e7ba84067e5b81b39ef13d6c4b682ae20b06d0e8bc65f79f9ef0
14d881cbad963cc24abf17d9eaddbaa61fa15fa363ddb6951df0439e3341760f
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
b120996b0c0407256932ad352551cd3b57386a51ac07e14a50e2b0f99c15597c
850f96f66fe3d2872c797dda2100358e0e92ecc7661e447ecb7d71e525ae7958
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
2af20bfd432256aae61cea81fa5c6a2807b272e257e8cedac3c23bafe0d9789d
a56c82dce6035ee8ae2367bc188c05e2d7ad5520ba6c1fb9bf58586b92f5326a
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
13dc72091bf3b94cde9c8f06a2d47c7a16ba12097a4c0bf5968a3bef3450d2cf
8b1377bb6901a5b8595a5818d997cd8fd7d4287269c54c138032f7de6b44b219
+2
Переглянути файл
@@ -16,3 +16,5 @@ pub use deploy::{
pub use mapping::{Excludes, Mappings, ResolvedMapping};
pub use service::{DeployedPath, DeploymentRoot, RemoteService};
pub use target::{RemoteRuns, RemoteStart};
pub mod plugin_target;
+120
Переглянути файл
@@ -0,0 +1,120 @@
//! Shell-free argv construction for plugin-owned run targets.
use ide_core::remote_settings::PluginRunTarget;
use ide_core::{IdeError, IdeResult};
use ide_run::{RunConfig, wrap};
use std::path::Path;
/// Validates a bounded target before replacing an existing registration.
pub fn validate(target: &PluginRunTarget) -> IdeResult<()> {
let label = |s: &str, max: usize| !s.is_empty() && s.len() <= max && !s.chars().any(char::is_control);
if !label(&target.id, 128) || !label(&target.name, 256) || !label(&target.program, 256) {
return Err(IdeError::invalid("invalid run target id, name or program"));
}
let argv = |args: &[String]| args.len() <= 256 && args.iter().all(|a| a.len() <= 16384 && !a.contains('\0'));
let mut names = std::collections::BTreeSet::new();
if !argv(&target.args)
|| !argv(&target.workdir_args)
|| target.commands.len() > 64
|| target.commands.iter().any(|(name, args)| {
!label(name, 256) || wrap::program_name(name) != *name || !names.insert(name) || !argv(args)
})
|| serde_json::to_vec(target).map_or(true, |v| v.len() > 256 << 10)
|| target
.container_root
.as_ref()
.is_some_and(|r| !r.starts_with('/') || r.contains(['\0', '\n', '\r']) || r.split('/').any(|p| p == ".."))
{
return Err(IdeError::invalid("invalid run target arguments or container root"));
}
Ok(())
}
/// Wraps argv, keeping the local cwd and environment for the approved wrapper.
/// The wrapper decides whether to forward environment into its container.
pub fn prepare(root: &Path, target: &PluginRunTarget, program: &Path, config: &RunConfig) -> IdeResult<RunConfig> {
validate(target)?;
let cwd = wrap::run_dir(root, config);
let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
let cwd = cwd.canonicalize().unwrap_or(cwd);
let relative =
cwd.strip_prefix(&root).ok().filter(|p| !p.components().any(|c| matches!(c, std::path::Component::ParentDir)));
let mapped_cwd = target.container_root.as_deref().zip(relative).map(|(container, rel)| {
if rel.as_os_str().is_empty() {
container.to_owned()
} else {
format!("{}/{}", container.trim_end_matches('/'), rel.to_string_lossy().replace('\\', "/"))
}
});
let mapped = target
.container_root
.as_deref()
.map(|container| crate::target::argv_command(config, &Default::default(), &root, container));
let command = mapped.as_ref().map_or_else(
|| {
let p = Path::new(&config.command);
if p.is_absolute() && !p.starts_with(&root) {
wrap::program_name(&config.command)
} else {
config.command.clone()
}
},
|m| m.program.clone(),
);
let name = wrap::program_name(&config.command);
let override_args = target.commands.iter().find(|(n, _)| n == &name).map(|(_, a)| a);
let mut args = override_args.unwrap_or(&target.args).clone();
if let Some(cwd) = mapped_cwd {
args.extend(target.workdir_args.iter().map(|a| a.replace("{cwd}", &cwd)));
}
if override_args.is_none() {
args.push(command);
}
args.extend(mapped.as_ref().map_or_else(|| config.args.clone(), |m| m.args.clone()));
let mut result = config.clone();
result.command = program.to_string_lossy().into_owned();
result.args = args;
result.cwd = Some(cwd.into());
result.extras.target = None;
// A wrapper's -c/-e are its own flags, not interpreter flags to inspect.
result.kind = "shell".into();
Ok(result)
}
#[cfg(test)]
mod tests {
use super::*;
fn config(command: &str, args: &[&str], cwd: &str) -> RunConfig {
serde_json::from_value(serde_json::json!({"id":"test", "name":"Test", "kind":"php", "command":command, "args":args, "cwd":cwd, "env":{}, "detected":false, "isTest":false})).unwrap()
}
#[test]
fn prefix_override_cwd_and_literal_argv() {
let target = PluginRunTarget {
id: "ddev".into(),
name: "DDEV".into(),
program: "ddev".into(),
args: vec!["exec".into()],
workdir_args: vec!["--dir".into(), "{cwd}".into()],
container_root: Some("/var/www/html".into()),
commands: vec![("composer".into(), vec!["composer".into()])],
};
let root = Path::new("/project");
let program = Path::new("/approved/ddev");
let run =
prepare(root, &target, program, &config("/usr/bin/php", &["x.php", "$(touch bad); a b"], "src")).unwrap();
assert_eq!(run.command, "/approved/ddev");
assert_eq!(run.args, ["exec", "--dir", "/var/www/html/src", "php", "x.php", "$(touch bad); a b"]);
assert_eq!(run.cwd.unwrap().to_string_lossy(), "/project/src");
let run = prepare(root, &target, program, &config(r"C:\tools\composer.exe", &["install"], "/outside")).unwrap();
assert_eq!(run.args, ["composer", "install"]);
let in_project = prepare(root, &target, program, &config("/tools/composer", &["install"], "src")).unwrap();
assert_eq!(in_project.args, ["composer", "--dir", "/var/www/html/src", "install"]);
let run = prepare(root, &target, program, &config("composer", &["install"], "../outside")).unwrap();
assert_eq!(run.args, ["composer", "install"]);
let mut target = target;
target.container_root = None;
let run = prepare(root, &target, program, &config("php", &["x.php"], "src")).unwrap();
assert_eq!(run.args, ["exec", "php", "x.php"]);
let run = prepare(root, &target, program, &config("echo a; touch bad", &[], ".")).unwrap();
assert_eq!(run.args, ["exec", "echo a; touch bad"]);
}
}
+17 -1
Переглянути файл
@@ -109,6 +109,22 @@ fn interpreter<'a>(program: &str, target: &'a RunTarget) -> Option<&'a str> {
/// Builds the remote command of `config`; `root` (the project) maps onto `remote_root`.
pub fn remote_command(config: &RunConfig, target: &RunTarget, root: &Path, remote_root: &str) -> RemoteCommand {
target_command(config, target, root, remote_root, true)
}
/// Maps paths and interpreters while preserving argv, including a command containing spaces.
/// Unlike SSH/container shell configurations, plugin wrappers never accept a shell line.
pub fn argv_command(config: &RunConfig, target: &RunTarget, root: &Path, remote_root: &str) -> RemoteCommand {
target_command(config, target, root, remote_root, false)
}
fn target_command(
config: &RunConfig,
target: &RunTarget,
root: &Path,
remote_root: &str,
allow_shell: bool,
) -> RemoteCommand {
let root_str = root.to_string_lossy().into_owned();
let map = |s: &str| -> String {
if root_str.is_empty() {
@@ -129,7 +145,7 @@ pub fn remote_command(config: &RunConfig, target: &RunTarget, root: &Path, remot
};
let env = config.env.iter().map(|(k, v)| (k.clone(), map_text(v))).collect();
let command = config.command.trim();
if config.args.is_empty() && command.contains(char::is_whitespace) {
if allow_shell && config.args.is_empty() && command.contains(char::is_whitespace) {
return RemoteCommand {
program: String::new(),
args: Vec::new(),
+39 -7
Переглянути файл
@@ -1173,6 +1173,29 @@ fn add_maven_options(args: &mut Vec<String>, options: &[String], additive_profil
args.splice(0..0, missing);
}
/// The interpreter target or project default; an explicit local choice returns an empty id.
pub fn run_target<'a>(config: &RunConfig, settings: &'a Settings) -> Option<&'a str> {
let name = ide_run::wrap::program_name(&config.command);
let target = if matches!(name.as_str(), "php" | "composer" | "phpunit" | "pest")
|| matches!(config.kind.as_str(), "php" | "composer" | "phpunit")
{
&settings.languages.php.run_target
} else if matches!(name.as_str(), "node" | "npm" | "npx" | "pnpm" | "yarn" | "bun")
|| matches!(config.kind.as_str(), "node" | "npm" | "vitest" | "jest" | "mocha")
{
&settings.languages.node.run_target
} else {
return non_empty(&settings.run.default_target);
};
if target == "local" {
Some("")
} else if target.is_empty() {
non_empty(&settings.run.default_target)
} else {
Some(target)
}
}
/// Points run configurations at the selected toolchains: Python configs use the
/// project interpreter, npm scripts the chosen package manager and Node.js,
/// cargo / go configs the selected toolchain, Maven / Gradle their runner JDK
@@ -1210,6 +1233,19 @@ pub fn apply_to_run_configs(configs: &mut [RunConfig], root: &Path, s: &Settings
};
for c in configs.iter_mut() {
if let Some(pm) = pm
&& c.kind == "npm"
&& c.detected
&& matches!(c.command.as_str(), "npm" | "pnpm" | "yarn" | "bun")
{
c.command = pm.to_owned();
}
if c.extras.target.is_none() {
c.extras.target = run_target(c, s).map(str::to_owned);
}
if c.extras.target.as_deref().is_some_and(|t| t.starts_with("plugin-target:")) {
continue;
}
let owner = ide_run::scope::owner(root, c);
resolve_run_command(c, root, s);
let mut path_dirs: Vec<PathBuf> = Vec::new();
@@ -1243,13 +1279,6 @@ pub fn apply_to_run_configs(configs: &mut [RunConfig], root: &Path, s: &Settings
}
}
"npm" | "node" | "deno" | "bun" => {
if let Some(pm) = pm
&& c.kind == "npm"
&& c.detected
&& matches!(c.command.as_str(), "npm" | "pnpm" | "yarn" | "bun")
{
c.command = pm.to_owned();
}
// The configuration's own Node interpreter, else the project's.
let own = c.extras.params.get("nodeInterpreter").and_then(|p| setting_path(root, p));
if let Some(dir) =
@@ -1367,6 +1396,9 @@ pub fn without_derived(config: &RunConfig, root: &Path, s: &Settings) -> RunConf
c
};
let mut out = config.clone();
if out.extras.target.as_deref() == run_target(&out, s) {
out.extras.target = None;
}
// Until nothing changes: some entries are derived only once others are gone
// (the virtualenv's `PATH` is added only without `VIRTUAL_ENV`). An entry derived before
// the configuration's own choice (an npm script's Node interpreter) is derived too.
+28
Переглянути файл
@@ -2169,3 +2169,31 @@ fn project_structure_module_jdk_language_level_and_external_libraries() {
let groups = crate::libraries::project_libraries(root, &settings, &[]);
assert!(groups.iter().any(|g| g.name == "servlet-api" && g.kind == "library" && g.roots.len() == 1));
}
#[test]
fn plugin_interpreter_targets_route_all_php_node_command_families() {
let mut settings = Settings::default();
settings.languages.php.run_target = "plugin-target:php".into();
settings.languages.node.run_target = "plugin-target:node".into();
settings.languages.php.interpreter = "/local/php".into();
settings.languages.node.interpreter = "/local/node".into();
for (command, kind, expected) in [
("php", "php", "php"),
("composer", "composer", "php"),
("vendor/bin/phpunit", "phpunit", "php"),
("node", "node", "node"),
("npm", "npm", "node"),
("node_modules/.bin/vitest", "vitest", "node"),
("npx", "node", "node"),
] {
let mut config: ide_run::RunConfig = serde_json::from_value(serde_json::json!({ "id":"run", "name":"run", "kind":kind, "command":command, "args":[], "env":{}, "detected":true, "isTest":false })).unwrap();
crate::apply::apply_to_run_configs(std::slice::from_mut(&mut config), Path::new("/project"), &settings);
assert_eq!(config.extras.target.as_deref(), Some(format!("plugin-target:{expected}").as_str()));
assert_eq!(config.command, command);
assert!(config.env.is_empty());
assert!(crate::apply::without_derived(&config, Path::new("/project"), &settings).extras.target.is_none());
config.extras.target = Some(String::new());
crate::apply::apply_to_run_configs(std::slice::from_mut(&mut config), Path::new("/project"), &settings);
assert_eq!(config.extras.target.as_deref(), Some(""));
}
}
+56
Переглянути файл
@@ -495,6 +495,8 @@ then run `openidea-plugin check`.
| `host::reveal_view(view)` | `views.reveal` | Brings one of your declared `[[contributes.views]]` to the front in the calling window. |
| `host::post_view_message(view, text)` | `views.post-message` | To the script of the view's `html` body. |
| `host::open_terminal(title, program, args)` | `views.open-terminal` | A terminal tab in the invoking window running the approved `process:<program>` in the project root: output that keeps coming, interactive sessions. |
| `host::register_run_target(project, target)` | `run-targets.register` | API 1.4: project-scoped, read-only argv wrapper; requires its process grant, executable pin and project trust; remote projects run on the server. |
| `host::unregister_run_target(project, id)` | `run-targets.unregister` | Withdraw this plugin's target; remembered prompt answers remain. |
| `host::start_run(config, args, debug)` | `run.start` | API 1.4: start an owned configuration in this window's Run tool window; returns an id, followed by `run-exited`. Approved `process:` program; commands/events only. |
| `host::open_terminal_session(key, title, cmd)` | `views.open-terminal-session` | API 1.4: keyed, pinned terminal in this window, append-only env; returns its operation id and later `terminal-exited`. |
| `host::write_terminal(key, text)` | `views.write-terminal` | API 1.4: write only to this plugin's still-running terminal in this window; trusted project, commands/events only. |
@@ -2060,3 +2062,57 @@ one dismisses the balloon and runs the command in the receiving window with
its normal editor and project context. No capability is needed. Invalid or
undeclared actions reject the whole notification. Labels are limited to 256
bytes and arguments to 64 KiB. Plain `host::notify` behaves as before.
### Plugin-provided run targets (API 1.4)
`host::register_run_target(project, target)` registers or replaces a read-only,
project-scoped target owned by the plugin. `host::unregister_run_target(project,
id)` removes it. `PluginRunTarget` has `id`, `name`, a granted `process:` `program`,
`args`, `workdir_args`, optional `container_root`, and `commands` (pairs of tool
names and replacement argv). Targets appear in Settings › Run Targets and every
run configuration's Run on selector, labelled with their plugin. They survive
idle instance reclamation; stopping, disabling, reloading or uninstalling a plugin
withdraws them. Registrations and execution for remote projects are on the server.
A missing target fails the run rather than silently using the local tool.
For each launch the host checks project trust and the wrapper's current process
grant and executable pin, including per-project executable choices. Debugging on
plugin targets returns `invalid`; language servers are not run in these targets.
There are at most 32 targets per plugin/project, 64 unique command overrides and
256 arguments per prefix (16 KiB each, 256 KiB metadata per registration).
The host constructs argv directly, without a shell:
- No override: `program + args + workdir_args + command + command arguments`.
- Override matching `wrap::program_name(command)` (basename without `.exe`, `.cmd`
or `.bat`): `program + override + workdir_args + command arguments`. The override
replaces **both** the prefix and the command name and includes the tool itself.
DDEV, for example: `program = "ddev"`, `args = ["exec"]`,
`commands = [("composer", ["composer"])]` runs `php x.php` as
`ddev exec php x.php` and `composer install` as `ddev composer install`.
Local absolute tool paths outside the project use the tool basename.
When `container_root` is set, project paths in argv map under that root. Each
`workdir_args` element may contain `{cwd}`; for example `["--dir", "{cwd}"]`.
The host substitutes the configuration's working directory mapped under
`container_root`. It omits **all** workdir arguments when there is no container
root or the working directory is outside the project. Without `workdir_args`,
the wrapper manages its container directory itself. The wrapper process always
starts in the configuration's **local** working directory, so tools such as DDEV
can find their project. Configuration env and env files reach the local wrapper;
no generic env-forwarding flags are added. Container env is forwarded only if
the wrapper's own conventions allow it.
Registration never changes a selection. The first registration prompts the
project's windows: “Use <name> for running PHP / Node / Composer in this project?”
with **Use** / **Not now**. The first answer is remembered on the host per
project + plugin + target id. Use sets the project's default run target and its
PHP and Node run-target choices; Not now leaves settings alone. Interpreters
also have a Run in target choice in Settings (Default run target, Local machine,
or a named target). The `languages.php.runTarget` / `languages.node.runTarget`
settings store a selector id, empty for the default, or `local` for local execution. Code-created PHP/Node runs,
Composer/npm scripts, PHPUnit and Node tests use that choice through the normal
Run flow. Explicit per-configuration targets take precedence. Choosing Local
machine explicitly overrides defaults. Language servers, tool discovery/version
probes and external analysis helpers remain local to the host.
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
1fff539520d04708c37de01116f55f2453d638600cd879d0494d405427d7253e
ff03abdb82800057592e18466292e642ad18f644eab5855993cd67e00850698b
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
da99bca60545937b82fc6f88aeca392cd991c6d8f21bbd04fb25965c3cb24856
6429c38a0dbc856e4b992e4ec80148e75b54a87730c8e1b137169d259f3d6d54
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
334dc90682133da39fa190e0a95a85d32bbeeadba704c918122fe390d3989c6d
41c3f77d244a40c27a52cd66b1514dea9be0cb6cde85515d72f67cd1b8dabab1
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
d0886a4b074f2cdb119a8c74bf13b95592a3f4f4b1df80dffca92554560821dc
14f8678dd23d0dd9d6e25b4af27a6d964010eebd5715c6ea8fe49aff91811dbe
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
1aaa0540c035bcf93dc81756b771ebb77f70bebf63cf43cededc80a0688c1aac
765857e31af345347bda02016f4162e90cd5e3f4fc4d19957d867ea1a0d88b02
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
c062aec81853deafa036eac3174475935f41ff0fb75567aba570be64bb6dc4e2
f1b38b7bde8db372ef45077db017d2612712bc4ff1d3946136e3b3bc2c197a75
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
0a1a92812b92b7d62ec662d73316767cb8c0435c7b4823842ba873be7bfa771d
661638c93c0e695bf61b647289cf5f242c5d057fa1ebc176768166053254d364
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
e036b4f5dc4d6e072ebaa4d3be8072236c130a6ec3c5d303f2a0680245d4e223
ccbfb3bd2f763aaca519947d7205236108201919effd848f7963c850337f0773
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
2a48ef3332a70b6b71ebc0469dcb01e8ba8c56cdfc360af0fc75b27886d76577
d83934c41880875ac20ffa119dba61d9fc04339653df1cbcc2da9f6465360dcf
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
815f433e3a004079ab0cc2e9f07943488df17e933735b86875fc980d4ccff506
1f423f8744f7470b43b364ed3b42b283039a3700fa908b7052d163afe9fdb427
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
6e70e57bf86e2d65e0b299e8ec02f9e74323a6d5ca8507bae5b4ccd59dbcefe3
4f70b1ec6d7ba5e67d5d49607ba30185cd7c0842b229a732ad6f17bf32ebb24c
+13
Переглянути файл
@@ -178,3 +178,16 @@ impl crate::Event {
(kind == expected).then(|| serde_json::from_str(data).ok()).flatten()
}
}
/// A plugin-owned argv wrapper for project runs (API 1.4).
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PluginRunTarget {
pub id: String,
pub name: String,
pub program: String,
pub args: Vec<String>,
pub workdir_args: Vec<String>,
pub container_root: Option<String>,
pub commands: Vec<(String, Vec<String>)>,
}
+27
Переглянути файл
@@ -690,6 +690,24 @@ mod imp {
}
}
pub fn register_run_target(project: &ProjectRes, target: &crate::PluginRunTarget) -> Result<(), Error> {
wit::run_targets::register(
project,
&wit::run_targets::RunTarget {
id: target.id.clone(),
name: target.name.clone(),
program: target.program.clone(),
args: target.args.clone(),
workdir_args: target.workdir_args.clone(),
container_root: target.container_root.clone(),
commands: target.commands.clone(),
},
)
.map_err(error)
}
pub fn unregister_run_target(project: &ProjectRes, id: &str) {
wit::run_targets::unregister(project, id);
}
pub fn start_run(config: &str, args: &[String], debug: bool) -> Result<String, Error> {
wit::run::start(config, args, debug).map_err(error)
}
@@ -1599,3 +1617,12 @@ pub fn open_content_tab(tab: &crate::ContentTab) -> Result<(), Error> {
pub fn reply_content_tab(request: &str, reply: &crate::ContentTabReply) -> Result<(), Error> {
imp::reply_content_tab(request, reply)
}
/// Registers/replaces a read-only project target. Requires the program's process grant.
pub fn register_run_target(project: &Project, target: &crate::PluginRunTarget) -> Result<(), Error> {
imp::register_run_target(&project.inner, target)
}
/// Withdraws a target owned by this plugin.
pub fn unregister_run_target(project: &Project, id: &str) {
imp::unregister_run_target(&project.inner, id);
}
+28
Переглянути файл
@@ -150,6 +150,7 @@ struct State {
terminal_writes: Vec<(String, String)>,
content_tabs: BTreeMap<String, crate::ContentTab>,
content_replies: Vec<(String, crate::ContentTabReply)>,
run_targets: BTreeMap<(String, String), crate::PluginRunTarget>,
run_configurations: BTreeMap<String, crate::PluginRunConfiguration>,
configuration_runs: Vec<(String, String, Vec<String>, bool)>,
log_tabs: Vec<MockLogTab>,
@@ -478,6 +479,10 @@ impl MockHost {
self.state.borrow().locations.clone()
}
/// Registered targets of this mock plugin, scoped by project root.
pub fn run_targets(&self) -> BTreeMap<(String, String), crate::PluginRunTarget> {
self.state.borrow().run_targets.clone()
}
/// Configurations available to start_run in native tests.
pub fn set_run_configurations(&self, configs: Vec<crate::PluginRunConfiguration>) {
self.state.borrow_mut().run_configurations = configs.into_iter().map(|c| (c.id.clone(), c)).collect();
@@ -1754,6 +1759,29 @@ pub mod current {
Ok(())
}
pub fn register_run_target(project: &ProjectRes, target: &crate::PluginRunTarget) -> Result<(), Error> {
with(|s| {
require(s, &format!("process:{}", target.program))?;
if target.id.is_empty()
|| target.name.is_empty()
|| target
.args
.iter()
.chain(&target.workdir_args)
.chain(target.commands.iter().flat_map(|(_, a)| a))
.any(|a| a.contains('\0'))
{
return Err(Error::Invalid("invalid run target".into()));
}
s.run_targets.insert((project.root.clone(), target.id.clone()), target.clone());
Ok(())
})
}
pub fn unregister_run_target(project: &ProjectRes, id: &str) {
with(|s| {
s.run_targets.remove(&(project.root.clone(), id.into()));
});
}
pub fn start_run(config: &str, args: &[String], debug: bool) -> Result<String, Error> {
with(|s| {
let c = s.run_configurations.get(config).ok_or_else(|| Error::NotFound(config.into()))?;
Loaded 100 of 131 files, more files were not shown because too many files have changed in this diff. Show more