From 1cebc09e7e5212afe72310425072357ff9a15c2c Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Wed, 18 Nov 2026 20:16:26 +0800 Subject: [PATCH 1/2] =?UTF-8?q?feat(run-config):=20=E6=8F=92=E4=BB=B6?= =?UTF-8?q?=E5=A3=B0=E6=98=8E=E5=90=AF=E5=8A=A8=E5=89=8D=E4=BB=BB=E5=8A=A1?= =?UTF-8?q?=EF=BC=88beforeLaunchTasks=200=EF=BC=89=EF=BC=8C=E5=90=AF?= =?UTF-8?q?=E5=8A=A8=E5=89=8D=E5=8F=AF=E6=B7=BB=E5=8A=A0=E6=8F=92=E4=BB=B6?= =?UTF-8?q?=E4=BB=BB=E5=8A=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 对标 IntelliJ IDEA 运行配置“启动前”的“添加新任务”(如 Go 插件的“运行 Go 命令”), 由插件注入任务种类,Core 不含任何插件特判(1lck/Lithe-IDEA#2100)。 - 契约:buildSystems[].beforeLaunchTasks(最多 16 个),声明方式同 runConfigurationTypes, 但不能写 execution,arguments 不能用 ${userArguments};任务 ID 与类型 ID 各自唯一; requires.beforeLaunchTasks 0;语言文件新增 beforeLaunchTasks 一节;新 fixture before-launch-tasks/。 - 运行配置:beforeLaunch 步骤新增 {task: {pluginID, buildSystemID, type, values}}, 在拥有该列表的配置的工作目录里运行;步骤对象不允许其他键。 - 命令:新增 runConfig.checkBeforeLaunchTask(校验“添加新任务”表单值)和 build.beforeLaunchTaskPlan(把任务步骤展开成 argv 计划);runConfig.beforeLaunch、 updateOptions、saveEditorChanges 新增 runTypePlugins;拒绝码新增 taskNotDeclared、 invalidTaskValues;确认指纹覆盖任务、值和工作目录。 - 编辑器:beforeLaunch 字段新增 tasks(任务种类与表单),字段值里的任务步骤为 {task, name, summary, values},插件已卸载的为 {task, name, summary, missing: true}。 - 修复:runConfigurationTypes 的必填 arguments 字段留空以前不会被拒绝。 - 文档:rust-core-api、run-configuration-v2 schema、契约 README 与两份 schema、 能力表、API 总表、build-systems 领域页、协议更新记录(同时把已合入的 #96 managedRuntimes 从“待合入”移进时间线和首次出现表)。没有新增宿主方法或通知。 --- .../run-configuration-v2.schema.json | 30 +- rust/contracts/rust-core-api.md | 126 +++-- rust/crates/build/src/commands.rs | 38 +- rust/crates/build/src/manifest.rs | 6 + rust/crates/build/src/manifest/checks.rs | 23 + rust/crates/build/src/manifest/options.rs | 6 + rust/crates/build/src/manifest/run_types.rs | 114 +++- rust/crates/build/src/run_types.rs | 284 +++++++--- rust/crates/core/src/protocol/command.rs | 8 + .../core/src/runtime/dispatcher/build.rs | 5 + .../core/src/runtime/dispatcher/run_config.rs | 94 ++-- .../core/src/tests/before_launch_tasks.rs | 506 ++++++++++++++++++ .../core/src/tests/declarative_plugins.rs | 4 + rust/crates/core/src/tests/mod.rs | 1 + rust/crates/execution/src/configuration.rs | 11 +- .../src/configuration/before_launch.rs | 424 ++++++++++++--- .../execution/src/configuration/declared.rs | 193 ++++++- .../execution/src/configuration/document.rs | 7 +- .../execution/src/configuration/editing.rs | 23 +- .../execution/src/configuration/form.rs | 77 ++- .../execution/src/configuration/requests.rs | 14 +- rust/crates/plugin-manifest/src/validation.rs | 6 + rust/crates/plugin-model/src/capabilities.rs | 5 + shared/plugins/contract/v1/README.md | 64 ++- .../before-launch-tasks.plugin.json | 67 +++ .../before-launch-tasks/l10n/zh-Hans.json | 19 + .../contract/v1/plugin-l10n.schema.json | 12 +- .../contract/v1/plugin-manifest.schema.json | 31 ++ shared/plugins/reference/api-catalog.md | 4 +- .../reference/capabilities-and-versions.md | 2 + .../reference/domains/build-systems.md | 12 +- .../plugins/reference/protocol-changelog.md | 6 +- 32 files changed, 1879 insertions(+), 343 deletions(-) create mode 100644 rust/crates/core/src/tests/before_launch_tasks.rs create mode 100644 shared/plugins/contract/v1/fixtures/before-launch-tasks/before-launch-tasks.plugin.json create mode 100644 shared/plugins/contract/v1/fixtures/before-launch-tasks/l10n/zh-Hans.json diff --git a/rust/contracts/run-configuration-v2.schema.json b/rust/contracts/run-configuration-v2.schema.json index 651472ef..38507826 100644 --- a/rust/contracts/run-configuration-v2.schema.json +++ b/rust/contracts/run-configuration-v2.schema.json @@ -56,7 +56,7 @@ }, "runTypeReference": { "type": "object", - "description": "A configuration of a run configuration type a build system declares (buildSystems[].runConfigurationTypes).", + "description": "A configuration of a run configuration type a build system declares (buildSystems[].runConfigurationTypes), or a before-launch task step of a task it declares (buildSystems[].beforeLaunchTasks).", "required": ["pluginID", "buildSystemID", "type"], "properties": { "pluginID": { "$ref": "#/$defs/runTypeIdentifier" }, @@ -258,14 +258,28 @@ "beforeLaunch": { "type": "array", "maxItems": 16, - "description": "Built-in process runs started in order before this one; each must exit with 0 first. A layer replaces the whole list.", + "description": "Steps started in order before this one: built-in process runs and tasks installed plugins declare; each must exit with 0 first. A layer replaces the whole list.", "items": { - "type": "object", - "required": ["configuration"], - "properties": { - "configuration": { "type": "string", "minLength": 1, "maxLength": 256 } - }, - "additionalProperties": false + "oneOf": [ + { + "type": "object", + "description": "A built-in process run of the same project to start first.", + "required": ["configuration"], + "properties": { + "configuration": { "type": "string", "minLength": 1, "maxLength": 256 } + }, + "additionalProperties": false + }, + { + "type": "object", + "description": "A task a plugin declares, run in this configuration's working directory.", + "required": ["task"], + "properties": { + "task": { "$ref": "#/$defs/runTypeReference" } + }, + "additionalProperties": false + } + ] } }, "disabled": { "type": "boolean" }, diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 493a6136..89aad8eb 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -526,6 +526,7 @@ or removing a command fails until the table changes in the same commit. | `build.modelPlan` | Expand the command that prints a command-sourced build model, or the request a build provider answers | | `build.taskPlan` | Expand one declared or model task for a workspace, project, or target | | `build.runConfigurationPlan` | Expand a saved configuration of a declared run configuration type into an argv plan | +| `build.beforeLaunchTaskPlan` | Expand a plugin task step of a Before Launch list into an argv plan | | `build.testPlan` | Plan a test run for a scope, suite, or case and say where its reports will be | | `build.prepareDebugPlan` | Plan same-plugin native debug preparation | | `build.decodeDebugPreparation` | Validate an existing instance-contained native debug program and bounded process facts | @@ -722,7 +723,8 @@ or removing a command fails until the table changes in the same commit. | `runConfig.deleteConfiguration` | Return the file changes that delete a saved user configuration | | `runConfig.copyConfiguration` | Return the file changes that save a copy of any configuration under a new name | | `runConfig.arrange` | Return the file changes that move configurations between folders and save the list order | -| `runConfig.beforeLaunch` | Expand the built-in process runs a configuration starts first, and say whether the user must confirm them | +| `runConfig.beforeLaunch` | Expand the process runs and plugin tasks a configuration starts first, and say whether the user must confirm them | +| `runConfig.checkBeforeLaunchTask` | Check the values of a plugin task step being added or edited and return the step for the `beforeLaunch` editor value | | `runConfig.createLaunchPlan` | Project one effective configuration into a platform-neutral Run or Debug plan | | `runConfig.providerLaunchInputs` | Resolve user choices for a provider-owned launch | | `git.status` | Resolve the repository, current branch, and working-tree changes | @@ -4040,6 +4042,16 @@ program arguments, working directory and environment in `args`, `cwd` and with the plugin it needs. `build.runConfigurationPlan` expands it into the argv plan the host starts like a task plan. +A build system's `beforeLaunchTasks` (`beforeLaunchTasks` 0) declare kinds of +step for a configuration's Before Launch list the same way, such as Run Go +Command: an `id`, `displayName`, `description?`, `icon?`, fields and +`arguments`, translated from the `beforeLaunchTasks` section of the plugin's +localization. A task runs to completion in the working directory of the +configuration whose list names it, so it declares no `execution` and its +arguments cannot take `${userArguments}`. Tasks are not configuration types: +`runConfig.configurationTypes` does not list them; the `beforeLaunch` field +offers them (see [Steps before launch](#steps-before-launch)). + #### Folders and order A configuration may name a `folder`, the folder it is listed in within its @@ -4073,50 +4085,91 @@ an omitted field keeps the saved value, and saving the defaults removes #### Steps before launch A configuration of any provider may name `beforeLaunch`, an ordered list of at -most 16 `{configuration}` steps. Each step is the ID of a built-in process run -of the same project, which starts and must exit with 0 before the next step, -and the configuration itself, starts (IntelliJ IDEA's "Before launch: Run -Another Configuration"). A shell script that compiles a module or a program -that generates sources is saved as a process run and named as a step, so a step -has the interpreter, arguments, working directory, environment and launch plan -a process run already has. A layer replaces the whole list: an empty list in the +most 16 steps, each of which starts and must exit with 0 before the next step, +and the configuration itself, starts (IntelliJ IDEA's "Before launch"). A step +is one of: + +- `{configuration}`: the ID of a built-in process run of the same project + ("Run Another Configuration"). A shell script that compiles a module or a + program that generates sources is saved as a process run and named as a + step, so the step has the interpreter, arguments, working directory, + environment and launch plan a process run already has. +- `{task: {pluginID, buildSystemID, type, values}}`: a task an installed + plugin declares (see [Plugin-declared types](#plugin-declared-types)), with + the values of its fields by declared field ID, saved like the `values` of a + declared configuration. It runs in the working directory of the + configuration whose list names it, without program arguments or an + environment of its own. + +A step has no other keys. A layer replaces the whole list: an empty list in the local layer hides the steps the project layer names. A step that names the -configuration itself makes the configuration unavailable -(`invalidConfiguration`); a step whose target is missing or cannot run is -reported when the configuration starts, so the list still resolves. - -`runConfig.beforeLaunch` accepts `{root, configurationId, localDocument?}` and -replies `{status: "ok", steps, confirmation}` or `{status: "rejected", refusal: -{code, configurationId}}`. `steps` are the runs to start, in order, each -`{configurationId, name, summary}`; `summary` is one line naming what it starts -(the program or script and its arguments) for the confirmation. A step whose run -names steps of its own starts them first, as starting that run alone would; at -most 32 steps are expanded. `refusal.code` is `notFound` (no such -configuration), `notAllowed` (not a built-in process run), `unavailable` (the -run cannot start, see its `availability`), `cycle` (a step leads back to a -configuration being started) or `tooLong`; `configurationId` names the step. +configuration itself, or a task reference of an invalid shape, makes the +configuration unavailable (`invalidConfiguration`); a step whose target is +missing or cannot run, such as a task whose plugin was removed, is reported +when the configuration starts, so the list still resolves. + +The commands below take the installed plugins as `runTypePlugins`, like the +editor commands of declared types; without them every task step is +`taskNotDeclared`. + +`runConfig.beforeLaunch` accepts `{root, configurationId, localDocument?, +runTypePlugins?}` and replies `{status: "ok", steps, confirmation}` or +`{status: "rejected", refusal: {code, configurationId, task?}}`. `steps` are +what to start, in order: a run is `{configurationId, name, summary}`, a task +`{task, name, summary, workingDirectory}`; `summary` is one line naming what it +starts (the program or script and its arguments, or the task's visible field +values) for the confirmation. A step whose run names steps of its own starts +them first, as starting that run alone would, and its task steps run in that +run's working directory; at most 32 steps are expanded. `refusal.code` is +`notFound` (no such configuration), `notAllowed` (not a built-in process run), +`unavailable` (the run cannot start, see its `availability`), `cycle` (a step +leads back to a configuration being started), `tooLong`, `taskNotDeclared` (no +installed plugin declares the task) or `invalidTaskValues` (its saved values no +longer fit the task, such as an empty required field); `configurationId` names +the step, or for a task the configuration whose list names it, and `task` +(`{pluginID, buildSystemID, type}`) is set for the two task codes. `confirmation` is `{fingerprint}` when the project layer names any of the expanded lists, and `null` otherwise. Those steps run code from the repository that nobody chose on this machine, so the host asks the user before running them, showing each step's name and summary, and remembers the fingerprint per project in its own storage, never in the project. The fingerprint is a SHA-256 -over the lists and the definitions of the runs they start, so changing either -asks again; it does not cover the contents of a script file a step runs. A list -the local layer names, including one that starts runs the project defines, was -chosen on this machine and needs no confirmation. The host runs each step -through `runConfig.createLaunchPlan`, writes its output to the console of the -configuration that starts, stops it with that configuration, and does not start -the configuration when a step fails or is stopped. Run and Debug both run the -steps. +over the lists, the definitions of the runs they start, and each task with its +values and working directory, so changing any of them asks again; it does not +cover the contents of a script file a step runs or the plugin's declaration of +a task. A list the local layer names, including one that starts runs the +project defines, was chosen on this machine and needs no confirmation. The +host runs a run step through `runConfig.createLaunchPlan` and a task step +through `build.beforeLaunchTaskPlan`, writes their output to the console of the +configuration that starts, stops them with that configuration, and does not +start the configuration when a step fails or is stopped. Run and Debug both run +the steps. `runConfig.editorForm` adds a `beforeLaunch` field to every process run with -`candidates: [{id, name}]`, the runnable process runs other than the edited one; -its value is the list of IDs. `runConfig.saveConfiguration` checks it like -`runConfig.beforeLaunch` and reports `{field: "beforeLaunch", code}` with -`notFound`, `notAllowed`, `unavailable`, `conflict` (a cycle) or `tooLong`. -`runConfig.updateOptions` and `runConfig.saveEditorChanges` accept an optional -`beforeLaunch` list of IDs for any configuration: omission keeps the saved +`candidates: [{id, name}]`, the runnable process runs other than the edited +one, and `tasks`, each task kind the installed plugins declare as `{runType, +displayName, description?, icon?, fields, values}`: `runType` is `{pluginID, +buildSystemID, type}`, and `fields` and `values` describe the task's own form, +keyed `field:` like the editor of a declared type, with the defaults as +`values`. The field's value is the list of steps: a run is its configuration +ID, a task `{task, name, summary, values}` with the form values of its fields, +and a task no installed plugin declares `{task, name, summary, missing: true}`, +so the editor still shows and keeps it. + +`runConfig.checkBeforeLaunchTask` accepts `{root, runType, values?, +runTypePlugins?}`, the form values of a task step being added or edited, and +replies `{status: "ok", step}` with the step to put in the field's value, or +`{status: "invalid", errors: [{field, code}]}` with the codes and `field:` +keys of a declared editor. A task no installed plugin declares fails the call +with `not_supported`. Nothing is written; the step is saved with the +configuration. + +`runConfig.saveConfiguration` checks the field like `runConfig.beforeLaunch` +and reports `{field: "beforeLaunch", code}` with `notFound`, `notAllowed`, +`unavailable`, `conflict` (a cycle), `tooLong`, `taskNotDeclared` or +`invalidTaskValues`. `runConfig.updateOptions` and `runConfig.saveEditorChanges` +accept an optional `beforeLaunch` list for any configuration, in the field's +value shape, with an optional `runTypePlugins`: omission keeps the saved steps, an empty list removes them from the edited layer (and in the local layer hides the project's), and a list that cannot run is `invalid_request` with `beforeLaunch: ` in the details. @@ -5199,6 +5252,7 @@ and the directories are absolute host paths used only as substitution text. | `build.modelPlan`, `build.dependencyPlan` | plan fields plus `project?` (dependencies), `outputFile?`, and for provider sources `refresh?` (boolean) and `tool?: { executable }` (absolute path) | `plan`: `{ buildSystemID, root, arguments, environment, workingDirectory, execution, optionFingerprint, output, decoder, executesProjectCode, mayUseNetwork }`; for a `provider` source `{ buildSystemID, root, provider: { method, params }, decoder, executesProjectCode, mayUseNetwork, optionFingerprint }`, where `method` is `lithe/build/model` or `lithe/build/dependencies` and `params` is `{ buildSystemID, root, options, optionArguments, environment, project?, refresh?, tool? }`; `refresh` appears only when `true` and `tool` only when the host sent it | | `build.taskPlan` | plan fields plus `task`, `project?`, `target?`, `modelTask?`, `userArguments?` | command `plan` with `arguments`, `environment`, `workingDirectory`, `execution`, and `optionFingerprint`; a provider task instead returns `provider: {method: "lithe/build/execute", params}` with effective options, selected task/entities, user arguments and effect metadata | | `build.runConfigurationPlan` | `manifest`, `buildSystemID`, required `workspaceRoot`, and `request: {configurationId, localDocument?, instances: [{root, options?, modelInputs?}], pluginDirectory?, workspaceStateDirectory?}` | `plan` as `build.taskPlan` returns it plus `runType: {pluginID, buildSystemID, type}`: the global arguments, then the type's `arguments` with the saved field values, the instance's options and the configuration's program arguments, at the configuration's working directory, with its environment over the options'. The instance is the deepest one whose root holds the working directory, or the only one; `plugin.build.invalidSelection` when several exist and none holds it or the configuration belongs to another plugin or build system, `plugin.build.unavailable` when the type is no longer declared, `plugin.build.invalidRunConfiguration` with `field: values.` when a saved value no longer fits. A configuration that is missing, disabled, unavailable or of another provider fails the call | +| `build.beforeLaunchTaskPlan` | `manifest`, `buildSystemID`, required `workspaceRoot`, and `request: {task, workingDirectory, instances: [{root, options?, modelInputs?}], pluginDirectory?, workspaceStateDirectory?}`, with `task` and `workingDirectory` as `runConfig.beforeLaunch` returned the step | `plan` as `build.taskPlan` returns it plus `beforeLaunchTask: {pluginID, buildSystemID, type}`: the global arguments, then the task's `arguments` with the saved field values and the instance's options, at the step's working directory with the options' environment, as a `task` execution. The instance is chosen as for `build.runConfigurationPlan`; `plugin.build.invalidSelection` when several exist and none holds the working directory or the task belongs to another plugin or build system, `plugin.build.unavailable` when the task is no longer declared, `plugin.build.invalidBeforeLaunchTask` with `field: values.` when a saved value no longer fits. A working directory outside the workspace fails the call | | `build.testPlan` | plan fields plus `project?`, `target?`, `suite?`, `case?`, `userArguments?`, `projects?` (the model's project directories) | command plan or `provider: {method: "lithe/build/test", params}`, plus `results`: `null`, `{ decoder, reports }` with workspace-relative globs (for the selected project, or for the root and every listed project when none is selected), or command-only `{ decoder: "hostIntegration" }`. Command filters that templates cannot place, such as a case without its suite when the tool only addresses `Suite#case`, are `plugin.build.invalidSelection`; Provider filters remain separate typed values and must be declared supported | | `build.testDiscoveryPlan` | common plan fields plus `refresh?`, `tool?`; no project/output file | `plan.provider` for `lithe/build/discoverTests`, only with `test.discovery: true`, using the same effective options and effect metadata | | `build.decodeTestDiscovery` | common plan fields plus canonical `result` | `discovery.tests` with validated `{id, suite, case, project?, target?}` selectors; bounded at 10,000 items/32 MiB, deterministic and exactly runnable; malformed replies reject in full | diff --git a/rust/crates/build/src/commands.rs b/rust/crates/build/src/commands.rs index 279a09cb..5e284680 100644 --- a/rust/crates/build/src/commands.rs +++ b/rust/crates/build/src/commands.rs @@ -15,7 +15,7 @@ use super::outputs::{ DecodeTestResultsRequest, SyncFingerprintRequest, }; use super::plans::{self, OutputPlanRequest, TaskPlanRequest, TestPlanRequest}; -use super::run_types::{self, RunConfigurationPlanRequest}; +use super::run_types::{self, BeforeLaunchTaskPlanRequest, RunConfigurationPlanRequest}; use super::test_discovery::{self, DecodeTestDiscoveryRequest}; use super::tree::{self, ModelTreeRequest}; use super::BuildManifest; @@ -147,6 +147,42 @@ pub fn build_run_configuration_plan_command( ))) } +/// `build.beforeLaunchTaskPlan`: the argv plan of a before-launch task step +/// as `runConfig.beforeLaunch` returned it, in `workspaceRoot`, which it +/// requires. A task the build system no longer declares, a working directory +/// outside the project, or values the task cannot run fail the call. +pub fn build_before_launch_task_plan_command( + payload: Value, +) -> Result { + let command = "build.beforeLaunchTaskPlan"; + let payload: BuildPayload = decode_payload(payload, command)?; + let workspace_root = payload.workspace_root.as_deref().ok_or_else(|| { + CoreError::new( + ErrorCode::InvalidRequest, + "build.beforeLaunchTaskPlan needs workspaceRoot", + ) + })?; + let request = &payload.request; + let launch = lithe_execution::declared_task_launch( + workspace_root, + request.task.clone(), + &request.working_directory, + )?; + Ok(outcome(M::validate(payload.manifest).and_then( + |manifest| { + let build_system = find_build_system(&manifest, &payload.build_system_id)?; + run_types::before_launch_task_plan( + manifest.id(), + build_system, + &launch, + request, + &launch.root, + ) + .map(|plan| ("plan", plan)) + }, + ))) +} + /// `build.detect`: build-system instances of a workspace, with the models /// that need no process. pub fn build_detect_command(payload: Value) -> Result { diff --git a/rust/crates/build/src/manifest.rs b/rust/crates/build/src/manifest.rs index 6f8b3047..e1b8d888 100644 --- a/rust/crates/build/src/manifest.rs +++ b/rust/crates/build/src/manifest.rs @@ -107,6 +107,12 @@ pub struct BuildSystemDeclaration { /// Configurations dialog; `runConfigurationTypes` 0. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub(crate) run_configuration_types: Vec, + /// Kinds of step a configuration runs before it starts, offered in the + /// "Add New Task" menu of its Before Launch list; `beforeLaunchTasks` 0. + /// They are declared like run configuration types, without an execution + /// or program arguments. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub(crate) before_launch_tasks: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] pub(crate) test: Option, #[serde(default, skip_serializing_if = "Option::is_none")] diff --git a/rust/crates/build/src/manifest/checks.rs b/rust/crates/build/src/manifest/checks.rs index 55922255..3a089ff1 100644 --- a/rust/crates/build/src/manifest/checks.rs +++ b/rust/crates/build/src/manifest/checks.rs @@ -89,6 +89,26 @@ fn program(build_system: &BuildSystemDeclaration) -> Value { }) }) .collect(); + // A task's command line runs like a run configuration's, so it is + // reviewed the same way; it has no execution. + let before_launch_tasks: Vec = build_system + .before_launch_tasks + .iter() + .map(|task| { + json!({ + "id": task.id, + "arguments": task.arguments, + "fields": task.fields.iter().map(|field| json!({ + "id": field.id, + "kind": field.kind, + "default": field.default, + "choices": field.choices.iter().map(|choice| &choice.value).collect::>(), + "visibleWhen": field.visible_when, + "arguments": field.arguments, + })).collect::>(), + }) + }) + .collect(); let mut program = json!({ "kind": "buildSystem", "buildSystemID": build_system.id, @@ -111,6 +131,9 @@ fn program(build_system: &BuildSystemDeclaration) -> Value { if !run_types.is_empty() { program["runConfigurationTypes"] = json!(run_types); } + if !before_launch_tasks.is_empty() { + program["beforeLaunchTasks"] = json!(before_launch_tasks); + } // Build requests reaching a language server change what that process // is asked to do, so the shared form is part of this entry. if let Some(ProviderDeclaration::LanguageServer(shared)) = &build_system.provider { diff --git a/rust/crates/build/src/manifest/options.rs b/rust/crates/build/src/manifest/options.rs index b2fd6dfe..3d3a533a 100644 --- a/rust/crates/build/src/manifest/options.rs +++ b/rust/crates/build/src/manifest/options.rs @@ -224,6 +224,12 @@ impl BuildSystemDeclaration { &run_type.arguments, )); } + for (index, task) in self.before_launch_tasks.iter().enumerate() { + lists.push(( + format!("{field}.beforeLaunchTasks[{index}].arguments"), + &task.arguments, + )); + } if let Some(test) = &self.test { lists.push((format!("{field}.test.arguments"), &test.arguments)); } diff --git a/rust/crates/build/src/manifest/run_types.rs b/rust/crates/build/src/manifest/run_types.rs index 5d4cbd4d..dbed0123 100644 --- a/rust/crates/build/src/manifest/run_types.rs +++ b/rust/crates/build/src/manifest/run_types.rs @@ -1,10 +1,14 @@ //! `runConfigurationTypes`: kinds of run configuration a build system adds to -//! the Run/Debug Configurations dialog. +//! the Run/Debug Configurations dialog, and `beforeLaunchTasks`: kinds of step +//! a configuration runs before it starts. //! //! A type is data only: the fields its editor shows and the argv template //! those fields fill. The host draws the fields Core describes, Core checks //! and stores the values, and a run expands the template with them, so a //! plugin adds a configuration kind such as `Go Build` without a backend. +//! A before-launch task is declared the same way; it runs to completion in +//! the owning configuration's working directory and takes no program +//! arguments, so it has neither an `execution` nor `${userArguments}`. use super::*; @@ -14,7 +18,8 @@ const MAX_FIELD_ARGUMENTS: usize = 8; /// Longest description of a type or a field. const MAX_DESCRIPTION: usize = 512; -/// One kind of run configuration the user can create. +/// One kind of run configuration the user can create, or one kind of +/// before-launch task. #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(crate) struct RunTypeDeclaration { @@ -91,6 +96,25 @@ pub(crate) enum RunFieldKind { Arguments, } +/// Which list of a build system a declaration belongs to. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum RunTypeRole { + /// `runConfigurationTypes`: a configuration the user creates and runs. + Configuration, + /// `beforeLaunchTasks`: a step of another configuration's Before Launch list. + BeforeLaunchTask, +} + +impl RunTypeRole { + /// The manifest key of the list. + pub(crate) fn key(self) -> &'static str { + match self { + Self::Configuration => "runConfigurationTypes", + Self::BeforeLaunchTask => "beforeLaunchTasks", + } + } +} + impl RunFieldKind { /// Whether another field can be shown depending on this one's value. fn controls_visibility(self) -> bool { @@ -113,9 +137,23 @@ impl BuildSystemDeclaration { !self.run_configuration_types.is_empty() } - /// The run configuration type `id`. - pub(crate) fn run_type(&self, id: &str) -> Option<&RunTypeDeclaration> { - self.run_configuration_types + /// Whether the build system adds before-launch tasks, which + /// `beforeLaunchTasks` introduced. + pub fn has_before_launch_tasks(&self) -> bool { + !self.before_launch_tasks.is_empty() + } + + /// The declarations of one list. + pub(crate) fn run_types(&self, role: RunTypeRole) -> &[RunTypeDeclaration] { + match role { + RunTypeRole::Configuration => &self.run_configuration_types, + RunTypeRole::BeforeLaunchTask => &self.before_launch_tasks, + } + } + + /// The declaration `id` of one list. + pub(crate) fn run_type(&self, role: RunTypeRole, id: &str) -> Option<&RunTypeDeclaration> { + self.run_types(role) .iter() .find(|run_type| run_type.id == id) } @@ -125,22 +163,32 @@ impl BuildSystemDeclaration { field: &str, options: &BTreeSet, ) -> Validation<()> { - if self.run_configuration_types.len() > MAX_RUN_TYPES { - return Err(invalid( - format!("{field}.runConfigurationTypes"), - "Too many run configuration types.", - )); - } - let mut ids = BTreeSet::new(); - for (index, run_type) in self.run_configuration_types.iter().enumerate() { - let field = format!("{field}.runConfigurationTypes[{index}]"); - if !is_entry_identifier(&run_type.id) || !ids.insert(run_type.id.clone()) { + for role in [RunTypeRole::Configuration, RunTypeRole::BeforeLaunchTask] { + let list = format!("{field}.{}", role.key()); + let declarations = self.run_types(role); + if declarations.len() > MAX_RUN_TYPES { return Err(invalid( - format!("{field}.id"), - "Run configuration type IDs are unique identifiers that start with a letter.", + list, + match role { + RunTypeRole::Configuration => "Too many run configuration types.", + RunTypeRole::BeforeLaunchTask => "Too many before-launch tasks.", + }, )); } - run_type.validate(&field, options)?; + let mut ids = BTreeSet::new(); + for (index, run_type) in declarations.iter().enumerate() { + let field = format!("{list}[{index}]"); + if !is_entry_identifier(&run_type.id) || !ids.insert(run_type.id.clone()) { + return Err(invalid( + format!("{field}.id"), + match role { + RunTypeRole::Configuration => "Run configuration type IDs are unique identifiers that start with a letter.", + RunTypeRole::BeforeLaunchTask => "Before-launch task IDs are unique identifiers that start with a letter.", + }, + )); + } + run_type.validate(&field, options, role)?; + } } Ok(()) } @@ -157,7 +205,12 @@ impl RunTypeDeclaration { template::user_argument_references(&self.arguments) == 1 } - fn validate(&self, field: &str, options: &BTreeSet) -> Validation<()> { + fn validate( + &self, + field: &str, + options: &BTreeSet, + role: RunTypeRole, + ) -> Validation<()> { check_text( &self.display_name, &format!("{field}.displayName"), @@ -169,11 +222,20 @@ impl RunTypeDeclaration { if let Some(icon) = &self.icon { icon.validate_at(&format!("{field}.icon"))?; } - if self.execution == Some(BuildExecution::Service) { - return Err(invalid( - format!("{field}.execution"), - "A run configuration type runs an application or a task.", - )); + match role { + RunTypeRole::Configuration if self.execution == Some(BuildExecution::Service) => { + return Err(invalid( + format!("{field}.execution"), + "A run configuration type runs an application or a task.", + )); + } + RunTypeRole::BeforeLaunchTask if self.execution.is_some() => { + return Err(invalid( + format!("{field}.execution"), + "A before-launch task always runs to completion; it declares no execution.", + )); + } + _ => {} } if self.fields.len() > MAX_RUN_FIELDS { return Err(invalid(format!("{field}.fields"), "Too many fields.")); @@ -191,9 +253,11 @@ impl RunTypeDeclaration { } let arguments_field = format!("{field}.arguments"); check_argument_count(&self.arguments, &arguments_field)?; + // A before-launch task has no program arguments field, so its + // command line cannot name them. let allowed = Allowed { root: true, - user_arguments: true, + user_arguments: role == RunTypeRole::Configuration, options: Some(options), fields: Some(&ids), ..Allowed::none() diff --git a/rust/crates/build/src/run_types.rs b/rust/crates/build/src/run_types.rs index 627d4217..6c932cbc 100644 --- a/rust/crates/build/src/run_types.rs +++ b/rust/crates/build/src/run_types.rs @@ -8,18 +8,24 @@ //! stores. `build.runConfigurationPlan` reads a saved configuration of such a //! type and expands the type's template into an argv plan, like a task plan, //! so the host starts it as it starts any build command. +//! +//! Before-launch tasks (`beforeLaunchTasks`) are declared the same way and +//! become [`DeclaredRunType`]s of the [`DeclaredRole::BeforeLaunchTask`] +//! role. `build.beforeLaunchTaskPlan` expands a task step that +//! `runConfig.beforeLaunch` returned into the same kind of plan; a task +//! always runs to completion and takes no program arguments. use super::decode; use super::manifest::{ check_description, check_text, BuildExecution, BuildSystemDeclaration, RunFieldDeclaration, - RunFieldKind, RunTypeDeclaration, + RunFieldKind, RunTypeDeclaration, RunTypeRole, }; use super::plans::{self, invalid_selection, unavailable, PlanBase, PlanContext}; use super::template::{self, Values}; use super::BuildManifest; use lithe_execution::{ DeclaredChoice, DeclaredCondition, DeclaredField, DeclaredFieldKind, DeclaredLaunch, - DeclaredRunType, DeclaredValue, Execution, RunTypeKey, + DeclaredRole, DeclaredRunType, DeclaredValue, Execution, RunTypeKey, RunTypeReference, }; use lithe_plugin_model::settings::{parse_localization_file, present, LocalizationRequest}; use lithe_plugin_model::{PluginRejection, Validation}; @@ -34,12 +40,15 @@ use std::path::Path; const INVALID_LOCALIZATION: &str = "plugin.build.invalidLocalization"; /// Error code of a saved configuration whose values the type cannot run. const INVALID_RUN_CONFIGURATION: &str = "plugin.build.invalidRunConfiguration"; +/// Error code of a before-launch task step whose values the task cannot run. +const INVALID_BEFORE_LAUNCH_TASK: &str = "plugin.build.invalidBeforeLaunchTask"; /// Most plugins one editor request may name. const MAX_PLUGINS: usize = 512; /// Most build-system instances one plan request may name. const MAX_INSTANCES: usize = 4_096; -/// The installed plugins whose run configuration types the editor offers. +/// The installed plugins whose run configuration types and before-launch +/// tasks the editor offers. #[derive(Debug, Default, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct RunTypePlugins { @@ -64,8 +73,9 @@ pub struct RunTypePlugin { pub localizations: Option>, } -/// The types the plugins declare, in plugin and declaration order, with one -/// translation report per plugin that declares a type when a language is +/// The run configuration types and before-launch tasks the plugins declare, +/// in plugin and declaration order, each with its role, with one +/// translation report per plugin that declares either when a language is /// named: `{pluginID, language, candidates, maximumBytes, readRequired, /// applied, rejected}`, the report of `plugins.settings`. /// @@ -90,7 +100,9 @@ pub fn declared_run_types( let systems: Vec<&BuildSystemDeclaration> = manifest .build_systems() .iter() - .filter(|system| system.has_run_configuration_types()) + .filter(|system| { + system.has_run_configuration_types() || system.has_before_launch_tasks() + }) .collect(); if systems.is_empty() { continue; @@ -113,22 +125,23 @@ pub fn declared_run_types( } None => Localization::default(), }; - for system in systems { - for declaration in &system.run_configuration_types { - let text = localization - .types - .get(&(system.id.clone(), declaration.id.clone())); - types.push(declared(manifest.id(), system, declaration, text)); + for role in [RunTypeRole::Configuration, RunTypeRole::BeforeLaunchTask] { + for system in &systems { + for declaration in system.run_types(role) { + let text = localization.text(role, &system.id, &declaration.id); + types.push(declared(manifest.id(), system, role, declaration, text)); + } } } } Ok((types, reports)) } -/// The run type of a validated declaration, with translated text. +/// The run type or task of a validated declaration, with translated text. fn declared( plugin_id: &str, system: &BuildSystemDeclaration, + role: RunTypeRole, declaration: &RunTypeDeclaration, text: Option<&TypeText>, ) -> DeclaredRunType { @@ -149,6 +162,10 @@ fn declared( build_system_id: system.id.clone(), type_id: declaration.id.clone(), }, + role: match role { + RunTypeRole::Configuration => DeclaredRole::Configuration, + RunTypeRole::BeforeLaunchTask => DeclaredRole::BeforeLaunchTask, + }, display_name: text .and_then(|text| text.display_name.clone()) .unwrap_or_else(|| declaration.display_name.clone()), @@ -159,7 +176,7 @@ fn declared( .icon .as_ref() .map(|icon| serde_json::to_value(icon).expect("icons encode")), - execution: match declaration.execution() { + execution: match execution(role, declaration) { BuildExecution::Task => Execution::Task, // Validation rejects `service`. BuildExecution::Application | BuildExecution::Service => Execution::Application, @@ -169,6 +186,14 @@ fn declared( } } +/// How a started declaration behaves: a task always runs to completion. +fn execution(role: RunTypeRole, declaration: &RunTypeDeclaration) -> BuildExecution { + match role { + RunTypeRole::Configuration => declaration.execution(), + RunTypeRole::BeforeLaunchTask => BuildExecution::Task, + } +} + fn declared_field(field: &RunFieldDeclaration, text: Option<&FieldText>) -> DeclaredField { let options = text.and_then(|text| text.options.as_ref()); DeclaredField { @@ -213,13 +238,16 @@ fn declared_field(field: &RunFieldDeclaration, text: Option<&FieldText>) -> Decl } /// The part of a translation file this module reads: -/// `runConfigurationTypes..`. Other top-level keys -/// belong to other surfaces. +/// `runConfigurationTypes..` and +/// `beforeLaunchTasks..`. Other top-level keys belong +/// to other surfaces. #[derive(Deserialize)] #[serde(rename_all = "camelCase")] struct LocalizationFile { #[serde(default)] run_configuration_types: UniqueMap>, + #[serde(default)] + before_launch_tasks: UniqueMap>, } /// Translated text of one type, by the manifest field it replaces. @@ -250,42 +278,68 @@ struct FieldText { options: Option>, } -/// A checked translation of one plugin's types, by build system and type ID. +/// A checked translation of one plugin's types and tasks, by build system +/// and declaration ID. #[derive(Debug, Default)] struct Localization { types: BTreeMap<(String, String), TypeText>, + tasks: BTreeMap<(String, String), TypeText>, +} + +impl Localization { + fn entries(&mut self, role: RunTypeRole) -> &mut BTreeMap<(String, String), TypeText> { + match role { + RunTypeRole::Configuration => &mut self.types, + RunTypeRole::BeforeLaunchTask => &mut self.tasks, + } + } + + fn text(&self, role: RunTypeRole, system_id: &str, id: &str) -> Option<&TypeText> { + let entries = match role { + RunTypeRole::Configuration => &self.types, + RunTypeRole::BeforeLaunchTask => &self.tasks, + }; + entries.get(&(system_id.to_string(), id.to_string())) + } } /// Parses one translation file and checks it against the declarations: it -/// names only declared build systems, types, fields and choices, translates -/// only text the manifest has, and every text fits the manifest's limits. -/// A file that does not fit is refused whole. +/// names only declared build systems, types, tasks, fields and choices, +/// translates only text the manifest has, and every text fits the +/// manifest's limits. A file that does not fit is refused whole. fn decode_file(text: &str, systems: &[&BuildSystemDeclaration]) -> Validation { let file: LocalizationFile = parse_localization_file(text, INVALID_LOCALIZATION)?; let mut localization = Localization::default(); - for (system_id, types) in file.run_configuration_types.0 { - let field = format!("runConfigurationTypes.{system_id}"); - let system = systems - .iter() - .find(|system| system.id == system_id) - .ok_or_else(|| { - rejection( - &field, - "The plugin declares no build system with run configuration types under this ID.", - ) - })?; - for (type_id, text) in types.0 { - let field = format!("{field}.{type_id}"); - let declaration = system.run_type(&type_id).ok_or_else(|| { - rejection( - &field, - "The build system declares no run configuration type with this ID.", - ) - })?; - check_type_text(&text, declaration, &field)?; - localization - .types - .insert((system_id.clone(), type_id), text); + for (role, section) in [ + (RunTypeRole::Configuration, file.run_configuration_types), + (RunTypeRole::BeforeLaunchTask, file.before_launch_tasks), + ] { + let (no_system, no_entry) = match role { + RunTypeRole::Configuration => ( + "The plugin declares no build system with run configuration types under this ID.", + "The build system declares no run configuration type with this ID.", + ), + RunTypeRole::BeforeLaunchTask => ( + "The plugin declares no build system with before-launch tasks under this ID.", + "The build system declares no before-launch task with this ID.", + ), + }; + for (system_id, entries) in section.0 { + let field = format!("{}.{system_id}", role.key()); + let system = systems + .iter() + .find(|system| system.id == system_id && !system.run_types(role).is_empty()) + .ok_or_else(|| rejection(&field, no_system))?; + for (id, text) in entries.0 { + let field = format!("{field}.{id}"); + let declaration = system + .run_type(role, &id) + .ok_or_else(|| rejection(&field, no_entry))?; + check_type_text(&text, declaration, &field)?; + localization + .entries(role) + .insert((system_id.clone(), id), text); + } } } Ok(localization) @@ -315,7 +369,7 @@ fn check_type_text( .fields .iter() .find(|declared| &declared.id == id) - .ok_or_else(|| rejection(&field, "The type declares no field with this ID."))?; + .ok_or_else(|| rejection(&field, "The declaration has no field with this ID."))?; if let Some(title) = &field_text.title { relabel(check_text(title, &format!("{field}.title"), "title"))?; } @@ -414,6 +468,65 @@ pub(crate) struct RunTypeInstance { model_inputs: Option, } +/// `build.beforeLaunchTaskPlan`: the argv plan of one before-launch task +/// step, as `runConfig.beforeLaunch` returned it. +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct BeforeLaunchTaskPlanRequest { + /// The step's `task`: the plugin, build system, task ID and saved values. + pub(crate) task: RunTypeReference, + /// The step's `workingDirectory`, workspace-relative. + pub(crate) working_directory: String, + /// The detected instances of the build system, as in + /// `build.runConfigurationPlan`. + pub(crate) instances: Vec, + /// Absolute installed plugin directory, for `${pluginDir}`. + #[serde(default)] + pub(crate) plugin_directory: Option, + /// Absolute writable directory of this plugin for this workspace. + #[serde(default)] + pub(crate) workspace_state_directory: Option, +} + +/// What a plan takes from its request besides the launch. +struct PlanSources<'a> { + instances: &'a [RunTypeInstance], + plugin_directory: Option, + workspace_state_directory: Option, +} + +/// The wording and identity of one role in a plan. +struct PlanRole { + role: RunTypeRole, + other_owner: &'static str, + entry: &'static str, + code: &'static str, + required: &'static str, + does_not_fit: &'static str, + /// The plan key that names the kind. + key: &'static str, +} + +const CONFIGURATION_PLAN: PlanRole = PlanRole { + role: RunTypeRole::Configuration, + other_owner: "The run configuration belongs to another plugin or build system.", + entry: "the run configuration type", + code: INVALID_RUN_CONFIGURATION, + required: "A required field of the run configuration is empty.", + does_not_fit: "A saved value does not fit the run configuration type.", + key: "runType", +}; + +const TASK_PLAN: PlanRole = PlanRole { + role: RunTypeRole::BeforeLaunchTask, + other_owner: "The before-launch task belongs to another plugin or build system.", + entry: "the before-launch task", + code: INVALID_BEFORE_LAUNCH_TASK, + required: "A required field of the before-launch task is empty.", + does_not_fit: "A saved value does not fit the before-launch task.", + key: "beforeLaunchTask", +}; + /// The plan of `launch`, a saved configuration of a type `system` declares. /// /// The plan is the task plan shape plus `runType`: the global arguments and @@ -426,32 +539,71 @@ pub(crate) fn run_configuration_plan( launch: &DeclaredLaunch, request: &RunConfigurationPlanRequest, workspace_root: &Path, +) -> Validation { + declared_plan( + plugin_id, + system, + &CONFIGURATION_PLAN, + launch, + PlanSources { + instances: &request.instances, + plugin_directory: request.plugin_directory.clone(), + workspace_state_directory: request.workspace_state_directory.clone(), + }, + workspace_root, + ) +} + +/// The plan of `launch`, a before-launch task step of a task `system` +/// declares: the task plan shape plus `beforeLaunchTask`, the global +/// arguments and the task's arguments with the field values and the +/// instance's options, at the step's working directory. A task always runs +/// to completion. +pub(crate) fn before_launch_task_plan( + plugin_id: &str, + system: &BuildSystemDeclaration, + launch: &DeclaredLaunch, + request: &BeforeLaunchTaskPlanRequest, + workspace_root: &Path, +) -> Validation { + declared_plan( + plugin_id, + system, + &TASK_PLAN, + launch, + PlanSources { + instances: &request.instances, + plugin_directory: request.plugin_directory.clone(), + workspace_state_directory: request.workspace_state_directory.clone(), + }, + workspace_root, + ) +} + +fn declared_plan( + plugin_id: &str, + system: &BuildSystemDeclaration, + role: &PlanRole, + launch: &DeclaredLaunch, + sources: PlanSources<'_>, + workspace_root: &Path, ) -> Validation { let reference = &launch.reference; if reference.plugin_id != plugin_id || reference.build_system_id != system.id { - return Err(invalid_selection( - "The run configuration belongs to another plugin or build system.", - )); + return Err(invalid_selection(role.other_owner)); } - let declaration = system.run_type(&reference.type_id).ok_or_else(|| { - unavailable( - system, - &format!("the run configuration type {}", reference.type_id), - ) - })?; - let run_type = declared(plugin_id, system, declaration, None); + let declaration = system + .run_type(role.role, &reference.type_id) + .ok_or_else(|| unavailable(system, &format!("{} {}", role.entry, reference.type_id)))?; + let run_type = declared(plugin_id, system, role.role, declaration, None); let values = run_type .launch_values(&reference.values, workspace_root) .map_err(|error| { let message = match error.code { - "required" => "A required field of the run configuration is empty.", - _ => "A saved value does not fit the run configuration type.", + "required" => role.required, + _ => role.does_not_fit, }; - PluginRejection::at( - INVALID_RUN_CONFIGURATION, - format!("values.{}", error.field), - message, - ) + PluginRejection::at(role.code, format!("values.{}", error.field), message) })?; plans::check_user_arguments(&launch.arguments, &declaration.arguments)?; let mut field_arguments = Vec::new(); @@ -463,24 +615,24 @@ pub(crate) fn run_configuration_plan( .expect("launch values name declared fields"); field_arguments.push((id.clone(), field_value_arguments(field, value)?)); } - let instance = instance_of(&request.instances, &launch.working_directory)?; + let instance = instance_of(sources.instances, &launch.working_directory)?; let base = PlanBase { model_inputs: instance.model_inputs.clone(), root: instance.root.clone(), options: instance.options.clone(), - plugin_directory: request.plugin_directory.clone(), - workspace_state_directory: request.workspace_state_directory.clone(), + plugin_directory: sources.plugin_directory, + workspace_state_directory: sources.workspace_state_directory, }; let context = PlanContext::new(system, &base)?; let mut values = context.values(&launch.arguments); values.field_arguments = &field_arguments; let mut extra = Map::new(); extra.insert("workingDirectory".into(), json!(launch.working_directory)); - extra.insert("runType".into(), json!(reference.key())); + extra.insert(role.key.into(), json!(reference.key())); let mut plan = context.plan( &declaration.arguments, &values, - declaration.execution(), + execution(role.role, declaration), extra, )?; if let Some(environment) = plan["environment"].as_object_mut() { diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index b70eb2cd..4c255035 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -454,6 +454,8 @@ pub enum BuildCommand { TaskPlan, /// Expands a saved configuration of a declared run configuration type into an argv plan (`build.runConfigurationPlan`). RunConfigurationPlan, + /// Expands a before-launch task a build system declares into an argv plan (`build.beforeLaunchTaskPlan`). + BeforeLaunchTaskPlan, /// Expands a build test run and its result location (`build.testPlan`). TestPlan, /// Plans typed provider run preparation (`build.prepareRunPlan`). @@ -756,6 +758,8 @@ pub enum RunConfigCommand { Arrange, /// Expands the steps run before a configuration starts (`runConfig.beforeLaunch`). BeforeLaunch, + /// Checks the values of a plugin task step before launch (`runConfig.checkBeforeLaunchTask`). + CheckBeforeLaunchTask, /// Produces the process plan for one configuration (`runConfig.createLaunchPlan`). CreateLaunchPlan, /// Resolves user choices for a provider-owned launch (`runConfig.providerLaunchInputs`). @@ -1187,6 +1191,7 @@ impl CoreCommand { "build.modelPlan" => Some(Self::Build(BuildCommand::ModelPlan)), "build.taskPlan" => Some(Self::Build(BuildCommand::TaskPlan)), "build.runConfigurationPlan" => Some(Self::Build(BuildCommand::RunConfigurationPlan)), + "build.beforeLaunchTaskPlan" => Some(Self::Build(BuildCommand::BeforeLaunchTaskPlan)), "build.testPlan" => Some(Self::Build(BuildCommand::TestPlan)), "build.prepareDebugPlan" => Some(Self::Build(BuildCommand::PrepareDebugPlan)), "build.decodeDebugPreparation" => { @@ -1462,6 +1467,9 @@ impl CoreCommand { } "runConfig.arrange" => Some(Self::RunConfig(RunConfigCommand::Arrange)), "runConfig.beforeLaunch" => Some(Self::RunConfig(RunConfigCommand::BeforeLaunch)), + "runConfig.checkBeforeLaunchTask" => { + Some(Self::RunConfig(RunConfigCommand::CheckBeforeLaunchTask)) + } "runConfig.createLaunchPlan" => { Some(Self::RunConfig(RunConfigCommand::CreateLaunchPlan)) } diff --git a/rust/crates/core/src/runtime/dispatcher/build.rs b/rust/crates/core/src/runtime/dispatcher/build.rs index 1447e3bb..3b4e0056 100644 --- a/rust/crates/core/src/runtime/dispatcher/build.rs +++ b/rust/crates/core/src/runtime/dispatcher/build.rs @@ -56,6 +56,11 @@ pub(super) fn dispatch(command: BuildCommand, id: Option, payload: Value payload, crate::build::build_run_configuration_plan_command::, ), + BuildCommand::BeforeLaunchTaskPlan => plugin_response( + id, + payload, + crate::build::build_before_launch_task_plan_command::, + ), BuildCommand::PrepareDebugPlan => plugin_response( id, payload, diff --git a/rust/crates/core/src/runtime/dispatcher/run_config.rs b/rust/crates/core/src/runtime/dispatcher/run_config.rs index 93474b94..eda798a3 100644 --- a/rust/crates/core/src/runtime/dispatcher/run_config.rs +++ b/rust/crates/core/src/runtime/dispatcher/run_config.rs @@ -115,18 +115,18 @@ pub(super) fn dispatch( ), } } - RunConfigCommand::UpdateOptions => { - match serde_json::from_value::(payload) - .map_err(|error| { - CoreError::new(ErrorCode::InvalidRequest, "Invalid run options request") - .with_details(error.to_string()) - }) - .and_then(crate::execution::update_options) - { - Ok(data) => CoreResponse::success(id, data), - Err(error) => CoreResponse::failure(id, error), - } - } + RunConfigCommand::UpdateOptions => respond( + id, + with_run_types( + payload, + "Invalid run options request", + false, + |mut request: crate::execution::UpdateOptionsRequest, run_types| { + request.run_types = run_types; + crate::execution::update_options(request) + }, + ), + ), RunConfigCommand::UpdateToolPreferences => { match serde_json::from_value::(payload) .map_err(|error| { @@ -142,21 +142,18 @@ pub(super) fn dispatch( Err(error) => CoreResponse::failure(id, error), } } - RunConfigCommand::SaveEditorChanges => { - match serde_json::from_value::(payload) - .map_err(|error| { - CoreError::new( - ErrorCode::InvalidRequest, - "Invalid run configuration editor request", - ) - .with_details(error.to_string()) - }) - .and_then(crate::execution::save_editor_changes) - { - Ok(data) => CoreResponse::success(id, data), - Err(error) => CoreResponse::failure(id, error), - } - } + RunConfigCommand::SaveEditorChanges => respond( + id, + with_run_types( + payload, + "Invalid run configuration editor request", + false, + |mut request: crate::execution::UpdateOptionsRequest, run_types| { + request.run_types = run_types; + crate::execution::save_editor_changes(request) + }, + ), + ), RunConfigCommand::CreateUserConfiguration => { match serde_json::from_value::( payload, @@ -210,21 +207,30 @@ pub(super) fn dispatch( }, ), ), - RunConfigCommand::BeforeLaunch => { - match serde_json::from_value::(payload) - .map_err(|error| { - CoreError::new( - ErrorCode::InvalidRequest, - "Invalid run configuration before launch request", - ) - .with_details(error.to_string()) - }) - .and_then(crate::execution::before_launch) - { - Ok(data) => CoreResponse::success(id, data), - Err(error) => CoreResponse::failure(id, error), - } - } + RunConfigCommand::BeforeLaunch => respond( + id, + with_run_types( + payload, + "Invalid run configuration before launch request", + false, + |mut request: crate::execution::BeforeLaunchRequest, run_types| { + request.run_types = run_types; + crate::execution::before_launch(request) + }, + ), + ), + RunConfigCommand::CheckBeforeLaunchTask => respond( + id, + with_run_types( + payload, + "Invalid before-launch task request", + false, + |mut request: crate::execution::CheckBeforeLaunchTaskRequest, run_types| { + request.run_types = run_types; + crate::execution::check_before_launch_task(request) + }, + ), + ), RunConfigCommand::DeleteConfiguration => { match serde_json::from_value::(payload) .map_err(|error| { @@ -307,8 +313,8 @@ fn respond(id: Option, result: Result) -> CoreResponse } } -/// Runs an editor command that offers the run configuration types installed -/// plugins declare. The payload's `runTypePlugins` (`{language, plugins: +/// Runs a command that needs the run configuration types and before-launch +/// tasks installed plugins declare. The payload's `runTypePlugins` (`{language, plugins: /// [{manifest, localizations}]}`) is taken out and checked by the build /// crate; the rest is the command's request. With `report`, the answer /// carries the plugins' translation reports as `localizations`, so the host diff --git a/rust/crates/core/src/tests/before_launch_tasks.rs b/rust/crates/core/src/tests/before_launch_tasks.rs new file mode 100644 index 00000000..fe1cfeb8 --- /dev/null +++ b/rust/crates/core/src/tests/before_launch_tasks.rs @@ -0,0 +1,506 @@ +//! Before-launch tasks plugins declare in `buildSystems[].beforeLaunchTasks` +//! (API-29): the `beforeLaunch` editor field offers them as kinds of step, +//! `runConfig.checkBeforeLaunchTask` checks the step's form, +//! `runConfig.beforeLaunch` expands them with the runs, and +//! `build.beforeLaunchTaskPlan` turns one into the argv plan the host starts. + +use super::support::{apply_run_changes, temporary_root, write_run_document, Cleanup}; +use crate::execute_json; +use serde_json::{json, Value}; +use std::fs; + +macro_rules! contract_file { + ($path:literal) => { + include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../../shared/plugins/contract/v1/", + $path + )) + }; +} + +const MANIFEST: &str = + contract_file!("fixtures/before-launch-tasks/before-launch-tasks.plugin.json"); +const CHINESE: &str = contract_file!("fixtures/before-launch-tasks/l10n/zh-Hans.json"); +const PLUGIN: &str = "dev.lithe.fixture.before-launch-tasks"; + +fn manifest() -> Value { + serde_json::from_str(MANIFEST).unwrap() +} + +/// The whole reply, `ok` or not. +fn reply(command: &str, payload: Value) -> Value { + serde_json::from_str(&execute_json( + &json!({ "id": command, "command": command, "payload": payload }).to_string(), + )) + .unwrap() +} + +/// The data of a reply that must succeed. +fn call(command: &str, payload: Value) -> Value { + let reply = reply(command, payload); + assert_eq!(reply["ok"], true, "{command}: {reply}"); + reply["data"].clone() +} + +/// The `runTypePlugins` of a request with the fixture installed. +fn plugins() -> Value { + json!({ "plugins": [{ "manifest": manifest() }] }) +} + +fn task(id: &str) -> Value { + json!({ "pluginID": PLUGIN, "buildSystemID": "go", "type": id }) +} + +/// A saved task step of kind `id` with `values`. +fn task_step(id: &str, values: Value) -> Value { + let mut reference = task(id); + reference["values"] = values; + json!({ "task": reference }) +} + +fn executable(id: &str, cwd: &str, steps: Vec) -> Value { + let mut entry = json!({ + "id": id, "name": id.trim_start_matches("user:"), "provider": "process.executable", + "confidence": "declared", "extensions": {"process": {"program": "echo"}} + }); + if cwd != "." { + entry["cwd"] = json!(cwd); + } + if !steps.is_empty() { + entry["beforeLaunch"] = json!(steps); + } + entry +} + +fn before_launch_field(form: &Value) -> Value { + form["fields"] + .as_array() + .unwrap() + .iter() + .find(|field| field["id"] == "beforeLaunch") + .cloned() + .unwrap_or_else(|| panic!("no beforeLaunch field in {form}")) +} + +fn plan(root: &std::path::Path, request: Value) -> Value { + reply( + "build.beforeLaunchTaskPlan", + json!({ + "manifest": manifest(), + "buildSystemID": "go", + "workspaceRoot": root, + "request": request, + }), + ) +} + +#[test] +fn task_kinds_are_offered_on_the_step_field_and_not_as_configurations() { + let root = temporary_root("before-launch-task-kinds"); + let _cleanup = Cleanup(root.clone()); + write_run_document( + &root, + ".lithe/run/local.yaml", + &json!({"version": 2, "configurations": [executable("user:app", ".", vec![])]}), + ); + + // A task is a step, not a configuration the user creates. + let types = call( + "runConfig.configurationTypes", + json!({ "runTypePlugins": plugins() }), + ); + assert!( + types["types"] + .as_array() + .unwrap() + .iter() + .all(|item| item["provider"] != "build.run-type"), + "{types}" + ); + + let form = call( + "runConfig.editorForm", + json!({ + "root": root, "configurationId": "user:app", + "runTypePlugins": { "language": "zh-Hans", "plugins": [{ + "manifest": manifest(), + "localizations": { "l10n/zh-Hans.json": CHINESE }, + }] }, + }), + ); + assert_eq!(form["localizations"][0]["applied"], "l10n/zh-Hans.json"); + let field = before_launch_field(&form); + let tasks = field["tasks"].as_array().unwrap(); + assert_eq!(tasks.len(), 2, "{field}"); + assert_eq!(tasks[0]["runType"], task("command")); + assert_eq!(tasks[0]["displayName"], "运行 Go 命令"); + assert_eq!( + tasks[0]["description"], + "在配置的工作目录中运行一条 go 命令,例如 generate ./...。" + ); + assert_eq!(tasks[0]["icon"]["host"], "run"); + let command = &tasks[0]["fields"][0]; + assert_eq!(command["id"], "field:command", "{command}"); + assert_eq!(command["kind"], "arguments"); + assert_eq!(command["label"], "命令"); + assert_eq!(command["required"], true); + assert_eq!(tasks[0]["values"], json!({ "field:command": "" })); + assert_eq!(tasks[1]["displayName"], "Go 生成"); + assert_eq!( + tasks[1]["values"], + json!({ "field:verbose": false, "field:package": "./..." }) + ); + + // Without a plugin that declares tasks the field offers runs only. + let plain = call( + "runConfig.editorForm", + json!({ "root": root, "configurationId": "user:app" }), + ); + assert!( + before_launch_field(&plain).get("tasks").is_none(), + "{plain}" + ); +} + +#[test] +fn task_steps_are_checked_saved_and_reopened() { + let root = temporary_root("before-launch-task-save"); + let _cleanup = Cleanup(root.clone()); + let local = ".lithe/run/local.yaml"; + write_run_document( + &root, + local, + &json!({"version": 2, "configurations": [ + executable("user:app", ".", vec![]), + executable("user:gen", ".", vec![]), + ]}), + ); + + // The step's form is checked by field. + let check = |run_type: Value, values: Value| { + call( + "runConfig.checkBeforeLaunchTask", + json!({ "root": root, "runType": run_type, "values": values, "runTypePlugins": plugins() }), + ) + }; + let empty = check(task("command"), json!({ "field:command": " " })); + assert_eq!( + empty, + json!({ "status": "invalid", "errors": [{ "field": "field:command", "code": "required" }] }) + ); + let checked = check( + task("command"), + json!({ "field:command": "generate ./..." }), + ); + assert_eq!(checked["status"], "ok", "{checked}"); + let step = checked["step"].clone(); + assert_eq!( + step, + json!({ + "task": { + "pluginID": PLUGIN, "buildSystemID": "go", "type": "command", + "values": { "command": ["generate", "./..."] }, + }, + "name": "Run Go Command", + "summary": "generate ./...", + "values": { "field:command": "generate ./..." }, + }) + ); + let generate = check(task("generate"), json!({ "field:verbose": true })); + assert_eq!( + generate["step"]["summary"], "Print files ./...", + "{generate}" + ); + // A task no installed plugin declares fails the call. + let unknown = reply( + "runConfig.checkBeforeLaunchTask", + json!({ "root": root, "runType": task("vet"), "runTypePlugins": plugins() }), + ); + assert_eq!(unknown["error"]["code"], "not_supported", "{unknown}"); + + // The editor saves the step as the reference it names. + let form = call( + "runConfig.editorForm", + json!({ "root": root, "configurationId": "user:app", "runTypePlugins": plugins() }), + ); + let mut values = form["values"].as_object().unwrap().clone(); + values.insert("beforeLaunch".into(), json!([step, "user:gen"])); + let saved = call( + "runConfig.saveConfiguration", + json!({ + "root": root, "provider": "process.executable", "configurationId": "user:app", + "values": values, "runTypePlugins": plugins(), + }), + ); + assert_eq!(saved["status"], "saved", "{saved}"); + apply_run_changes(&root, &saved); + let document = serde_yaml_value(&fs::read_to_string(root.join(local)).unwrap()); + let entry = document["configurations"] + .as_array() + .unwrap() + .iter() + .find(|entry| entry["id"] == "user:app") + .cloned() + .unwrap(); + assert_eq!( + entry["beforeLaunch"], + json!([ + task_step("command", json!({ "command": ["generate", "./..."] })), + { "configuration": "user:gen" }, + ]), + "{document}" + ); + + // It reopens with its form values, and without the plugin as a step the + // editor keeps but cannot describe. + let reopened = call( + "runConfig.editorForm", + json!({ "root": root, "configurationId": "user:app", "runTypePlugins": plugins() }), + ); + assert_eq!( + reopened["values"]["beforeLaunch"], + json!([step, "user:gen"]) + ); + let removed = call( + "runConfig.editorForm", + json!({ "root": root, "configurationId": "user:app" }), + ); + assert_eq!( + removed["values"]["beforeLaunch"][0], + json!({ + "task": step["task"], "name": "command", "summary": "", "missing": true, + }) + ); + // Saving it without the plugin names why the list cannot run. + let mut values = removed["values"].as_object().unwrap().clone(); + values.insert("name".into(), json!("app")); + let refused = call( + "runConfig.saveConfiguration", + json!({ "root": root, "provider": "process.executable", "configurationId": "user:app", "values": values }), + ); + assert_eq!( + refused, + json!({ "status": "invalid", "errors": [{ "field": "beforeLaunch", "code": "taskNotDeclared" }] }) + ); + + // updateOptions checks a task step against the installed plugins too. + let update = |plugins: Option| { + let mut payload = json!({ + "root": root, "scope": "local", "configurationId": "user:gen", + "beforeLaunch": [task_step("generate", json!({}))], + }); + if let Some(plugins) = plugins { + payload["runTypePlugins"] = plugins; + } + reply("runConfig.updateOptions", payload) + }; + let missing = update(None); + assert_eq!(missing["ok"], false, "{missing}"); + assert!( + missing["error"]["details"] + .as_str() + .unwrap() + .contains("taskNotDeclared"), + "{missing}" + ); + let updated = update(Some(plugins())); + assert_eq!(updated["ok"], true, "{updated}"); + apply_run_changes(&root, &updated["data"]); + let gen = call( + "runConfig.beforeLaunch", + json!({ "root": root, "configurationId": "user:gen", "runTypePlugins": plugins() }), + ); + assert_eq!(gen["steps"][0]["task"]["type"], "generate", "{gen}"); +} + +#[test] +fn task_steps_run_in_the_owning_configuration_directory() { + let root = temporary_root("before-launch-task-expand"); + let _cleanup = Cleanup(root.clone()); + fs::create_dir_all(root.join("services/api")).unwrap(); + fs::create_dir_all(root.join("tools")).unwrap(); + let project = ".lithe/run/configurations.yaml"; + let generate = task_step( + "generate", + json!({ "verbose": true, "package": "./internal/..." }), + ); + let document = json!({"version": 2, "configurations": [ + executable("user:app", "services/api", vec![generate.clone(), json!({ "configuration": "user:gen" })]), + executable("user:gen", "tools", vec![task_step("command", json!({ "command": ["mod", "tidy"] }))]), + ]}); + write_run_document(&root, project, &document); + + // gen's own steps run first, each task in the directory of the + // configuration whose list names it. + let expand = |plugins: Value| { + call( + "runConfig.beforeLaunch", + json!({ "root": root, "configurationId": "user:app", "runTypePlugins": plugins }), + ) + }; + let app = expand(plugins()); + assert_eq!(app["status"], "ok", "{app}"); + assert_eq!( + app["steps"], + json!([ + { + "task": generate["task"], "name": "Go Generate", + "summary": "Print files ./internal/...", "workingDirectory": "services/api", + }, + { + "task": { + "pluginID": PLUGIN, "buildSystemID": "go", "type": "command", + "values": { "command": ["mod", "tidy"] }, + }, + "name": "Run Go Command", "summary": "mod tidy", "workingDirectory": "tools", + }, + { "configurationId": "user:gen", "name": "gen", "summary": "echo" }, + ]) + ); + // A project file names the lists, so the user confirms them; changing a + // task's values asks again. + let fingerprint = app["confirmation"]["fingerprint"].clone(); + assert_eq!(fingerprint.as_str().unwrap().len(), 64); + let mut changed = document.clone(); + changed["configurations"][0]["beforeLaunch"][0]["task"]["values"]["verbose"] = json!(false); + write_run_document(&root, project, &changed); + assert_ne!( + expand(plugins())["confirmation"]["fingerprint"], + fingerprint + ); + + // A task no installed plugin declares, or whose values no longer fit it, + // is refused by the configuration whose list names it. + let refused = expand(json!({ "plugins": [] })); + assert_eq!( + refused, + json!({ "status": "rejected", "refusal": { + "code": "taskNotDeclared", "configurationId": "user:app", "task": task("generate"), + } }) + ); + let mut emptied = document.clone(); + emptied["configurations"][1]["beforeLaunch"][0]["task"]["values"] = json!({}); + write_run_document(&root, project, &emptied); + assert_eq!( + expand(plugins())["refusal"], + json!({ "code": "invalidTaskValues", "configurationId": "user:gen", "task": task("command") }) + ); + write_run_document(&root, project, &document); + + // The host plans a step as runConfig.beforeLaunch returned it: the task's + // command line with the options of the instance holding its directory. + let instances = json!([ + { "root": ".", "options": { "tags": "root" } }, + { "root": "services/api", "options": { "tags": "api" } }, + ]); + let planned = plan( + &root, + json!({ "task": app["steps"][0]["task"], "workingDirectory": "services/api", "instances": instances }), + ); + assert_eq!(planned["data"]["status"], "ok", "{planned}"); + let value = &planned["data"]["plan"]; + assert_eq!( + value["arguments"], + json!(["generate", "-tags", "api", "-v", "./internal/..."]), + "{value}" + ); + assert_eq!(value["root"], "services/api"); + assert_eq!(value["workingDirectory"], "services/api"); + assert_eq!(value["execution"], "task"); + assert_eq!(value["beforeLaunchTask"], task("generate")); + assert!(value.get("runType").is_none(), "{value}"); + let tools = plan( + &root, + json!({ "task": app["steps"][1]["task"], "workingDirectory": "tools", "instances": instances }), + ); + assert_eq!( + tools["data"]["plan"]["arguments"], + json!(["mod", "tidy"]), + "{tools}" + ); + assert_eq!(tools["data"]["plan"]["root"], "."); + // Values that do not fit are named by field; a directory outside the + // project, or a task of another plugin, fails. + let empty = plan( + &root, + json!({ "task": task_step("command", json!({}))["task"], "workingDirectory": ".", "instances": instances }), + ); + assert_eq!(empty["data"]["status"], "rejected", "{empty}"); + assert_eq!( + empty["data"]["error"]["code"], + "plugin.build.invalidBeforeLaunchTask" + ); + assert_eq!(empty["data"]["error"]["field"], "values.command"); + let outside = plan( + &root, + json!({ "task": app["steps"][1]["task"], "workingDirectory": "../elsewhere", "instances": instances }), + ); + assert_eq!(outside["ok"], false, "{outside}"); + let mut foreign = app["steps"][1]["task"].clone(); + foreign["pluginID"] = json!("dev.lithe.fixture.other"); + let other = plan( + &root, + json!({ "task": foreign, "workingDirectory": "tools", "instances": instances }), + ); + assert_eq!(other["data"]["status"], "rejected", "{other}"); +} + +#[test] +fn before_launch_task_declarations_are_validated() { + let validate = |manifest: Value| { + lithe_plugin_manifest::validate_command(json!({ "manifest": manifest })).unwrap() + }; + assert_eq!( + validate(manifest())["status"], + "ok", + "{}", + validate(manifest()) + ); + + let mut missing = manifest(); + missing["requires"] + .as_object_mut() + .unwrap() + .remove("beforeLaunchTasks"); + assert_eq!(validate(missing)["status"], "rejected"); + + let tasks = "/buildSystems/0/beforeLaunchTasks"; + let cases = [ + // A task always runs to completion. + ("/0/execution", json!("task"), "plugin.manifest.invalid"), + // It has no program arguments to pass. + ( + "/0/arguments/-", + json!("${userArguments}"), + "plugin.template.invalid", + ), + ("/1/id", json!("command"), "plugin.manifest.invalid"), + ( + "/0/fields/0/id", + json!("go-command"), + "plugin.manifest.invalid", + ), + ]; + for (pointer, value, code) in cases { + let mut manifest = manifest(); + let (parent, key) = format!("{tasks}{pointer}") + .rsplit_once('/') + .map(|(parent, key)| (parent.to_string(), key.to_string())) + .unwrap(); + match manifest.pointer_mut(&parent).unwrap() { + Value::Object(object) => { + object.insert(key, value); + } + Value::Array(items) => items.push(value), + _ => unreachable!(), + } + let outcome = validate(manifest); + assert_eq!(outcome["status"], "rejected", "{pointer}: {outcome}"); + assert_eq!(outcome["error"]["code"], code, "{pointer}: {outcome}"); + } +} + +fn serde_yaml_value(text: &str) -> Value { + serde_yaml_ng::from_str(text).expect("run documents are YAML") +} diff --git a/rust/crates/core/src/tests/declarative_plugins.rs b/rust/crates/core/src/tests/declarative_plugins.rs index 361e86c2..26d9b138 100644 --- a/rust/crates/core/src/tests/declarative_plugins.rs +++ b/rust/crates/core/src/tests/declarative_plugins.rs @@ -71,6 +71,8 @@ const COMMAND_INSTALLER_PLANS: &str = contract_file!("fixtures/command-installers/command-installer-plans.json"); const RUN_CONFIGURATION_TYPES_FIXTURE: &str = contract_file!("fixtures/run-configuration-types/run-configuration-types.plugin.json"); +const BEFORE_LAUNCH_TASKS_FIXTURE: &str = + contract_file!("fixtures/before-launch-tasks/before-launch-tasks.plugin.json"); const INVALID_MANIFESTS: &str = contract_file!("fixtures/manifest/invalid-manifests.json"); const COMMAND_PLANS: &str = contract_file!("fixtures/languages/command-plans.json"); @@ -105,6 +107,7 @@ fn fixture(name: &str) -> Value { "project-generator-tool-field.plugin.json" => PROJECT_GENERATOR_TOOL_FIXTURE, "command-installer.plugin.json" => COMMAND_INSTALLER_FIXTURE, "run-configuration-types.plugin.json" => RUN_CONFIGURATION_TYPES_FIXTURE, + "before-launch-tasks.plugin.json" => BEFORE_LAUNCH_TASKS_FIXTURE, other => panic!("unknown fixture {other}"), }; serde_json::from_str(source).expect("fixture manifest is JSON") @@ -138,6 +141,7 @@ fn contract_fixtures_and_official_plugins_validate() { PROJECT_GENERATOR_TOOL_FIXTURE, COMMAND_INSTALLER_FIXTURE, RUN_CONFIGURATION_TYPES_FIXTURE, + BEFORE_LAUNCH_TASKS_FIXTURE, ] { let outcome = validate(serde_json::from_str(source).unwrap()); assert_eq!(outcome["status"], "ok", "{outcome}"); diff --git a/rust/crates/core/src/tests/mod.rs b/rust/crates/core/src/tests/mod.rs index 7619c281..5e903742 100644 --- a/rust/crates/core/src/tests/mod.rs +++ b/rust/crates/core/src/tests/mod.rs @@ -1,4 +1,5 @@ mod before_launch_steps; +mod before_launch_tasks; mod build_configuration; mod build_model_tree; mod build_project_options; diff --git a/rust/crates/execution/src/configuration.rs b/rust/crates/execution/src/configuration.rs index f5a3d810..b2f25306 100644 --- a/rust/crates/execution/src/configuration.rs +++ b/rust/crates/execution/src/configuration.rs @@ -36,12 +36,15 @@ mod validation; pub use arrangement::{arrange, ArrangeRequest}; pub(crate) use arrangement::{valid_folder, Arrangement}; -pub use before_launch::{before_launch, BeforeLaunchRequest, BeforeLaunchStep}; +pub use before_launch::{ + before_launch, check_before_launch_task, BeforeLaunchRequest, BeforeLaunchStep, + CheckBeforeLaunchTaskRequest, ConfigurationStep, TaskStep, +}; pub use copying::{copy_configuration, CopyConfigurationRequest}; pub use declared::{ - declared_launch, DeclaredChoice, DeclaredCondition, DeclaredField, DeclaredFieldKind, - DeclaredLaunch, DeclaredRunType, DeclaredValue, DeclaredValueError, RunTypeKey, - RunTypeReference, RUN_TYPE_PROVIDER, + declared_launch, declared_task_launch, DeclaredChoice, DeclaredCondition, DeclaredField, + DeclaredFieldKind, DeclaredLaunch, DeclaredRole, DeclaredRunType, DeclaredValue, + DeclaredValueError, RunTypeKey, RunTypeReference, RUN_TYPE_PROVIDER, }; pub use document::*; pub use editing::*; diff --git a/rust/crates/execution/src/configuration/before_launch.rs b/rust/crates/execution/src/configuration/before_launch.rs index 2f1257f9..abec5736 100644 --- a/rust/crates/execution/src/configuration/before_launch.rs +++ b/rust/crates/execution/src/configuration/before_launch.rs @@ -1,22 +1,32 @@ //! Steps run before a configuration starts (IDEA's "Before launch"). //! -//! A configuration may name, in order, built-in process runs to start first: -//! a shell script that compiles a module, a program that generates sources. -//! Each step must exit with 0 before the next one, and before the -//! configuration itself, starts. A step reuses everything a process run -//! already has (interpreter, arguments, working directory, environment and -//! launch plan), so a step is a reference to such a run, not a second command -//! format. A referenced run that names steps of its own runs them first, as -//! starting it on its own would. +//! A configuration may name, in order, steps to run first, each of which must +//! exit with 0 before the next one, and before the configuration itself, +//! starts. A step is one of: //! -//! Core checks the references, expands them into one ordered list, and says +//! - a built-in process run to start first: a shell script that compiles a +//! module, a program that generates sources. The step reuses everything the +//! run already has (interpreter, arguments, working directory, environment +//! and launch plan), so it is a reference to the run, not a second command +//! format. A referenced run that names steps of its own runs them first, as +//! starting it on its own would. +//! - a task an installed plugin declares (`buildSystems[].beforeLaunchTasks`), +//! such as running a Go command. The step keeps the task's reference with +//! the values of its fields, like a saved configuration of a declared kind, +//! and runs in the working directory of the configuration whose list names +//! it. +//! +//! Core checks the steps, expands them into one ordered list, and says //! whether the list needs the user's confirmation: steps a project file names //! run code from the repository the user did not choose on this machine, so -//! the host asks before running a list it has not seen. The host runs each -//! step through `runConfig.createLaunchPlan`. +//! the host asks before running a list it has not seen. The host runs a +//! process run through `runConfig.createLaunchPlan` and a task through +//! `build.beforeLaunchTaskPlan`. -use super::process::{self, ProcessOptions}; +use super::declared::{declared_task, DeclaredRunType, RunTypeKey, RunTypeReference}; +use super::process::{self, FieldError, ProcessOptions}; use super::*; +use serde_json::Map; use sha2::{Digest, Sha256}; /// Most steps one configuration names. @@ -26,17 +36,45 @@ const MAXIMUM_EXPANDED_STEPS: usize = 32; /// Longest configuration ID a step names. const MAXIMUM_ID_BYTES: usize = 256; -/// One step of `beforeLaunch`: the run configuration to start first. +/// One step of `beforeLaunch`: `{configuration}` or `{task}`. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(untagged)] +pub enum BeforeLaunchStep { + /// A run configuration to start first. + Configuration(ConfigurationStep), + /// A task a plugin declares. + Task(TaskStep), +} + +/// A step that starts a run configuration. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] -pub struct BeforeLaunchStep { +pub struct ConfigurationStep { /// ID of a built-in process run of the same project. pub configuration: String, } -/// Checks the shape of a configuration's own steps: their number, and IDs -/// that are not empty, not too long and not the configuration itself. Whether -/// a step names a runnable process run is checked when it starts, so a +/// A step that runs a task a plugin declares. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct TaskStep { + /// The plugin, build system and task ID, with the saved field values. + pub task: RunTypeReference, +} + +impl BeforeLaunchStep { + /// A step that starts the run configuration `id`. + pub fn configuration(id: impl Into) -> Self { + Self::Configuration(ConfigurationStep { + configuration: id.into(), + }) + } +} + +/// Checks the shape of a configuration's own steps: their number, IDs that +/// are not empty, not too long and not the configuration itself, and task +/// references of a valid shape. Whether a step names a runnable process run, +/// or a task an installed plugin declares, is checked when it starts, so a /// removed step target never hides the configuration from the list. pub(crate) fn validate_shape(configuration: &RunConfiguration) -> Result<(), CoreError> { let steps = &configuration.before_launch; @@ -47,13 +85,23 @@ pub(crate) fn validate_shape(configuration: &RunConfiguration) -> Result<(), Cor )); } for step in steps { - let id = step.configuration.as_str(); - if id.trim().is_empty() || id.len() > MAXIMUM_ID_BYTES || id == configuration.id { - return Err(CoreError::new( - ErrorCode::InvalidRequest, - "A step before launch names another run configuration", - ) - .with_details(id.to_string())); + match step { + BeforeLaunchStep::Configuration(step) => { + let id = step.configuration.as_str(); + if id.trim().is_empty() || id.len() > MAXIMUM_ID_BYTES || id == configuration.id { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "A step before launch names another run configuration", + ) + .with_details(id.to_string())); + } + } + BeforeLaunchStep::Task(step) => step.task.validate().map_err(|_| { + CoreError::new( + ErrorCode::InvalidRequest, + "A step before launch names an invalid task", + ) + })?, } } Ok(()) @@ -62,14 +110,19 @@ pub(crate) fn validate_shape(configuration: &RunConfiguration) -> Result<(), Cor /// Why a list of steps cannot run, for the field or the step it names. #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct StepRefusal { - /// `notFound`, `notAllowed`, `unavailable`, `cycle` or `tooLong`. + /// `notFound`, `notAllowed`, `unavailable`, `cycle`, `tooLong`, + /// `taskNotDeclared` or `invalidTaskValues`. pub(crate) code: &'static str, - /// The configuration the refusal is about. + /// The configuration the refusal is about; for a task, the one whose + /// list names it. pub(crate) configuration: String, + /// The task the refusal is about. + pub(crate) task: Option, } /// The resolved configurations by ID. pub(crate) struct Resolved { + root: PathBuf, by_id: BTreeMap, } @@ -82,6 +135,7 @@ impl Resolved { .with_details(error.to_string()) })?; Ok(Self { + root: root.to_path_buf(), by_id: configurations .into_iter() .map(|configuration| (configuration.id.clone(), configuration)) @@ -109,17 +163,23 @@ impl Resolved { candidates } - /// Expands `steps`, the steps `owner` would have, into the runs they - /// start, nested steps first. `owner` may be a configuration being - /// created, which nothing names yet. + /// Expands `steps`, the steps `owner` would have, into the runs and tasks + /// they start, nested steps first. `owner` may be a configuration being + /// created, which nothing names yet; its tasks then run at the workspace + /// root. `tasks` are the kinds installed plugins declare. pub(crate) fn expand( &self, owner: &str, steps: &[BeforeLaunchStep], + tasks: &[DeclaredRunType], ) -> Result { let mut expansion = Expansion::default(); let mut stack = vec![owner.to_string()]; - self.expand_into(steps, &mut stack, &mut expansion)?; + let working_directory = self + .by_id + .get(owner) + .map_or(".", |configuration| configuration.cwd.as_str()); + self.expand_into(steps, working_directory, tasks, &mut stack, &mut expansion)?; expansion.owners.insert(0, owner.to_string()); Ok(expansion) } @@ -127,41 +187,79 @@ impl Resolved { fn expand_into( &self, steps: &[BeforeLaunchStep], + working_directory: &str, + tasks: &[DeclaredRunType], stack: &mut Vec, expansion: &mut Expansion, ) -> Result<(), StepRefusal> { + let owner = stack.last().cloned().unwrap_or_default(); if steps.len() > MAXIMUM_STEPS { return Err(StepRefusal { code: "tooLong", - configuration: stack.last().cloned().unwrap_or_default(), + configuration: owner, + task: None, }); } for step in steps { - let id = &step.configuration; - let refuse = |code| StepRefusal { - code, - configuration: id.clone(), + let expanded = match step { + BeforeLaunchStep::Configuration(step) => { + let id = &step.configuration; + let refuse = |code| StepRefusal { + code, + configuration: id.clone(), + task: None, + }; + if stack.contains(id) { + return Err(refuse("cycle")); + } + let target = self.by_id.get(id).ok_or_else(|| refuse("notFound"))?; + if !process::is_process_provider(&target.provider) { + return Err(refuse("notAllowed")); + } + if target.availability.is_some() { + return Err(refuse("unavailable")); + } + if !target.before_launch.is_empty() { + stack.push(id.clone()); + expansion.owners.push(id.clone()); + self.expand_into( + &target.before_launch, + &target.cwd, + tasks, + stack, + expansion, + )?; + stack.pop(); + } + ExpandedStep::Run(Box::new(target.clone())) + } + BeforeLaunchStep::Task(step) => { + let reference = &step.task; + let refuse = |code| StepRefusal { + code, + configuration: owner.clone(), + task: Some(reference.key()), + }; + let task = declared_task(tasks, &reference.key()) + .map_err(|_| refuse("taskNotDeclared"))?; + task.launch_values(&reference.values, &self.root) + .map_err(|_| refuse("invalidTaskValues"))?; + ExpandedStep::Task(Box::new(ExpandedTask { + reference: reference.clone(), + name: task.display_name.clone(), + summary: task.summary(&reference.values), + working_directory: working_directory.to_string(), + })) + } }; - if stack.contains(id) { - return Err(refuse("cycle")); - } - let target = self.by_id.get(id).ok_or_else(|| refuse("notFound"))?; - if !process::is_process_provider(&target.provider) { - return Err(refuse("notAllowed")); - } - if target.availability.is_some() { - return Err(refuse("unavailable")); - } - if !target.before_launch.is_empty() { - stack.push(id.clone()); - expansion.owners.push(id.clone()); - self.expand_into(&target.before_launch, stack, expansion)?; - stack.pop(); - } if expansion.steps.len() >= MAXIMUM_EXPANDED_STEPS { - return Err(refuse("tooLong")); + return Err(StepRefusal { + code: "tooLong", + configuration: owner, + task: None, + }); } - expansion.steps.push(target.clone()); + expansion.steps.push(expanded); } Ok(()) } @@ -170,27 +268,102 @@ impl Resolved { /// Steps expanded for one start. #[derive(Default)] pub(crate) struct Expansion { - /// The runs to start, in order. - pub(crate) steps: Vec, + /// What to run, in order. + pub(crate) steps: Vec, /// The configurations whose step lists were read: the one that starts, /// then each referenced run that names steps of its own. pub(crate) owners: Vec, } +/// One step of an expanded list. Both variants are boxed because they differ +/// widely in size. +pub(crate) enum ExpandedStep { + /// A process run to start. + Run(Box), + /// A plugin task to run. + Task(Box), +} + +/// A plugin task of an expanded list. +pub(crate) struct ExpandedTask { + reference: RunTypeReference, + name: String, + summary: String, + /// The working directory of the configuration whose list names it. + working_directory: String, +} + /// A step that refused to expand, in the shape the host shows. fn refusal_value(refusal: &StepRefusal) -> Value { - json!({ "code": refusal.code, "configurationId": refusal.configuration }) + let mut value = json!({ "code": refusal.code, "configurationId": refusal.configuration }); + if let Some(task) = &refusal.task { + value["task"] = json!(task); + } + value } -/// The steps a list of configuration IDs names, read from an editor. -pub(crate) fn steps_of(ids: &[String]) -> Vec { - ids.iter() - .map(|id| BeforeLaunchStep { - configuration: id.trim().to_string(), +/// The steps of a `beforeLaunch` editor value: a configuration ID string, or +/// a task step as [`editor_items`] and `runConfig.checkBeforeLaunchTask` +/// return it, of which only `task` is read. `None` when an item has another +/// shape. +pub(crate) fn steps_from_editor(items: &[Value]) -> Option> { + items + .iter() + .map(|item| match item { + Value::String(id) => Some(BeforeLaunchStep::configuration(id.trim())), + Value::Object(object) => { + let task = serde_json::from_value(object.get("task")?.clone()).ok()?; + Some(BeforeLaunchStep::Task(TaskStep { task })) + } + _ => None, + }) + .collect() +} + +/// The `beforeLaunch` editor value of saved steps: a configuration ID for a +/// run, `{task, name, summary, values}` for a task an installed plugin +/// declares, and `{task, name, summary, missing: true}` for one no installed +/// plugin declares, so the editor still shows and keeps it. +pub(crate) fn editor_items(steps: &[BeforeLaunchStep], tasks: &[DeclaredRunType]) -> Vec { + steps + .iter() + .map(|step| match step { + BeforeLaunchStep::Configuration(step) => json!(step.configuration), + BeforeLaunchStep::Task(step) => match declared_task(tasks, &step.task.key()) { + Ok(task) => task.task_step_item(&step.task), + Err(_) => json!({ + "task": step.task, + "name": step.task.type_id, + "summary": "", + "missing": true, + }), + }, }) .collect() } +/// What a `beforeLaunch` editor field offers: the configurations a step may +/// start and the kinds of task installed plugins declare. +pub(crate) struct StepChoices { + /// `{id, name}` of each configuration, as [`Resolved::candidates`]. + pub(crate) candidates: Vec, + /// Each declared task kind, as `DeclaredRunType::task_kind_item`. + pub(crate) tasks: Vec, +} + +impl StepChoices { + pub(crate) fn new(resolved: &Resolved, owner: Option<&str>, kinds: &[DeclaredRunType]) -> Self { + Self { + candidates: resolved.candidates(owner), + tasks: kinds + .iter() + .filter(|kind| kind.role == super::declared::DeclaredRole::BeforeLaunchTask) + .map(DeclaredRunType::task_kind_item) + .collect(), + } + } +} + /// The layer a configuration's own step list was read from: the local layer /// when it names `beforeLaunch` there, else the project layer. fn list_from_project(layers: &Layers, id: &str) -> bool { @@ -253,18 +426,25 @@ pub struct BeforeLaunchRequest { /// Host-owned replacement for the machine-local layer. #[serde(default)] pub local_document: Option, + /// The kinds installed plugins declare, set by the dispatcher from + /// `runTypePlugins`. + #[serde(skip)] + pub run_types: Vec, } -/// `runConfig.beforeLaunch`: the runs to start, in order, before +/// `runConfig.beforeLaunch`: the runs and tasks to start, in order, before /// configuration `configurationId` starts. /// -/// Replies `{status: "ok", steps, confirmation}` with each step's -/// `{configurationId, name, summary}` and, when a project file names any of -/// the step lists, `confirmation: {fingerprint}`. The fingerprint covers the -/// lists and the runs they start; the host asks once per fingerprint before -/// running them. A list that cannot run replies `{status: "rejected", refusal: -/// {code, configurationId}}` with `notFound`, `notAllowed` (not a built-in -/// process run), `unavailable`, `cycle` or `tooLong`. +/// Replies `{status: "ok", steps, confirmation}` with each run step's +/// `{configurationId, name, summary}`, each task step's `{task, name, +/// summary, workingDirectory}` and, when a project file names any of the step +/// lists, `confirmation: {fingerprint}`. The fingerprint covers the lists and +/// what they start; the host asks once per fingerprint before running them. A +/// list that cannot run replies `{status: "rejected", refusal: {code, +/// configurationId, task}}` with `notFound`, `notAllowed` (not a built-in +/// process run), `unavailable`, `cycle`, `tooLong`, `taskNotDeclared` (no +/// installed plugin declares the task) or `invalidTaskValues` (its values no +/// longer fit the task); `task` is set for the last two. pub fn before_launch(request: BeforeLaunchRequest) -> Result { let root = existing_root(&request.root)?; let layers = read_layers(&root, None, request.local_document)?; @@ -275,7 +455,11 @@ pub fn before_launch(request: BeforeLaunchRequest) -> Result { .ok_or_else(|| { CoreError::new(ErrorCode::InvalidRequest, "Run configuration was not found") })?; - let expansion = match resolved.expand(&configuration.id, &configuration.before_launch) { + let expansion = match resolved.expand( + &configuration.id, + &configuration.before_launch, + &request.run_types, + ) { Ok(expansion) => expansion, Err(refusal) => { return Ok(json!({ "status": "rejected", "refusal": refusal_value(&refusal) })) @@ -284,8 +468,16 @@ pub fn before_launch(request: BeforeLaunchRequest) -> Result { let steps = expansion .steps .iter() - .map(|step| { - json!({ "configurationId": step.id, "name": step.name, "summary": summary(step) }) + .map(|step| match step { + ExpandedStep::Run(step) => { + json!({ "configurationId": step.id, "name": step.name, "summary": summary(step) }) + } + ExpandedStep::Task(task) => json!({ + "task": task.reference, + "name": task.name, + "summary": task.summary, + "workingDirectory": task.working_directory, + }), }) .collect::>(); let from_project = expansion @@ -297,8 +489,9 @@ pub fn before_launch(request: BeforeLaunchRequest) -> Result { Ok(json!({ "status": "ok", "steps": steps, "confirmation": confirmation })) } -/// Identity of what the steps start: each list and each run's definition. -/// Changing a list or a run the steps start asks the user again. +/// Identity of what the steps start: each list, each run's definition, and +/// each task with its values and working directory. Changing a list or what +/// it starts asks the user again. fn fingerprint(resolved: &Resolved, expansion: &Expansion) -> String { let lists = expansion .owners @@ -315,15 +508,19 @@ fn fingerprint(resolved: &Resolved, expansion: &Expansion) -> String { let runs = expansion .steps .iter() - .map(|step| { - json!({ + .map(|step| match step { + ExpandedStep::Run(step) => json!({ "id": step.id, "provider": step.provider, "args": step.args, "cwd": step.cwd, "env": step.env, "process": step.extensions.get("process"), - }) + }), + ExpandedStep::Task(task) => json!({ + "task": task.reference, + "workingDirectory": task.working_directory, + }), }) .collect::>(); let bytes = serde_json::to_vec(&json!({ "lists": lists, "runs": runs })) @@ -332,28 +529,83 @@ fn fingerprint(resolved: &Resolved, expansion: &Expansion) -> String { } /// Checks the steps an editor names for configuration `owner` against the -/// saved configurations; the code of the first that is wrong. +/// saved configurations and the installed plugins' tasks; the code of the +/// first that is wrong. pub(crate) fn check_edit( root: &Path, layers: &Layers, owner: &str, - ids: &[String], + steps: &[BeforeLaunchStep], + tasks: &[DeclaredRunType], ) -> Result, CoreError> { - if ids.len() > MAXIMUM_STEPS { + if steps.len() > MAXIMUM_STEPS { return Ok(Some("tooLong")); } - if ids - .iter() - .any(|id| id.trim().is_empty() || id.trim() == owner) - { - return Ok(Some("notAllowed")); + for step in steps { + match step { + BeforeLaunchStep::Configuration(step) => { + let id = step.configuration.trim(); + if id.is_empty() || id == owner { + return Ok(Some("notAllowed")); + } + } + BeforeLaunchStep::Task(step) => { + if step.task.validate().is_err() { + return Ok(Some("invalidTaskValues")); + } + } + } } let resolved = Resolved::read(root, layers)?; Ok(resolved - .expand(owner, &steps_of(ids)) + .expand(owner, steps, tasks) .err() .map(|refusal| match refusal.code { "cycle" => "conflict", code => code, })) } + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +/// Request to check the values of a task step being added or edited. +pub struct CheckBeforeLaunchTaskRequest { + /// Canonical workspace root, which file and directory values are + /// resolved against. + pub root: String, + /// The task kind, as in the `tasks` of a `beforeLaunch` field. + pub run_type: RunTypeKey, + /// The values of the task's form by editor key, as `values` of the task + /// kind or step item gave them. + #[serde(default)] + pub values: Map, + /// The kinds installed plugins declare, set by the dispatcher from + /// `runTypePlugins`. + #[serde(skip)] + pub run_types: Vec, +} + +/// `runConfig.checkBeforeLaunchTask`: checks the form of a task step and +/// returns the step to put in the `beforeLaunch` editor value. +/// +/// Replies `{status: "ok", step: {task, name, summary, values}}`, or +/// `{status: "invalid", errors: [{field, code}]}` with the editor keys of the +/// wrong fields. A task no installed plugin declares fails the call with +/// `NotSupported`. Nothing is written; the step is saved with the +/// configuration. +pub fn check_before_launch_task(request: CheckBeforeLaunchTaskRequest) -> Result { + let root = existing_root(&request.root)?; + let task = declared_task(&request.run_types, &request.run_type)?; + let (values, errors): (_, Vec) = task.store(&root, &request.values)?; + if !errors.is_empty() { + return Ok(json!({ "status": "invalid", "errors": errors })); + } + let reference = RunTypeReference { + plugin_id: task.key.plugin_id.clone(), + build_system_id: task.key.build_system_id.clone(), + type_id: task.key.type_id.clone(), + values, + }; + reference.validate()?; + Ok(json!({ "status": "ok", "step": task.task_step_item(&reference) })) +} diff --git a/rust/crates/execution/src/configuration/declared.rs b/rust/crates/execution/src/configuration/declared.rs index 476e669e..4e032f5e 100644 --- a/rust/crates/execution/src/configuration/declared.rs +++ b/rust/crates/execution/src/configuration/declared.rs @@ -9,6 +9,12 @@ //! saved entry. A saved entry keeps the plugin, build system, kind and field //! values in `extensions.build`; its arguments, working directory and //! environment are the top-level keys every run has. +//! +//! A build system declares kinds of before-launch task the same way +//! (`buildSystems[].beforeLaunchTasks`). A task is a step of another +//! configuration's Before Launch list, so it has no entry of its own: the +//! step keeps the same reference, and a task runs in the working directory +//! of the configuration whose list names it, without program arguments. use super::process::{self, FieldError}; use super::*; @@ -128,18 +134,32 @@ fn invalid_reference() -> CoreError { ) } -/// A kind of run configuration a plugin declares, checked by the build crate. +/// Which list of its build system a declared kind comes from. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DeclaredRole { + /// `runConfigurationTypes`: a configuration the user creates. + Configuration, + /// `beforeLaunchTasks`: a step of a configuration's Before Launch list. + BeforeLaunchTask, +} + +/// A kind of run configuration or of before-launch task a plugin declares, +/// checked by the build crate. #[derive(Debug, Clone)] pub struct DeclaredRunType { - /// Its identity. + /// Its identity. A configuration kind and a task kind of one build + /// system may share an ID; [`role`](Self::role) tells them apart. pub key: RunTypeKey, + /// The list it comes from. + pub role: DeclaredRole, /// Shown in the + menu and as the default name of a new configuration. pub display_name: String, /// One sentence on what the kind runs. pub description: Option, /// The plugin's `UIIcon`, passed to the host unchanged. pub icon: Option, - /// How a started configuration behaves; never `service` or `group`. + /// How a started configuration behaves; never `service` or `group`, and + /// always `task` for a before-launch task. pub execution: Execution, /// Whether its command line takes the user's program arguments; the /// editor shows the program arguments field only then. @@ -413,11 +433,16 @@ impl DeclaredRunType { DeclaredFieldKind::Arguments => { let arguments = super::launch::split_arguments(value.as_str().unwrap_or_default()); - match process::arguments_limit_error( - &arguments, - MAX_VALUE_ARGUMENTS, - MAX_VALUE_BYTES, - ) { + let error = if arguments.is_empty() && field.required { + Some("required") + } else { + process::arguments_limit_error( + &arguments, + MAX_VALUE_ARGUMENTS, + MAX_VALUE_BYTES, + ) + }; + match error { Some(code) => { errors.push(FieldError::new(key, code)); None @@ -493,6 +518,9 @@ impl DeclaredRunType { .map(|item| item.as_str().map(str::to_string)) .collect::>>() .ok_or_else(|| error("invalidValue"))?; + if arguments.is_empty() && field.required { + return Err(error("required")); + } (!arguments.is_empty()).then_some(DeclaredValue::Arguments(arguments)) } ( @@ -530,6 +558,73 @@ impl DeclaredRunType { Ok(launch) } + /// A one-line description of what a task step with the saved `values` + /// runs, for the Before Launch list and its confirmation: the shown + /// values in field order, a checked checkbox by its title. + pub(super) fn summary(&self, values: &Map) -> String { + let mut words = Vec::new(); + for field in &self.fields { + if !self.visible(field, values) { + continue; + } + let value = values + .get(&field.id) + .cloned() + .unwrap_or_else(|| field.initial()); + match (field.kind, &value) { + (DeclaredFieldKind::Checkbox, Value::Bool(true)) => words.push(field.title.clone()), + (DeclaredFieldKind::Arguments, Value::Array(_)) => { + let text = field.editor_value(value.clone()); + if let Some(text) = text.as_str().filter(|text| !text.is_empty()) { + words.push(text.to_string()); + } + } + (DeclaredFieldKind::Choice, Value::String(choice)) => words.push( + field + .choices + .iter() + .find(|known| &known.value == choice) + .and_then(|known| known.title.clone()) + .unwrap_or_else(|| choice.clone()), + ), + (_, Value::String(text)) if !text.is_empty() => words.push(text.clone()), + _ => {} + } + } + words.join(" ") + } + + /// A kind of before-launch task in the `tasks` of a `beforeLaunch` + /// editor field: `{runType, displayName, description, icon, fields, + /// values}`, the fields of its form and the values of a new step. + pub(super) fn task_kind_item(&self) -> Value { + let mut item = json!({ + "runType": self.key, + "displayName": self.display_name, + "fields": self.editor_fields(), + "values": self.default_values(), + }); + if let Some(description) = &self.description { + item["description"] = json!(description); + } + if let Some(icon) = &self.icon { + item["icon"] = icon.clone(); + } + item + } + + /// A task step of this kind as the `beforeLaunch` editor value holds it: + /// `{task, name, summary, values}`, the saved reference with the editor + /// values of its fields. + pub(super) fn task_step_item(&self, reference: &RunTypeReference) -> Value { + json!({ + "task": reference, + "name": self.display_name, + "summary": self.summary(&reference.values), + "values": self.saved_values(reference), + }) + } + /// The entry of this kind in `runConfig.configurationTypes`. pub(super) fn type_item(&self) -> Value { let mut item = json!({ @@ -548,33 +643,60 @@ impl DeclaredRunType { } } -/// The declared kind `key` among `types`; `NotSupported` when no installed -/// plugin declares it, such as after the plugin was removed. +/// The declared configuration kind `key` among `types`; `NotSupported` when +/// no installed plugin declares it, such as after the plugin was removed. pub(super) fn declared<'a>( types: &'a [DeclaredRunType], key: &RunTypeKey, ) -> Result<&'a DeclaredRunType, CoreError> { - types.iter().find(|item| &item.key == key).ok_or_else(|| { - CoreError::new( - ErrorCode::NotSupported, - "No installed plugin declares this run configuration type", - ) - .with_details(format!( - "{}/{}/{}", - key.plugin_id, key.build_system_id, key.type_id - )) - }) + declared_as( + types, + key, + DeclaredRole::Configuration, + "No installed plugin declares this run configuration type", + ) } -/// What a launch of a saved `build.run-type` entry uses besides the plugin's -/// declaration. +/// The declared before-launch task kind `key` among `types`; `NotSupported` +/// when no installed plugin declares it. +pub(super) fn declared_task<'a>( + types: &'a [DeclaredRunType], + key: &RunTypeKey, +) -> Result<&'a DeclaredRunType, CoreError> { + declared_as( + types, + key, + DeclaredRole::BeforeLaunchTask, + "No installed plugin declares this before-launch task", + ) +} + +fn declared_as<'a>( + types: &'a [DeclaredRunType], + key: &RunTypeKey, + role: DeclaredRole, + message: &'static str, +) -> Result<&'a DeclaredRunType, CoreError> { + types + .iter() + .find(|item| item.role == role && &item.key == key) + .ok_or_else(|| { + CoreError::new(ErrorCode::NotSupported, message).with_details(format!( + "{}/{}/{}", + key.plugin_id, key.build_system_id, key.type_id + )) + }) +} + +/// What a launch of a saved `build.run-type` entry, or of a before-launch +/// task, uses besides the plugin's declaration. #[derive(Debug, Clone)] pub struct DeclaredLaunch { /// Canonical workspace root, which relative paths are resolved against. pub root: PathBuf, /// The kind and the saved field values. pub reference: RunTypeReference, - /// The user's program arguments. + /// The user's program arguments; none for a task. pub arguments: Vec, /// Workspace-relative working directory; `.` is the workspace root. pub working_directory: String, @@ -611,6 +733,30 @@ pub fn declared_launch( }) } +/// What a launch of the before-launch task `task` uses, as +/// `runConfig.beforeLaunch` returned the step: it runs in +/// `working_directory` of the workspace `root`, a directory inside the +/// project, without program arguments or an environment of its own. +pub fn declared_task_launch( + root: &str, + task: RunTypeReference, + working_directory: &str, +) -> Result { + let root = existing_root(root)?; + task.validate()?; + let working_directory = match working_directory.trim() { + "" | "." => ".".to_string(), + directory => normalize_working_directory(&root, directory)?, + }; + Ok(DeclaredLaunch { + root, + reference: task, + arguments: Vec::new(), + working_directory, + environment: BTreeMap::new(), + }) +} + /// Checks a saved `build.run-type` entry: a valid reference, an execution /// that is a process, and no keys only other providers use. pub(crate) fn validate(configuration: &RunConfiguration) -> Result<(), CoreError> { @@ -643,6 +789,7 @@ mod tests { build_system_id: "tool".into(), type_id: "check".into(), }, + role: DeclaredRole::Configuration, display_name: "Tool Check".into(), description: None, icon: None, diff --git a/rust/crates/execution/src/configuration/document.rs b/rust/crates/execution/src/configuration/document.rs index 6337809c..ff5ef34b 100644 --- a/rust/crates/execution/src/configuration/document.rs +++ b/rust/crates/execution/src/configuration/document.rs @@ -203,9 +203,10 @@ pub struct RunConfiguration { /// Provider-specific payload keyed by namespace, such as `build`. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub extensions: BTreeMap, - /// Built-in process runs started in order before this one, each of which - /// must exit with 0 first (`runConfig.beforeLaunch`). A layer replaces the - /// whole list, so an empty list clears the steps of a lower layer. + /// Steps run in order before this one, each of which must exit with 0 + /// first (`runConfig.beforeLaunch`): a built-in process run, or a task an + /// installed plugin declares. A layer replaces the whole list, so an empty + /// list clears the steps of a lower layer. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub before_launch: Vec, /// Hidden from the resolved list; set by a user or when the working directory is missing. diff --git a/rust/crates/execution/src/configuration/editing.rs b/rust/crates/execution/src/configuration/editing.rs index 40e926af..8b890e92 100644 --- a/rust/crates/execution/src/configuration/editing.rs +++ b/rust/crates/execution/src/configuration/editing.rs @@ -193,10 +193,21 @@ fn update_configuration_options( request.working_directory.trim(), )?) }; - if let Some(ids) = &request.before_launch { - if let Some(code) = - super::before_launch::check_edit(root, layers, &request.configuration_id, ids)? - { + let steps = + match &request.before_launch { + None => None, + Some(items) => Some(super::before_launch::steps_from_editor(items).ok_or_else( + || CoreError::new(ErrorCode::InvalidRequest, "Invalid steps before launch"), + )?), + }; + if let Some(steps) = &steps { + if let Some(code) = super::before_launch::check_edit( + root, + layers, + &request.configuration_id, + steps, + &request.run_types, + )? { return Err(CoreError::new( ErrorCode::InvalidRequest, "A step before launch cannot run", @@ -228,11 +239,11 @@ fn update_configuration_options( } patch["args"] = json!(split_arguments(&request.arguments)); let mut drop_steps = false; - match request.before_launch.as_deref() { + match steps.as_deref() { None => {} Some([]) if local_layer && project_names_steps => patch["beforeLaunch"] = json!([]), Some([]) => drop_steps = true, - Some(ids) => patch["beforeLaunch"] = json!(super::before_launch::steps_of(ids)), + Some(steps) => patch["beforeLaunch"] = json!(steps), } if provider == "build.provider" { if let Some(options) = &request.provider_run_options { diff --git a/rust/crates/execution/src/configuration/form.rs b/rust/crates/execution/src/configuration/form.rs index 7e34b4d6..502d6d9d 100644 --- a/rust/crates/execution/src/configuration/form.rs +++ b/rust/crates/execution/src/configuration/form.rs @@ -12,8 +12,12 @@ //! request, already checked and localized; a configuration whose plugin is //! gone cannot be edited until the plugin is back. -use super::before_launch::{check_edit, steps_of, Resolved}; -use super::declared::{declared, DeclaredRunType, RunTypeKey, RunTypeReference, RUN_TYPE_PROVIDER}; +use super::before_launch::{ + check_edit, editor_items, steps_from_editor, BeforeLaunchStep, Resolved, StepChoices, +}; +use super::declared::{ + declared, DeclaredRole, DeclaredRunType, RunTypeKey, RunTypeReference, RUN_TYPE_PROVIDER, +}; use super::process::{self, FieldError, Kind, ProcessOptions}; use super::*; @@ -48,7 +52,13 @@ pub fn configuration_types(request: ConfigurationTypesRequest) -> Result>(); - types.extend(request.run_types.iter().map(DeclaredRunType::type_item)); + types.extend( + request + .run_types + .iter() + .filter(|run_type| run_type.role == DeclaredRole::Configuration) + .map(DeclaredRunType::type_item), + ); Ok(json!({ "types": types })) } @@ -95,7 +105,7 @@ pub fn editor_form(request: EditorFormRequest) -> Result { { return Err(different_provider()); } - (editor, saved.values(editor)?) + (editor, saved.values(editor, run_types)?) } None => { let editor = Editor::new( @@ -107,13 +117,16 @@ pub fn editor_form(request: EditorFormRequest) -> Result { } }; values.extend(request.values.unwrap_or_default()); - let candidates = - Resolved::read(&root, &layers)?.candidates(request.configuration_id.as_deref()); + let choices = StepChoices::new( + &Resolved::read(&root, &layers)?, + request.configuration_id.as_deref(), + run_types, + ); let fields = match editor { - Editor::Process(kind) => fields(kind, &root, &Draft::read(kind, &values)?, candidates), + Editor::Process(kind) => fields(kind, &root, &Draft::read(kind, &values)?, choices), Editor::Declared(run_type) => { Common::read(&values, DECLARED_ARGUMENTS_FIELD)?; - declared_fields(run_type, candidates) + declared_fields(run_type, choices) } }; let mut form = json!({ @@ -216,7 +229,7 @@ pub fn save_configuration(request: SaveConfigurationRequest) -> Result saved.id.clone(), None => unique_user_configuration_id(&stored.name, &existing_ids(&root, &layers)), }; - if let Some(code) = check_edit(&root, &layers, &id, &common.before_launch)? { + if let Some(code) = check_edit(&root, &layers, &id, &common.before_launch, run_types)? { errors.push(FieldError::new("beforeLaunch", code)); } if !errors.is_empty() { @@ -264,7 +277,7 @@ pub fn save_configuration(request: SaveConfigurationRequest) -> Result) -> Result, CoreError> { + /// The editor values of the saved entry; `run_types` describe its task + /// steps. + fn values( + &self, + editor: Editor<'_>, + run_types: &[DeclaredRunType], + ) -> Result, CoreError> { let configuration = self.configuration()?; let mut values = editor.default_values(); values.insert("name".into(), json!(configuration.name)); @@ -562,11 +580,7 @@ impl SavedEntry { ); values.insert( "beforeLaunch".into(), - json!(configuration - .before_launch - .iter() - .map(|step| step.configuration.clone()) - .collect::>()), + json!(editor_items(&configuration.before_launch, run_types)), ); let kind = match editor { Editor::Process(kind) => kind, @@ -657,7 +671,7 @@ fn header_fields(automatic_name: Option) -> Vec { } /// The fields of `kind`'s editor, with automatic values for `draft`. -fn fields(kind: Kind, root: &Path, draft: &Draft, candidates: Vec) -> Vec { +fn fields(kind: Kind, root: &Path, draft: &Draft, choices: StepChoices) -> Vec { let platform = Platform::HOST; let options = draft.options(); let mut fields = header_fields(process::default_name(&options)); @@ -711,13 +725,13 @@ fn fields(kind: Kind, root: &Path, draft: &Draft, candidates: Vec) -> Vec field("environment", "environment"), ]); } - fields.push(field("beforeLaunch", "beforeLaunch").candidates(candidates)); + fields.push(field("beforeLaunch", "beforeLaunch").steps(choices)); fields.into_iter().map(|field| field.0).collect() } /// The fields of a declared kind's editor: the header, the kind's own /// fields, then the fields every run has. -fn declared_fields(run_type: &DeclaredRunType, candidates: Vec) -> Vec { +fn declared_fields(run_type: &DeclaredRunType, choices: StepChoices) -> Vec { let mut fields = header_fields(Some(run_type.display_name.clone())) .into_iter() .map(|field| field.0) @@ -730,7 +744,7 @@ fn declared_fields(run_type: &DeclaredRunType, candidates: Vec) -> Vec) -> Self { - self.0["candidates"] = json!(candidates); + /// What a `beforeLaunch` field offers: `candidates`, the run + /// configurations a step may start as `{id, name}`, and, when installed + /// plugins declare any, `tasks`, the kinds of task a step may run. + fn steps(mut self, choices: StepChoices) -> Self { + self.0["candidates"] = json!(choices.candidates); + if !choices.tasks.is_empty() { + self.0["tasks"] = json!(choices.tasks); + } self } @@ -832,8 +851,8 @@ struct Common { arguments: String, working_directory: String, environment: Vec<(String, String)>, - /// The configurations started before this one, by ID. - before_launch: Vec, + /// The steps run before this one. + before_launch: Vec, } /// The fields every editable run has, in the form they are saved. @@ -868,8 +887,10 @@ impl Common { environment, before_launch: match values.get("beforeLaunch") { None | Some(Value::Null) => Vec::new(), - Some(value) => serde_json::from_value::>(value.clone()) - .map_err(|_| invalid_value("beforeLaunch"))?, + Some(Value::Array(items)) => { + steps_from_editor(items).ok_or_else(|| invalid_value("beforeLaunch"))? + } + Some(_) => return Err(invalid_value("beforeLaunch")), }, }) } diff --git a/rust/crates/execution/src/configuration/requests.rs b/rust/crates/execution/src/configuration/requests.rs index 85f19424..2fbc5dc5 100644 --- a/rust/crates/execution/src/configuration/requests.rs +++ b/rust/crates/execution/src/configuration/requests.rs @@ -134,11 +134,13 @@ pub struct UpdateOptionsRequest { /// into the local layer instead of patching one configuration. #[serde(default)] pub toolchain: Option, - /// IDs of the built-in process runs to start first, in order. Omission - /// keeps the saved steps; an empty list removes them from this layer and, - /// in the local layer, also hides the project's. + /// The steps to run first, in order, as the `beforeLaunch` editor value + /// holds them: the ID of a built-in process run, or a task step whose + /// `task` is read. Omission keeps the saved steps; an empty list removes + /// them from this layer and, in the local layer, also hides the + /// project's. #[serde(default)] - pub before_launch: Option>, + pub before_launch: Option>, /// Host-owned local layer used to resolve the configuration first. A /// local edit is refused while it is set: only files can be changed. #[serde(default)] @@ -146,6 +148,10 @@ pub struct UpdateOptionsRequest { /// The installed plugins, whose identity a written plugin document records. #[serde(default)] pub plugins: Option>, + /// The kinds installed plugins declare, which task steps are checked + /// against; set by the dispatcher from `runTypePlugins`. + #[serde(skip)] + pub run_types: Vec, } #[derive(Debug, Deserialize)] diff --git a/rust/crates/plugin-manifest/src/validation.rs b/rust/crates/plugin-manifest/src/validation.rs index ac3e5729..b117ed83 100644 --- a/rust/crates/plugin-manifest/src/validation.rs +++ b/rust/crates/plugin-manifest/src/validation.rs @@ -359,6 +359,12 @@ impl DeclarativePluginManifest { .iter() .any(|system| system.has_run_configuration_types()), ), + ( + capabilities::BEFORE_LAUNCH_TASKS, + self.build_systems + .iter() + .any(|system| system.has_before_launch_tasks()), + ), (capabilities::VCS_PROVIDERS, !self.vcs_providers.is_empty()), ( capabilities::DEBUG_ADAPTERS, diff --git a/rust/crates/plugin-model/src/capabilities.rs b/rust/crates/plugin-model/src/capabilities.rs index b9e44e12..fd92e116 100644 --- a/rust/crates/plugin-model/src/capabilities.rs +++ b/rust/crates/plugin-model/src/capabilities.rs @@ -73,6 +73,10 @@ pub const BUILD_MODEL_INPUTS: &str = "buildModelInputs"; /// `buildSystems[].runConfigurationTypes`: kinds of run configuration whose /// editor fields and command line the plugin declares. pub const RUN_CONFIGURATION_TYPES: &str = "runConfigurationTypes"; +/// `buildSystems[].beforeLaunchTasks`: kinds of before-launch step whose +/// fields and command line the plugin declares, offered in a configuration's +/// "Add New Task" menu next to running another configuration. +pub const BEFORE_LAUNCH_TASKS: &str = "beforeLaunchTasks"; /// `vcsProviders[]`: version control systems implemented by a plugin /// process; see `lithe_vcs`. pub const VCS_PROVIDERS: &str = "vcsProviders"; @@ -119,6 +123,7 @@ pub const OUTPUT_LINK_MATCHERS: &str = "outputLinkMatchers"; /// of a capability is appended to its list. pub const SUPPORTED_CAPABILITIES: &[(&str, &[u32])] = &[ (BACKEND, &[0]), + (BEFORE_LAUNCH_TASKS, &[0]), (BUILD_MODEL_INPUTS, &[0]), (BUILD_PROVIDERS, &[0, 1]), (BUILD_SYSTEMS, &[0]), diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 5e689337..120eba5c 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -817,6 +817,7 @@ in `fixtures/settings/localization-cases.json`. | `sections.` | A section heading, named exactly as `section` writes it | | `settingActions.` | The action's `title` and `description` | | `runConfigurationTypes..` | A [run configuration type](#run-configuration-types)'s `displayName` and `description`, and `fields.` with a field's `title`, `description`, `placeholder`, and `options.`; refused as `plugin.build.invalidLocalization` | +| `beforeLaunchTasks..` | A [before-launch task](#before-launch-tasks)'s text, shaped like `runConfigurationTypes`; refused as `plugin.build.invalidLocalization` | Every member is optional, and text a file leaves out stays as `plugin.json` writes it. IDs, option values and their order, stored values, and the grouping @@ -969,6 +970,7 @@ belongs to one capability: | `buildSystems` | [`buildSystems[]`](#build-systems) without `provider`: detection, options, project model, tasks, run entries, tests, diagnostics, dependencies, sync, and [declarative preparation](#declarative-project-preparation) | — | Detects projects, loads the model, and runs the declared commands. | | `buildProviders` | `buildSystems[].provider`, including own-process and shared language-server providers | `litheBuild` | Starts the provider and speaks `litheBuild` with workspace-owned sessions. | | `runConfigurationTypes` | [`buildSystems[].runConfigurationTypes`](#run-configuration-types) | — | Lists the types in the Run/Debug Configurations dialog, draws their editors, and runs their saved configurations through `build.runConfigurationPlan`. | +| `beforeLaunchTasks` | [`buildSystems[].beforeLaunchTasks`](#before-launch-tasks) | — | Offers the tasks in the Add New Task menu of a configuration's Before Launch list, draws their forms, and runs their steps through `build.beforeLaunchTaskPlan`. | | `buildModelInputs` | `buildSystems[].modelSharing` and `modelInputs`: [optional read-only model inputs](#optional-read-only-model-inputs) | — | Supplies the model snapshot between enabled workspace plugins. | | `vcsProviders` | [`vcsProviders[]`](#vcs-providers) | `litheVcs` | Starts the provider and speaks `litheVcs`. | | `debugAdapters` | [`debugAdapters[]`](#debug-adapters) | — | Starts the adapter and applies its [declared features and defaults](#adapter-features-and-defaults). | @@ -1907,6 +1909,7 @@ declaration are relative, use `/`, and stay inside their base directory | `tasks` | The task catalog. `scopes` say what a task runs on (`workspace`, `project`, `target`); `targetTags` restrict targets; `requiresUserArguments` makes the host ask for arguments. A `fromModel` task is the template for tasks the model lists. | | `run` | Run entries from model targets (`fromTargets.tags`, with `arguments`) or model tasks (`fromTasks`, reusing the template task's arguments). | | `runConfigurationTypes` | Kinds of run configuration the user creates in the Run/Debug Configurations dialog, from declared fields and a command line; see [Run configuration types](#run-configuration-types). | +| `beforeLaunchTasks` | Kinds of step a configuration's Before Launch list runs first, declared like run configuration types; see [Before-launch tasks](#before-launch-tasks). | | `test` | How tests run: `scopes`, `targetTags`, the `filters` (`suite`, `case`) it can select, and `results` (`junitXml` or `litheTestResults` report globs relative to the project). A workspace run reads the globs under the root and every model project. A requested filter must reach the command line through a template whose conditions hold; a `case` guarded by `suiteSelected` therefore needs its suite. | | `diagnostics` | `lineMatcher` patterns with capture-group numbers, or `litheDiagnostics` lines. | | `dependencies` | A command (with `scopes`) whose output Core decodes, as a flat list through a `map` or as a tree from `litheDependencies`; or `provider` (with `scopes`, `workspace` and `project` only). | @@ -2731,6 +2734,64 @@ The type's text is translated in the package's `l10n/.json` under [Translations](#translations). A file that does not fit is refused whole with `plugin.build.invalidLocalization`, and the manifest's text is shown. +### Before-launch tasks + +`beforeLaunchTasks` adds kinds of step to the *Before launch* list every run +configuration has, as IntelliJ IDEA's Go plugin adds Run Go Command to its +*Add New Task* menu. The host lists them in that menu after Run Another +Configuration; picking one opens a form of the task's fields, and the step +keeps their values. Before the configuration starts, each step runs and must +exit with 0. A build system that declares tasks needs `beforeLaunchTasks: 0` +in `requires` beside `buildSystems: 0`. Fixture: +`fixtures/before-launch-tasks/`, translated by its `l10n/zh-Hans.json`. + +```json +"beforeLaunchTasks": [{ + "id": "command", + "displayName": "Run Go Command", + "description": "Runs one go command, such as generate ./..., in the configuration's working directory.", + "icon": { "host": "run" }, + "fields": [ + { "id": "command", "title": "Command", "kind": "arguments", "required": true, + "placeholder": "generate ./..." } + ], + "arguments": ["${field:command}"] +}] +``` + +A task is declared like a [run configuration type](#run-configuration-types), +with the same `id`, `displayName`, `description`, `icon`, `fields` and +`arguments` rules, at most 16 per build system, with two differences: + +- A task always runs to completion, so it has no `execution`; declaring one + is `plugin.manifest.invalid`. +- A task has no program arguments, so its `arguments` do not take + `${userArguments}`; using it is `plugin.template.invalid`. + +A task's ID is separate from the type IDs: a build system may declare a type +and a task with the same ID. A step saves the task's identity and the visible +fields' values in the configuration's `beforeLaunch` list as `{task: +{pluginID, buildSystemID, type, values}}`, so removing the plugin keeps the +step, which then refuses to start until the plugin is installed again. + +A step runs in the working directory of the configuration whose list names +it, without that configuration's program arguments or environment. To run +one, the host calls `build.beforeLaunchTaskPlan` with the manifest, the build +system, `workspaceRoot`, the step and its working directory as +`runConfig.beforeLaunch` returned them, and the detected instances of the +build system with their stored options. Core picks the instance as for a run +configuration and returns a task plan: the global arguments, then the task's +`arguments` with the field values and the instance's options. A saved value +that no longer fits the task is `plugin.build.invalidBeforeLaunchTask` with +`field: "values."`; a task the plugin no longer declares is +`plugin.build.unavailable`. + +A step a project file names runs code from the repository, so the host asks +the user before running a list it has not seen, as for steps that start other +configurations. The text is translated under +`beforeLaunchTasks..`, shaped like +`runConfigurationTypes`. + ### Build providers Some tools expose their model only through their own API (the Gradle Tooling @@ -4697,7 +4758,8 @@ command payload is a Core `invalid_request` failure instead. | `plugin.build.invalidSelection` | Core | A build request selects a scope, target, filter, or argument the declaration does not allow, or misses a required path | | `plugin.build.invalidOutput` | Core | Build-tool output or a report does not fit its decoder | | `plugin.build.invalidRunConfiguration` | Core | A saved configuration of a [run configuration type](#run-configuration-types) holds a value the type no longer accepts; `field` is `values.` | -| `plugin.build.invalidLocalization` | Core | The `runConfigurationTypes` part of a [translation file](#translations) does not fit the declarations; the host shows the next candidate or the manifest text | +| `plugin.build.invalidBeforeLaunchTask` | Core | A step of a [before-launch task](#before-launch-tasks) holds a value the task no longer accepts; `field` is `values.` | +| `plugin.build.invalidLocalization` | Core | The `runConfigurationTypes` or `beforeLaunchTasks` part of a [translation file](#translations) does not fit the declarations; the host shows the next candidate or the manifest text | | `plugin.launch.invalidRequest` | Core | A launch plan request has an unusable directory or an unknown architecture | | `plugin.launch.notBackend` | Core | `decodeLaunch` named a language server that the plugin backend does not launch | | `plugin.launch.invalidResult` | Core | A [backend-resolved launch](#backend-resolved-launch) answer is malformed, unknown in a field, or over a bound | diff --git a/shared/plugins/contract/v1/fixtures/before-launch-tasks/before-launch-tasks.plugin.json b/shared/plugins/contract/v1/fixtures/before-launch-tasks/before-launch-tasks.plugin.json new file mode 100644 index 00000000..bf676b12 --- /dev/null +++ b/shared/plugins/contract/v1/fixtures/before-launch-tasks/before-launch-tasks.plugin.json @@ -0,0 +1,67 @@ +{ + "schemaVersion": 0, + "id": "dev.lithe.fixture.before-launch-tasks", + "displayName": "Before-Launch Tasks Fixture", + "version": "0.1.0", + "pluginAPIVersion": 0, + "requires": { "buildSystems": 0, "beforeLaunchTasks": 0 }, + "vendor": { + "id": "org.example", + "displayName": "Example", + "signatureRequirement": "publisherPackage" + }, + "permissions": ["process.build"], + "activationEvents": ["onBuildSystem:go"], + "languages": [], + "buildSystems": [ + { + "id": "go", + "displayName": "Go Modules", + "detection": { "markers": ["go.mod"] }, + "invocation": { + "executables": [{ "kind": "runtime", "runtime": "go" }], + "runtimeDependencies": [{ "id": "go", "minimumVersion": "1.21" }] + }, + "options": [ + { "id": "tags", "displayName": "Build Tags", "kind": "text", "arguments": ["-tags", "${value}"] } + ], + "beforeLaunchTasks": [ + { + "id": "command", + "displayName": "Run Go Command", + "description": "Runs one go command, such as generate ./..., in the configuration's working directory.", + "icon": { "host": "run" }, + "fields": [ + { + "id": "command", + "title": "Command", + "kind": "arguments", + "required": true, + "placeholder": "generate ./..." + } + ], + "arguments": ["${field:command}"] + }, + { + "id": "generate", + "displayName": "Go Generate", + "fields": [ + { + "id": "verbose", + "title": "Print files", + "kind": "checkbox", + "arguments": ["-v"] + }, + { + "id": "package", + "title": "Package", + "kind": "text", + "default": "./..." + } + ], + "arguments": ["generate", "${optionArguments}", "${field:verbose}", "${field:package}"] + } + ] + } + ] +} diff --git a/shared/plugins/contract/v1/fixtures/before-launch-tasks/l10n/zh-Hans.json b/shared/plugins/contract/v1/fixtures/before-launch-tasks/l10n/zh-Hans.json new file mode 100644 index 00000000..f1aeb918 --- /dev/null +++ b/shared/plugins/contract/v1/fixtures/before-launch-tasks/l10n/zh-Hans.json @@ -0,0 +1,19 @@ +{ + "beforeLaunchTasks": { + "go": { + "command": { + "displayName": "运行 Go 命令", + "description": "在配置的工作目录中运行一条 go 命令,例如 generate ./...。", + "fields": { + "command": { "title": "命令" } + } + }, + "generate": { + "displayName": "Go 生成", + "fields": { + "verbose": { "title": "列出文件" } + } + } + } + } +} diff --git a/shared/plugins/contract/v1/plugin-l10n.schema.json b/shared/plugins/contract/v1/plugin-l10n.schema.json index 40961f74..6a2c04d7 100644 --- a/shared/plugins/contract/v1/plugin-l10n.schema.json +++ b/shared/plugins/contract/v1/plugin-l10n.schema.json @@ -2,7 +2,7 @@ "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://raw.githubusercontent.com/Lithe-IDEA/Lithe-core-rust/main/shared/plugins/contract/v1/plugin-l10n.schema.json", "title": "Lithe plugin translation file (plugin contract v1)", - "description": "Shape of l10n/.json in a plugin package, such as l10n/zh-Hans.json: the plugin's own text in one interface language. Every member is optional, and text it leaves out stays as written in plugin.json. Rules that JSON Schema cannot express (every ID, option value and heading must exist in plugin.json, a field is translated only when plugin.json has it, no key repeats) are defined in README.md and enforced by plugins.declarative.settingsState, which reports a file that breaks one with plugin.settings.invalidLocalization and applies none of it; the run configuration editor checks runConfigurationTypes the same way and reports plugin.build.invalidLocalization. Core ignores top-level members it does not know, so a file that also translates text a later host supports stays usable on older hosts; this schema lists only the members Core reads today.", + "description": "Shape of l10n/.json in a plugin package, such as l10n/zh-Hans.json: the plugin's own text in one interface language. Every member is optional, and text it leaves out stays as written in plugin.json. Rules that JSON Schema cannot express (every ID, option value and heading must exist in plugin.json, a field is translated only when plugin.json has it, no key repeats) are defined in README.md and enforced by plugins.declarative.settingsState, which reports a file that breaks one with plugin.settings.invalidLocalization and applies none of it; the run configuration editor checks runConfigurationTypes and beforeLaunchTasks the same way and reports plugin.build.invalidLocalization. Core ignores top-level members it does not know, so a file that also translates text a later host supports stays usable on older hosts; this schema lists only the members Core reads today.", "type": "object", "additionalProperties": false, "properties": { @@ -34,6 +34,16 @@ "propertyNames": { "pattern": "^[a-z][a-z0-9-]*(?![\\s\\S])", "maxLength": 64 }, "additionalProperties": { "$ref": "#/$defs/runTypeText" } } + }, + "beforeLaunchTasks": { + "description": "Text of buildSystems[].beforeLaunchTasks, by build system ID, then task ID, shaped like runConfigurationTypes.", + "type": "object", + "propertyNames": { "pattern": "^[a-z][a-z0-9-]*(?![\\s\\S])", "maxLength": 64 }, + "additionalProperties": { + "type": "object", + "propertyNames": { "pattern": "^[a-z][a-z0-9-]*(?![\\s\\S])", "maxLength": 64 }, + "additionalProperties": { "$ref": "#/$defs/runTypeText" } + } } }, "$defs": { diff --git a/shared/plugins/contract/v1/plugin-manifest.schema.json b/shared/plugins/contract/v1/plugin-manifest.schema.json index 429cf2aa..f88383be 100644 --- a/shared/plugins/contract/v1/plugin-manifest.schema.json +++ b/shared/plugins/contract/v1/plugin-manifest.schema.json @@ -10,6 +10,7 @@ {"if": {"required": ["outputLinkMatchers"]}, "then": {"properties": {"requires": {"required": ["outputLinkMatchers"]}}}}, {"if": {"required": ["toolDefinitions"]}, "then": {"properties": {"requires": {"required": ["toolDefinitions"]}}}}, {"if": {"required": ["buildSystems"], "properties": {"buildSystems": {"contains": {"required": ["runConfigurationTypes"]}}}}, "then": {"properties": {"requires": {"required": ["runConfigurationTypes"]}}}}, + {"if": {"required": ["buildSystems"], "properties": {"buildSystems": {"contains": {"required": ["beforeLaunchTasks"]}}}}, "then": {"properties": {"requires": {"required": ["beforeLaunchTasks"]}}}}, {"if": {"required": ["commandInstallers"]}, "then": {"required": ["permissions"], "properties": {"requires": {"required": ["commandInstallers"]}, "permissions": {"contains": {"const": "commands.install"}}}}}, {"if": {"required": ["managedRuntimes"]}, "then": {"required": ["backend", "permissions"], "properties": {"requires": {"required": ["managedRuntimes", "backend"]}, "permissions": {"allOf": [{"contains": {"const": "runtimes.install"}}, {"contains": {"const": "backend.launch"}}]}}}}, {"if": {"required": ["toolchainProviders"]}, "then": {"required": ["backend"], "properties": {"requires": {"required": ["toolchainProviders", "backend"]}, "permissions": {"allOf": [{"contains": {"const": "toolchains.provide"}}, {"contains": {"const": "backend.launch"}}]}}}}, @@ -30,6 +31,7 @@ "additionalProperties": false, "properties": { "backend": { "description": "Required exactly when backend is present: the plugin's own process. It serves its web pages, may also start on onWorkspaceOpen or a plugin command, receives workspace contexts through the litheFunctions protocol, and may be granted workspace.metadata.", "enum": [0] }, + "beforeLaunchTasks": { "description": "Required exactly when any buildSystems[].beforeLaunchTasks is non-empty: kinds of step a run configuration's Before Launch list runs first, offered in its Add New Task menu, drawn from declared fields and run through a declared command line. Needs buildSystems.", "enum": [0] }, "buildModelInputs": {"description": "Optional public model sharing between already enabled workspace plugins; no installation, private function, or process authority. Required exactly when modelSharing or modelInputs is used. Consumers require buildProviders. A producer cannot also consume inputs.", "enum": [0]}, "buildProviders": { "description": "Required exactly when any buildSystems[].provider is present, including own-process and shared language-server providers. Declares host support for Provider orchestration (task execution, test execution and discovery, run preparation, native debug preparation, optional read-only model inputs, non-sensitive native configuration sources, inline test reports, opaque semantic test selectors, typed run options and service/task preparation, registry-selected adapters and host-owned connection targets for service debugging), independent of declarative buildSystems.", "enum": [0] }, "buildSystems": { "description": "Declarative build detection, models, and command plans, including the executable setting adapter, instance-scoped options, and declarative preparation roles; does not imply buildProviders support.", "enum": [0] }, @@ -2788,6 +2790,28 @@ } } }, + "beforeLaunchTask": { + "type": "object", + "additionalProperties": false, + "required": ["id", "displayName", "arguments"], + "description": "One kind of before-launch step. It is declared like a run configuration type with the same rules (task IDs are unique within the build system, every field that passes a value is named exactly once as ${field:} in arguments, visibleWhen names an earlier field), except that a task always runs to completion and has no program arguments: it declares no execution and its arguments do not use ${userArguments}.", + "properties": { + "id": { "type": "string", "pattern": "^[a-z][a-z0-9-]*$", "maxLength": 64 }, + "displayName": { "$ref": "#/$defs/runConfigurationText" }, + "description": { "$ref": "#/$defs/runConfigurationDescription" }, + "icon": { "description": "Icon of the task in the Add New Task menu and the Before Launch list; display only.", "$ref": "#/$defs/uiIcon" }, + "fields": { + "description": "The fields of the task's form, in display order.", + "type": "array", + "maxItems": 16, + "items": { "$ref": "#/$defs/runConfigurationField" } + }, + "arguments": { + "description": "The command line after the global arguments: build argument templates that may also use ${field:} for a field's arguments.", + "$ref": "#/$defs/buildArgumentList" + } + } + }, "runConfigurationField": { "type": "object", "additionalProperties": false, @@ -3266,6 +3290,13 @@ "maxItems": 16, "items": { "$ref": "#/$defs/runConfigurationType" } }, + "beforeLaunchTasks": { + "description": "requires.beforeLaunchTasks: kinds of step a run configuration's Before Launch list runs first, such as running one command of the build tool. Core draws the declared fields in the Add New Task form, checks and saves their values in the step, and expands arguments with them and the instance's options, in the working directory of the configuration whose list names the step.", + "type": "array", + "minItems": 1, + "maxItems": 16, + "items": { "$ref": "#/$defs/beforeLaunchTask" } + }, "run": { "type": "array", "items": { diff --git a/shared/plugins/reference/api-catalog.md b/shared/plugins/reference/api-catalog.md index 368e2b89..8b26958b 100644 --- a/shared/plugins/reference/api-catalog.md +++ b/shared/plugins/reference/api-catalog.md @@ -50,7 +50,7 @@ Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-I | API-24 | 终端 | 部分完成 | [插件自有原生终端](../contract/v1/README.md#plugin-owned-native-terminals) `terminal/create`、`show`、`close`、`reopen`、`dispose`、`onExit`(本机工作区) | 向终端发送文本、读取终端输出 | [插件后端](domains/backend.md) | | API-25 | 语言、语法、LSP | 部分完成 | [语言](../contract/v1/README.md#languages)与[语言服务器](../contract/v1/README.md#language-servers);[`languages` 的包内 Monarch 语法和编辑器配置](../contract/v1/README.md#grammars-and-editor-configuration);[编辑器语言功能 Provider `editor/registerProviders`](../contract/v1/README.md#editor-language-feature-providers),把 `definition`、`hover`、`completion`、`codeLens`、`foldingRange`、`semanticTokens`、`documentLink` 这 7 种类型绑定到普通插件函数,语言服务器优先、插件结果只补充;插件自有的语言服务器会话:[`languageServers` 的会话声明](../contract/v1/README.md#plugin-owned-sessions)给出后端可用的请求、命令、转发通知,[`languageServer/request`、`notify`、`setStatus`](../contract/v1/README.md#language-server-host-methods) 与 `languageServer/didChangeState`、`languageServer/didReceiveNotification` 两个通知,会话策略由 Core 执行;[`launch.kind: "backend"`](../contract/v1/README.md#backend-resolved-launch) 由插件后端决定启动方式 | 符号、格式化、重命名、Code Action、签名帮助、内联提示、运行期传入 JSON 动态注册高亮;远程工作区中由后端决定启动方式的服务器 | [语言](domains/languages.md)、[编辑器](domains/editor.md) | | API-27 | 编辑器动作、主题、装饰 | 部分完成 | [独立编辑器动作 `editor/registerActions`](../contract/v1/README.md#independent-editor-actions),绑定普通函数和文件范围,不依赖 LSP、构建或运行;支持行首多图标、至多 4 个 `alternatives`、点击结果的 `reveal` | 主题、代码片段、其他装饰 | [编辑器](domains/editor.md) | -| API-29 | 构建、任务、测试、运行准备 | 部分完成 | [`buildSystems`](../contract/v1/README.md#build-systems)、[`buildProviders`](../contract/v1/README.md#build-providers)、[`buildModelInputs`](../contract/v1/README.md#optional-read-only-model-inputs)、[`runConfigurationTypes`](../contract/v1/README.md#run-configuration-types) | 开发指南还不完整;Lithe 桌面端未声明 `buildModelInputs`;`runConfigurationTypes` 自 [1lck/Lithe-IDEA#2148](https://github.com/1lck/Lithe-IDEA/pull/2148) 起声明,插件类型只能运行、不能调试 | [声明式构建](domains/build-systems.md)、[构建提供者](domains/build-providers.md) | +| API-29 | 构建、任务、测试、运行准备 | 部分完成 | [`buildSystems`](../contract/v1/README.md#build-systems)、[`buildProviders`](../contract/v1/README.md#build-providers)、[`buildModelInputs`](../contract/v1/README.md#optional-read-only-model-inputs)、[`runConfigurationTypes`](../contract/v1/README.md#run-configuration-types)、[`beforeLaunchTasks`](../contract/v1/README.md#before-launch-tasks) | 开发指南还不完整;Lithe 桌面端未声明 `buildModelInputs` 和 `beforeLaunchTasks`;`runConfigurationTypes` 自 [1lck/Lithe-IDEA#2148](https://github.com/1lck/Lithe-IDEA/pull/2148) 起声明,插件类型只能运行、不能调试 | [声明式构建](domains/build-systems.md)、[构建提供者](domains/build-providers.md) | | API-30 | 调试适配器 | 部分完成 | [`debugAdapters`](../contract/v1/README.md#debug-adapters) 与宿主的 DAP 会话;[`features`、`defaults`](../contract/v1/README.md#adapter-features-and-defaults)(热代码替换、步进过滤器);后端发起的 [`debug/start`](../contract/v1/README.md#run-and-debug-sessions)(权限 `debug.start`) | 后端只能在本插件自己声明的适配器上启动会话,不能使用其他插件的适配器 | [调试适配器](domains/debug-adapters.md) | | API-31 | VCS 提供者 | 既有能力 | [`vcsProviders`](../contract/v1/README.md#vcs-providers) | 不含内置 Git 的公共读取(见 API-42);Lithe 桌面端未声明 `vcsProviders` | [VCS](domains/vcs.md) | | API-33 | 项目生成器 | 既有能力 | [`projectGenerators`](../contract/v1/README.md#project-generators) | — | [项目生成器](domains/project-generators.md) | @@ -222,7 +222,7 @@ Status meanings: | API-24 | Terminals | Partial | [Plugin-owned native terminals](../contract/v1/README.md#plugin-owned-native-terminals) `terminal/create`, `show`, `close`, `reopen`, `dispose`, `onExit` (local workspaces) | Sending text to a terminal, reading its output | [Plugin backend](domains/backend.md) | | API-25 | Languages, grammars, LSP | Partial | [Languages](../contract/v1/README.md#languages) and [language servers](../contract/v1/README.md#language-servers); [packaged Monarch grammars and editor configuration in `languages`](../contract/v1/README.md#grammars-and-editor-configuration); [editor language-feature providers `editor/registerProviders`](../contract/v1/README.md#editor-language-feature-providers), binding 7 types (`definition`, `hover`, `completion`, `codeLens`, `foldingRange`, `semanticTokens`, `documentLink`) to ordinary plugin functions, where the language server answers first and plugin results only add; plugin-owned language server sessions: [the session declaration of `languageServers`](../contract/v1/README.md#plugin-owned-sessions) lists the requests, commands, and forwarded notifications a backend may use, with [`languageServer/request`, `notify`, `setStatus`](../contract/v1/README.md#language-server-host-methods) and the `languageServer/didChangeState` and `languageServer/didReceiveNotification` notifications, and Core enforces the session policy; [`launch.kind: "backend"`](../contract/v1/README.md#backend-resolved-launch) lets the plugin backend decide how the server starts | Symbols, formatting, rename, code actions, signature help, inlay hints, dynamic registration of highlighting from JSON passed at runtime; servers whose launch the backend decides in remote workspaces | [Languages](domains/languages.md), [Editor](domains/editor.md) | | API-27 | Editor actions, themes, decorations | Partial | [Independent editor actions `editor/registerActions`](../contract/v1/README.md#independent-editor-actions), binding ordinary functions to file ranges without LSP, build, or run; several icons at a line start, up to 4 `alternatives`, and a `reveal` in the click result | Themes, snippets, other decorations | [Editor](domains/editor.md) | -| API-29 | Build, tasks, tests, run preparation | Partial | [`buildSystems`](../contract/v1/README.md#build-systems), [`buildProviders`](../contract/v1/README.md#build-providers), [`buildModelInputs`](../contract/v1/README.md#optional-read-only-model-inputs), [`runConfigurationTypes`](../contract/v1/README.md#run-configuration-types) | The developer guides are incomplete; the Lithe desktop client does not declare `buildModelInputs`; it declares `runConfigurationTypes` since [1lck/Lithe-IDEA#2148](https://github.com/1lck/Lithe-IDEA/pull/2148), and runs plugin types without debugging them | [Build systems](domains/build-systems.md), [Build providers](domains/build-providers.md) | +| API-29 | Build, tasks, tests, run preparation | Partial | [`buildSystems`](../contract/v1/README.md#build-systems), [`buildProviders`](../contract/v1/README.md#build-providers), [`buildModelInputs`](../contract/v1/README.md#optional-read-only-model-inputs), [`runConfigurationTypes`](../contract/v1/README.md#run-configuration-types), [`beforeLaunchTasks`](../contract/v1/README.md#before-launch-tasks) | The developer guides are incomplete; the Lithe desktop client does not declare `buildModelInputs` or `beforeLaunchTasks`; it declares `runConfigurationTypes` since [1lck/Lithe-IDEA#2148](https://github.com/1lck/Lithe-IDEA/pull/2148), and runs plugin types without debugging them | [Build systems](domains/build-systems.md), [Build providers](domains/build-providers.md) | | API-30 | Debug adapters | Partial | [`debugAdapters`](../contract/v1/README.md#debug-adapters) and the host's DAP sessions; [`features` and `defaults`](../contract/v1/README.md#adapter-features-and-defaults) (hot code replace, step filters); backend-started [`debug/start`](../contract/v1/README.md#run-and-debug-sessions) (permission `debug.start`) | A backend can start sessions only on adapters its own plugin declares, not on another plugin's adapters | [Debug adapters](domains/debug-adapters.md) | | API-31 | VCS providers | Existing | [`vcsProviders`](../contract/v1/README.md#vcs-providers) | Public reads of built-in Git are not included (see API-42); the Lithe desktop client does not declare `vcsProviders` | [VCS](domains/vcs.md) | | API-33 | Project generators | Existing | [`projectGenerators`](../contract/v1/README.md#project-generators) | — | [Project generators](domains/project-generators.md) | diff --git a/shared/plugins/reference/capabilities-and-versions.md b/shared/plugins/reference/capabilities-and-versions.md index 94ec6a61..bfa262ab 100644 --- a/shared/plugins/reference/capabilities-and-versions.md +++ b/shared/plugins/reference/capabilities-and-versions.md @@ -53,6 +53,7 @@ Core 列以本仓库 `main` 上的 Core 源码为准([`capabilities.rs`](https | `buildProviders` `1` | 在 `0` 之上加:运行声明 `entrypoints: true`(入口运行,不需要目标),提供者用 `lithe/build/runEntrypoints` 回答一个源文件里可运行的入口,宿主把它保存为运行配置并按入口启动 | ✅ | ✅ | [Run entrypoints](../contract/v1/README.md#run-entrypoints-buildproviders-1) | | `buildModelInputs` `0` | `buildSystems[].modelSharing` 与 `modelInputs`:[已启用工作区插件之间共享的只读模型输入](../contract/v1/README.md#optional-read-only-model-inputs)(可选) | ✅ | 未声明 | [构建提供者](domains/build-providers.md) | | `runConfigurationTypes` `0` | `buildSystems[].runConfigurationTypes`:插件声明的运行配置类型(如 Go Build、Go Test),宿主按声明的字段画编辑器,Core 用 `build.runConfigurationPlan` 把保存的配置展开成命令行;所有运行配置共用“允许多个实例”开关 | ✅ | ✅¹ | [Run configuration types](../contract/v1/README.md#run-configuration-types) | +| `beforeLaunchTasks` `0` | `buildSystems[].beforeLaunchTasks`:插件声明的启动前任务(如“运行 Go 命令”),列在运行配置“启动前”的“添加新任务”菜单里;宿主按声明的字段画任务表单,Core 用 `runConfig.checkBeforeLaunchTask` 校验值、`build.beforeLaunchTaskPlan` 在拥有这个步骤列表的配置的工作目录里展开命令行 | ✅ | 未声明 | [Before-launch tasks](../contract/v1/README.md#before-launch-tasks) | | `vcsProviders` `0` | [`vcsProviders[]`](../contract/v1/README.md#vcs-providers);说 `litheVcs` | ✅ | ✅¹ | [版本控制提供者](domains/vcs.md) | | `debugAdapters` `0` | [`debugAdapters[]`](../contract/v1/README.md#debug-adapters):独立适配器、语言服务器内的适配器、[远程附加](../contract/v1/README.md#remote-attach)、参数和环境变量、[`features` 与 `defaults`](../contract/v1/README.md#adapter-features-and-defaults) | ✅ | ✅ | [调试适配器](domains/debug-adapters.md) | | `managedRuntimes` `0` | 固定归档、插件后端资格检查、跨版本缓存与安装前准备;权限 `runtimes.install` | ✅ | 配套宿主接入后声明 | [Managed runtimes](../contract/v1/README.md#managed-runtimes) | @@ -165,6 +166,7 @@ Each row is one capability. `requires` lists **exactly** the capabilities a mani | `buildProviders` `1` | Adds to `0`: run declarations with `entrypoints: true` (entrypoint runs, without a target); the provider answers `lithe/build/runEntrypoints` with the runnable entrypoints of one source file, which the host saves as run configurations and starts | ✅ | ✅ | [Run entrypoints](../contract/v1/README.md#run-entrypoints-buildproviders-1) | | `buildModelInputs` `0` | `buildSystems[].modelSharing` and `modelInputs`: [optional read-only model inputs](../contract/v1/README.md#optional-read-only-model-inputs) shared between enabled workspace plugins | ✅ | Not declared | [Build providers](domains/build-providers.md) | | `runConfigurationTypes` `0` | `buildSystems[].runConfigurationTypes`: run configuration types a plugin declares (such as Go Build and Go Test); the host draws the editor from the declared fields and Core expands a saved configuration into a command line with `build.runConfigurationPlan`; every run configuration shares the Allow multiple instances switch | ✅ | ✅¹ | [Run configuration types](../contract/v1/README.md#run-configuration-types) | +| `beforeLaunchTasks` `0` | `buildSystems[].beforeLaunchTasks`: before-launch tasks a plugin declares (such as Run Go Command), listed in the Add New Task menu of a run configuration's Before Launch list; the host draws the task's form from the declared fields, Core checks the values with `runConfig.checkBeforeLaunchTask` and expands the command line with `build.beforeLaunchTaskPlan` in the working directory of the configuration whose list names the step | ✅ | Not declared | [Before-launch tasks](../contract/v1/README.md#before-launch-tasks) | | `vcsProviders` `0` | [`vcsProviders[]`](../contract/v1/README.md#vcs-providers); they speak `litheVcs` | ✅ | ✅¹ | [VCS providers](domains/vcs.md) | | `debugAdapters` `0` | [`debugAdapters[]`](../contract/v1/README.md#debug-adapters): standalone adapters, adapters inside a language server, [remote attach](../contract/v1/README.md#remote-attach), arguments and environment, [`features` and `defaults`](../contract/v1/README.md#adapter-features-and-defaults) | ✅ | ✅ | [Debug adapters](domains/debug-adapters.md) | | `managedRuntimes` `0` | Pinned archives, plugin-owned qualification, version-independent cache and install preflight; permission `runtimes.install` | ✅ | Declared with companion host integration | [Managed runtimes](../contract/v1/README.md#managed-runtimes) | diff --git a/shared/plugins/reference/domains/build-systems.md b/shared/plugins/reference/domains/build-systems.md index 3773b8e6..780eb948 100644 --- a/shared/plugins/reference/domains/build-systems.md +++ b/shared/plugins/reference/domains/build-systems.md @@ -6,7 +6,7 @@ `buildSystems` 用数据描述一个项目级构建工具(Cargo、Go、Gradle、Maven 等):怎么识别项目根目录、找哪个可执行文件、怎么得到项目模型、有哪些任务和运行入口、哪些文件变化要重新同步。所有构建工具共用同一套模型和命令:Core 校验声明、检测实例、解码模型、展开每一条命令行,宿主只执行 Core 规划好的进程并把输出交回。所以社区插件加一个构建工具不需要改宿主,宿主代码也不按构建系统 ID 分支。模型需要程序计算时,再加一个[构建提供者](build-providers.md)。 -> **宿主支持。** Lithe 桌面端声明 `buildSystems` 和 `buildProviders`(版本都是 `0`):构建窗口发现构建实例、加载提供者模型、解析 Core 返回的有序可执行文件候选,并运行命令任务和提供者任务。桌面端也声明 `runConfigurationTypes` `0`([1lck/Lithe-IDEA#2148](https://github.com/1lck/Lithe-IDEA/pull/2148)):运行/调试配置对话框在内置类型之后列出插件类型,按 Core 描述的表单和插件翻译编辑,存到 `.lithe/run/plugin/<插件 ID>.toml`,按 Core 为检测到的实例规划的命令运行;插件类型不能调试。桌面端不声明 `buildModelInputs`、`executionProviders` 和 `toolchainProviders`:`requires` 里有其中任何一个的插件不会被提供安装,所以 `modelSharing` 和 `modelInputs` 在桌面端用不上。 +> **宿主支持。** Lithe 桌面端声明 `buildSystems` 和 `buildProviders`(版本都是 `0`):构建窗口发现构建实例、加载提供者模型、解析 Core 返回的有序可执行文件候选,并运行命令任务和提供者任务。桌面端也声明 `runConfigurationTypes` `0`([1lck/Lithe-IDEA#2148](https://github.com/1lck/Lithe-IDEA/pull/2148)):运行/调试配置对话框在内置类型之后列出插件类型,按 Core 描述的表单和插件翻译编辑,存到 `.lithe/run/plugin/<插件 ID>.toml`,按 Core 为检测到的实例规划的命令运行;插件类型不能调试。桌面端还没有声明 `beforeLaunchTasks` `0`,声明它的插件暂时不会被提供安装。桌面端不声明 `buildModelInputs`、`executionProviders` 和 `toolchainProviders`:`requires` 里有其中任何一个的插件不会被提供安装,所以 `modelSharing` 和 `modelInputs` 在桌面端用不上。 > 构建系统的实例级选项(`scope: "instance"`)和项目任务的 `preparation`,桌面端尚未呈现:插件照常安装,这部分没有界面,也不会被调用。构建提供者的运行准备、测试、调试准备、模型输入、原生配置、内联测试报告和运行时调试同样尚未呈现,见[构建提供者](build-providers.md)。 > 宿主只呈现它实现的功能,插件不得依赖宿主一定会调用其中任何一个。该注释还写到系统命令的工具发现目前只读 `PATH`,依赖项目工具链或用户覆盖的计划会被拒绝,它是否也约束可执行文件候选里的 `setting` 和 `toolchain` 来源,注释没有说明;依赖这两种来源前,先在桌面端实际试一遍。说明见 [`pluginhost.go`](https://github.com/1lck/Lithe-IDEA/blob/preview/desktop/internal/pluginhost/pluginhost.go);各能力的对照见[能力与协议版本对照](../capabilities-and-versions.md#能力版本requires)。 > 对契约有疑问,请到 [Lithe-core-rust 的 Issues](https://github.com/Lithe-IDEA/Lithe-core-rust/issues) 反馈。 @@ -14,7 +14,7 @@ | 项目 | 内容 | | --- | --- | | 清单字段 | `buildSystems[]`:`id`、`displayName`、`icon`、`detection`、`invocation`、`options`、`model`、`provider`、`tasks`、`run`、`test`、`diagnostics`、`dependencies`、`sync`、`layout`、`hostIntegration`,以及可选的 `modelSharing`、`modelInputs`(见下文)和 `configuration`(原生配置,见[构建提供者](build-providers.md)) | -| 能力版本 | `buildSystems` `0`。不带 `provider` 的构建系统只需要它;带 `provider` 还要 `buildProviders: 0`;`modelSharing`、`modelInputs` 另需 `buildModelInputs: 0`(消费者还需要 `buildProviders: 0`);`runConfigurationTypes` 另需 `runConfigurationTypes: 0`;可执行文件候选用 `setting` 来源时还要 `settings: 0`(见 `build-tool-path`)。可执行文件解析本身是基础契约,不是能力,不需要在 `requires` 里声明。`requires` 必须恰好列出清单用到的能力,见[版本对照](../capabilities-and-versions.md#能力版本requires) | +| 能力版本 | `buildSystems` `0`。不带 `provider` 的构建系统只需要它;带 `provider` 还要 `buildProviders: 0`;`modelSharing`、`modelInputs` 另需 `buildModelInputs: 0`(消费者还需要 `buildProviders: 0`);`runConfigurationTypes` 另需 `runConfigurationTypes: 0`;`beforeLaunchTasks` 另需 `beforeLaunchTasks: 0`;可执行文件候选用 `setting` 来源时还要 `settings: 0`(见 `build-tool-path`)。可执行文件解析本身是基础契约,不是能力,不需要在 `requires` 里声明。`requires` 必须恰好列出清单用到的能力,见[版本对照](../capabilities-and-versions.md#能力版本requires) | | 协议 | 没有进程协议;`model.source: "provider"` 时走 [`litheBuild`](build-providers.md) | | API 编号 | [API-29](../api-catalog.md#现在能用的-api):构建、任务、测试、运行准备 | | 权限 | `process.build` | @@ -35,6 +35,7 @@ | `provider` | 没有命令能打印模型时,由[构建提供者](build-providers.md)回答模型和依赖请求 | | `tasks`、`run`、`test` | 任务目录、从模型目标或任务生成的运行入口、测试的范围、过滤器和结果文件 | | `runConfigurationTypes` | 用户可以在运行/调试配置对话框里新建的配置类型(如 Go Build、Go Test):字段、默认值、显示条件和命令行模板;宿主按字段画编辑器,Core 校验值并展开命令行,见[运行配置类型](../../contract/v1/README.md#run-configuration-types) | +| `beforeLaunchTasks` | 运行配置“启动前”列表里“添加新任务”菜单提供的任务(如“运行 Go 命令”):声明方式同运行配置类型,但没有 `execution` 和程序参数;任务在拥有该列表的配置的工作目录里运行,见[启动前任务](../../contract/v1/README.md#before-launch-tasks) | | `diagnostics`、`dependencies` | 诊断的行匹配或 `litheDiagnostics`;依赖列表或依赖树的来源 | | `sync`、`layout` | 哪些文件变化会让模型过期;每个项目要作为 `excluded` 内容根加入的目录;`layout.hiddenDirectoryNames` 是插件启用期间所有工作区在任意层级隐藏的目录名(如依赖、缓存和构建输出目录),项目树、搜索、文件事件、本地历史、运行发现、构建探测和仓库发现都会跳过 | @@ -72,6 +73,7 @@ | [Declarative project preparation](../../contract/v1/README.md#declarative-project-preparation) | 运行前准备任务 | | [Executable resolution](../../contract/v1/README.md#executable-resolution) | 可执行文件候选、排序、严格选择 | | [Run configuration types](../../contract/v1/README.md#run-configuration-types) | 插件声明的运行配置类型、字段、保存位置和 `build.runConfigurationPlan` | +| [Before-launch tasks](../../contract/v1/README.md#before-launch-tasks) | 插件声明的启动前任务、步骤的保存形式、工作目录和 `build.beforeLaunchTaskPlan` | | [Host integrations](../../contract/v1/README.md#host-integrations) | 构建系统的宿主集成(保留字段,Core 不实现) | | [Commands](../../contract/v1/README.md#commands) | `build.*` Core 命令:检测、规划、解码、同步指纹 | @@ -105,7 +107,7 @@ `buildSystems` describes a project-level build tool (Cargo, Go, Gradle, Maven, …) as data: how to recognize a project root, which executable to use, how to get the project model, which tasks and run entries exist, and which file changes require a re-sync. Every build tool shares the same model and commands: Core validates the declaration, detects instances, decodes the model, and expands every command line; the host only runs the processes Core planned and passes their output back. A community plugin therefore adds a build tool without any host change, and no host code branches on a build-system ID. When the model must be computed by a program, add a [build provider](build-providers.md). -> **Host support.** The Lithe desktop declares `buildSystems` and `buildProviders` (both version `0`): the Build window detects build instances, loads provider models, resolves the ordered executable candidates Core returns, and runs command and provider tasks. It also declares `runConfigurationTypes` `0` ([1lck/Lithe-IDEA#2148](https://github.com/1lck/Lithe-IDEA/pull/2148)): the Run/Debug Configurations dialog lists plugin types after the built-in ones, edits them with the form Core describes in the plugin's translation, saves them to `.lithe/run/plugin/.toml`, and runs them with the command Core plans for the detected instance; a plugin type has no debugger. The desktop does not declare `buildModelInputs`, `executionProviders` or `toolchainProviders`: a plugin whose `requires` lists any of them is not offered for installation, so `modelSharing` and `modelInputs` are unusable there. +> **Host support.** The Lithe desktop declares `buildSystems` and `buildProviders` (both version `0`): the Build window detects build instances, loads provider models, resolves the ordered executable candidates Core returns, and runs command and provider tasks. It also declares `runConfigurationTypes` `0` ([1lck/Lithe-IDEA#2148](https://github.com/1lck/Lithe-IDEA/pull/2148)): the Run/Debug Configurations dialog lists plugin types after the built-in ones, edits them with the form Core describes in the plugin's translation, saves them to `.lithe/run/plugin/.toml`, and runs them with the command Core plans for the detected instance; a plugin type has no debugger. The desktop does not declare `beforeLaunchTasks` `0` yet, so a plugin that declares it is not offered for installation. The desktop does not declare `buildModelInputs`, `executionProviders` or `toolchainProviders`: a plugin whose `requires` lists any of them is not offered for installation, so `modelSharing` and `modelInputs` are unusable there. > Build-system instance options (`scope: "instance"`) and project-task `preparation` are not presented on the desktop yet: the plugin installs, and that part has no surface and is never called. Build-provider run preparation, tests, debug preparation, model inputs, native configuration, inline test reports and runtime debug are not presented either; see [Build providers](build-providers.md). > A host presents the features it implements; a plugin must not depend on a host calling any of them. The same comment says tool discovery for system commands reads `PATH` only and that a plan depending on a project toolchain or a user override is refused. It does not say whether that also limits the `setting` and `toolchain` sources of executable candidates, so try those two on the desktop before relying on them. See [`pluginhost.go`](https://github.com/1lck/Lithe-IDEA/blob/preview/desktop/internal/pluginhost/pluginhost.go); the per-capability comparison is in [Capabilities and protocol versions](../capabilities-and-versions.md#capability-versions-requires). > Questions about the contract go to [Lithe-core-rust Issues](https://github.com/Lithe-IDEA/Lithe-core-rust/issues). @@ -113,7 +115,7 @@ | Item | Value | | --- | --- | | Manifest fields | `buildSystems[]`: `id`, `displayName`, `icon`, `detection`, `invocation`, `options`, `model`, `provider`, `tasks`, `run`, `test`, `diagnostics`, `dependencies`, `sync`, `layout`, `hostIntegration`, plus the optional `modelSharing`, `modelInputs` (below) and `configuration` (native configuration, see [Build providers](build-providers.md)) | -| Capability versions | `buildSystems` `0`. A build system without `provider` needs only it; with `provider` it also needs `buildProviders: 0`; `modelSharing` and `modelInputs` also need `buildModelInputs: 0` (a consumer also needs `buildProviders: 0`); `runConfigurationTypes` also needs `runConfigurationTypes: 0`; a `setting` executable source also needs `settings: 0` (see `build-tool-path`). Executable resolution itself is base contract, not a capability, and is not declared in `requires`. `requires` must list exactly the capabilities the manifest uses; see [versions](../capabilities-and-versions.md#capability-versions-requires) | +| Capability versions | `buildSystems` `0`. A build system without `provider` needs only it; with `provider` it also needs `buildProviders: 0`; `modelSharing` and `modelInputs` also need `buildModelInputs: 0` (a consumer also needs `buildProviders: 0`); `runConfigurationTypes` also needs `runConfigurationTypes: 0`; `beforeLaunchTasks` also needs `beforeLaunchTasks: 0`; a `setting` executable source also needs `settings: 0` (see `build-tool-path`). Executable resolution itself is base contract, not a capability, and is not declared in `requires`. `requires` must list exactly the capabilities the manifest uses; see [versions](../capabilities-and-versions.md#capability-versions-requires) | | Protocols | No process protocol; `model.source: "provider"` uses [`litheBuild`](build-providers.md) | | API IDs | [API-29](../api-catalog.md#apis-usable-now): build, tasks, tests, run preparation | | Permissions | `process.build` | @@ -134,6 +136,7 @@ IDs of build systems, tasks, and run entries start with a lowercase letter and u | `provider` | The [build provider](build-providers.md) that answers model and dependency requests when no command prints them | | `tasks`, `run`, `test` | The task catalog, run entries generated from model targets or tasks, and the scopes, filters, and result files of tests | | `runConfigurationTypes` | Configuration types a user can create in the Run/Debug Configurations dialog (such as Go Build and Go Test): fields, defaults, visibility conditions, and the command-line template; the host draws the editor from the fields and Core validates the values and expands the command line, see [Run configuration types](../../contract/v1/README.md#run-configuration-types) | +| `beforeLaunchTasks` | Tasks the Add New Task menu of a run configuration's Before Launch list offers (such as Run Go Command): declared like run configuration types, without an `execution` or program arguments; a task runs in the working directory of the configuration whose list names it, see [Before-launch tasks](../../contract/v1/README.md#before-launch-tasks) | | `diagnostics`, `dependencies` | Line matchers or `litheDiagnostics` for diagnostics; the source of the dependency list or tree | | `sync`, `layout` | Which file changes make the model stale; directories added to every project as `excluded` content roots; `layout.hiddenDirectoryNames`, folder names such as dependency, cache and build output folders that every workspace hides at any depth while the plugin is enabled: the project tree, search, file events, Local History, run discovery, build detection and repository discovery skip them | @@ -171,6 +174,7 @@ A build system's `hostIntegration` and a language server's `hostIntegration` are | [Declarative project preparation](../../contract/v1/README.md#declarative-project-preparation) | Tasks that run before a launch | | [Executable resolution](../../contract/v1/README.md#executable-resolution) | Executable candidates, ordering, strict selection | | [Run configuration types](../../contract/v1/README.md#run-configuration-types) | Plugin-declared run configuration types, their fields, storage, and `build.runConfigurationPlan` | +| [Before-launch tasks](../../contract/v1/README.md#before-launch-tasks) | Plugin-declared before-launch tasks, how a step is saved, its working directory, and `build.beforeLaunchTaskPlan` | | [Host integrations](../../contract/v1/README.md#host-integrations) | Host integrations for build systems (reserved; Core implements none) | | [Commands](../../contract/v1/README.md#commands) | `build.*` Core commands: detection, plans, decoding, sync fingerprints | diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index b8cc6223..f8eed517 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -14,7 +14,7 @@ ## 待合入 -- `managedRuntimes` 0(API-23):新增固定 HTTPS 归档与 SHA-256、平台选择、与插件版本无关的缓存身份,以及插件后端对外部/暂存依赖的资格检查契约。新增权限 `runtimes.install`、审查程序 `managedRuntime`、Core 命令 `plugins.managedRuntimes.plan` 与 `plugins.managedRuntimes.decodeResolution`;正常语言服务器启动可接收只读 `runtimes` 映射。原生 `lsp.startServer` 新增可选 `functionRelayEnabled`(默认 true),准备会话设为 false 隔离跨插件调用但保留宿主直接调用。无新增宿主 RPC 或 SDK 版本。实现见 [#96](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/96)(lithe-support[bot]);合入日期在合并后补入下方时间线。宿主须先发布对应能力,插件才可要求它。 +目前没有。 ## 按协议查首次出现 @@ -55,6 +55,8 @@ | `packageTrust` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `pluginFunctions` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `projectGenerators` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | +| `beforeLaunchTasks` | 0 | 2026-11-18 | [#97](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/97) | +| `managedRuntimes` | 0 | 2026-11-18 | [#96](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/96) | | `runConfigurationTypes` | 0 | 2026-11-18 | [#94](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/94) | | `sourceSettings` | 0 | 2026-11-15 | [#57](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/57) | | `sourceSettings` | 1 | 2026-11-17 | [#79](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/79) | @@ -145,6 +147,8 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改了什么 | | --- | --- | --- | --- | --- | +| [#97](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/97) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-29 | **`beforeLaunchTasks` 0** | 运行配置“启动前”的插件任务(对标 IntelliJ IDEA 的“添加新任务”,[1lck/Lithe-IDEA#2100](https://github.com/1lck/Lithe-IDEA/issues/2100)):构建系统新增 `beforeLaunchTasks`(最多 16 个),声明方式和 `runConfigurationTypes` 相同(`id`、`displayName`、可选 `description`、`icon`、最多 16 个 `fields` 和 `arguments` 模板),但任务总是运行到结束,不能写 `execution`,`arguments` 不能用 `${userArguments}`;任务 ID 与类型 ID 各自唯一。运行配置的 `beforeLaunch` 步骤除 `{configuration}` 外新增 `{task: {pluginID, buildSystemID, type, values}}`,任务在拥有这个步骤列表的配置的工作目录里运行,不带程序参数和环境变量;步骤对象不允许出现别的键。Core 新增命令 `runConfig.checkBeforeLaunchTask`(校验“添加新任务”小表单的值,返回要放进字段值的步骤)和 `build.beforeLaunchTaskPlan`(把任务步骤展开成 argv 计划);`runConfig.editorForm` 的 `beforeLaunch` 字段新增 `tasks`(已安装插件声明的任务种类及其表单),字段值里的任务步骤是 `{task, name, summary, values}`,插件已卸载的是 `{task, name, summary, missing: true}`;`runConfig.beforeLaunch`、`runConfig.updateOptions`、`runConfig.saveEditorChanges` 新增请求字段 `runTypePlugins`,`runConfig.beforeLaunch` 的任务步骤返回 `{task, name, summary, workingDirectory}`,拒绝码新增 `taskNotDeclared` 和 `invalidTaskValues`(带 `task`),确认指纹也覆盖任务及其值和工作目录。`runConfigurationTypes` 的必填 `arguments` 字段留空现在会被拒绝(以前没有执行 `required`)。语言文件新增 `beforeLaunchTasks.<构建系统 ID>.<任务 ID>`;保存的值不合法时是 `plugin.build.invalidBeforeLaunchTask`(字段 `values.`)。新增 fixture `before-launch-tasks/`。用到它的插件声明 `beforeLaunchTasks: 0`,不认识它的宿主不会安装。没有新增宿主方法或通知。 | +| [#96](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/96) | [@lithe-support[bot]](https://github.com/apps/lithe-support) | API-23 | **`managedRuntimes` 0** | 受管运行时:新增固定 HTTPS 归档与 SHA-256、平台选择、与插件版本无关的缓存身份,以及插件后端对外部/暂存依赖的资格检查契约。新增权限 `runtimes.install`、审查程序 `managedRuntime`、Core 命令 `plugins.managedRuntimes.plan` 与 `plugins.managedRuntimes.decodeResolution`;正常语言服务器启动可接收只读 `runtimes` 映射。原生 `lsp.startServer` 新增可选 `functionRelayEnabled`(默认 true),准备会话设为 false 隔离跨插件调用但保留宿主直接调用。无新增宿主 RPC 或 SDK 版本。宿主须先发布对应能力,插件才可要求它。 | | [#94](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/94) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-29 | **`runConfigurationTypes` 0** | 插件声明自己的运行配置类型([1lck/Lithe-IDEA#2100](https://github.com/1lck/Lithe-IDEA/issues/2100)):构建系统新增 `runConfigurationTypes`(最多 16 个),每个类型有 `id`、`displayName`、可选的 `description`、`execution`(`application` 或 `task`)、`arguments` 模板和最多 16 个字段 `fields`(`text`、`choice`、`checkbox`、`file`、`directory`、`arguments`,可带 `default`、`required`、`placeholder`、`visibleWhen` 和每个字段自己的 `arguments`)。新模板变量 `${field:}` 是整个参数,每个字段必须在类型参数或字段参数里恰好用一次(只控制显示、不带参数的字段除外);`${userArguments}` 恰好出现一次时,编辑器才显示程序参数。用户保存的配置类型是 `build.run-type`,`extensions.build` 记 `{pluginID, buildSystemID, type, values}`,仍存在 `.lithe/run/plugin/<插件 ID>.toml`。所有运行配置(含 Core 自带的)新增通用开关 `allowMultipleInstances`:关时再次启动先停掉正在运行的进程,开时宿主在旁边再起一个。Core 新增命令 `build.runConfigurationPlan`(把保存的配置展开成 argv 计划),`runConfig.configurationTypes`、`runConfig.editorForm`、`runConfig.saveConfiguration` 新增请求字段 `runTypePlugins`(清单和语言文件),语言文件新增 `runConfigurationTypes.<构建系统 ID>.<类型 ID>`。字段值不合法时是 `plugin.build.invalidRunConfiguration`(字段 `values.`),语言文件不合法时是 `plugin.build.invalidLocalization`。新增 fixture `run-configuration-types/`。用到它的插件声明 `runConfigurationTypes: 0`,不认识它的宿主不会安装。没有新增宿主方法或通知。 | | [#93](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/93) | [@Mucheen](https://github.com/Mucheen) | API-23 | `toolDefinitions` 0 内的补充 | 项目内工具环境解释器符号链接链校验与项目候选返回([1lck/Lithe-IDEA#2122](https://github.com/1lck/Lithe-IDEA/issues/2122)):`projectCodeAllowed != true` 时所有 `projectFile` 候选仍以 `projectCodeRequiresAction` 跳过且不返回探针目标;`projectKind: "environment"`(如 `.venv`)要求 `home`、到可执行文件之间的父目录(如 `.venv/bin`、`.venv/Scripts`)、环境内 `requires` 标记以及实际存在的 `pathPrepend` 目录规范化后留在工作区和 `home` 内(记为 `missing` 的跨平台 `pathPrepend` 子目录忽略,未观察到或软链逃逸以 `unsafePath` 拒绝),叶子可执行文件允许是指向工作区内或工作区外常规可执行文件的单跳或多跳符号链接,探测与选中结果均保留字面 `executable` 路径;`wrapper` 仍要求链接目标留在工作区根内。`toolchains.discoveryPlan` 的每个工具新增平台过滤后的 `projectFiles`;`toolchains.candidates` 新增根级 `project` 候选列表;`toolchains.resolve` 新增 `projectCandidates`,且没有候选解析成功时保留解析顺序中的首个失败原因。最近的项目声明遮住根目录的声明,可选发现无法表示的路径会被跳过,已验证的固定选择仍可生效。项目环境和外部安装都可以省略明确观测为缺失的 PATH 目录。`toolchains.catalogState` / `editCatalog` 支持在本机 `toolchains/global.json` 维护规范化的 `trustedWorkspaces` 并查询 `projectCodeAllowed`。同步更新过时宿主能力对照说明;清单格式和能力版本不变,没有新增插件 RPC 方法或通知。 | | [#89](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/89) | [@1lck](https://github.com/1lck) | — | **`buildProviders` 1**、**`litheBuild` 1** | 按源文件找运行入口([1lck/Lithe-IDEA#2104](https://github.com/1lck/Lithe-IDEA/issues/2104)):运行声明可写 `entrypoints: true`(只能是提供者的 `application`,不写 `fromTargets`、`fromTasks`、`arguments`、`extension`、`debug`),它不对应任何目标,宿主不按目标列出它。新提供者方法 `lithe/build/runEntrypoints`(参数多一个工作区相对路径 `file`)返回 `litheRunEntrypoints` 0 文档,列出这个文件里可运行的入口 `{run, name, entrypoint, project}`,最多 64 个;Core 新增 `build.runEntrypointsPlan` 和 `build.decodeRunEntrypoints` 校验。`lithe/build/prepareRun` 对入口运行不带 `target`,必须带 `launchOptions.entrypoint`。宿主提供 `litheBuild` 版本 `[0, 1]`,三个 SDK 回答宿主提供的最新版本,Java/Node SDK 新增 `onRunEntrypoints`/`build.runEntrypoints`。用入口运行的插件声明 `buildProviders: 1`,只支持 0 的宿主不会安装;其他插件不受影响。新增 fixture `build-provider-run-entrypoints.plugin.json`、`build-run-entrypoints.json`。没有新增宿主方法或通知。 | From 8adf87a392e69f0ad7f18d233a37d4a2e230f03c Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Wed, 18 Nov 2026 20:25:49 +0800 Subject: [PATCH 2/2] =?UTF-8?q?feat(run-config):=20=E6=96=B0=E5=A2=9E=20ru?= =?UTF-8?q?nConfig.beforeLaunchField=EF=BC=8C=E7=BB=99=E4=B8=8D=E7=94=A8?= =?UTF-8?q?=20editorForm=20=E7=9A=84=E7=BC=96=E8=BE=91=E5=99=A8=E8=AF=BB?= =?UTF-8?q?=E5=8F=96=E5=90=AF=E5=8A=A8=E5=89=8D=E5=88=97=E8=A1=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 构建运行的编辑器不走 runConfig.editorForm,以前由宿主自己算可选配置,也看不到插件任务。 新命令按已保存配置返回 beforeLaunch 字段的 candidates、tasks 和当前生效的 value, 编辑后的值照旧交给 runConfig.updateOptions。未知配置返回 invalid_request。 --- rust/contracts/rust-core-api.md | 9 ++++ rust/crates/core/src/protocol/command.rs | 5 +++ .../core/src/runtime/dispatcher/run_config.rs | 12 +++++ .../core/src/tests/before_launch_tasks.rs | 17 +++++++ rust/crates/execution/src/configuration.rs | 5 ++- .../src/configuration/before_launch.rs | 44 +++++++++++++++++++ .../plugins/reference/protocol-changelog.md | 2 +- 7 files changed, 91 insertions(+), 3 deletions(-) diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 89aad8eb..7706c4ad 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -725,6 +725,7 @@ or removing a command fails until the table changes in the same commit. | `runConfig.arrange` | Return the file changes that move configurations between folders and save the list order | | `runConfig.beforeLaunch` | Expand the process runs and plugin tasks a configuration starts first, and say whether the user must confirm them | | `runConfig.checkBeforeLaunchTask` | Check the values of a plugin task step being added or edited and return the step for the `beforeLaunch` editor value | +| `runConfig.beforeLaunchField` | Return the `beforeLaunch` editor field of a saved configuration for an editor that does not use `runConfig.editorForm` | | `runConfig.createLaunchPlan` | Project one effective configuration into a platform-neutral Run or Debug plan | | `runConfig.providerLaunchInputs` | Resolve user choices for a provider-owned launch | | `git.status` | Resolve the repository, current branch, and working-tree changes | @@ -4164,6 +4165,14 @@ keys of a declared editor. A task no installed plugin declares fails the call with `not_supported`. Nothing is written; the step is saved with the configuration. +`runConfig.beforeLaunchField` accepts `{root, configurationId, +localDocument?, runTypePlugins?}` and replies `{candidates, tasks, value}`: +the field of `runConfig.editorForm` for a saved configuration of any +provider, with `value` the effective list. It serves an editor that edits +the list without the rest of a form, such as the editor of a build run, which +then sends the edited value to `runConfig.updateOptions`. An unknown +configuration is `invalid_request`. + `runConfig.saveConfiguration` checks the field like `runConfig.beforeLaunch` and reports `{field: "beforeLaunch", code}` with `notFound`, `notAllowed`, `unavailable`, `conflict` (a cycle), `tooLong`, `taskNotDeclared` or diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 4c255035..3acc209c 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -760,6 +760,8 @@ pub enum RunConfigCommand { BeforeLaunch, /// Checks the values of a plugin task step before launch (`runConfig.checkBeforeLaunchTask`). CheckBeforeLaunchTask, + /// Reads the Before Launch list of a saved configuration for an editor (`runConfig.beforeLaunchField`). + BeforeLaunchField, /// Produces the process plan for one configuration (`runConfig.createLaunchPlan`). CreateLaunchPlan, /// Resolves user choices for a provider-owned launch (`runConfig.providerLaunchInputs`). @@ -1470,6 +1472,9 @@ impl CoreCommand { "runConfig.checkBeforeLaunchTask" => { Some(Self::RunConfig(RunConfigCommand::CheckBeforeLaunchTask)) } + "runConfig.beforeLaunchField" => { + Some(Self::RunConfig(RunConfigCommand::BeforeLaunchField)) + } "runConfig.createLaunchPlan" => { Some(Self::RunConfig(RunConfigCommand::CreateLaunchPlan)) } diff --git a/rust/crates/core/src/runtime/dispatcher/run_config.rs b/rust/crates/core/src/runtime/dispatcher/run_config.rs index eda798a3..49bb3516 100644 --- a/rust/crates/core/src/runtime/dispatcher/run_config.rs +++ b/rust/crates/core/src/runtime/dispatcher/run_config.rs @@ -231,6 +231,18 @@ pub(super) fn dispatch( }, ), ), + RunConfigCommand::BeforeLaunchField => respond( + id, + with_run_types( + payload, + "Invalid before-launch field request", + false, + |mut request: crate::execution::BeforeLaunchFieldRequest, run_types| { + request.run_types = run_types; + crate::execution::before_launch_field(request) + }, + ), + ), RunConfigCommand::DeleteConfiguration => { match serde_json::from_value::(payload) .map_err(|error| { diff --git a/rust/crates/core/src/tests/before_launch_tasks.rs b/rust/crates/core/src/tests/before_launch_tasks.rs index fe1cfeb8..26f8186e 100644 --- a/rust/crates/core/src/tests/before_launch_tasks.rs +++ b/rust/crates/core/src/tests/before_launch_tasks.rs @@ -1,6 +1,7 @@ //! Before-launch tasks plugins declare in `buildSystems[].beforeLaunchTasks` //! (API-29): the `beforeLaunch` editor field offers them as kinds of step, //! `runConfig.checkBeforeLaunchTask` checks the step's form, +//! `runConfig.beforeLaunchField` gives the field to an editor without a form, //! `runConfig.beforeLaunch` expands them with the runs, and //! `build.beforeLaunchTaskPlan` turns one into the argv plan the host starts. @@ -262,6 +263,22 @@ fn task_steps_are_checked_saved_and_reopened() { reopened["values"]["beforeLaunch"], json!([step, "user:gen"]) ); + // An editor without runConfig.editorForm reads the same field. + let field = call( + "runConfig.beforeLaunchField", + json!({ "root": root, "configurationId": "user:app", "runTypePlugins": plugins() }), + ); + assert_eq!(field["value"], json!([step, "user:gen"]), "{field}"); + assert_eq!( + field["candidates"], + json!([{ "id": "user:gen", "name": "gen" }]) + ); + assert_eq!(field["tasks"], before_launch_field(&reopened)["tasks"]); + let unknown = reply( + "runConfig.beforeLaunchField", + json!({ "root": root, "configurationId": "user:none" }), + ); + assert_eq!(unknown["error"]["code"], "invalid_request", "{unknown}"); let removed = call( "runConfig.editorForm", json!({ "root": root, "configurationId": "user:app" }), diff --git a/rust/crates/execution/src/configuration.rs b/rust/crates/execution/src/configuration.rs index b2f25306..bb546f44 100644 --- a/rust/crates/execution/src/configuration.rs +++ b/rust/crates/execution/src/configuration.rs @@ -37,8 +37,9 @@ mod validation; pub use arrangement::{arrange, ArrangeRequest}; pub(crate) use arrangement::{valid_folder, Arrangement}; pub use before_launch::{ - before_launch, check_before_launch_task, BeforeLaunchRequest, BeforeLaunchStep, - CheckBeforeLaunchTaskRequest, ConfigurationStep, TaskStep, + before_launch, before_launch_field, check_before_launch_task, BeforeLaunchFieldRequest, + BeforeLaunchRequest, BeforeLaunchStep, CheckBeforeLaunchTaskRequest, ConfigurationStep, + TaskStep, }; pub use copying::{copy_configuration, CopyConfigurationRequest}; pub use declared::{ diff --git a/rust/crates/execution/src/configuration/before_launch.rs b/rust/crates/execution/src/configuration/before_launch.rs index abec5736..5d0182a9 100644 --- a/rust/crates/execution/src/configuration/before_launch.rs +++ b/rust/crates/execution/src/configuration/before_launch.rs @@ -609,3 +609,47 @@ pub fn check_before_launch_task(request: CheckBeforeLaunchTaskRequest) -> Result reference.validate()?; Ok(json!({ "status": "ok", "step": task.task_step_item(&reference) })) } + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +/// Request for the Before Launch list of a saved configuration, for an editor +/// that does not use `runConfig.editorForm`. +pub struct BeforeLaunchFieldRequest { + /// Canonical workspace root. + pub root: String, + /// The saved configuration whose list is edited. + pub configuration_id: String, + /// Host-owned replacement for the machine-local layer. + #[serde(default)] + pub local_document: Option, + /// The kinds installed plugins declare, set by the dispatcher from + /// `runTypePlugins`. + #[serde(skip)] + pub run_types: Vec, +} + +/// `runConfig.beforeLaunchField`: the Before Launch list of configuration +/// `configurationId` as the `beforeLaunch` field of `runConfig.editorForm` +/// gives it. +/// +/// Replies `{candidates, tasks, value}`: the configurations a step may start, +/// the task kinds installed plugins declare, and the effective list as editor +/// items. The host sends the edited items back through +/// `runConfig.updateOptions`. An unknown ID fails with `InvalidRequest`. +pub fn before_launch_field(request: BeforeLaunchFieldRequest) -> Result { + let root = existing_root(&request.root)?; + let layers = read_layers(&root, None, request.local_document)?; + let resolved = Resolved::read(&root, &layers)?; + let configuration = resolved + .by_id + .get(&request.configuration_id) + .ok_or_else(|| { + CoreError::new(ErrorCode::InvalidRequest, "Run configuration was not found") + })?; + let choices = StepChoices::new(&resolved, Some(&configuration.id), &request.run_types); + Ok(json!({ + "candidates": choices.candidates, + "tasks": choices.tasks, + "value": editor_items(&configuration.before_launch, &request.run_types), + })) +} diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index f8eed517..09a92396 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -147,7 +147,7 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改了什么 | | --- | --- | --- | --- | --- | -| [#97](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/97) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-29 | **`beforeLaunchTasks` 0** | 运行配置“启动前”的插件任务(对标 IntelliJ IDEA 的“添加新任务”,[1lck/Lithe-IDEA#2100](https://github.com/1lck/Lithe-IDEA/issues/2100)):构建系统新增 `beforeLaunchTasks`(最多 16 个),声明方式和 `runConfigurationTypes` 相同(`id`、`displayName`、可选 `description`、`icon`、最多 16 个 `fields` 和 `arguments` 模板),但任务总是运行到结束,不能写 `execution`,`arguments` 不能用 `${userArguments}`;任务 ID 与类型 ID 各自唯一。运行配置的 `beforeLaunch` 步骤除 `{configuration}` 外新增 `{task: {pluginID, buildSystemID, type, values}}`,任务在拥有这个步骤列表的配置的工作目录里运行,不带程序参数和环境变量;步骤对象不允许出现别的键。Core 新增命令 `runConfig.checkBeforeLaunchTask`(校验“添加新任务”小表单的值,返回要放进字段值的步骤)和 `build.beforeLaunchTaskPlan`(把任务步骤展开成 argv 计划);`runConfig.editorForm` 的 `beforeLaunch` 字段新增 `tasks`(已安装插件声明的任务种类及其表单),字段值里的任务步骤是 `{task, name, summary, values}`,插件已卸载的是 `{task, name, summary, missing: true}`;`runConfig.beforeLaunch`、`runConfig.updateOptions`、`runConfig.saveEditorChanges` 新增请求字段 `runTypePlugins`,`runConfig.beforeLaunch` 的任务步骤返回 `{task, name, summary, workingDirectory}`,拒绝码新增 `taskNotDeclared` 和 `invalidTaskValues`(带 `task`),确认指纹也覆盖任务及其值和工作目录。`runConfigurationTypes` 的必填 `arguments` 字段留空现在会被拒绝(以前没有执行 `required`)。语言文件新增 `beforeLaunchTasks.<构建系统 ID>.<任务 ID>`;保存的值不合法时是 `plugin.build.invalidBeforeLaunchTask`(字段 `values.`)。新增 fixture `before-launch-tasks/`。用到它的插件声明 `beforeLaunchTasks: 0`,不认识它的宿主不会安装。没有新增宿主方法或通知。 | +| [#97](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/97) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-29 | **`beforeLaunchTasks` 0** | 运行配置“启动前”的插件任务(对标 IntelliJ IDEA 的“添加新任务”,[1lck/Lithe-IDEA#2100](https://github.com/1lck/Lithe-IDEA/issues/2100)):构建系统新增 `beforeLaunchTasks`(最多 16 个),声明方式和 `runConfigurationTypes` 相同(`id`、`displayName`、可选 `description`、`icon`、最多 16 个 `fields` 和 `arguments` 模板),但任务总是运行到结束,不能写 `execution`,`arguments` 不能用 `${userArguments}`;任务 ID 与类型 ID 各自唯一。运行配置的 `beforeLaunch` 步骤除 `{configuration}` 外新增 `{task: {pluginID, buildSystemID, type, values}}`,任务在拥有这个步骤列表的配置的工作目录里运行,不带程序参数和环境变量;步骤对象不允许出现别的键。Core 新增命令 `runConfig.checkBeforeLaunchTask`(校验“添加新任务”小表单的值,返回要放进字段值的步骤)、`runConfig.beforeLaunchField`(给不用 `runConfig.editorForm` 的编辑器,例如构建运行的编辑器,返回已保存配置的 `beforeLaunch` 字段)和 `build.beforeLaunchTaskPlan`(把任务步骤展开成 argv 计划);`runConfig.editorForm` 的 `beforeLaunch` 字段新增 `tasks`(已安装插件声明的任务种类及其表单),字段值里的任务步骤是 `{task, name, summary, values}`,插件已卸载的是 `{task, name, summary, missing: true}`;`runConfig.beforeLaunch`、`runConfig.updateOptions`、`runConfig.saveEditorChanges` 新增请求字段 `runTypePlugins`,`runConfig.beforeLaunch` 的任务步骤返回 `{task, name, summary, workingDirectory}`,拒绝码新增 `taskNotDeclared` 和 `invalidTaskValues`(带 `task`),确认指纹也覆盖任务及其值和工作目录。`runConfigurationTypes` 的必填 `arguments` 字段留空现在会被拒绝(以前没有执行 `required`)。语言文件新增 `beforeLaunchTasks.<构建系统 ID>.<任务 ID>`;保存的值不合法时是 `plugin.build.invalidBeforeLaunchTask`(字段 `values.`)。新增 fixture `before-launch-tasks/`。用到它的插件声明 `beforeLaunchTasks: 0`,不认识它的宿主不会安装。没有新增宿主方法或通知。 | | [#96](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/96) | [@lithe-support[bot]](https://github.com/apps/lithe-support) | API-23 | **`managedRuntimes` 0** | 受管运行时:新增固定 HTTPS 归档与 SHA-256、平台选择、与插件版本无关的缓存身份,以及插件后端对外部/暂存依赖的资格检查契约。新增权限 `runtimes.install`、审查程序 `managedRuntime`、Core 命令 `plugins.managedRuntimes.plan` 与 `plugins.managedRuntimes.decodeResolution`;正常语言服务器启动可接收只读 `runtimes` 映射。原生 `lsp.startServer` 新增可选 `functionRelayEnabled`(默认 true),准备会话设为 false 隔离跨插件调用但保留宿主直接调用。无新增宿主 RPC 或 SDK 版本。宿主须先发布对应能力,插件才可要求它。 | | [#94](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/94) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-29 | **`runConfigurationTypes` 0** | 插件声明自己的运行配置类型([1lck/Lithe-IDEA#2100](https://github.com/1lck/Lithe-IDEA/issues/2100)):构建系统新增 `runConfigurationTypes`(最多 16 个),每个类型有 `id`、`displayName`、可选的 `description`、`execution`(`application` 或 `task`)、`arguments` 模板和最多 16 个字段 `fields`(`text`、`choice`、`checkbox`、`file`、`directory`、`arguments`,可带 `default`、`required`、`placeholder`、`visibleWhen` 和每个字段自己的 `arguments`)。新模板变量 `${field:}` 是整个参数,每个字段必须在类型参数或字段参数里恰好用一次(只控制显示、不带参数的字段除外);`${userArguments}` 恰好出现一次时,编辑器才显示程序参数。用户保存的配置类型是 `build.run-type`,`extensions.build` 记 `{pluginID, buildSystemID, type, values}`,仍存在 `.lithe/run/plugin/<插件 ID>.toml`。所有运行配置(含 Core 自带的)新增通用开关 `allowMultipleInstances`:关时再次启动先停掉正在运行的进程,开时宿主在旁边再起一个。Core 新增命令 `build.runConfigurationPlan`(把保存的配置展开成 argv 计划),`runConfig.configurationTypes`、`runConfig.editorForm`、`runConfig.saveConfiguration` 新增请求字段 `runTypePlugins`(清单和语言文件),语言文件新增 `runConfigurationTypes.<构建系统 ID>.<类型 ID>`。字段值不合法时是 `plugin.build.invalidRunConfiguration`(字段 `values.`),语言文件不合法时是 `plugin.build.invalidLocalization`。新增 fixture `run-configuration-types/`。用到它的插件声明 `runConfigurationTypes: 0`,不认识它的宿主不会安装。没有新增宿主方法或通知。 | | [#93](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/93) | [@Mucheen](https://github.com/Mucheen) | API-23 | `toolDefinitions` 0 内的补充 | 项目内工具环境解释器符号链接链校验与项目候选返回([1lck/Lithe-IDEA#2122](https://github.com/1lck/Lithe-IDEA/issues/2122)):`projectCodeAllowed != true` 时所有 `projectFile` 候选仍以 `projectCodeRequiresAction` 跳过且不返回探针目标;`projectKind: "environment"`(如 `.venv`)要求 `home`、到可执行文件之间的父目录(如 `.venv/bin`、`.venv/Scripts`)、环境内 `requires` 标记以及实际存在的 `pathPrepend` 目录规范化后留在工作区和 `home` 内(记为 `missing` 的跨平台 `pathPrepend` 子目录忽略,未观察到或软链逃逸以 `unsafePath` 拒绝),叶子可执行文件允许是指向工作区内或工作区外常规可执行文件的单跳或多跳符号链接,探测与选中结果均保留字面 `executable` 路径;`wrapper` 仍要求链接目标留在工作区根内。`toolchains.discoveryPlan` 的每个工具新增平台过滤后的 `projectFiles`;`toolchains.candidates` 新增根级 `project` 候选列表;`toolchains.resolve` 新增 `projectCandidates`,且没有候选解析成功时保留解析顺序中的首个失败原因。最近的项目声明遮住根目录的声明,可选发现无法表示的路径会被跳过,已验证的固定选择仍可生效。项目环境和外部安装都可以省略明确观测为缺失的 PATH 目录。`toolchains.catalogState` / `editCatalog` 支持在本机 `toolchains/global.json` 维护规范化的 `trustedWorkspaces` 并查询 `projectCodeAllowed`。同步更新过时宿主能力对照说明;清单格式和能力版本不变,没有新增插件 RPC 方法或通知。 |