Files
openidea/crates/ide-plugin/tests/fixtures/execution/src/lib.rs
T
l0ng-ai 74e66a5dae feat(plugins): environment and debugger for plugin run configurations (API 1.9) (#3476)
Plugin run configurations could not set environment variables, and Debug
only worked when a source file in the arguments let the IDE infer a
debugger, so a plugin could run `func start` for an Azure Functions app but
not debug the worker it starts.

API 1.9 adds the optional `launch-configurations` export, preferred over
`run-configurations` when a component has both. Each configuration can add
environment variables (only names the IDE's environment doesn't already
have, like `process` commands) and name a debugger: launch the program
under a language's debugger, or run it and attach to the first process of
an Attach to Process kind that the run starts. Only the run's own
descendants are candidates; the IDE waits up to a minute while the run
lasts and otherwise leaves it running without the debugger. Remote projects
resolve the process on the server.

The SDK gets `LaunchConfigurations` / `launch_configurations`, the README
and docs describe the export, and the bundled components and fixtures are
rebuilt for 1.9.
2026-11-15 11:01:12 +08:00

205 lines
8.2 KiB
Rust

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> {
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)
}
"target-overrides" => {
let project = ctx.project().ok_or_else(|| Error::Invalid("no project".into()))?;
let workdir_args = match arg {
Some("empty") => Some(vec![]),
Some("own") => Some(vec!["--working-dir={cwd}".into()]),
Some("invalid") => Some(vec!["bad\0arg".into()]),
_ => None,
};
host::register_run_target_with_overrides(
&project,
&PluginRunTargetWithOverrides {
id: "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![PluginCommandOverride {
name: "composer".into(),
args: vec!["composer".into()],
workdir_args,
}],
},
)?;
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)
}
"terminal" => host::open_terminal_session(
"session",
"Execution",
&host::Command::new("execution-tool").args(["interactive"]),
)
.map(Some),
"write" => {
host::write_terminal("session", arg.unwrap_or("input\n"))?;
Ok(None)
}
"content" => {
host::open_content_tab(&ContentTab {
key: "config".into(),
title: "Config".into(),
content: "hello".into(),
actions: vec![ContentAction {
id: "save".into(),
label: "Save".into(),
save: true,
..Default::default()
}],
..Default::default()
})?;
Ok(None)
}
"diff" => {
host::open_diff(
&ContentDiff {
left: "before\n".into(),
right: "after\n".into(),
title: Some("Review".into()),
..Default::default()
},
Some("src/review.rs"),
)?;
Ok(None)
}
"events" => host::storage::get("events"),
"validation" => host::storage::get("validation"),
_ => Err(Error::NotFound(id.into())),
}
}
fn handle_events(&mut self, events: &[Event], _: &Invocation) {
let mut received: Vec<serde_json::Value> =
host::storage::get("events").unwrap().and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default();
for event in events {
if let Event::Other { kind, data } = event {
received.push(serde_json::json!({"kind": kind, "data": data}));
if kind == "content-tab-action" {
let a: ContentTabAction = serde_json::from_str(data).unwrap();
host::reply_content_tab(
&a.request_id,
&ContentTabReply { saved: Some(true), status: Some("Saved".into()), ..Default::default() },
)
.unwrap();
}
}
}
host::storage::set("events", &serde_json::to_string(&received).unwrap()).unwrap();
}
}
impl LaunchConfigurations for Execution {
fn launch_configurations(&mut self, _: &str) -> Vec<PluginLaunchConfiguration> {
vec![
PluginLaunchConfiguration {
config: PluginRunConfiguration {
id: "dynamic".into(),
name: "Dynamic tests".into(),
program: "execution-tool".into(),
args: vec!["test".into()],
test: true,
framework: Some("plugin".into()),
..Default::default()
},
env: vec![("OPENIDEA_EXECUTION_FIXTURE".into(), "1".into())],
debugger: Some(Debugger::Launch { language: "python".into() }),
},
PluginLaunchConfiguration {
config: PluginRunConfiguration {
id: "worker".into(),
name: "Worker".into(),
program: "execution-tool".into(),
args: vec!["start".into()],
..Default::default()
},
env: Vec::new(),
debugger: Some(Debugger::AttachChild {
kind: "dotnet".into(),
command_contains: Some("Worker.dll".into()),
}),
},
]
}
}
impl TestResults for Execution {
fn select_tests(&mut self, config: &str, tests: &[Vec<String>]) -> Option<Vec<String>> {
match tests.first()?.first()?.as_str() {
"none" => return None,
"trap" => panic!("selection failed"),
"timeout" => loop {
std::hint::spin_loop();
},
_ => {}
}
Some(std::iter::once(config.to_owned()).chain(tests.iter().map(|p| p.join("::"))).collect())
}
fn parse(&mut self, _: &str, chunk: &str) -> Vec<PluginTestEvent> {
if chunk == "trap" {
panic!("parser failed");
}
vec![
PluginTestEvent::SuiteStarted(TestStart {
id: "suite".into(),
parent: None,
name: "Suite".into(),
location: None,
}),
PluginTestEvent::TestStarted(TestStart {
id: "test".into(),
parent: Some("suite".into()),
name: "Test".into(),
location: None,
}),
PluginTestEvent::Passed(TestPassed { id: "test".into(), duration_ms: Some(7) }),
]
}
}
impl RunTargetValidation for Execution {
fn validate(&mut self, project: &str, target: &str, launch: &RunTargetLaunch) -> Result<(), String> {
host::storage::set(
"validation",
&format!("{project}|{target}|{:?}|{}|{}", launch.operation, launch.program, launch.cwd),
)
.unwrap();
match target {
"refuse" => Err("Project runtime is stopped".into()),
"long-refusal" => Err("x".repeat(10000)),
"trap" => panic!("validator failed"),
"timeout" => {
let _task = host::begin_task("Validation", true);
loop {
std::hint::spin_loop();
}
}
_ => Ok(()),
}
}
}
register_plugin!(Execution, launch_configurations, test_results, run_target_validation);