From 947b3f283070ce7bfd3461756cdea6097d29ad2f Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Wed, 18 Nov 2026 15:22:50 +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=E8=BF=90=E8=A1=8C=E9=85=8D=E7=BD=AE=E7=B1=BB?= =?UTF-8?q?=E5=9E=8B=EF=BC=88runConfigurationTypes=200=EF=BC=89=EF=BC=8C?= =?UTF-8?q?=E6=89=80=E6=9C=89=E8=BF=90=E8=A1=8C=E9=85=8D=E7=BD=AE=E5=8A=A0?= =?UTF-8?q?=E2=80=9C=E5=85=81=E8=AE=B8=E5=A4=9A=E4=B8=AA=E5=AE=9E=E4=BE=8B?= =?UTF-8?q?=E2=80=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 构建系统新增 runConfigurationTypes:类型 id、名称、说明、execution、arguments 模板和最多 16 个字段 (text、choice、checkbox、file、directory、arguments),字段可带默认值、必填、占位符、显示条件和自己的参数 - 新模板变量 ${field:};每个字段恰好引用一次;${userArguments} 恰好出现一次时编辑器显示程序参数 - 保存的配置类型 build.run-type,extensions.build 记 {pluginID, buildSystemID, type, values}, 仍存 .lithe/run/plugin/<插件 ID>.toml - 新命令 build.runConfigurationPlan 把保存的配置展开成 argv 计划 - runConfig.configurationTypes / editorForm / saveConfiguration 新增 runTypePlugins(清单和语言文件), 语言文件新增 runConfigurationTypes 词条 - 所有运行配置的通用开关 allowMultipleInstances,只在开启时保存 - 新增 fixture run-configuration-types/,更新契约 README、schema、Core API 文档、更新记录和能力对照 --- .../run-configuration-v2.schema.json | 47 + rust/contracts/rust-core-api.md | 99 +- rust/crates/build/src/commands.rs | 76 +- rust/crates/build/src/lib.rs | 2 + rust/crates/build/src/manifest.rs | 7 + rust/crates/build/src/manifest/checks.rs | 23 + rust/crates/build/src/manifest/options.rs | 6 + rust/crates/build/src/manifest/run_types.rs | 384 ++++++++ rust/crates/build/src/plans.rs | 7 +- rust/crates/build/src/run_types.rs | 566 +++++++++++ rust/crates/build/src/template.rs | 64 +- rust/crates/core/src/protocol/command.rs | 7 +- .../core/src/runtime/dispatcher/build.rs | 5 + .../core/src/runtime/dispatcher/run_config.rs | 123 ++- .../core/src/tests/declarative_plugins.rs | 4 + rust/crates/core/src/tests/mod.rs | 1 + .../crates/core/src/tests/plugin_run_types.rs | 686 +++++++++++++ .../core/src/tests/run_configuration.rs | 1 + rust/crates/execution/src/configuration.rs | 6 + .../execution/src/configuration/declared.rs | 908 ++++++++++++++++++ .../execution/src/configuration/document.rs | 4 + .../execution/src/configuration/form.rs | 693 +++++++++---- .../execution/src/configuration/process.rs | 62 +- .../execution/src/configuration/resolve.rs | 7 +- .../execution/src/configuration/validation.rs | 3 + rust/crates/execution/src/lib.rs | 1 + rust/crates/execution/src/provider_runs.rs | 1 + rust/crates/plugin-manifest/src/validation.rs | 6 + rust/crates/plugin-model/src/capabilities.rs | 4 + rust/crates/plugin-model/src/settings.rs | 3 +- .../plugin-model/src/settings/localization.rs | 61 +- shared/plugins/contract/v1/README.md | 114 ++- .../run-configuration-types/l10n/zh-Hans.json | 22 + .../run-configuration-types.plugin.json | 122 +++ .../contract/v1/plugin-l10n.schema.json | 48 +- .../contract/v1/plugin-manifest.schema.json | 86 ++ shared/plugins/reference/api-catalog.md | 4 +- .../reference/capabilities-and-versions.md | 2 + .../reference/domains/build-systems.md | 8 +- .../plugins/reference/protocol-changelog.md | 2 + 40 files changed, 3941 insertions(+), 334 deletions(-) create mode 100644 rust/crates/build/src/manifest/run_types.rs create mode 100644 rust/crates/build/src/run_types.rs create mode 100644 rust/crates/core/src/tests/plugin_run_types.rs create mode 100644 rust/crates/execution/src/configuration/declared.rs create mode 100644 shared/plugins/contract/v1/fixtures/run-configuration-types/l10n/zh-Hans.json create mode 100644 shared/plugins/contract/v1/fixtures/run-configuration-types/run-configuration-types.plugin.json diff --git a/rust/contracts/run-configuration-v2.schema.json b/rust/contracts/run-configuration-v2.schema.json index 9eca040d..651472ef 100644 --- a/rust/contracts/run-configuration-v2.schema.json +++ b/rust/contracts/run-configuration-v2.schema.json @@ -54,6 +54,33 @@ "type": "string", "pattern": "^(?!/)(?!.*(^|/)\\.\\.(?:/|$)).*$" }, + "runTypeReference": { + "type": "object", + "description": "A configuration of a run configuration type a build system declares (buildSystems[].runConfigurationTypes).", + "required": ["pluginID", "buildSystemID", "type"], + "properties": { + "pluginID": { "$ref": "#/$defs/runTypeIdentifier" }, + "buildSystemID": { "$ref": "#/$defs/runTypeIdentifier" }, + "type": { "$ref": "#/$defs/runTypeIdentifier" }, + "values": { + "type": "object", + "description": "Field values by declared field ID; hidden fields are not saved.", + "maxProperties": 16, + "propertyNames": { "$ref": "#/$defs/runTypeIdentifier" }, + "additionalProperties": { + "oneOf": [ + { "type": "boolean" }, + { "type": "string", "maxLength": 4096 }, + { "type": "array", "maxItems": 64, "items": { "type": "string", "maxLength": 4096 } } + ] + } + } + }, + "additionalProperties": false + }, + "runTypeIdentifier": { + "type": "string", "minLength": 1, "maxLength": 200, "pattern": "^[A-Za-z0-9._-]+$" + }, "buildProviderReference": { "type": "object", "required": [ @@ -242,6 +269,10 @@ } }, "disabled": { "type": "boolean" }, + "allowMultipleInstances": { + "type": "boolean", + "description": "Starting the configuration while it runs starts another instance beside it instead of stopping the running one." + }, "source": { "type": "string" } }, "additionalProperties": false, @@ -263,6 +294,22 @@ } } } + }, { + "if": { "properties": { "provider": { "const": "build.run-type" } } }, + "then": { + "required": ["extensions"], + "properties": { + "execution": { "enum": ["application", "task"] }, + "command": false, + "toolchains": { "maxProperties": 0 }, + "debug": false, + "members": { "maxItems": 0 }, + "extensions": { + "required": ["build"], + "properties": { "build": { "$ref": "#/$defs/runTypeReference" } } + } + } + } }, { "if": { "properties": { "provider": { "pattern": "^process\\." } } }, "then": { diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 49c31947..6c7a52fd 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -523,6 +523,7 @@ or removing a command fails until the table changes in the same commit. | `build.resolveOptions` | Check stored build options against the declaration and return effective values, choices, and the fingerprint | | `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.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 | @@ -713,8 +714,8 @@ or removing a command fails until the table changes in the same commit. | `runConfig.updateToolPreferences` | Replace only generic preferences in the local layer, preserving legacy defaults and unrelated metadata | | `runConfig.saveEditorChanges` | Prepare the file changes of the local and optional project layers for one editor save | | `runConfig.createUserConfiguration` | Validate a typed user configuration and return the file changes that save it | -| `runConfig.configurationTypes` | List the built-in run configuration types a user can create, with the availability of a kind this platform cannot run | -| `runConfig.editorForm` | Describe the editor fields and current values of a built-in run configuration | +| `runConfig.configurationTypes` | List the run configuration types a user can create, built-in and plugin-declared, with the availability of a kind this platform cannot run | +| `runConfig.editorForm` | Describe the editor fields and current values of a built-in or plugin-declared run configuration | | `runConfig.saveConfiguration` | Validate an editor form's values and return field errors or the file changes that save it | | `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 | @@ -3912,15 +3913,19 @@ becomes `bash -e`), else `bash`, both looked up on `PATH`. PowerShell uses `pwsh` outside Windows and `powershell` on Windows, with `-NoLogo -NoProfile`; batch uses `cmd /d`. A chosen interpreter drops the automatic arguments. -`runConfig.configurationTypes` accepts `{}` and returns `{types: [{provider, -availability?}]}`, every kind a user can create, in display order. Every -platform creates and edits every kind; a kind this platform cannot run carries -the `availability` its configurations resolve with (`unsupportedPlatform` for -batch outside Windows), so hosts can say so before the user saves one. - -`runConfig.editorForm` accepts `{root, provider?, configurationId?, values?}` -and describes the editor of a new configuration of `provider` or of the saved -`configurationId` (its provider must match `provider` when both are given). +`runConfig.configurationTypes` accepts `{runTypePlugins?}` and returns +`{types: [{provider, availability?}], localizations?}`, every kind a user can +create, in display order: the built-in process runs, then the types installed +plugins declare (see [Plugin-declared types](#plugin-declared-types)). Every +platform creates and edits every built-in kind; a kind this platform cannot run +carries the `availability` its configurations resolve with +(`unsupportedPlatform` for batch outside Windows), so hosts can say so before +the user saves one. + +`runConfig.editorForm` accepts `{root, provider?, runType?, configurationId?, +values?, runTypePlugins?}` and describes the editor of a new configuration of +`provider` (with `runType` for a declared type) or of the saved +`configurationId` (its provider and type must match when both are given). `values` holds the open editor's unsaved values; they replace the saved ones so automatic values follow the edit. It returns `{formVersion, provider, configurationId, values, fields, availability?}`. `availability` is present @@ -3928,7 +3933,7 @@ when this platform cannot run the kind, as in `runConfig.configurationTypes`; the form still edits and saves it. `formVersion` is `1`; a host refuses a newer one. `values` maps field IDs to the current values. `fields` is the ordered list of `{id, kind, required?, placement?, automatic?, options?, visibleWhen?, -note?, shellFamily?}`: +note?, shellFamily?, label?, description?, placeholder?, optionLabels?}`: | Attribute | Meaning | | --- | --- | @@ -3937,21 +3942,30 @@ note?, shellFamily?}`: | `automatic` | The value used while the field is empty, shown as its placeholder | | `visibleWhen` | `{field, equals}`: shown only while that field has that value | | `note` | An explanation key; `windowsOnly` says the field matters only on Windows | +| `label`, `description`, `placeholder` | Text a plugin declared for its field, already translated; built-in fields have none and hosts label them from the field ID | +| `optionLabels` | On a declared `choice` field, the display title of each value that has one | | `shellFamily` | On an `executable` field, the family of shell it takes: `posix` (sh, bash, zsh and the like), `powershell` (Windows PowerShell and `pwsh`) or `cmd`. A host that finds the installed shells may offer those of the family as choices beside the automatic value and a path of the user's own; the value is still a program name or path. The `interpreter` field of each script kind has it | Hosts draw the fields in order, skip a field whose `kind` they do not know and send back every value they received, including keys they do not show, so a -later Core adds fields without a host change. Script kinds show `name`, -`storeAsProjectFile`, `source` (`file` or `text`), `script`, `text`, +later Core adds fields without a host change. Every editor starts with the +header fields `name`, `storeAsProjectFile` and `allowMultipleInstances`. +Script kinds then show `source` (`file` or `text`), `script`, `text`, `scriptOptions`, `workingDirectory`, `environment`, `interpreter`, `interpreterArguments` and, for PowerShell, `executionPolicyBypass`; a program -shows `name`, `storeAsProjectFile`, `program`, `programArguments`, -`workingDirectory` and `environment`. An empty name saves the automatic name, -the script or program file name. A saved entry that is not a built-in process -run is `not_supported`. - -`runConfig.saveConfiguration` accepts `{root, provider, configurationId?, -values, plugins?}`. It replies `{status: "invalid", errors: [{field, code}]}` +shows `program`, `programArguments`, `workingDirectory` and `environment`. An +empty name saves the automatic name, the script or program file name. A saved +entry that is neither a built-in process run nor of a declared type is +`not_supported`. + +`allowMultipleInstances` (IntelliJ IDEA's "Allow multiple instances") is saved +on the configuration only when `true` and resolved like any other key. While a +configuration runs, starting it again stops the running process first; with +`allowMultipleInstances` the host starts another process beside it and keeps a +console for each. + +`runConfig.saveConfiguration` accepts `{root, provider, runType?, +configurationId?, values, plugins?, runTypePlugins?}`. It replies `{status: "invalid", errors: [{field, code}]}` when a value is wrong, else `{status: "saved", id, changes}`. `code` is `required`, `conflict`, `notAllowed`, `tooLong`, `invalidCharacter`, `invalidPath`, `notFound`, `outsideProject` (a working directory outside the @@ -3979,6 +3993,48 @@ generated run with the same selector, so copying a generated one also saves the original whole in the local layer under its own ID; both stay listed, and the original stops following later name changes of the build model. +#### Plugin-declared types + +A build system may declare run configuration types +(`buildSystems[].runConfigurationTypes` in the plugin contract): data only, +the fields of the editor and the command line the values make, so a plugin +adds a kind such as Go Build without a backend. The editor commands take the +installed plugins as `runTypePlugins: {language?, plugins: [{manifest, +localizations?}]}`, in the order their types are listed. A manifest that does +not validate adds nothing. With a `language`, `runConfig.configurationTypes` +and `runConfig.editorForm` return `localizations`, one report per plugin that +declares a type, shaped as the report of `plugins.settings`: the host reads +the `readRequired` candidates from the package and sends them back as +`localizations` (package-relative path to text), and Core applies the first +one that fits. A file that does not fit is reported as +`plugin.build.invalidLocalization` and the manifest's wording is kept. + +A declared type is listed as `{provider: "build.run-type", runType: +{pluginID, buildSystemID, type}, displayName, execution, description?, +icon?}`, with translated text. Its editor shows the header fields, the +declared fields as `field:` with their translated `label`, `description`, +`placeholder` and `optionLabels`, then `programArguments` when the type's +arguments take `${userArguments}`, `workingDirectory`, `environment` and +`beforeLaunch`. A declared field's `kind` is `text`, `choice`, `checkbox`, +`file`, `directory` or `arguments`; its `visibleWhen` names another +`field:`. The form of a declared type carries `runType` instead of +`availability`. A type no installed plugin declares, such as after the plugin +was removed, is `not_supported` in the editor; its saved configurations stay +in the run files. + +Saving checks the visible declared fields (`required`, `notFound`, +`tooLong`, `invalidCharacter` and the path codes, keyed `field:`) and +saves the entry with provider `build.run-type` in the plugin's document of +the chosen layer (`.lithe/run/plugin/.toml` or +`.local.toml`). It keeps `extensions.build: {pluginID, +buildSystemID, type, values}`, the visible fields' values by declared field +ID (a string, a boolean, or the list of arguments of an `arguments` field; +files and directories project-relative inside the project), with the +program arguments, working directory and environment in `args`, `cwd` and +`env`, and the type's `execution` (`application` or `task`). `runConfig.resolve` lists it +with the plugin it needs. `build.runConfigurationPlan` expands it into the +argv plan the host starts like a task plan. + #### Folders and order A configuration may name a `folder`, the folder it is listed in within its @@ -5109,6 +5165,7 @@ and the directories are absolute host paths used only as substitution text. | `build.decodeConfigurationEdit` | `{ snapshot, edits, result }` | `edit: { sourceID, revision, changed }`; validates bounded receipt and exact draft/source identity; native adapter verifies staged hash and publishes atomically | | `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.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 40ace8b3..279a09cb 100644 --- a/rust/crates/build/src/commands.rs +++ b/rust/crates/build/src/commands.rs @@ -15,11 +15,12 @@ use super::outputs::{ DecodeTestResultsRequest, SyncFingerprintRequest, }; use super::plans::{self, OutputPlanRequest, TaskPlanRequest, TestPlanRequest}; +use super::run_types::{self, RunConfigurationPlanRequest}; use super::test_discovery::{self, DecodeTestDiscoveryRequest}; use super::tree::{self, ModelTreeRequest}; use super::BuildManifest; use lithe_plugin_model::{decode_payload, outcome, PluginRejection, Validation}; -use lithe_protocol::CoreError; +use lithe_protocol::{CoreError, ErrorCode}; use serde::de::DeserializeOwned; use serde::Deserialize; use serde_json::Value; @@ -31,9 +32,11 @@ struct BuildPayload { manifest: Value, #[serde(rename = "buildSystemID")] build_system_id: String, - /// Routing identity for plans that otherwise contain only relative paths. + /// Routing identity for plans that otherwise contain only relative + /// paths; the workspace whose saved run configurations + /// `build.runConfigurationPlan` reads. #[serde(default, rename = "workspaceRoot")] - _workspace_root: Option, + workspace_root: Option, request: T, } @@ -85,24 +88,65 @@ fn with_manifest( let payload: BuildPayload = decode_payload(payload, command)?; Ok(outcome(M::validate(payload.manifest).and_then( |manifest| { - let build_system = manifest - .build_systems() - .iter() - .find(|build_system| build_system.id == payload.build_system_id) - .ok_or_else(|| { - PluginRejection::new( - "plugin.build.unavailable", - format!( - "The plugin declares no build system {}.", - payload.build_system_id - ), - ) - })?; + let build_system = find_build_system(&manifest, &payload.build_system_id)?; run(build_system, &payload.request, &manifest).map(|value| (key, value)) }, ))) } +fn find_build_system<'m, M: BuildManifest>( + manifest: &'m M, + id: &str, +) -> Validation<&'m BuildSystemDeclaration> { + manifest + .build_systems() + .iter() + .find(|build_system| build_system.id == id) + .ok_or_else(|| { + PluginRejection::new( + "plugin.build.unavailable", + format!("The plugin declares no build system {id}."), + ) + }) +} + +/// `build.runConfigurationPlan`: the argv plan of a saved configuration of a +/// run configuration type the build system declares. It reads the saved +/// configuration from `workspaceRoot`, which it requires; a configuration +/// that is missing, disabled, unavailable or of another provider fails the +/// call, and values the type cannot run are rejected. +pub fn build_run_configuration_plan_command( + payload: Value, +) -> Result { + let command = "build.runConfigurationPlan"; + let payload: BuildPayload = decode_payload(payload, command)?; + let workspace_root = payload.workspace_root.as_deref().ok_or_else(|| { + CoreError::new( + ErrorCode::InvalidRequest, + "build.runConfigurationPlan needs workspaceRoot", + ) + })?; + let request = &payload.request; + let launch = lithe_execution::declared_launch( + workspace_root, + &request.configuration_id, + request.local_document.clone(), + )?; + Ok(outcome(M::validate(payload.manifest).and_then( + |manifest| { + let build_system = find_build_system(&manifest, &payload.build_system_id)?; + run_types::run_configuration_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/lib.rs b/rust/crates/build/src/lib.rs index f571e923..de03b8a3 100644 --- a/rust/crates/build/src/lib.rs +++ b/rust/crates/build/src/lib.rs @@ -32,6 +32,7 @@ mod project_options; mod run_entrypoints; mod run_preparation; mod run_start; +mod run_types; mod select; mod stored_options; mod template; @@ -47,6 +48,7 @@ pub use manifest::{ }; pub use project_options::project_options_command; pub use run_start::run_decode_start_command; +pub use run_types::{declared_run_types, RunTypePlugin, RunTypePlugins}; pub use stored_options::{edit_ignored_paths_command, resolve_stored_options_command}; pub use test_outcome::resolve_test_run_outcome; pub use test_outcome_merge::merge_test_outcomes; diff --git a/rust/crates/build/src/manifest.rs b/rust/crates/build/src/manifest.rs index 7b089098..6f8b3047 100644 --- a/rust/crates/build/src/manifest.rs +++ b/rust/crates/build/src/manifest.rs @@ -33,6 +33,7 @@ mod model; mod options; mod provider; mod run; +mod run_types; mod tasks; mod testing; @@ -45,6 +46,7 @@ pub(crate) use model::*; pub(crate) use options::*; pub use provider::*; pub(crate) use run::*; +pub(crate) use run_types::*; pub(crate) use tasks::*; pub(crate) use testing::*; @@ -101,6 +103,10 @@ pub struct BuildSystemDeclaration { pub(crate) tasks: Vec, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub(crate) run: Vec, + /// Kinds of run configuration the user creates in the Run/Debug + /// Configurations dialog; `runConfigurationTypes` 0. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub(crate) run_configuration_types: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] pub(crate) test: Option, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -215,6 +221,7 @@ impl BuildSystemDeclaration { let model_templates = self.validate_tasks(field, &option_ids)?; self.validate_model(field, &option_ids)?; self.validate_run(field, &option_ids, &model_templates)?; + self.validate_run_types(field, &option_ids)?; self.validate_test(field, &option_ids)?; self.validate_diagnostics(field)?; self.validate_dependencies(field, &option_ids)?; diff --git a/rust/crates/build/src/manifest/checks.rs b/rust/crates/build/src/manifest/checks.rs index 58d423a9..55922255 100644 --- a/rust/crates/build/src/manifest/checks.rs +++ b/rust/crates/build/src/manifest/checks.rs @@ -70,6 +70,25 @@ fn program(build_system: &BuildSystemDeclaration) -> Value { Some(DependenciesSource::Command { arguments, .. }) => json!({ "arguments": arguments }), _ => Value::Null, }; + let run_types: Vec = build_system + .run_configuration_types + .iter() + .map(|run_type| { + json!({ + "id": run_type.id, + "execution": run_type.execution(), + "arguments": run_type.arguments, + "fields": run_type.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, @@ -88,6 +107,10 @@ fn program(build_system: &BuildSystemDeclaration) -> Value { "model": model, "dependencies": dependencies, }); + // Absent while empty, so a plugin without types keeps its review. + if !run_types.is_empty() { + program["runConfigurationTypes"] = json!(run_types); + } // 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 4371ac5f..b2fd6dfe 100644 --- a/rust/crates/build/src/manifest/options.rs +++ b/rust/crates/build/src/manifest/options.rs @@ -218,6 +218,12 @@ impl BuildSystemDeclaration { for (index, run) in self.run.iter().enumerate() { lists.push((format!("{field}.run[{index}].arguments"), &run.arguments)); } + for (index, run_type) in self.run_configuration_types.iter().enumerate() { + lists.push(( + format!("{field}.runConfigurationTypes[{index}].arguments"), + &run_type.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 new file mode 100644 index 00000000..5d4cbd4d --- /dev/null +++ b/rust/crates/build/src/manifest/run_types.rs @@ -0,0 +1,384 @@ +//! `runConfigurationTypes`: kinds of run configuration a build system adds to +//! the Run/Debug Configurations dialog. +//! +//! 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. + +use super::*; + +const MAX_RUN_TYPES: usize = 16; +const MAX_RUN_FIELDS: usize = 16; +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. +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct RunTypeDeclaration { + /// Unique within the build system; stored in every configuration of the type. + pub(crate) id: String, + pub(crate) display_name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) description: Option, + /// Icon of the type in the dialog's `+` menu and list; display only. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) icon: Option, + /// How the started process behaves; `application` by default. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) execution: Option, + /// The fields of the editor, in display order, between the name and the + /// program arguments. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub(crate) fields: Vec, + /// The command line after the global arguments. It names every field + /// that passes a value as `${field:}`, and the program arguments as + /// `${userArguments}` when the type takes them; the editor shows the + /// program arguments field only then. + pub(crate) arguments: Vec, +} + +/// One field of a run configuration type's editor. +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct RunFieldDeclaration { + pub(crate) id: String, + pub(crate) title: String, + pub(crate) kind: RunFieldKind, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) description: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) placeholder: Option, + /// The values of a `choice` field, in display order. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub(crate) choices: Vec, + /// The value of a new configuration: a string for `text` and `choice`, + /// a boolean for `checkbox`, a list of strings for `arguments`. File and + /// directory fields have none; a plugin cannot know a path of this machine. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) default: Option, + /// A visible field may not be left empty. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub(crate) required: bool, + /// The field is shown, checked and passed only while an earlier `choice` + /// or `checkbox` field holds `equals`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) visible_when: Option, + /// Templates that pass the value, `${value}` standing for it, such as + /// `["-o", "${value}"]`. Without them a value is passed as one argument; + /// a checkbox passes them while it is checked. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub(crate) arguments: Vec, +} + +/// What a run configuration field holds. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub(crate) enum RunFieldKind { + /// One line of text, passed as is. + Text, + /// One of the declared choices. + Choice, + /// On or off. + Checkbox, + /// A file, passed as an absolute path. + File, + /// A directory, passed as an absolute path. + Directory, + /// Arguments the user types, split like the program arguments. + Arguments, +} + +impl RunFieldKind { + /// Whether another field can be shown depending on this one's value. + fn controls_visibility(self) -> bool { + matches!(self, Self::Choice | Self::Checkbox) + } +} + +/// The value an earlier field must hold for a field to be shown. +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct RunFieldCondition { + pub(crate) field: String, + pub(crate) equals: Value, +} + +impl BuildSystemDeclaration { + /// Whether the build system adds run configuration types, which + /// `runConfigurationTypes` introduced. + pub fn has_run_configuration_types(&self) -> bool { + !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 + .iter() + .find(|run_type| run_type.id == id) + } + + pub(crate) fn validate_run_types( + &mut self, + 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()) { + return Err(invalid( + format!("{field}.id"), + "Run configuration type IDs are unique identifiers that start with a letter.", + )); + } + run_type.validate(&field, options)?; + } + Ok(()) + } +} + +impl RunTypeDeclaration { + /// How a configuration of this type runs. + pub(crate) fn execution(&self) -> BuildExecution { + self.execution.unwrap_or(BuildExecution::Application) + } + + /// Whether the command line takes the user's program arguments. + pub(crate) fn takes_arguments(&self) -> bool { + template::user_argument_references(&self.arguments) == 1 + } + + fn validate(&self, field: &str, options: &BTreeSet) -> Validation<()> { + check_text( + &self.display_name, + &format!("{field}.displayName"), + "display name", + )?; + if let Some(description) = &self.description { + check_description(description, &format!("{field}.description"))?; + } + 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.", + )); + } + if self.fields.len() > MAX_RUN_FIELDS { + return Err(invalid(format!("{field}.fields"), "Too many fields.")); + } + let mut ids = BTreeSet::new(); + for (index, declared) in self.fields.iter().enumerate() { + let field = format!("{field}.fields[{index}]"); + if !is_setting_identifier(&declared.id) || !ids.insert(declared.id.clone()) { + return Err(invalid( + format!("{field}.id"), + "Field IDs are unique, start with a lowercase letter, and use letters and digits.", + )); + } + declared.validate(&field, &self.fields[..index])?; + } + let arguments_field = format!("{field}.arguments"); + check_argument_count(&self.arguments, &arguments_field)?; + let allowed = Allowed { + root: true, + user_arguments: true, + options: Some(options), + fields: Some(&ids), + ..Allowed::none() + }; + template::validate_arguments(&self.arguments, &allowed, &arguments_field)?; + let references = template::field_references(&self.arguments); + if let Some(twice) = references.iter().find(|(_, count)| **count > 1) { + return Err(template_error( + arguments_field, + format!("${{field:{}}} is named more than once.", twice.0), + )); + } + if template::user_argument_references(&self.arguments) > 1 { + return Err(template_error( + arguments_field, + "The arguments name ${userArguments} at most once, where the program arguments go.", + )); + } + for (index, declared) in self.fields.iter().enumerate() { + if references.contains_key(&declared.id) { + continue; + } + // A field the command line does not name only shows or hides + // other fields. + let controls = self.fields.iter().any(|other| { + other + .visible_when + .as_ref() + .is_some_and(|condition| condition.field == declared.id) + }); + if !controls || !declared.arguments.is_empty() { + return Err(template_error( + format!("{field}.fields[{index}]"), + format!( + "The field is never passed; name it as ${{field:{}}} in the arguments.", + declared.id + ), + )); + } + } + Ok(()) + } +} + +impl RunFieldDeclaration { + /// Checks the field against the fields declared before it. + fn validate(&self, field: &str, earlier: &[RunFieldDeclaration]) -> Validation<()> { + check_text(&self.title, &format!("{field}.title"), "title")?; + if let Some(description) = &self.description { + check_description(description, &format!("{field}.description"))?; + } + if let Some(placeholder) = &self.placeholder { + check_text(placeholder, &format!("{field}.placeholder"), "placeholder")?; + } + if (self.kind == RunFieldKind::Choice) == self.choices.is_empty() { + return Err(invalid( + format!("{field}.choices"), + "A choice field needs choices, and only a choice field has them.", + )); + } + if self.choices.len() > MAX_CHOICES { + return Err(invalid(format!("{field}.choices"), "Too many choices.")); + } + let mut values = BTreeSet::new(); + for (index, choice) in self.choices.iter().enumerate() { + if !is_option_value(&choice.value) || !values.insert(choice.value.as_str()) { + return Err(invalid( + format!("{field}.choices[{index}].value"), + "Choice values are unique and printable.", + )); + } + if let Some(title) = &choice.title { + check_text(title, &format!("{field}.choices[{index}].title"), "title")?; + } + } + if self.required && matches!(self.kind, RunFieldKind::Checkbox | RunFieldKind::Choice) { + return Err(invalid( + format!("{field}.required"), + "A checkbox or choice field always holds a value.", + )); + } + if let Some(default) = &self.default { + if !self.fits(default) + || matches!(self.kind, RunFieldKind::File | RunFieldKind::Directory) + { + return Err(invalid( + format!("{field}.default"), + "The default does not fit the field's kind and choices; file and directory fields have no default.", + )); + } + } + if let Some(condition) = &self.visible_when { + let controller = earlier + .iter() + .find(|other| other.id == condition.field) + .filter(|other| other.kind.controls_visibility()); + if !controller.is_some_and(|controller| controller.fits(&condition.equals)) { + return Err(invalid( + format!("{field}.visibleWhen"), + "visibleWhen names an earlier choice or checkbox field and one of its values.", + )); + } + } + self.validate_arguments(field) + } + + fn validate_arguments(&self, field: &str) -> Validation<()> { + let field = format!("{field}.arguments"); + if self.arguments.len() > MAX_FIELD_ARGUMENTS { + return Err(invalid( + field, + format!("A field maps to at most {MAX_FIELD_ARGUMENTS} arguments."), + )); + } + match self.kind { + RunFieldKind::Arguments if !self.arguments.is_empty() => { + return Err(invalid( + field, + "An arguments field passes the arguments the user typed.", + )) + } + RunFieldKind::Checkbox if self.arguments.is_empty() => { + return Err(invalid( + field, + "A checkbox passes its arguments while it is checked; declare them.", + )) + } + _ => {} + } + let checkbox = self.kind == RunFieldKind::Checkbox; + let allowed = Allowed { + value: !checkbox, + ..Allowed::none() + }; + for (index, argument) in self.arguments.iter().enumerate() { + template::validate_text(argument, &allowed, &format!("{field}[{index}]"))?; + } + if !checkbox + && !self.arguments.is_empty() + && !self + .arguments + .iter() + .any(|argument| argument.contains("${value}")) + { + return Err(template_error( + field, + "The field's value is never passed; use ${value}.", + )); + } + Ok(()) + } + + /// Whether `value` is a value of this field. + pub(crate) fn fits(&self, value: &Value) -> bool { + match (self.kind, value) { + (RunFieldKind::Checkbox, Value::Bool(_)) => true, + (RunFieldKind::Choice, Value::String(value)) => { + self.choices.iter().any(|choice| &choice.value == value) + } + ( + RunFieldKind::Text | RunFieldKind::File | RunFieldKind::Directory, + Value::String(value), + ) => value.is_empty() || is_option_value(value), + (RunFieldKind::Arguments, Value::Array(items)) => { + items.len() <= MAX_ARGUMENTS + && items + .iter() + .all(|item| item.as_str().is_some_and(is_option_value)) + } + _ => false, + } + } +} + +pub(crate) fn check_description(value: &str, field: &str) -> Validation<()> { + if value.trim().is_empty() + || value.len() > MAX_DESCRIPTION + || value + .chars() + .any(|character| character.is_control() && character != '\n') + { + return Err(invalid( + field, + format!("The description must be 1-{MAX_DESCRIPTION} printable characters."), + )); + } + Ok(()) +} diff --git a/rust/crates/build/src/plans.rs b/rust/crates/build/src/plans.rs index a9e84b27..f39ce2d0 100644 --- a/rust/crates/build/src/plans.rs +++ b/rust/crates/build/src/plans.rs @@ -334,7 +334,7 @@ impl<'a> PlanContext<'a> { }) } - fn values<'v>(&'v self, user_arguments: &'v [String]) -> Values<'v> { + pub(crate) fn values<'v>(&'v self, user_arguments: &'v [String]) -> Values<'v> { Values { root: &self.root, option_arguments: &self.contribution.arguments, @@ -436,7 +436,10 @@ fn declared_provider(build_system: &BuildSystemDeclaration) -> Validation<&Provi .ok_or_else(|| unavailable(build_system, "a provider")) } -fn check_user_arguments(arguments: &[String], declared: &[BuildArgument]) -> Validation<()> { +pub(crate) fn check_user_arguments( + arguments: &[String], + declared: &[BuildArgument], +) -> Validation<()> { if arguments.is_empty() { return Ok(()); } diff --git a/rust/crates/build/src/run_types.rs b/rust/crates/build/src/run_types.rs new file mode 100644 index 00000000..627d4217 --- /dev/null +++ b/rust/crates/build/src/run_types.rs @@ -0,0 +1,566 @@ +//! Run configuration types build systems declare, for the run configuration +//! editor and for a launch. +//! +//! The editor commands (`runConfig.configurationTypes`, `editorForm`, +//! `saveConfiguration`) take the installed plugins' manifests with their +//! translation files; [`declared_run_types`] checks them and turns every +//! declared type into the [`DeclaredRunType`] the execution crate draws and +//! 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. + +use super::decode; +use super::manifest::{ + check_description, check_text, BuildExecution, BuildSystemDeclaration, RunFieldDeclaration, + RunFieldKind, RunTypeDeclaration, +}; +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, +}; +use lithe_plugin_model::settings::{parse_localization_file, present, LocalizationRequest}; +use lithe_plugin_model::{PluginRejection, Validation}; +use lithe_protocol::json_document::UniqueMap; +use lithe_protocol::{CoreError, ErrorCode}; +use serde::Deserialize; +use serde_json::{json, Map, Value}; +use std::collections::BTreeMap; +use std::path::Path; + +/// Error code of a translation file Core did not apply. +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"; +/// 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. +#[derive(Debug, Default, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct RunTypePlugins { + /// Interface language the shown text is translated to; absent keeps the + /// manifests' wording and reads no translation file. + #[serde(default)] + pub language: Option, + /// Installed plugins, in the order their types are listed. + #[serde(default)] + pub plugins: Vec, +} + +/// One installed plugin. +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct RunTypePlugin { + /// The plugin's `plugin.json`, validated again here. + pub manifest: Value, + /// The translation files the native adapter read, by package-relative + /// path; absent until it has read the candidates a report names. + #[serde(default)] + 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 +/// named: `{pluginID, language, candidates, maximumBytes, readRequired, +/// applied, rejected}`, the report of `plugins.settings`. +/// +/// A manifest that does not validate adds nothing, as on every other surface +/// of an installed plugin; a translation file that does not fit is reported +/// and the manifest's wording is kept. +pub fn declared_run_types( + plugins: &RunTypePlugins, +) -> Result<(Vec, Vec), CoreError> { + if plugins.plugins.len() > MAX_PLUGINS { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Too many plugins in the run configuration type request", + )); + } + let mut types = Vec::new(); + let mut reports = Vec::new(); + for plugin in &plugins.plugins { + let Ok(manifest) = M::validate(plugin.manifest.clone()) else { + continue; + }; + let systems: Vec<&BuildSystemDeclaration> = manifest + .build_systems() + .iter() + .filter(|system| system.has_run_configuration_types()) + .collect(); + if systems.is_empty() { + continue; + } + let request = + LocalizationRequest::new(plugins.language.as_deref(), plugin.localizations.as_ref()) + .map_err(|message| { + CoreError::new( + ErrorCode::InvalidRequest, + "Invalid run configuration type localization request", + ) + .with_details(message) + })?; + let localization = match request { + Some(request) => { + let (chosen, mut report) = request.select_with(|text| decode_file(text, &systems)); + report["pluginID"] = json!(manifest.id()); + reports.push(report); + chosen.unwrap_or_default() + } + 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)); + } + } + } + Ok((types, reports)) +} + +/// The run type of a validated declaration, with translated text. +fn declared( + plugin_id: &str, + system: &BuildSystemDeclaration, + declaration: &RunTypeDeclaration, + text: Option<&TypeText>, +) -> DeclaredRunType { + let fields = declaration + .fields + .iter() + .map(|field| { + declared_field( + field, + text.and_then(|text| text.fields.as_ref()) + .and_then(|fields| fields.0.get(&field.id)), + ) + }) + .collect(); + DeclaredRunType { + key: RunTypeKey { + plugin_id: plugin_id.to_string(), + build_system_id: system.id.clone(), + type_id: declaration.id.clone(), + }, + display_name: text + .and_then(|text| text.display_name.clone()) + .unwrap_or_else(|| declaration.display_name.clone()), + description: text + .and_then(|text| text.description.clone()) + .or_else(|| declaration.description.clone()), + icon: declaration + .icon + .as_ref() + .map(|icon| serde_json::to_value(icon).expect("icons encode")), + execution: match declaration.execution() { + BuildExecution::Task => Execution::Task, + // Validation rejects `service`. + BuildExecution::Application | BuildExecution::Service => Execution::Application, + }, + takes_arguments: declaration.takes_arguments(), + fields, + } +} + +fn declared_field(field: &RunFieldDeclaration, text: Option<&FieldText>) -> DeclaredField { + let options = text.and_then(|text| text.options.as_ref()); + DeclaredField { + id: field.id.clone(), + kind: match field.kind { + RunFieldKind::Text => DeclaredFieldKind::Text, + RunFieldKind::Choice => DeclaredFieldKind::Choice, + RunFieldKind::Checkbox => DeclaredFieldKind::Checkbox, + RunFieldKind::File => DeclaredFieldKind::File, + RunFieldKind::Directory => DeclaredFieldKind::Directory, + RunFieldKind::Arguments => DeclaredFieldKind::Arguments, + }, + title: text + .and_then(|text| text.title.clone()) + .unwrap_or_else(|| field.title.clone()), + description: text + .and_then(|text| text.description.clone()) + .or_else(|| field.description.clone()), + placeholder: text + .and_then(|text| text.placeholder.clone()) + .or_else(|| field.placeholder.clone()), + choices: field + .choices + .iter() + .map(|choice| DeclaredChoice { + value: choice.value.clone(), + title: options + .and_then(|options| options.0.get(&choice.value).cloned()) + .or_else(|| choice.title.clone()), + }) + .collect(), + default: field.default.clone(), + required: field.required, + visible_when: field + .visible_when + .as_ref() + .map(|condition| DeclaredCondition { + field: condition.field.clone(), + equals: condition.equals.clone(), + }), + } +} + +/// The part of a translation file this module reads: +/// `runConfigurationTypes..`. Other top-level keys +/// belong to other surfaces. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct LocalizationFile { + #[serde(default)] + run_configuration_types: UniqueMap>, +} + +/// Translated text of one type, by the manifest field it replaces. +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct TypeText { + #[serde(default, deserialize_with = "present")] + display_name: Option, + #[serde(default, deserialize_with = "present")] + description: Option, + /// Field text by field ID. + #[serde(default, deserialize_with = "present")] + fields: Option>, +} + +/// Translated text of one field. +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct FieldText { + #[serde(default, deserialize_with = "present")] + title: Option, + #[serde(default, deserialize_with = "present")] + description: Option, + #[serde(default, deserialize_with = "present")] + placeholder: Option, + /// Choice titles by choice value. + #[serde(default, deserialize_with = "present")] + options: Option>, +} + +/// A checked translation of one plugin's types, by build system and type ID. +#[derive(Debug, Default)] +struct Localization { + types: BTreeMap<(String, String), TypeText>, +} + +/// 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. +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); + } + } + Ok(localization) +} + +fn check_type_text( + text: &TypeText, + declaration: &RunTypeDeclaration, + field: &str, +) -> Validation<()> { + if let Some(name) = &text.display_name { + relabel(check_text( + name, + &format!("{field}.displayName"), + "display name", + ))?; + } + translated( + text.description.as_deref(), + declaration.description.is_some(), + &format!("{field}.description"), + check_description, + )?; + for (id, field_text) in text.fields.iter().flat_map(|fields| &fields.0) { + let field = format!("{field}.fields.{id}"); + let declared = declaration + .fields + .iter() + .find(|declared| &declared.id == id) + .ok_or_else(|| rejection(&field, "The type declares no field with this ID."))?; + if let Some(title) = &field_text.title { + relabel(check_text(title, &format!("{field}.title"), "title"))?; + } + translated( + field_text.description.as_deref(), + declared.description.is_some(), + &format!("{field}.description"), + check_description, + )?; + translated( + field_text.placeholder.as_deref(), + declared.placeholder.is_some(), + &format!("{field}.placeholder"), + |value, field| check_text(value, field, "placeholder"), + )?; + for (value, title) in field_text.options.iter().flat_map(|options| &options.0) { + let field = format!("{field}.options.{value}"); + if !declared.choices.iter().any(|choice| &choice.value == value) { + return Err(rejection( + &field, + "The field declares no choice with this value.", + )); + } + relabel(check_text(title, &field, "title"))?; + } + } + Ok(()) +} + +/// Checks a translation of text the manifest may lack: a translation +/// replaces text and never adds it. +fn translated( + value: Option<&str>, + declared: bool, + field: &str, + check: impl Fn(&str, &str) -> Validation<()>, +) -> Validation<()> { + let Some(value) = value else { + return Ok(()); + }; + if !declared { + return Err(rejection( + field, + "The manifest has no text here to translate.", + )); + } + relabel(check(value, field)) +} + +/// A manifest check's rejection, as a rejection of the translation file. +fn relabel(result: Validation<()>) -> Validation<()> { + result.map_err(|error| PluginRejection { + code: INVALID_LOCALIZATION, + ..error + }) +} + +fn rejection(field: impl Into, message: impl Into) -> PluginRejection { + PluginRejection::at(INVALID_LOCALIZATION, field, message) +} + +/// `build.runConfigurationPlan`: the argv plan of a saved configuration of a +/// declared type. +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct RunConfigurationPlanRequest { + /// The saved `build.run-type` configuration. + pub(crate) configuration_id: String, + /// The host's replacement for the machine-local layer, as in + /// `runConfig.launchPlan`. + #[serde(default)] + pub(crate) local_document: Option, + /// The detected instances of the build system, with their stored + /// options; the plan runs with the instance whose root holds the + /// working directory. + 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, +} + +/// One detected instance of the build system. +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct RunTypeInstance { + /// Instance root, workspace-relative. + root: String, + /// Stored option values by option ID. + #[serde(default)] + options: BTreeMap, + /// Host-resolved public input snapshot, as in a task plan. + #[serde(default)] + model_inputs: Option, +} + +/// 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 +/// the type's arguments with the field values, the user's program arguments +/// and the instance's options, at the configuration's working directory, +/// with the configuration's environment over the options'. +pub(crate) fn run_configuration_plan( + plugin_id: &str, + system: &BuildSystemDeclaration, + launch: &DeclaredLaunch, + request: &RunConfigurationPlanRequest, + 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.", + )); + } + 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 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.", + }; + PluginRejection::at( + INVALID_RUN_CONFIGURATION, + format!("values.{}", error.field), + message, + ) + })?; + plans::check_user_arguments(&launch.arguments, &declaration.arguments)?; + let mut field_arguments = Vec::new(); + for (id, value) in &values { + let field = declaration + .fields + .iter() + .find(|field| &field.id == id) + .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 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(), + }; + 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())); + let mut plan = context.plan( + &declaration.arguments, + &values, + declaration.execution(), + extra, + )?; + if let Some(environment) = plan["environment"].as_object_mut() { + environment.extend( + launch + .environment + .iter() + .map(|(name, value)| (name.clone(), json!(value))), + ); + } + Ok(plan) +} + +/// The arguments one field value passes: its templates with `${value}`, or +/// the value itself when the field declares none. +fn field_value_arguments( + field: &RunFieldDeclaration, + value: &DeclaredValue, +) -> Validation> { + match value { + DeclaredValue::Arguments(arguments) => Ok(arguments.clone()), + DeclaredValue::Text(text) if field.arguments.is_empty() => Ok(vec![text.clone()]), + DeclaredValue::Text(text) => { + let values = Values { + value: Some(text), + ..Values::default() + }; + field + .arguments + .iter() + .map(|argument| template::expand_text(argument, &values)) + .collect() + } + DeclaredValue::Checked => field + .arguments + .iter() + .map(|argument| template::expand_text(argument, &Values::default())) + .collect(), + } +} + +/// The instance a configuration runs with: the deepest one whose root holds +/// the working directory, or the only one when the working directory is +/// outside every instance, such as an absolute directory outside the +/// workspace. +fn instance_of<'a>( + instances: &'a [RunTypeInstance], + working_directory: &str, +) -> Validation<&'a RunTypeInstance> { + if instances.is_empty() { + return Err(invalid_selection( + "No project of this build system is open.", + )); + } + if instances.len() > MAX_INSTANCES { + return Err(invalid_selection("Too many build system instances.")); + } + let roots = instances + .iter() + .map(|instance| decode::request_path(&instance.root, "root")) + .collect::>>()?; + let directory = decode::request_path(working_directory, "working directory").ok(); + let holding = directory.and_then(|directory| { + roots + .iter() + .enumerate() + .filter(|(_, root)| decode::contains(root, &directory)) + .max_by_key(|(_, root)| { + if *root == "." { + 0 + } else { + root.split('/').count() + } + }) + .map(|(index, _)| &instances[index]) + }); + match (holding, instances) { + (Some(instance), _) | (None, [instance]) => Ok(instance), + (None, _) => Err(invalid_selection( + "The working directory is outside every project of this build system; choose one inside a project.", + )), + } +} diff --git a/rust/crates/build/src/template.rs b/rust/crates/build/src/template.rs index abe8897d..0aaf5565 100644 --- a/rust/crates/build/src/template.rs +++ b/rust/crates/build/src/template.rs @@ -145,6 +145,9 @@ pub(crate) enum Variable { OptionArguments(Option), /// Arguments the user typed. Whole-argument. UserArguments, + /// Arguments of one field of a run configuration type, from the value the + /// user entered. Whole-argument: expands to zero or more elements. + Field(String), PluginDir, WorkspaceStateDir, OutputFile, @@ -154,6 +157,7 @@ const PROJECT_PROPERTY: &str = "project.property:"; const TARGET_PROPERTY: &str = "target.property:"; const TASK_PROPERTY: &str = "task.property:"; const OPTION_ARGUMENTS: &str = "optionArguments:"; +const FIELD: &str = "field:"; /// Longest property key a template may name. const MAX_PROPERTY_KEY: usize = 64; @@ -186,6 +190,8 @@ impl Variable { Self::TargetProperty(key) } else if let Some(key) = property(TASK_PROPERTY) { Self::TaskProperty(key) + } else if let Some(id) = name.strip_prefix(FIELD) { + Self::Field(Some(id).filter(|id| is_setting_identifier(id))?.to_string()) } else { let id = name .strip_prefix(OPTION_ARGUMENTS) @@ -197,7 +203,10 @@ impl Variable { } fn is_whole_argument(&self) -> bool { - matches!(self, Self::OptionArguments(_) | Self::UserArguments) + matches!( + self, + Self::OptionArguments(_) | Self::UserArguments | Self::Field(_) + ) } } @@ -238,6 +247,9 @@ pub(crate) struct Allowed<'a> { pub(crate) conditions: bool, /// Declared option IDs, or `None` when option arguments are not allowed. pub(crate) options: Option<&'a BTreeSet>, + /// Field IDs of the run configuration type whose arguments these are, or + /// `None` outside a run configuration type. + pub(crate) fields: Option<&'a BTreeSet>, } impl Allowed<'_> { @@ -254,6 +266,7 @@ impl Allowed<'_> { host_directories: false, conditions: false, options: None, + fields: None, } } } @@ -332,7 +345,7 @@ fn validate_element( if variable.is_whole_argument() && parts.len() != 1 { return Err(invalid_template( field, - "${optionArguments} and ${userArguments} must be a whole argument.", + "${optionArguments}, ${userArguments}, and ${field:...} must be a whole argument.", )); } let unavailable = || { @@ -391,6 +404,17 @@ fn validate_element( { return Err(unavailable()) } + Variable::Field(id) => { + let Some(fields) = allowed.fields else { + return Err(unavailable()); + }; + if !fields.contains(id) { + return Err(invalid_template( + field, + format!("${{field:{id}}} names an undeclared field."), + )); + } + } Variable::OptionArguments(id) => { let Some(options) = allowed.options else { return Err(unavailable()); @@ -429,6 +453,28 @@ pub(crate) fn option_references(arguments: &[BuildArgument]) -> (bool, BTreeSet< (all, named) } +/// How many times a list of templates names each run configuration field. +pub(crate) fn field_references(arguments: &[BuildArgument]) -> BTreeMap { + let mut references = BTreeMap::new(); + for argument in arguments { + for part in parse(argument.value()).unwrap_or_default() { + if let TemplatePart::Variable(Variable::Field(id)) = part { + *references.entry(id).or_insert(0) += 1; + } + } + } + references +} + +/// How many times a list of templates names `${userArguments}`. +pub(crate) fn user_argument_references(arguments: &[BuildArgument]) -> usize { + arguments + .iter() + .flat_map(|argument| parse(argument.value()).unwrap_or_default()) + .filter(|part| matches!(part, TemplatePart::Variable(Variable::UserArguments))) + .count() +} + /// Whether one list could emit an option's arguments twice: two references /// that cover a common option and whose conditions can hold together, such /// as `${optionArguments}` beside `${optionArguments:release}`. References @@ -515,6 +561,8 @@ pub(crate) struct Values<'a> { /// Expanded arguments per option, in declaration order. pub(crate) option_arguments: &'a [(String, Vec)], pub(crate) user_arguments: &'a [String], + /// Expanded arguments per run configuration type field, by field ID. + pub(crate) field_arguments: &'a [(String, Vec)], pub(crate) plugin_dir: Option<&'a str>, pub(crate) workspace_state_dir: Option<&'a str>, pub(crate) output_file: Option<&'a str>, @@ -556,6 +604,14 @@ pub(crate) fn expand(arguments: &[BuildArgument], values: &Values<'_>) -> Valida } continue; } + Variable::Field(id) => { + if let Some((_, expanded)) = + values.field_arguments.iter().find(|(field, _)| field == id) + { + result.extend(expanded.iter().cloned()); + } + continue; + } _ => {} } } @@ -654,6 +710,8 @@ fn substitute(variable: &Variable, values: &Values<'_>) -> Validation { .to_string(), // Whole-argument variables never reach here: validation rejects them // inside a longer element and `expand` handles them alone. - Variable::OptionArguments(_) | Variable::UserArguments => String::new(), + Variable::OptionArguments(_) | Variable::UserArguments | Variable::Field(_) => { + String::new() + } }) } diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 82764638..deb6ace3 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -448,6 +448,8 @@ pub enum BuildCommand { ModelPlan, /// Expands one build task into an argv plan (`build.taskPlan`). TaskPlan, + /// Expands a saved configuration of a declared run configuration type into an argv plan (`build.runConfigurationPlan`). + RunConfigurationPlan, /// Expands a build test run and its result location (`build.testPlan`). TestPlan, /// Plans typed provider run preparation (`build.prepareRunPlan`). @@ -738,9 +740,9 @@ pub enum RunConfigCommand { CreateUserConfiguration, /// Lists the configuration kinds a user can create (`runConfig.configurationTypes`). ConfigurationTypes, - /// Describes the editor of a built-in process run (`runConfig.editorForm`). + /// Describes the editor of a built-in process run or a declared type (`runConfig.editorForm`). EditorForm, - /// Checks and saves a built-in process run editor (`runConfig.saveConfiguration`). + /// Checks and saves a built-in process run or declared type editor (`runConfig.saveConfiguration`). SaveConfiguration, /// Removes a user-authored run configuration (`runConfig.deleteConfiguration`). DeleteConfiguration, @@ -1174,6 +1176,7 @@ impl CoreCommand { "build.resolveOptions" => Some(Self::Build(BuildCommand::ResolveOptions)), "build.modelPlan" => Some(Self::Build(BuildCommand::ModelPlan)), "build.taskPlan" => Some(Self::Build(BuildCommand::TaskPlan)), + "build.runConfigurationPlan" => Some(Self::Build(BuildCommand::RunConfigurationPlan)), "build.testPlan" => Some(Self::Build(BuildCommand::TestPlan)), "build.prepareDebugPlan" => Some(Self::Build(BuildCommand::PrepareDebugPlan)), "build.decodeDebugPreparation" => { diff --git a/rust/crates/core/src/runtime/dispatcher/build.rs b/rust/crates/core/src/runtime/dispatcher/build.rs index 45c03668..1447e3bb 100644 --- a/rust/crates/core/src/runtime/dispatcher/build.rs +++ b/rust/crates/core/src/runtime/dispatcher/build.rs @@ -51,6 +51,11 @@ pub(super) fn dispatch(command: BuildCommand, id: Option, payload: Value payload, crate::build::build_task_plan_command::, ), + BuildCommand::RunConfigurationPlan => plugin_response( + id, + payload, + crate::build::build_run_configuration_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 59b933d9..93474b94 100644 --- a/rust/crates/core/src/runtime/dispatcher/run_config.rs +++ b/rust/crates/core/src/runtime/dispatcher/run_config.rs @@ -1,6 +1,8 @@ //! `runConfig.*` commands: run configurations and their launch plans. use crate::protocol::{CoreError, CoreResponse, ErrorCode, RunConfigCommand}; +/// The manifest type every domain command validates plugin manifests with. +use lithe_plugin_manifest::DeclarativePluginManifest as Manifest; use serde_json::Value; /// Runs one `runConfig.*` command. @@ -172,51 +174,42 @@ pub(super) fn dispatch( Err(error) => CoreResponse::failure(id, error), } } - RunConfigCommand::ConfigurationTypes => { - match serde_json::from_value::(payload) - .map_err(|error| { - CoreError::new( - ErrorCode::InvalidRequest, - "Invalid configuration types request", - ) - .with_details(error.to_string()) - }) - .and_then(crate::execution::configuration_types) - { - Ok(data) => CoreResponse::success(id, data), - Err(error) => CoreResponse::failure(id, error), - } - } - RunConfigCommand::EditorForm => { - match serde_json::from_value::(payload) - .map_err(|error| { - CoreError::new( - ErrorCode::InvalidRequest, - "Invalid run configuration form request", - ) - .with_details(error.to_string()) - }) - .and_then(crate::execution::editor_form) - { - Ok(data) => CoreResponse::success(id, data), - Err(error) => CoreResponse::failure(id, error), - } - } - RunConfigCommand::SaveConfiguration => { - match serde_json::from_value::(payload) - .map_err(|error| { - CoreError::new( - ErrorCode::InvalidRequest, - "Invalid run configuration save request", - ) - .with_details(error.to_string()) - }) - .and_then(crate::execution::save_configuration) - { - Ok(data) => CoreResponse::success(id, data), - Err(error) => CoreResponse::failure(id, error), - } - } + RunConfigCommand::ConfigurationTypes => respond( + id, + with_run_types( + payload, + "Invalid configuration types request", + true, + |mut request: crate::execution::ConfigurationTypesRequest, run_types| { + request.run_types = run_types; + crate::execution::configuration_types(request) + }, + ), + ), + RunConfigCommand::EditorForm => respond( + id, + with_run_types( + payload, + "Invalid run configuration form request", + true, + |mut request: crate::execution::EditorFormRequest, run_types| { + request.run_types = run_types; + crate::execution::editor_form(request) + }, + ), + ), + RunConfigCommand::SaveConfiguration => respond( + id, + with_run_types( + payload, + "Invalid run configuration save request", + false, + |mut request: crate::execution::SaveConfigurationRequest, run_types| { + request.run_types = run_types; + crate::execution::save_configuration(request) + }, + ), + ), RunConfigCommand::BeforeLaunch => { match serde_json::from_value::(payload) .map_err(|error| { @@ -306,3 +299,43 @@ pub(super) fn dispatch( } } } + +fn respond(id: Option, result: Result) -> CoreResponse { + match result { + Ok(data) => CoreResponse::success(id, data), + Err(error) => CoreResponse::failure(id, error), + } +} + +/// Runs an editor command that offers the run configuration types 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 +/// can read the files a report asks for and call again. +fn with_run_types( + mut payload: Value, + invalid: &'static str, + report: bool, + run: impl FnOnce(T, Vec) -> Result, +) -> Result { + let invalid = |error: serde_json::Error| { + CoreError::new(ErrorCode::InvalidRequest, invalid).with_details(error.to_string()) + }; + let plugins = match payload + .as_object_mut() + .and_then(|object| object.remove("runTypePlugins")) + { + Some(plugins) => { + serde_json::from_value::(plugins).map_err(invalid)? + } + None => crate::build::RunTypePlugins::default(), + }; + let request = serde_json::from_value::(payload).map_err(invalid)?; + let (run_types, reports) = crate::build::declared_run_types::(&plugins)?; + let mut data = run(request, run_types)?; + if report && !reports.is_empty() { + data["localizations"] = Value::Array(reports); + } + Ok(data) +} diff --git a/rust/crates/core/src/tests/declarative_plugins.rs b/rust/crates/core/src/tests/declarative_plugins.rs index 0659afb5..361e86c2 100644 --- a/rust/crates/core/src/tests/declarative_plugins.rs +++ b/rust/crates/core/src/tests/declarative_plugins.rs @@ -69,6 +69,8 @@ const COMMAND_INSTALLER_FIXTURE: &str = contract_file!("fixtures/command-installers/command-installer.plugin.json"); 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 INVALID_MANIFESTS: &str = contract_file!("fixtures/manifest/invalid-manifests.json"); const COMMAND_PLANS: &str = contract_file!("fixtures/languages/command-plans.json"); @@ -102,6 +104,7 @@ fn fixture(name: &str) -> Value { "project-generator.plugin.json" => PROJECT_GENERATOR_FIXTURE, "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, other => panic!("unknown fixture {other}"), }; serde_json::from_str(source).expect("fixture manifest is JSON") @@ -134,6 +137,7 @@ fn contract_fixtures_and_official_plugins_validate() { EDITOR_PROVIDERS_FIXTURE, PROJECT_GENERATOR_TOOL_FIXTURE, COMMAND_INSTALLER_FIXTURE, + RUN_CONFIGURATION_TYPES_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 62b9cf2f..d4a3f32c 100644 --- a/rust/crates/core/src/tests/mod.rs +++ b/rust/crates/core/src/tests/mod.rs @@ -47,6 +47,7 @@ mod marketplace_plugins; mod notification_read; mod plugin_editor_resources; mod plugin_run_debug; +mod plugin_run_types; mod plugin_settings_documents; mod plugin_source_settings; mod process_memory; diff --git a/rust/crates/core/src/tests/plugin_run_types.rs b/rust/crates/core/src/tests/plugin_run_types.rs new file mode 100644 index 00000000..89813424 --- /dev/null +++ b/rust/crates/core/src/tests/plugin_run_types.rs @@ -0,0 +1,686 @@ +//! Run configuration types plugins declare in `buildSystems[].runConfigurationTypes`: +//! the dialog lists them with translated text, the editor draws and saves +//! their fields, and `build.runConfigurationPlan` expands a saved entry into +//! the argv plan the host starts. + +use super::support::{apply_run_changes, changed_run_document, temporary_root, Cleanup}; +use crate::execute_json; +use serde_json::{json, Value}; +use std::collections::BTreeMap; +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/run-configuration-types/run-configuration-types.plugin.json"); +const CHINESE: &str = contract_file!("fixtures/run-configuration-types/l10n/zh-Hans.json"); +const PLUGIN: &str = "dev.lithe.fixture.run-configuration-types"; + +fn manifest() -> Value { + serde_json::from_str(MANIFEST).unwrap() +} + +fn call(command: &str, payload: Value) -> Value { + serde_json::from_str(&execute_json( + &json!({ "id": command, "command": command, "payload": payload }).to_string(), + )) + .unwrap() +} + +/// The `runTypePlugins` of a request with the fixture installed. +fn plugins() -> Value { + json!({ "plugins": [{ "manifest": manifest() }] }) +} + +fn run_type(id: &str) -> Value { + json!({ "pluginID": PLUGIN, "buildSystemID": "go", "type": id }) +} + +fn field<'a>(form: &'a Value, id: &str) -> &'a Value { + form["data"]["fields"] + .as_array() + .unwrap() + .iter() + .find(|field| field["id"] == id) + .unwrap_or(&Value::Null) +} + +fn plan(root: &std::path::Path, manifest: Value, request: Value) -> Value { + call( + "build.runConfigurationPlan", + json!({ + "manifest": manifest, + "buildSystemID": "go", + "workspaceRoot": root, + "request": request, + }), + ) +} + +#[test] +fn declared_types_follow_the_built_in_kinds_with_translated_text() { + let plain = call( + "runConfig.configurationTypes", + json!({ "runTypePlugins": plugins() }), + ); + assert_eq!(plain["ok"], true, "{plain}"); + let declared: Vec<&Value> = plain["data"]["types"] + .as_array() + .unwrap() + .iter() + .filter(|item| item["provider"] == "build.run-type") + .collect(); + assert_eq!( + declared, + [ + &json!({ + "provider": "build.run-type", + "runType": run_type("build"), + "displayName": "Go Build", + "description": "Builds and runs a Go package, file or directory.", + "execution": "application", + "icon": { "host": "run", "mode": "template" }, + }), + &json!({ + "provider": "build.run-type", + "runType": run_type("test"), + "displayName": "Go Test", + "execution": "task", + }), + ] + ); + // No language names no translation and reports nothing. + assert!(plain["data"].get("localizations").is_none(), "{plain}"); + + // A language first asks for the files, then applies the one read. + let asked = call( + "runConfig.configurationTypes", + json!({ "runTypePlugins": { "language": "zh-Hans-CN", "plugins": [{ "manifest": manifest() }] } }), + ); + assert_eq!( + asked["data"]["localizations"], + json!([{ + "pluginID": PLUGIN, + "language": "zh-Hans-CN", + "candidates": ["l10n/zh-Hans-CN.json", "l10n/zh-Hans.json", "l10n/zh.json"], + "maximumBytes": 1048576, + "readRequired": true, + "applied": null, + "rejected": [], + }]) + ); + let translated = call( + "runConfig.configurationTypes", + json!({ "runTypePlugins": { "language": "zh-Hans-CN", "plugins": [{ + "manifest": manifest(), + "localizations": { "l10n/zh-Hans.json": CHINESE }, + }] } }), + ); + let report = &translated["data"]["localizations"][0]; + assert_eq!(report["applied"], "l10n/zh-Hans.json", "{report}"); + assert_eq!(report["readRequired"], false, "{report}"); + let names: Vec<&str> = translated["data"]["types"] + .as_array() + .unwrap() + .iter() + .filter(|item| item["provider"] == "build.run-type") + .map(|item| item["displayName"].as_str().unwrap()) + .collect(); + assert_eq!(names, ["Go 构建", "Go 测试"]); + + // A manifest that does not validate adds no type, as on every surface. + let mut broken = manifest(); + broken["buildSystems"][0]["runConfigurationTypes"][0]["execution"] = json!("service"); + let skipped = call( + "runConfig.configurationTypes", + json!({ "runTypePlugins": { "plugins": [{ "manifest": broken }] } }), + ); + assert_eq!(skipped["ok"], true, "{skipped}"); + assert!(!skipped["data"]["types"] + .as_array() + .unwrap() + .iter() + .any(|item| item["provider"] == "build.run-type")); + + // A malformed list is a host fault. + let malformed = call( + "runConfig.configurationTypes", + json!({ "runTypePlugins": { "plugins": [{ "manifest": manifest(), "extra": 1 }] } }), + ); + assert_eq!(malformed["ok"], false, "{malformed}"); + assert_eq!(malformed["error"]["code"], "invalid_request"); + let without_language = call( + "runConfig.configurationTypes", + json!({ "runTypePlugins": { "plugins": [{ "manifest": manifest(), "localizations": {} }] } }), + ); + assert_eq!(without_language["ok"], false, "{without_language}"); +} + +/// A translation replaces only text the manifest has; a file naming +/// anything else is refused whole and the manifest's wording stays. +#[test] +fn a_translation_that_does_not_fit_the_declarations_is_rejected_whole() { + let mut cases: Vec<(&str, Value)> = Vec::new(); + let mut base: Value = serde_json::from_str(CHINESE).unwrap(); + base["runConfigurationTypes"]["cargo"] = json!({}); + cases.push(("unknown build system", base)); + let mut base: Value = serde_json::from_str(CHINESE).unwrap(); + base["runConfigurationTypes"]["go"]["remote"] = json!({ "displayName": "远程" }); + cases.push(("unknown type", base)); + let mut base: Value = serde_json::from_str(CHINESE).unwrap(); + base["runConfigurationTypes"]["go"]["build"]["fields"]["missing"] = json!({ "title": "无" }); + cases.push(("unknown field", base)); + let mut base: Value = serde_json::from_str(CHINESE).unwrap(); + base["runConfigurationTypes"]["go"]["build"]["fields"]["runKind"]["options"]["module"] = + json!("模块"); + cases.push(("unknown choice", base)); + let mut base: Value = serde_json::from_str(CHINESE).unwrap(); + base["runConfigurationTypes"]["go"]["test"]["description"] = json!("新增的说明"); + cases.push(("text the manifest lacks", base)); + let mut base: Value = serde_json::from_str(CHINESE).unwrap(); + base["runConfigurationTypes"]["go"]["build"]["fields"]["race"]["title"] = json!(""); + cases.push(("empty title", base)); + let mut base: Value = serde_json::from_str(CHINESE).unwrap(); + base["runConfigurationTypes"]["go"]["build"]["displayName"] = Value::Null; + cases.push(("null text", base)); + + for (name, file) in cases { + let reply = call( + "runConfig.configurationTypes", + json!({ "runTypePlugins": { "language": "zh-Hans", "plugins": [{ + "manifest": manifest(), + "localizations": { "l10n/zh-Hans.json": file.to_string() }, + }] } }), + ); + let report = &reply["data"]["localizations"][0]; + assert_eq!(report["applied"], Value::Null, "{name}: {report}"); + assert_eq!( + report["rejected"][0]["error"]["code"], "plugin.build.invalidLocalization", + "{name}: {report}" + ); + let build = reply["data"]["types"] + .as_array() + .unwrap() + .iter() + .find(|item| item["runType"]["type"] == "build") + .unwrap(); + assert_eq!(build["displayName"], "Go Build", "{name}"); + } +} + +#[test] +fn the_editor_draws_declared_fields_and_shows_program_arguments_only_when_taken() { + let root = temporary_root("run-types-editor"); + let _cleanup = Cleanup(root.clone()); + fs::create_dir_all(&root).unwrap(); + + let build = call( + "runConfig.editorForm", + json!({ + "root": root, "provider": "build.run-type", "runType": run_type("build"), + "runTypePlugins": { "language": "zh-Hans", "plugins": [{ + "manifest": manifest(), + "localizations": { "l10n/zh-Hans.json": CHINESE }, + }] }, + }), + ); + assert_eq!(build["ok"], true, "{build}"); + assert_eq!(build["data"]["runType"], run_type("build")); + assert_eq!( + build["data"]["localizations"][0]["applied"], + "l10n/zh-Hans.json" + ); + assert_eq!(field(&build, "name")["automatic"], "Go 构建"); + assert_eq!( + field(&build, "field:runKind"), + &json!({ + "id": "field:runKind", "kind": "choice", "label": "运行种类", + "options": ["package", "file", "directory"], + "optionLabels": { "package": "软件包", "file": "文件", "directory": "目录" }, + }) + ); + assert_eq!( + field(&build, "field:package"), + &json!({ + "id": "field:package", "kind": "text", "label": "软件包路径", + "placeholder": "example.com/app/cmd/server", "required": true, + "visibleWhen": { "field": "field:runKind", "equals": "package" }, + }) + ); + // Untranslated text keeps the manifest's wording. + assert_eq!(field(&build, "field:output")["label"], "Output name"); + assert_eq!( + field(&build, "field:goToolArguments")["description"], + "放在软件包之前传给 go run。" + ); + assert_eq!(build["data"]["values"]["field:runKind"], "package"); + assert_eq!(build["data"]["values"]["field:race"], false); + assert_eq!(build["data"]["values"]["field:goToolArguments"], ""); + assert_eq!(field(&build, "programArguments")["kind"], "arguments"); + assert_eq!(field(&build, "allowMultipleInstances")["kind"], "checkbox"); + + // Go Test names no ${userArguments}, so it has no program arguments. + let test = call( + "runConfig.editorForm", + json!({ + "root": root, "provider": "build.run-type", "runType": run_type("test"), + "runTypePlugins": plugins(), + }), + ); + assert_eq!(test["ok"], true, "{test}"); + assert!(field(&test, "programArguments").is_null(), "{test}"); + assert_eq!(test["data"]["values"]["field:package"], "./..."); + + // A type no installed plugin declares cannot be edited. + let missing = call( + "runConfig.editorForm", + json!({ "root": root, "provider": "build.run-type", "runType": run_type("remote"), + "runTypePlugins": plugins() }), + ); + assert_eq!(missing["error"]["code"], "not_supported", "{missing}"); + let unnamed = call( + "runConfig.editorForm", + json!({ "root": root, "provider": "build.run-type", "runTypePlugins": plugins() }), + ); + assert_eq!(unnamed["ok"], false, "{unnamed}"); +} + +#[test] +fn saved_declared_runs_expand_into_the_types_command_line() { + let root = temporary_root("run-types-plan"); + let _cleanup = Cleanup(root.clone()); + fs::create_dir_all(root.join("services/api/cmd")).unwrap(); + fs::create_dir_all(root.join("tools")).unwrap(); + fs::write(root.join("services/api/cmd/main.go"), "package main\n").unwrap(); + // A declared run lives in its plugin's run document. + let local = ".lithe/run/plugin/dev.lithe.fixture.run-configuration-types.local.toml"; + + // Wrong values come back by field. + let invalid = call( + "runConfig.saveConfiguration", + json!({ + "root": root, "provider": "build.run-type", "runType": run_type("build"), + "runTypePlugins": plugins(), + "values": { "name": "api", "field:runKind": "file", "field:file": "missing.go" }, + }), + ); + assert_eq!(invalid["data"]["status"], "invalid", "{invalid}"); + assert_eq!( + invalid["data"]["errors"], + json!([{ "field": "field:file", "code": "notFound" }]) + ); + let required = call( + "runConfig.saveConfiguration", + json!({ + "root": root, "provider": "build.run-type", "runType": run_type("build"), + "runTypePlugins": plugins(), "values": { "name": "api" }, + }), + ); + assert_eq!( + required["data"]["errors"], + json!([{ "field": "field:package", "code": "required" }]), + "{required}" + ); + + let saved = call( + "runConfig.saveConfiguration", + json!({ + "root": root, "provider": "build.run-type", "runType": run_type("build"), + "runTypePlugins": plugins(), + "values": { + "name": "api", "storeAsProjectFile": false, "allowMultipleInstances": true, + "field:runKind": "package", "field:package": "./cmd", + // Hidden by the run kind, so neither checked nor saved. + "field:file": "missing.go", + "field:goToolArguments": "-v -trimpath", "field:race": true, "field:output": "", + "programArguments": "--port 8080", + "workingDirectory": "services/api", + "environment": [{ "name": "MODE", "value": "dev" }], + }, + }), + ); + assert_eq!(saved["data"]["status"], "saved", "{saved}"); + let id = saved["data"]["id"].as_str().unwrap().to_string(); + let document = changed_run_document(&saved["data"], local).unwrap_or_else(|| panic!("{saved}")); + let entry = &document["configurations"][0]; + assert_eq!(entry["provider"], "build.run-type"); + assert_eq!(entry["allowMultipleInstances"], true); + assert_eq!(entry["args"], json!(["--port", "8080"])); + assert_eq!( + entry["extensions"]["build"], + json!({ + "pluginID": PLUGIN, "buildSystemID": "go", "type": "build", + "values": { + "runKind": "package", "package": "./cmd", + "goToolArguments": ["-v", "-trimpath"], "race": true, "output": "", + }, + }) + ); + apply_run_changes(&root, &saved["data"]); + + // The saved entry is listed and reopens with its values. + let resolved = call("runConfig.resolve", json!({ "root": root })); + let listed = resolved["data"]["configurations"] + .as_array() + .unwrap() + .iter() + .find(|entry| entry["id"] == id.as_str()) + .unwrap(); + assert_eq!(listed["plugin"]["id"], PLUGIN, "{listed}"); + let reopened = call( + "runConfig.editorForm", + json!({ "root": root, "configurationId": id, "runTypePlugins": plugins() }), + ); + assert_eq!( + reopened["data"]["values"]["field:goToolArguments"], + "-v -trimpath" + ); + assert_eq!( + reopened["data"]["values"]["programArguments"], + "--port 8080" + ); + assert_eq!(reopened["data"]["values"]["allowMultipleInstances"], true); + // Without the plugin the entry cannot be edited. + let removed = call( + "runConfig.editorForm", + json!({ "root": root, "configurationId": id }), + ); + assert_eq!(removed["error"]["code"], "not_supported", "{removed}"); + + // The plan runs with the deepest instance holding the working directory. + let instances = json!([ + { "root": ".", "options": { "tags": "root" } }, + { "root": "services/api", "options": { "tags": "api" } }, + { "root": "tools" }, + ]); + let planned = plan( + &root, + manifest(), + json!({ "configurationId": id, "instances": instances }), + ); + assert_eq!(planned["ok"], true, "{planned}"); + assert_eq!(planned["data"]["status"], "ok", "{planned}"); + let plan_value = &planned["data"]["plan"]; + assert_eq!(plan_value["root"], "services/api"); + assert_eq!( + plan_value["arguments"], + json!([ + "run", + "-tags", + "api", + "-v", + "-trimpath", + "-race", + "./cmd", + "--port", + "8080" + ]) + ); + assert_eq!(plan_value["workingDirectory"], "services/api"); + assert_eq!(plan_value["environment"], json!({ "MODE": "dev" })); + assert_eq!(plan_value["execution"], "application"); + assert_eq!(plan_value["runType"], run_type("build")); + + // Another plugin's manifest cannot plan the entry. + let mut other = manifest(); + other["id"] = json!("dev.lithe.fixture.other-run-types"); + let foreign = plan( + &root, + other, + json!({ "configurationId": id, "instances": instances }), + ); + assert_eq!(foreign["data"]["status"], "rejected", "{foreign}"); + // A working directory in no instance needs a single instance. + let outside = plan( + &root, + manifest(), + json!({ "configurationId": id, "instances": [{ "root": "tools" }, { "root": "docs" }] }), + ); + assert_eq!(outside["data"]["status"], "rejected", "{outside}"); + let only = plan( + &root, + manifest(), + json!({ "configurationId": id, "instances": [{ "root": "tools" }] }), + ); + assert_eq!(only["data"]["plan"]["root"], "tools", "{only}"); + // Unknown configurations and other providers fail the call. + let unknown = plan( + &root, + manifest(), + json!({ "configurationId": "user:none", "instances": instances }), + ); + assert_eq!(unknown["ok"], false, "{unknown}"); + let without_root = call( + "build.runConfigurationPlan", + json!({ "manifest": manifest(), "buildSystemID": "go", + "request": { "configurationId": id, "instances": instances } }), + ); + assert_eq!(without_root["ok"], false, "{without_root}"); + + // A file run passes the absolute file. + let file_run = call( + "runConfig.saveConfiguration", + json!({ + "root": root, "provider": "build.run-type", "runType": run_type("build"), + "configurationId": id, "runTypePlugins": plugins(), + "values": { + "name": "api", "field:runKind": "file", "field:file": "services/api/cmd/main.go", + "field:output": "bin/api", + }, + }), + ); + assert_eq!(file_run["data"]["status"], "saved", "{file_run}"); + apply_run_changes(&root, &file_run["data"]); + let planned = plan( + &root, + manifest(), + json!({ "configurationId": id, "instances": instances }), + ); + let main = root.join("services/api/cmd/main.go"); + assert_eq!( + planned["data"]["plan"]["arguments"], + json!([ + "run", + "-tags", + "root", + "-o", + "bin/api", + main.to_string_lossy() + ]), + "{planned}" + ); + assert_eq!(planned["data"]["plan"]["root"], "."); +} + +#[test] +fn a_type_without_program_arguments_stores_none() { + let root = temporary_root("run-types-no-arguments"); + let _cleanup = Cleanup(root.clone()); + fs::create_dir_all(&root).unwrap(); + let saved = call( + "runConfig.saveConfiguration", + json!({ + "root": root, "provider": "build.run-type", "runType": run_type("test"), + "runTypePlugins": plugins(), + "values": { + "name": "unit", "storeAsProjectFile": true, + "field:pattern": "TestParse", "programArguments": "--ignored", + }, + }), + ); + assert_eq!(saved["data"]["status"], "saved", "{saved}"); + let document = changed_run_document( + &saved["data"], + ".lithe/run/plugin/dev.lithe.fixture.run-configuration-types.toml", + ) + .unwrap(); + let entry = &document["configurations"][0]; + assert!(entry.get("args").is_none(), "{entry}"); + assert!(entry.get("allowMultipleInstances").is_none(), "{entry}"); + assert_eq!(entry["execution"], "task"); + apply_run_changes(&root, &saved["data"]); + let planned = plan( + &root, + manifest(), + json!({ "configurationId": saved["data"]["id"], "instances": [{ "root": "." }] }), + ); + assert_eq!( + planned["data"]["plan"]["arguments"], + json!(["test", "-run=TestParse", "./..."]), + "{planned}" + ); + assert_eq!(planned["data"]["plan"]["execution"], "task"); +} + +/// The manifest refuses declarations a host could not draw or run. +#[test] +fn run_configuration_type_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("runConfigurationTypes"); + let refused = validate(missing); + assert_eq!(refused["status"], "rejected", "{refused}"); + + let path = "/buildSystems/0/runConfigurationTypes/0"; + let manifest_error = "plugin.manifest.invalid"; + let template_error = "plugin.template.invalid"; + let cases: BTreeMap<&str, (&str, Value, &str)> = BTreeMap::from([ + ("service", ("/execution", json!("service"), manifest_error)), + ( + "unknown field", + ("/arguments/-", json!("${field:missing}"), template_error), + ), + ( + "field named twice", + ("/arguments/-", json!("${field:race}"), template_error), + ), + ( + "program arguments twice", + ("/arguments/-", json!("${userArguments}"), template_error), + ), + ( + "choice without choices", + ("/fields/0/choices", json!([]), manifest_error), + ), + ( + "choices on a text field", + ( + "/fields/1/choices", + json!([{ "value": "a" }]), + manifest_error, + ), + ), + ( + "required checkbox", + ("/fields/5/required", json!(true), manifest_error), + ), + ( + "file default", + ("/fields/2/default", json!("main.go"), manifest_error), + ), + ( + "default outside the choices", + ("/fields/0/default", json!("module"), manifest_error), + ), + ( + "later controller", + ( + "/fields/1/visibleWhen", + json!({ "field": "race", "equals": true }), + manifest_error, + ), + ), + ( + "text controller", + ( + "/fields/6/visibleWhen", + json!({ "field": "package", "equals": "x" }), + manifest_error, + ), + ), + ( + "controller value outside its choices", + ( + "/fields/1/visibleWhen", + json!({ "field": "runKind", "equals": "module" }), + manifest_error, + ), + ), + ( + "checkbox without arguments", + ("/fields/5/arguments", json!([]), manifest_error), + ), + ( + "value never passed", + ("/fields/6/arguments", json!(["-o"]), template_error), + ), + ( + "arguments field with templates", + ("/fields/4/arguments", json!(["${value}"]), manifest_error), + ), + ( + "field ID with a dash", + ("/fields/6/id", json!("out-name"), manifest_error), + ), + ( + "unsafe icon", + ("/icon", json!({ "path": "../run.svg" }), manifest_error), + ), + ("bad type ID", ("/id", json!("Build Run"), manifest_error)), + ]); + for (name, (pointer, value, code)) in cases { + let mut manifest = manifest(); + set(&mut manifest, &format!("{path}{pointer}"), value); + let outcome = validate(manifest); + assert_eq!(outcome["status"], "rejected", "{name}: {outcome}"); + assert_eq!(outcome["error"]["code"], code, "{name}: {outcome}"); + } + + // A field the command line never names must only show or hide others. + let mut unnamed = manifest(); + unnamed["buildSystems"][0]["runConfigurationTypes"][0]["arguments"] + .as_array_mut() + .unwrap() + .retain(|argument| argument != "${field:output}"); + assert_eq!(validate(unnamed)["status"], "rejected"); + // Duplicate type IDs. + let mut duplicate = manifest(); + let types = duplicate["buildSystems"][0]["runConfigurationTypes"] + .as_array_mut() + .unwrap(); + types[1]["id"] = json!("build"); + assert_eq!(validate(duplicate)["status"], "rejected"); +} + +/// Sets the value at a JSON Pointer whose parent exists; `-` appends. +fn set(manifest: &mut Value, pointer: &str, value: Value) { + let (parent, key) = pointer.rsplit_once('/').unwrap(); + match manifest.pointer_mut(parent) { + Some(Value::Object(object)) => { + object.insert(key.to_string(), value); + } + Some(Value::Array(items)) if key == "-" => items.push(value), + Some(Value::Array(items)) => items[key.parse::().unwrap()] = value, + _ => panic!("{parent} is not a container"), + } +} diff --git a/rust/crates/core/src/tests/run_configuration.rs b/rust/crates/core/src/tests/run_configuration.rs index ae456b3d..30d7f153 100644 --- a/rust/crates/core/src/tests/run_configuration.rs +++ b/rust/crates/core/src/tests/run_configuration.rs @@ -2116,6 +2116,7 @@ fn powershell_and_program_editors_store_their_own_choices() { [ "name", "storeAsProjectFile", + "allowMultipleInstances", "program", "programArguments", "workingDirectory", diff --git a/rust/crates/execution/src/configuration.rs b/rust/crates/execution/src/configuration.rs index cf9dc39b..f5a3d810 100644 --- a/rust/crates/execution/src/configuration.rs +++ b/rust/crates/execution/src/configuration.rs @@ -19,6 +19,7 @@ use std::path::{Path, PathBuf}; mod arrangement; mod before_launch; mod copying; +mod declared; mod document; mod editing; mod form; @@ -37,6 +38,11 @@ pub use arrangement::{arrange, ArrangeRequest}; pub(crate) use arrangement::{valid_folder, Arrangement}; pub use before_launch::{before_launch, BeforeLaunchRequest, BeforeLaunchStep}; pub use copying::{copy_configuration, CopyConfigurationRequest}; +pub use declared::{ + declared_launch, DeclaredChoice, DeclaredCondition, DeclaredField, DeclaredFieldKind, + DeclaredLaunch, DeclaredRunType, DeclaredValue, DeclaredValueError, RunTypeKey, + RunTypeReference, RUN_TYPE_PROVIDER, +}; pub use document::*; pub use editing::*; pub use form::{ diff --git a/rust/crates/execution/src/configuration/declared.rs b/rust/crates/execution/src/configuration/declared.rs new file mode 100644 index 00000000..476e669e --- /dev/null +++ b/rust/crates/execution/src/configuration/declared.rs @@ -0,0 +1,908 @@ +//! Run configuration kinds a plugin declares (`build.run-type`). +//! +//! A build system may declare kinds of run configuration as data: the fields +//! their editor shows and the command line the values make +//! (`buildSystems[].runConfigurationTypes`). The build crate checks the +//! declaration and turns it into a [`DeclaredRunType`]; this module draws the +//! fields of such a kind, checks and stores the values the editor returns, and +//! reads them back for a launch, so neither the host nor the plugin parses a +//! 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. + +use super::process::{self, FieldError}; +use super::*; +use serde_json::Map; + +/// Provider of a configuration of a plugin-declared kind. +pub const RUN_TYPE_PROVIDER: &str = "build.run-type"; + +/// Prefix of a declared field's ID among the editor's own fields, so a +/// plugin field never takes the ID of a field every run has. +const FIELD_PREFIX: &str = "field:"; +const MAX_IDENTIFIER_BYTES: usize = 200; +/// Matches the most fields a kind may declare. +const MAX_VALUES: usize = 16; +const MAX_VALUE_BYTES: usize = 4096; +const MAX_VALUE_ARGUMENTS: usize = 64; + +/// The identity of a declared kind: the plugin, its build system, and the +/// kind's ID within it. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct RunTypeKey { + /// Plugin that declares the build system. + #[serde(rename = "pluginID")] + pub plugin_id: String, + /// Build system within that plugin. + #[serde(rename = "buildSystemID")] + pub build_system_id: String, + /// Kind ID within the build system. + #[serde(rename = "type")] + pub type_id: String, +} + +/// What a saved entry of a declared kind keeps in `extensions.build`. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct RunTypeReference { + /// Plugin that declares the build system. + #[serde(rename = "pluginID")] + pub plugin_id: String, + /// Build system within that plugin. + #[serde(rename = "buildSystemID")] + pub build_system_id: String, + /// Kind ID within the build system. + #[serde(rename = "type")] + pub type_id: String, + /// Field values by declared field ID: a string, a boolean, or a list of + /// strings. Hidden fields are not saved. + #[serde(default, skip_serializing_if = "Map::is_empty")] + pub values: Map, +} + +impl RunTypeReference { + /// The kind the entry belongs to. + pub fn key(&self) -> RunTypeKey { + RunTypeKey { + plugin_id: self.plugin_id.clone(), + build_system_id: self.build_system_id.clone(), + type_id: self.type_id.clone(), + } + } + + /// The reference of a saved `build.run-type` entry. + pub(crate) fn of(configuration: &RunConfiguration) -> Result { + let reference: Self = serde_json::from_value( + configuration + .extensions + .get("build") + .cloned() + .unwrap_or(Value::Null), + ) + .map_err(|_| invalid_reference())?; + reference.validate()?; + Ok(reference) + } + + /// Persistence checks shapes and sizes only; whether the kind is still + /// declared and the values still fit it is checked by the editor and at + /// launch. + pub(crate) fn validate(&self) -> Result<(), CoreError> { + let identifier = |value: &str| { + !value.is_empty() + && value.len() <= MAX_IDENTIFIER_BYTES + && value + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || b"._-".contains(&byte)) + }; + let text = |value: &str| value.len() <= MAX_VALUE_BYTES && !value.contains('\0'); + let value = |value: &Value| match value { + Value::Bool(_) => true, + Value::String(value) => text(value), + Value::Array(items) => { + items.len() <= MAX_VALUE_ARGUMENTS + && items.iter().all(|item| item.as_str().is_some_and(&text)) + } + _ => false, + }; + if [&self.plugin_id, &self.build_system_id, &self.type_id] + .iter() + .any(|id| !identifier(id)) + || self.values.len() > MAX_VALUES + || self + .values + .iter() + .any(|(id, item)| !identifier(id) || !value(item)) + { + return Err(invalid_reference()); + } + Ok(()) + } +} + +fn invalid_reference() -> CoreError { + CoreError::new( + ErrorCode::InvalidRequest, + "Invalid run configuration type reference", + ) +} + +/// A kind of run configuration a plugin declares, checked by the build crate. +#[derive(Debug, Clone)] +pub struct DeclaredRunType { + /// Its identity. + pub key: RunTypeKey, + /// 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`. + pub execution: Execution, + /// Whether its command line takes the user's program arguments; the + /// editor shows the program arguments field only then. + pub takes_arguments: bool, + /// The fields of its editor, in display order. + pub fields: Vec, +} + +/// What a declared field edits. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DeclaredFieldKind { + /// One line of text. + Text, + /// One of the declared choices. + Choice, + /// On or off. + Checkbox, + /// A file, saved project-relative when it is inside the project. + File, + /// A directory, saved like a file. + Directory, + /// A command line split into arguments. + Arguments, +} + +impl DeclaredFieldKind { + /// The editor field kind a host draws. + fn editor_kind(self) -> &'static str { + match self { + Self::Text => "text", + Self::Choice => "choice", + Self::Checkbox => "checkbox", + Self::File => "file", + Self::Directory => "directory", + Self::Arguments => "arguments", + } + } +} + +/// One field of a declared kind. +#[derive(Debug, Clone)] +pub struct DeclaredField { + /// ID within the kind. + pub id: String, + /// What it edits. + pub kind: DeclaredFieldKind, + /// Its label. + pub title: String, + /// A sentence shown with it. + pub description: Option, + /// Shown while it is empty. + pub placeholder: Option, + /// The values of a choice field. + pub choices: Vec, + /// The value of a new configuration; checked against `kind` by the build + /// crate. Absent means empty, off, or the first choice. + pub default: Option, + /// A launch needs a value. + pub required: bool, + /// Shown, saved and used only while an earlier choice or checkbox field + /// has this value. + pub visible_when: Option, +} + +/// One value of a choice field. +#[derive(Debug, Clone)] +pub struct DeclaredChoice { + /// The saved value. + pub value: String, + /// Its label; the value itself when absent. + pub title: Option, +} + +/// When a field is shown. +#[derive(Debug, Clone)] +pub struct DeclaredCondition { + /// An earlier choice or checkbox field. + pub field: String, + /// The value it must have. + pub equals: Value, +} + +/// The value a launch uses of one field. A field without one — empty, off, +/// or hidden — adds nothing to the command line. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum DeclaredValue { + /// A text, choice, file or directory value; files and directories are absolute. + Text(String), + /// A checkbox that is on. + Checked, + /// The arguments of an arguments field. + Arguments(Vec), +} + +/// A saved value a launch cannot use. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DeclaredValueError { + /// Declared field ID. + pub field: String, + /// `required` when a required field is empty, `invalidValue` when the + /// value does not fit the field. + pub code: &'static str, +} + +impl DeclaredField { + /// The value of a new configuration. + fn initial(&self) -> Value { + if let Some(value) = &self.default { + return value.clone(); + } + match self.kind { + DeclaredFieldKind::Choice => self + .choices + .first() + .map_or_else(|| json!(""), |choice| json!(choice.value)), + DeclaredFieldKind::Checkbox => json!(false), + DeclaredFieldKind::Arguments => json!([]), + DeclaredFieldKind::Text | DeclaredFieldKind::File | DeclaredFieldKind::Directory => { + json!("") + } + } + } + + /// The editor key of the field. + fn editor_key(&self) -> String { + format!("{FIELD_PREFIX}{}", self.id) + } + + /// The editor value of a saved value: arguments become argument text. + fn editor_value(&self, value: Value) -> Value { + match (self.kind, &value) { + (DeclaredFieldKind::Arguments, Value::Array(items)) => { + json!(super::form::argument_text( + &items + .iter() + .filter_map(Value::as_str) + .map(str::to_string) + .collect::>() + )) + } + _ => value, + } + } +} + +impl DeclaredRunType { + fn field(&self, id: &str) -> Option<&DeclaredField> { + self.fields.iter().find(|field| field.id == id) + } + + /// Whether `field` is shown for `values`, keyed by declared field ID; a + /// missing value is the field's initial one. + fn visible(&self, field: &DeclaredField, values: &Map) -> bool { + let Some(condition) = &field.visible_when else { + return true; + }; + let Some(controller) = self.field(&condition.field) else { + return false; + }; + let current = values + .get(&controller.id) + .cloned() + .unwrap_or_else(|| controller.initial()); + current == condition.equals && self.visible(controller, values) + } + + /// The editor values of a new configuration, by editor key. + pub(super) fn default_values(&self) -> Map { + self.fields + .iter() + .map(|field| (field.editor_key(), field.editor_value(field.initial()))) + .collect() + } + + /// The editor values of saved field values, by editor key. A field the + /// entry does not hold, such as one a newer plugin added, starts with its + /// initial value. + pub(super) fn saved_values(&self, reference: &RunTypeReference) -> Map { + self.fields + .iter() + .map(|field| { + let value = reference + .values + .get(&field.id) + .cloned() + .unwrap_or_else(|| field.initial()); + (field.editor_key(), field.editor_value(value)) + }) + .collect() + } + + /// The field descriptions of the editor, after the header fields. + pub(super) fn editor_fields(&self) -> Vec { + self.fields + .iter() + .map(|field| { + let mut item = json!({ + "id": field.editor_key(), + "kind": field.kind.editor_kind(), + "label": field.title, + }); + if let Some(description) = &field.description { + item["description"] = json!(description); + } + if let Some(placeholder) = &field.placeholder { + item["placeholder"] = json!(placeholder); + } + if field.required { + item["required"] = json!(true); + } + if field.kind == DeclaredFieldKind::Choice { + item["options"] = json!(field + .choices + .iter() + .map(|choice| choice.value.as_str()) + .collect::>()); + item["optionLabels"] = json!(field + .choices + .iter() + .filter_map(|choice| Some((choice.value.clone(), choice.title.clone()?))) + .collect::>()); + } + if let Some(condition) = &field.visible_when { + item["visibleWhen"] = json!({ + "field": format!("{FIELD_PREFIX}{}", condition.field), + "equals": condition.equals, + }); + } + item + }) + .collect() + } + + /// Checks the editor values and returns the field values in their saved + /// form, with every value that is wrong. Hidden fields are not saved. + /// A value of the wrong JSON type is a host fault, not a field error. + pub(super) fn store( + &self, + root: &Path, + editor: &Map, + ) -> Result<(Map, Vec), CoreError> { + let mut current = Map::new(); + for field in &self.fields { + let key = field.editor_key(); + let value = match editor.get(&key) { + None | Some(Value::Null) => field.editor_value(field.initial()), + Some(value) => value.clone(), + }; + let fits = match field.kind { + DeclaredFieldKind::Checkbox => value.is_boolean(), + DeclaredFieldKind::Choice => value + .as_str() + .is_some_and(|value| field.choices.iter().any(|choice| choice.value == value)), + _ => value.is_string(), + }; + if !fits { + return Err(super::form::invalid_value(&key)); + } + current.insert(field.id.clone(), value); + } + let mut stored = Map::new(); + let mut errors = Vec::new(); + for field in &self.fields { + if !self.visible(field, ¤t) { + continue; + } + let value = ¤t[&field.id]; + let key = field.editor_key(); + let saved = match field.kind { + DeclaredFieldKind::Checkbox | DeclaredFieldKind::Choice => Some(value.clone()), + 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, + ) { + Some(code) => { + errors.push(FieldError::new(key, code)); + None + } + None => Some(json!(arguments)), + } + } + DeclaredFieldKind::Text + | DeclaredFieldKind::File + | DeclaredFieldKind::Directory => { + let text = value.as_str().unwrap_or_default().trim(); + let checked = if text.is_empty() { + if field.required { + Err("required") + } else { + Ok(String::new()) + } + } else { + match field.kind { + DeclaredFieldKind::File => super::form::stored_file(root, text, false), + DeclaredFieldKind::Directory => { + super::form::stored_directory(root, text) + } + _ => process::text_error(text, MAX_VALUE_BYTES) + .map_or_else(|| Ok(text.to_string()), Err), + } + }; + match checked { + Ok(text) => Some(json!(text)), + Err(code) => { + errors.push(FieldError::new(key, code)); + None + } + } + } + }; + if let Some(saved) = saved { + stored.insert(field.id.clone(), saved); + } + } + Ok((stored, errors)) + } + + /// The values a launch of an entry with the saved `values` uses, in + /// field order. Files and directories become absolute against + /// `workspace_root`; a saved value the kind no longer declares is + /// ignored. + pub fn launch_values( + &self, + values: &Map, + workspace_root: &Path, + ) -> Result, DeclaredValueError> { + let mut launch = Vec::new(); + for field in &self.fields { + if !self.visible(field, values) { + continue; + } + let error = |code| DeclaredValueError { + field: field.id.clone(), + code, + }; + let value = values + .get(&field.id) + .cloned() + .unwrap_or_else(|| field.initial()); + let used = match (field.kind, value) { + (DeclaredFieldKind::Checkbox, Value::Bool(on)) => { + on.then_some(DeclaredValue::Checked) + } + (DeclaredFieldKind::Arguments, Value::Array(items)) => { + let arguments = items + .iter() + .map(|item| item.as_str().map(str::to_string)) + .collect::>>() + .ok_or_else(|| error("invalidValue"))?; + (!arguments.is_empty()).then_some(DeclaredValue::Arguments(arguments)) + } + ( + DeclaredFieldKind::Text + | DeclaredFieldKind::Choice + | DeclaredFieldKind::File + | DeclaredFieldKind::Directory, + Value::String(text), + ) => { + if text.is_empty() { + if field.required { + return Err(error("required")); + } + None + } else if field.kind == DeclaredFieldKind::Choice + && !field.choices.iter().any(|choice| choice.value == text) + { + return Err(error("invalidValue")); + } else if matches!( + field.kind, + DeclaredFieldKind::File | DeclaredFieldKind::Directory + ) { + let path = process::file_path(workspace_root, &text, Platform::HOST); + Some(DeclaredValue::Text(path.to_string_lossy().into_owned())) + } else { + Some(DeclaredValue::Text(text)) + } + } + _ => return Err(error("invalidValue")), + }; + if let Some(used) = used { + launch.push((field.id.clone(), used)); + } + } + Ok(launch) + } + + /// The entry of this kind in `runConfig.configurationTypes`. + pub(super) fn type_item(&self) -> Value { + let mut item = json!({ + "provider": RUN_TYPE_PROVIDER, + "runType": self.key, + "displayName": self.display_name, + "execution": self.execution, + }); + if let Some(description) = &self.description { + item["description"] = json!(description); + } + if let Some(icon) = &self.icon { + item["icon"] = icon.clone(); + } + item + } +} + +/// The declared 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 + )) + }) +} + +/// What a launch of a saved `build.run-type` entry 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. + pub arguments: Vec, + /// Workspace-relative working directory; `.` is the workspace root. + pub working_directory: String, + /// Environment variables added to the plugin's. + pub environment: BTreeMap, +} + +/// Reads the saved `build.run-type` entry `configuration_id` of the workspace +/// `root` for a launch, through the same layers the run list resolves. +/// `local_document` replaces the machine-local layer for this request. +pub fn declared_launch( + root: &str, + configuration_id: &str, + local_document: Option, +) -> Result { + let root = existing_root(root)?; + let layers = read_layers(&root, None, local_document)?; + let resolved = resolve_layers(&root, &layers, None)?; + let entry = runnable_configuration(&resolved, configuration_id)?; + let configuration: RunConfiguration = serde_json::from_value(entry.clone()) + .map_err(|_| CoreError::new(ErrorCode::ParseFailed, "Invalid saved run configuration"))?; + if configuration.provider != RUN_TYPE_PROVIDER || configuration.disabled { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Run configuration is not an enabled configuration of a declared type", + )); + } + Ok(DeclaredLaunch { + reference: RunTypeReference::of(&configuration)?, + root, + arguments: configuration.args, + working_directory: configuration.cwd, + environment: configuration.env, + }) +} + +/// 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> { + RunTypeReference::of(configuration)?; + if configuration.command.is_some() + || !configuration.toolchains.is_empty() + || configuration.debug.is_some() + || !configuration.members.is_empty() + || matches!( + configuration.execution, + Execution::Service | Execution::Group + ) + { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Declared run configurations cannot store commands, tool bindings, debug adapters or members", + )); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn kind() -> DeclaredRunType { + DeclaredRunType { + key: RunTypeKey { + plugin_id: "dev.lithe.test.tool".into(), + build_system_id: "tool".into(), + type_id: "check".into(), + }, + display_name: "Tool Check".into(), + description: None, + icon: None, + execution: Execution::Task, + takes_arguments: true, + fields: vec![ + DeclaredField { + id: "scope".into(), + kind: DeclaredFieldKind::Choice, + title: "Scope".into(), + description: None, + placeholder: None, + choices: vec![ + DeclaredChoice { + value: "package".into(), + title: Some("Package".into()), + }, + DeclaredChoice { + value: "file".into(), + title: None, + }, + ], + default: None, + required: false, + visible_when: None, + }, + DeclaredField { + id: "package".into(), + kind: DeclaredFieldKind::Text, + title: "Package".into(), + description: None, + placeholder: Some("./...".into()), + choices: Vec::new(), + default: Some(json!("./...")), + required: true, + visible_when: Some(DeclaredCondition { + field: "scope".into(), + equals: json!("package"), + }), + }, + DeclaredField { + id: "file".into(), + kind: DeclaredFieldKind::File, + title: "File".into(), + description: None, + placeholder: None, + choices: Vec::new(), + default: None, + required: true, + visible_when: Some(DeclaredCondition { + field: "scope".into(), + equals: json!("file"), + }), + }, + DeclaredField { + id: "verbose".into(), + kind: DeclaredFieldKind::Checkbox, + title: "Verbose".into(), + description: None, + placeholder: None, + choices: Vec::new(), + default: None, + required: false, + visible_when: None, + }, + DeclaredField { + id: "flags".into(), + kind: DeclaredFieldKind::Arguments, + title: "Tool arguments".into(), + description: None, + placeholder: None, + choices: Vec::new(), + default: None, + required: false, + visible_when: None, + }, + ], + } + } + + /// A fresh project directory, removed when dropped. + struct Project(PathBuf); + + impl Drop for Project { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + + impl Project { + fn new() -> Self { + use std::sync::atomic::{AtomicU64, Ordering}; + static SEQUENCE: AtomicU64 = AtomicU64::new(0); + let root = std::env::temp_dir().join(format!( + "lithe-declared-run-{}-{}", + std::process::id(), + SEQUENCE.fetch_add(1, Ordering::Relaxed) + )); + let _ = fs::remove_dir_all(&root); + fs::create_dir_all(&root).unwrap(); + Self(root) + } + + fn path(&self) -> &Path { + &self.0 + } + } + + fn editor(values: Value) -> Map { + values.as_object().unwrap().clone() + } + + // A new configuration starts with each field's default, its first choice, + // off, or empty, and its editor names every field after its declared ID. + #[test] + fn new_values_are_the_initial_ones() { + let values = kind().default_values(); + assert_eq!( + Value::Object(values), + json!({"field:scope": "package", "field:package": "./...", "field:file": "", + "field:verbose": false, "field:flags": ""}) + ); + let fields = kind().editor_fields(); + assert_eq!(fields[0]["options"], json!(["package", "file"])); + assert_eq!(fields[0]["optionLabels"], json!({"package": "Package"})); + assert_eq!( + fields[1]["visibleWhen"], + json!({"field": "field:scope", "equals": "package"}) + ); + assert_eq!(fields[1]["required"], json!(true)); + assert_eq!(fields[4]["kind"], json!("arguments")); + } + + // Saving keeps only the fields shown for the chosen values, trims text, + // splits arguments, stores a file project-relative, and names a missing + // required value by its editor key. + #[test] + fn store_keeps_the_shown_fields() { + let root = Project::new(); + fs::write(root.path().join("main_test.go"), "").unwrap(); + let (stored, errors) = kind() + .store( + root.path(), + &editor( + json!({"field:scope": "package", "field:package": " ./cmd/... ", + "field:file": "ignored", "field:verbose": true, + "field:flags": "-race -count 1"}), + ), + ) + .unwrap(); + assert!(errors.is_empty(), "{errors:?}"); + assert_eq!( + Value::Object(stored), + json!({"scope": "package", "package": "./cmd/...", "verbose": true, + "flags": ["-race", "-count", "1"]}) + ); + + let (stored, errors) = kind() + .store( + root.path(), + &editor(json!({"field:scope": "file", "field:file": "main_test.go"})), + ) + .unwrap(); + assert!(errors.is_empty(), "{errors:?}"); + assert_eq!(stored["file"], json!("main_test.go")); + + let (_, errors) = kind() + .store( + root.path(), + &editor(json!({"field:scope": "file", "field:file": ""})), + ) + .unwrap(); + assert_eq!(errors, vec![FieldError::new("field:file", "required")]); + let (_, errors) = kind() + .store( + root.path(), + &editor(json!({"field:scope": "file", "field:file": "missing.go"})), + ) + .unwrap(); + assert_eq!(errors, vec![FieldError::new("field:file", "notFound")]); + assert!(kind() + .store(root.path(), &editor(json!({"field:scope": "module"}))) + .is_err()); + assert!(kind() + .store(root.path(), &editor(json!({"field:verbose": "yes"}))) + .is_err()); + } + + // A launch uses the shown fields that hold a value, makes files absolute, + // and refuses a required field that is empty or a choice the kind no + // longer has. + #[test] + fn launch_values_follow_the_shown_fields() { + let root = Path::new("/workspace"); + let values = editor( + json!({"scope": "file", "package": "./...", "file": "a_test.go", + "verbose": false, "flags": ["-v"], "gone": 1}), + ); + assert_eq!( + kind().launch_values(&values, root).unwrap(), + vec![ + ("scope".to_string(), DeclaredValue::Text("file".into())), + ( + "file".to_string(), + DeclaredValue::Text( + process::file_path(root, "a_test.go", Platform::HOST) + .to_string_lossy() + .into_owned() + ) + ), + ( + "flags".to_string(), + DeclaredValue::Arguments(vec!["-v".into()]) + ), + ] + ); + let defaults = kind().launch_values(&Map::new(), root).unwrap(); + assert_eq!( + defaults, + vec![ + ("scope".to_string(), DeclaredValue::Text("package".into())), + ("package".to_string(), DeclaredValue::Text("./...".into())), + ] + ); + assert_eq!( + kind() + .launch_values(&editor(json!({"package": ""})), root) + .unwrap_err() + .field, + "package" + ); + assert_eq!( + kind() + .launch_values(&editor(json!({"scope": "module"})), root) + .unwrap_err() + .code, + "invalidValue" + ); + } + + // A reference holds identifiers and small values only. + #[test] + fn references_are_bounded() { + let reference = |values: Value| RunTypeReference { + plugin_id: "dev.lithe.test.tool".into(), + build_system_id: "tool".into(), + type_id: "check".into(), + values: values.as_object().unwrap().clone(), + }; + assert!(reference(json!({"a": "x", "b": true, "c": ["y"]})) + .validate() + .is_ok()); + assert!(reference(json!({"a": 1})).validate().is_err()); + assert!(reference(json!({"a": [1]})).validate().is_err()); + assert!(reference(json!({"a b": "x"})).validate().is_err()); + assert!(reference(json!({"a": "\0"})).validate().is_err()); + let mut many = Map::new(); + for index in 0..=MAX_VALUES { + many.insert(format!("f{index}"), json!("")); + } + assert!(reference(Value::Object(many)).validate().is_err()); + } +} diff --git a/rust/crates/execution/src/configuration/document.rs b/rust/crates/execution/src/configuration/document.rs index e4050c09..6337809c 100644 --- a/rust/crates/execution/src/configuration/document.rs +++ b/rust/crates/execution/src/configuration/document.rs @@ -211,6 +211,10 @@ pub struct RunConfiguration { /// Hidden from the resolved list; set by a user or when the working directory is missing. #[serde(default)] pub disabled: bool, + /// Starting the configuration while it runs starts another instance + /// beside it instead of stopping the running one first. Off by default. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub allow_multiple_instances: bool, /// Layer the resolved entry last took a value from: `generated`, /// `project` or `local`. Computed by resolution; never read from a layer. #[serde(default, skip_serializing_if = "Option::is_none")] diff --git a/rust/crates/execution/src/configuration/form.rs b/rust/crates/execution/src/configuration/form.rs index baaf8184..7e34b4d6 100644 --- a/rust/crates/execution/src/configuration/form.rs +++ b/rust/crates/execution/src/configuration/form.rs @@ -1,4 +1,4 @@ -//! The editor of built-in process runs, described as data. +//! The editor of user-authored runs, described as data. //! //! Core decides which fields a configuration kind has, their current and //! automatic values, and how saved values are checked and stored; the host @@ -6,25 +6,39 @@ //! draws fields in the order given, skips a field whose `kind` it does not //! know, and sends back value keys it does not know unchanged, so a later //! Core can add fields without a host change. +//! +//! The kinds are the built-in process runs and the kinds installed plugins +//! declare (`build.run-type`). The host passes the declared kinds with each +//! 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::process::{self, FieldError, Kind, ProcessOptions}; use super::*; /// Version of the editor form description; a host refuses a newer one. const FORM_VERSION: u32 = 1; +/// The editor field of the program arguments of a declared kind. +const DECLARED_ARGUMENTS_FIELD: &str = "programArguments"; + #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] /// Request for the configuration kinds a user can create on this platform. -pub struct ConfigurationTypesRequest {} - -/// The kinds of configuration a user can create, in display order. Every -/// platform creates and edits every kind, so a project shared with Windows -/// keeps its batch scripts editable elsewhere; a kind this platform cannot -/// run carries the `availability` its configurations resolve with. -pub fn configuration_types(_request: ConfigurationTypesRequest) -> Result { - let types = Kind::ALL +pub struct ConfigurationTypesRequest { + /// The kinds installed plugins declare, set by the dispatcher. + #[serde(skip)] + pub run_types: Vec, +} + +/// The kinds of configuration a user can create, in display order: the +/// built-in process runs, then the kinds installed plugins declare. Every +/// platform creates and edits every built-in kind, so a project shared with +/// Windows keeps its batch scripts editable elsewhere; a kind this platform +/// cannot run carries the `availability` its configurations resolve with. +pub fn configuration_types(request: ConfigurationTypesRequest) -> Result { + let mut types = Kind::ALL .into_iter() .map(|kind| { let mut item = json!({ "provider": kind.provider() }); @@ -34,18 +48,22 @@ pub fn configuration_types(_request: ConfigurationTypesRequest) -> Result>(); + types.extend(request.run_types.iter().map(DeclaredRunType::type_item)); Ok(json!({ "types": types })) } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] -/// Request for the editor of a new or saved process run. +/// Request for the editor of a new or saved user-authored run. pub struct EditorFormRequest { /// Canonical workspace root. pub root: String, /// Provider of a new configuration, such as `process.shell`. #[serde(default)] pub provider: Option, + /// The declared kind of a new `build.run-type` configuration. + #[serde(default)] + pub run_type: Option, /// Saved configuration to edit; its provider wins over `provider`. #[serde(default)] pub configuration_id: Option, @@ -53,58 +71,80 @@ pub struct EditorFormRequest { /// values, so automatic values follow the edit. #[serde(default)] pub values: Option>, + /// The kinds installed plugins declare, set by the dispatcher. + #[serde(skip)] + pub run_types: Vec, } -/// The fields, values and automatic values of a process run editor. +/// The fields, values and automatic values of a run editor. pub fn editor_form(request: EditorFormRequest) -> Result { let root = existing_root(&request.root)?; let layers = read_layers(&root, None, None)?; - let (kind, mut values) = match request.configuration_id.as_deref() { + let run_types = &request.run_types; + let (editor, mut values) = match request.configuration_id.as_deref() { Some(id) => { let saved = SavedEntry::find(&layers, id)?; - let kind = saved.kind()?; - if request - .provider - .as_deref() - .is_some_and(|provider| provider != kind.provider()) + let editor = saved.editor(run_types)?; + if request.provider.is_some() + && !Editor::new( + request.provider.as_deref().unwrap_or_default(), + request.run_type.as_ref(), + run_types, + )? + .same(editor) { - return Err(CoreError::new( - ErrorCode::InvalidRequest, - "Run configuration has a different provider", - )); + return Err(different_provider()); } - (kind, saved.values(kind)?) + (editor, saved.values(editor)?) } None => { - let kind = creatable_kind(request.provider.as_deref().unwrap_or_default())?; - (kind, default_values(kind)) + let editor = Editor::new( + request.provider.as_deref().unwrap_or_default(), + request.run_type.as_ref(), + run_types, + )?; + (editor, editor.default_values()) } }; values.extend(request.values.unwrap_or_default()); - let draft = Draft::read(kind, &values)?; let candidates = Resolved::read(&root, &layers)?.candidates(request.configuration_id.as_deref()); + let fields = match editor { + Editor::Process(kind) => fields(kind, &root, &Draft::read(kind, &values)?, candidates), + Editor::Declared(run_type) => { + Common::read(&values, DECLARED_ARGUMENTS_FIELD)?; + declared_fields(run_type, candidates) + } + }; let mut form = json!({ "formVersion": FORM_VERSION, - "provider": kind.provider(), + "provider": editor.provider(), "configurationId": request.configuration_id, "values": values, - "fields": fields(kind, &root, &draft, candidates), + "fields": fields, }); - if let Some(availability) = process::platform_availability(kind, Platform::HOST) { - form["availability"] = json!(availability); + match editor { + Editor::Process(kind) => { + if let Some(availability) = process::platform_availability(kind, Platform::HOST) { + form["availability"] = json!(availability); + } + } + Editor::Declared(run_type) => form["runType"] = json!(run_type.key), } Ok(form) } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] -/// Request to save the values of a process run editor. +/// Request to save the values of a run editor. pub struct SaveConfigurationRequest { /// Canonical workspace root. pub root: String, /// Provider of the configuration, such as `process.shell`. pub provider: String, + /// The declared kind of a `build.run-type` configuration. + #[serde(default)] + pub run_type: Option, /// Saved configuration the values replace; absent creates one. #[serde(default)] pub configuration_id: Option, @@ -113,6 +153,9 @@ pub struct SaveConfigurationRequest { /// The installed plugins, whose identity a written plugin document records. #[serde(default)] pub plugins: Option>, + /// The kinds installed plugins declare, set by the dispatcher. + #[serde(skip)] + pub run_types: Vec, } /// Checks the editor's values and returns the changes that save them. @@ -120,32 +163,60 @@ pub struct SaveConfigurationRequest { /// Replies `{status: "invalid", errors: [{field, code}]}` when a value is /// wrong, else `{status: "saved", id, changes}`. The entry is saved whole in /// the project layer when `storeAsProjectFile` is set and in the local layer -/// otherwise, and removed from the other layer, so it lives in one file. +/// otherwise, and removed from the other layer, so it lives in one file; an +/// entry of a declared kind goes to its plugin's document of that layer. /// Keys and extension namespaces the editor does not show are kept. pub fn save_configuration(request: SaveConfigurationRequest) -> Result { let root = existing_root(&request.root)?; - let kind = creatable_kind(&request.provider)?; + let run_types = &request.run_types; + let editor = Editor::new(&request.provider, request.run_type.as_ref(), run_types)?; let layers = read_layers(&root, None, None)?; let saved = match request.configuration_id.as_deref() { Some(id) => { let saved = SavedEntry::find(&layers, id)?; - if saved.kind()? != kind { - return Err(CoreError::new( - ErrorCode::InvalidRequest, - "Run configuration has a different provider", - )); + if !saved.editor(run_types)?.same(editor) { + return Err(different_provider()); } Some(saved) } None => None, }; - let draft = Draft::read(kind, &request.values)?; - let (stored, mut errors) = draft.store(&root); + let common = Common::read(&request.values, editor.arguments_field())?; + let (stored, extension, mut errors) = match editor { + Editor::Process(kind) => { + let (stored, errors) = Draft::read(kind, &request.values)?.store(&root); + (stored.common, Extension::Process(stored.options), errors) + } + Editor::Declared(run_type) => { + let (values, mut errors) = run_type.store(&root, &request.values)?; + let mut stored = common.store(&root, Some(run_type.display_name.clone()), &mut errors); + if !run_type.takes_arguments { + // A kind without program arguments keeps none, whatever an + // older editor sent. + stored.arguments.clear(); + } + let reference = RunTypeReference { + plugin_id: run_type.key.plugin_id.clone(), + build_system_id: run_type.key.build_system_id.clone(), + type_id: run_type.key.type_id.clone(), + values, + }; + let draft = stored.configuration(RUN_TYPE_PROVIDER, "build", json!(reference)); + for error in process::name_error(&stored.name).into_iter().chain( + process::arguments_and_environment_errors(&draft, DECLARED_ARGUMENTS_FIELD), + ) { + if !errors.iter().any(|known| known.field == error.field) { + errors.push(error); + } + } + (stored, Extension::Declared(reference), errors) + } + }; let id = match &saved { Some(saved) => saved.id.clone(), None => unique_user_configuration_id(&stored.name, &existing_ids(&root, &layers)), }; - if let Some(code) = check_edit(&root, &layers, &id, &draft.before_launch)? { + if let Some(code) = check_edit(&root, &layers, &id, &common.before_launch)? { errors.push(FieldError::new("beforeLaunch", code)); } if !errors.is_empty() { @@ -166,8 +237,15 @@ pub fn save_configuration(request: SaveConfigurationRequest) -> Result Result Result(previous.clone()) - .map(|previous| previous.other) - .unwrap_or_default(); - } - extensions.insert( - "process".into(), - serde_json::to_value(options).expect("process options encode"), - ); + match extension { + Extension::Process(mut options) => { + if let Some(previous) = extensions.get("process") { + // A later release's keys survive an edit made with this one. + options.other = serde_json::from_value::(previous.clone()) + .map(|previous| previous.other) + .unwrap_or_default(); + } + extensions.insert( + "process".into(), + serde_json::to_value(options).expect("process options encode"), + ); + } + Extension::Declared(reference) => { + extensions.insert( + "build".into(), + serde_json::to_value(reference).expect("run type references encode"), + ); + } + } let typed: RunConfiguration = serde_json::from_value(entry.clone()) .map_err(|_| CoreError::new(ErrorCode::ParseFailed, "Invalid saved run configuration"))?; validate_configuration(&typed)?; @@ -244,6 +336,12 @@ pub fn save_configuration(request: SaveConfigurationRequest) -> Result Result Result { - Kind::from_provider(provider).ok_or_else(|| { - CoreError::new( - ErrorCode::NotSupported, - "Only built-in process runs have an editor form", - ) - .with_details(provider) - }) +/// What an editor edits: a built-in process kind, or a kind an installed +/// plugin declares. +#[derive(Clone, Copy)] +enum Editor<'a> { + Process(Kind), + Declared(&'a DeclaredRunType), +} + +impl<'a> Editor<'a> { + /// The kind of `provider`, and for `build.run-type` the declared kind + /// `run_type`. Every platform creates and edits every built-in kind, + /// also one it cannot run. + fn new( + provider: &str, + run_type: Option<&RunTypeKey>, + run_types: &'a [DeclaredRunType], + ) -> Result { + match (provider, run_type) { + (RUN_TYPE_PROVIDER, Some(key)) => Ok(Self::Declared(declared(run_types, key)?)), + (RUN_TYPE_PROVIDER, None) | (_, Some(_)) => Err(CoreError::new( + ErrorCode::InvalidRequest, + "A run configuration type is named with the build.run-type provider only", + )), + (provider, None) => Kind::from_provider(provider) + .map(Self::Process) + .ok_or_else(|| { + CoreError::new( + ErrorCode::NotSupported, + "Only built-in process runs and declared run configuration types have an editor form", + ) + .with_details(provider) + }), + } + } + + fn provider(self) -> &'static str { + match self { + Self::Process(kind) => kind.provider(), + Self::Declared(_) => RUN_TYPE_PROVIDER, + } + } + + fn arguments_field(self) -> &'static str { + match self { + Self::Process(kind) => kind.arguments_field(), + Self::Declared(_) => DECLARED_ARGUMENTS_FIELD, + } + } + + fn same(self, other: Editor<'_>) -> bool { + match (self, other) { + (Self::Process(left), Editor::Process(right)) => left == right, + (Self::Declared(left), Editor::Declared(right)) => left.key == right.key, + _ => false, + } + } + + /// Values of a new configuration. + fn default_values(self) -> serde_json::Map { + let mut values = common_default_values(self.arguments_field()); + match self { + Self::Process(kind) => values.extend(process_default_values(kind)), + Self::Declared(run_type) => values.extend(run_type.default_values()), + } + values + } +} + +fn different_provider() -> CoreError { + CoreError::new( + ErrorCode::InvalidRequest, + "Run configuration has a different provider", + ) } /// Removes configuration `id` from a layer document; whether it was there. @@ -365,20 +526,29 @@ impl SavedEntry { .map_err(|_| CoreError::new(ErrorCode::ParseFailed, "Invalid saved run configuration")) } - fn kind(&self) -> Result { + /// The editor of the saved entry; a declared kind no installed plugin + /// declares has none. + fn editor<'a>(&self, run_types: &'a [DeclaredRunType]) -> Result, CoreError> { let configuration = self.configuration()?; - creatable_kind(&configuration.provider) + if configuration.provider == RUN_TYPE_PROVIDER { + let reference = RunTypeReference::of(&configuration)?; + return Editor::new(RUN_TYPE_PROVIDER, Some(&reference.key()), run_types); + } + Editor::new(&configuration.provider, None, run_types) } /// The editor values of the saved entry. - fn values(&self, kind: Kind) -> Result, CoreError> { + fn values(&self, editor: Editor<'_>) -> Result, CoreError> { let configuration = self.configuration()?; - let options = ProcessOptions::of(&configuration)?; - let mut values = default_values(kind); + let mut values = editor.default_values(); values.insert("name".into(), json!(configuration.name)); values.insert("storeAsProjectFile".into(), json!(self.in_project)); values.insert( - kind.arguments_field().into(), + "allowMultipleInstances".into(), + json!(configuration.allow_multiple_instances), + ); + values.insert( + editor.arguments_field().into(), json!(argument_text(&configuration.args)), ); values.insert("workingDirectory".into(), json!(configuration.cwd)); @@ -398,6 +568,14 @@ impl SavedEntry { .map(|step| step.configuration.clone()) .collect::>()), ); + let kind = match editor { + Editor::Process(kind) => kind, + Editor::Declared(run_type) => { + values.extend(run_type.saved_values(&RunTypeReference::of(&configuration)?)); + return Ok(values); + } + }; + let options = ProcessOptions::of(&configuration)?; if kind.runs_script() { let text = options.script().is_none() && options.text.is_some(); values.insert("source".into(), json!(if text { "text" } else { "file" })); @@ -428,25 +606,30 @@ impl SavedEntry { } } -/// Values of a new configuration of `kind`. -fn default_values(kind: Kind) -> serde_json::Map { +/// Values of the fields every editable run has, for a new configuration. +fn common_default_values(arguments_field: &str) -> serde_json::Map { let mut values = serde_json::Map::new(); values.insert("name".into(), json!("")); values.insert("storeAsProjectFile".into(), json!(false)); - if kind.runs_script() { - values.insert("source".into(), json!("file")); - values.insert("script".into(), json!("")); - values.insert("text".into(), json!("")); - } else { - values.insert("program".into(), json!("")); - } - values.insert(kind.arguments_field().into(), json!("")); + values.insert("allowMultipleInstances".into(), json!(false)); + values.insert(arguments_field.into(), json!("")); values.insert("workingDirectory".into(), json!(".")); values.insert("environment".into(), json!([])); values.insert("beforeLaunch".into(), json!([])); + values +} + +/// Values of the fields of a new process run of `kind` beyond the common ones. +fn process_default_values(kind: Kind) -> serde_json::Map { + let mut values = serde_json::Map::new(); if kind.runs_script() { + values.insert("source".into(), json!("file")); + values.insert("script".into(), json!("")); + values.insert("text".into(), json!("")); values.insert("interpreter".into(), json!("")); values.insert("interpreterArguments".into(), json!("")); + } else { + values.insert("program".into(), json!("")); } if kind == Kind::PowerShell { values.insert("executionPolicyBypass".into(), json!(true)); @@ -454,24 +637,30 @@ fn default_values(kind: Kind) -> serde_json::Map { values } -fn argument_text(arguments: &[String]) -> String { +pub(super) fn argument_text(arguments: &[String]) -> String { crate::format_argument_text(crate::ArgumentTextRequest { argument_lists: vec![arguments.to_vec()], }) .remove(0) } -/// The fields of `kind`'s editor, with automatic values for `draft`. -fn fields(kind: Kind, root: &Path, draft: &Draft, candidates: Vec) -> Vec { - let platform = Platform::HOST; - let options = draft.options(); - let mut fields = vec![ +/// The fields at the top of every editor. +fn header_fields(automatic_name: Option) -> Vec { + vec![ field("name", "text") .required() .header() - .automatic(process::default_name(&options)), + .automatic(automatic_name), field("storeAsProjectFile", "checkbox").header(), - ]; + field("allowMultipleInstances", "checkbox").header(), + ] +} + +/// The fields of `kind`'s editor, with automatic values for `draft`. +fn fields(kind: Kind, root: &Path, draft: &Draft, candidates: Vec) -> Vec { + let platform = Platform::HOST; + let options = draft.options(); + let mut fields = header_fields(process::default_name(&options)); if kind.runs_script() { let shebang = match draft.source { Source::File => options @@ -526,6 +715,28 @@ fn fields(kind: Kind, root: &Path, draft: &Draft, candidates: Vec) -> Vec 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 { + let mut fields = header_fields(Some(run_type.display_name.clone())) + .into_iter() + .map(|field| field.0) + .collect::>(); + fields.extend(run_type.editor_fields()); + if run_type.takes_arguments { + fields.push(field(DECLARED_ARGUMENTS_FIELD, "arguments").0); + } + fields.extend( + [ + field("workingDirectory", "directory"), + field("environment", "environment"), + field("beforeLaunch", "beforeLaunch").candidates(candidates), + ] + .map(|field| field.0), + ); + fields +} + /// One field description being built. struct Field(Value); @@ -591,56 +802,55 @@ enum Source { Text, } -/// Editor values read into their types, before they are checked. -struct Draft { - kind: Kind, +/// A text editor value; absent is empty. +fn text_value(values: &serde_json::Map, key: &str) -> Result { + match values.get(key) { + None | Some(Value::Null) => Ok(String::new()), + Some(Value::String(value)) => Ok(value.clone()), + Some(_) => Err(invalid_value(key)), + } +} + +/// A checkbox editor value; absent is `default`. +fn flag_value( + values: &serde_json::Map, + key: &str, + default: bool, +) -> Result { + match values.get(key) { + None | Some(Value::Null) => Ok(default), + Some(Value::Bool(value)) => Ok(*value), + Some(_) => Err(invalid_value(key)), + } +} + +/// Editor values of the fields every editable run has, before they are checked. +struct Common { name: String, project: bool, - source: Source, - script: String, - text: String, - program: String, + multiple: bool, arguments: String, working_directory: String, environment: Vec<(String, String)>, - interpreter: String, - interpreter_arguments: String, - execution_policy_bypass: bool, /// The configurations started before this one, by ID. before_launch: Vec, } -/// Checked values, in the form they are saved. -struct Stored { +/// The fields every editable run has, in the form they are saved. +struct StoredCommon { name: String, project: bool, + multiple: bool, arguments: Vec, working_directory: String, environment: BTreeMap, - options: ProcessOptions, } -impl Draft { - fn read(kind: Kind, values: &serde_json::Map) -> Result { - let text = |key: &str| -> Result { - match values.get(key) { - None | Some(Value::Null) => Ok(String::new()), - Some(Value::String(value)) => Ok(value.clone()), - Some(_) => Err(invalid_value(key)), - } - }; - let flag = |key: &str, default: bool| -> Result { - match values.get(key) { - None | Some(Value::Null) => Ok(default), - Some(Value::Bool(value)) => Ok(*value), - Some(_) => Err(invalid_value(key)), - } - }; - let source = match text("source")?.as_str() { - "" | "file" => Source::File, - "text" => Source::Text, - _ => return Err(invalid_value("source")), - }; +impl Common { + fn read( + values: &serde_json::Map, + arguments_field: &str, + ) -> Result { let environment = match values.get("environment") { None | Some(Value::Null) => Vec::new(), Some(value) => serde_json::from_value::>(value.clone()) @@ -650,19 +860,12 @@ impl Draft { .collect(), }; Ok(Self { - kind, - name: text("name")?, - project: flag("storeAsProjectFile", false)?, - source, - script: text("script")?, - text: text("text")?, - program: text("program")?, - arguments: text(kind.arguments_field())?, - working_directory: text("workingDirectory")?, + name: text_value(values, "name")?, + project: flag_value(values, "storeAsProjectFile", false)?, + multiple: flag_value(values, "allowMultipleInstances", false)?, + arguments: text_value(values, arguments_field)?, + working_directory: text_value(values, "workingDirectory")?, environment, - interpreter: text("interpreter")?, - interpreter_arguments: text("interpreterArguments")?, - execution_policy_bypass: flag("executionPolicyBypass", true)?, before_launch: match values.get("beforeLaunch") { None | Some(Value::Null) => Vec::new(), Some(value) => serde_json::from_value::>(value.clone()) @@ -671,6 +874,127 @@ impl Draft { }) } + /// The values in their saved form; a wrong value is added to `errors`. + /// An empty name takes `automatic_name`. + fn store( + &self, + root: &Path, + automatic_name: Option, + errors: &mut Vec, + ) -> StoredCommon { + let working_directory = match self.working_directory.trim() { + "" | "." => ".".to_string(), + value => normalize_working_directory(root, value).unwrap_or_else(|_| { + let target = process::file_path(root, value, Platform::HOST); + let code = if target.is_dir() { + "outsideProject" + } else { + "notFound" + }; + errors.push(FieldError::new("workingDirectory", code)); + ".".to_string() + }), + }; + let mut environment = BTreeMap::new(); + for (name, value) in &self.environment { + let name = name.trim(); + if name.is_empty() && value.is_empty() { + continue; + } + if environment + .insert(name.to_string(), value.clone()) + .is_some() + { + errors.push(FieldError::new("environment", "duplicate")); + } + } + let name = match self.name.trim() { + "" => automatic_name.unwrap_or_default(), + name => name.to_string(), + }; + if name.is_empty() { + errors.push(FieldError::new("name", "required")); + } + StoredCommon { + name, + project: self.project, + multiple: self.multiple, + arguments: super::launch::split_arguments(&self.arguments), + working_directory, + environment, + } + } +} + +impl StoredCommon { + /// A configuration of these values with one extension, to run the + /// checks a launch makes before it is saved. + fn configuration(&self, provider: &str, namespace: &str, extension: Value) -> RunConfiguration { + RunConfiguration { + id: "user:draft".into(), + name: self.name.clone(), + folder: None, + provider: provider.into(), + execution: Execution::default(), + category: Default::default(), + command: None, + args: self.arguments.clone(), + cwd: self.working_directory.clone(), + env: self.environment.clone(), + confidence: Confidence::Declared, + toolchains: BTreeMap::new(), + debug: None, + members: Vec::new(), + extensions: BTreeMap::from([(namespace.to_string(), extension)]), + before_launch: Vec::new(), + disabled: false, + allow_multiple_instances: self.multiple, + source: None, + plugin: None, + availability: None, + } + } +} + +/// Editor values of a process run read into their types, before they are checked. +struct Draft { + kind: Kind, + common: Common, + source: Source, + script: String, + text: String, + program: String, + interpreter: String, + interpreter_arguments: String, + execution_policy_bypass: bool, +} + +/// Checked values of a process run, in the form they are saved. +struct Stored { + common: StoredCommon, + options: ProcessOptions, +} + +impl Draft { + fn read(kind: Kind, values: &serde_json::Map) -> Result { + let source = match text_value(values, "source")?.as_str() { + "" | "file" => Source::File, + "text" => Source::Text, + _ => return Err(invalid_value("source")), + }; + Ok(Self { + kind, + common: Common::read(values, kind.arguments_field())?, + source, + script: text_value(values, "script")?, + text: text_value(values, "text")?, + program: text_value(values, "program")?, + interpreter: text_value(values, "interpreter")?, + interpreter_arguments: text_value(values, "interpreterArguments")?, + execution_policy_bypass: flag_value(values, "executionPolicyBypass", true)?, + }) + } + /// The options as typed, without checking or normalizing paths. fn options(&self) -> ProcessOptions { let some = |value: &str| (!value.trim().is_empty()).then(|| value.trim().to_string()); @@ -727,76 +1051,18 @@ impl Draft { }, } } - let working_directory = match self.working_directory.trim() { - "" | "." => ".".to_string(), - value => normalize_working_directory(root, value).unwrap_or_else(|_| { - let target = process::file_path(root, value, Platform::HOST); - let code = if target.is_dir() { - "outsideProject" - } else { - "notFound" - }; - errors.push(FieldError::new("workingDirectory", code)); - ".".to_string() - }), - }; - let mut environment = BTreeMap::new(); - for (name, value) in &self.environment { - let name = name.trim(); - if name.is_empty() && value.is_empty() { - continue; - } - if environment - .insert(name.to_string(), value.clone()) - .is_some() - { - errors.push(FieldError::new("environment", "duplicate")); - } - } - let name = match self.name.trim() { - "" => process::default_name(&options).unwrap_or_default(), - name => name.to_string(), - }; - if name.is_empty() { - errors.push(FieldError::new("name", "required")); - } - let stored = Stored { - name, - project: self.project, - arguments: super::launch::split_arguments(&self.arguments), - working_directory, - environment, - options, - }; + let common = self + .common + .store(root, process::default_name(&options), &mut errors); // The saved entry must pass the same checks a launch makes; report // the ones the steps above do not, such as lengths and characters. // A missing value is left to the steps above, which name the field // of the chosen source: an empty text is not also a missing script. - let configuration = RunConfiguration { - id: "user:draft".into(), - name: stored.name.clone(), - folder: None, - provider: self.kind.provider().into(), - execution: Execution::default(), - category: Default::default(), - command: None, - args: stored.arguments.clone(), - cwd: stored.working_directory.clone(), - env: stored.environment.clone(), - confidence: Confidence::Declared, - toolchains: BTreeMap::new(), - debug: None, - members: Vec::new(), - extensions: BTreeMap::from([( - "process".to_string(), - serde_json::to_value(&stored.options).expect("process options encode"), - )]), - before_launch: Vec::new(), - disabled: false, - source: None, - plugin: None, - availability: None, - }; + let configuration = common.configuration( + self.kind.provider(), + "process", + serde_json::to_value(&options).expect("process options encode"), + ); if let Ok(found) = process::field_errors(&configuration, Platform::HOST) { for error in found { if error.code != "required" @@ -806,7 +1072,7 @@ impl Draft { } } } - (stored, errors) + (Stored { common, options }, errors) } } @@ -819,13 +1085,31 @@ struct EnvironmentRow { value: String, } -fn invalid_value(field: &str) -> CoreError { +pub(super) fn invalid_value(field: &str) -> CoreError { CoreError::new(ErrorCode::InvalidRequest, "Invalid editor value").with_details(field) } /// A script file as saved: project-relative with `/` when it is inside the /// project, else absolute. -fn stored_file(root: &Path, value: &str, keep_dot: bool) -> Result { +pub(super) fn stored_file( + root: &Path, + value: &str, + keep_dot: bool, +) -> Result { + stored_path(root, value, keep_dot, false) +} + +/// A directory as saved, like [`stored_file`]; the project itself is `.`. +pub(super) fn stored_directory(root: &Path, value: &str) -> Result { + stored_path(root, value, false, true) +} + +fn stored_path( + root: &Path, + value: &str, + keep_dot: bool, + directory: bool, +) -> Result { if let Some(code) = process::text_error(value, 4096) { return Err(code); } @@ -836,13 +1120,16 @@ fn stored_file(root: &Path, value: &str, keep_dot: bool) -> Result) -> Option<&str> { /// One invalid value of a process run, named by its editor field. #[derive(Debug, Clone, PartialEq, Eq, Serialize)] pub(crate) struct FieldError { - /// Editor field id, such as `script` or `workingDirectory`. - pub(crate) field: &'static str, + /// Editor field id, such as `script`, `workingDirectory` or, for a + /// plugin-declared field, `field:`. + pub(crate) field: std::borrow::Cow<'static, str>, /// Why the value is invalid: `required`, `conflict`, `notAllowed`, /// `tooLong`, `invalidCharacter`, `invalidPath`, `notFound`, /// `outsideProject` or `invalidName`. @@ -237,8 +238,14 @@ pub(crate) struct FieldError { } impl FieldError { - pub(crate) fn new(field: &'static str, code: &'static str) -> Self { - Self { field, code } + pub(crate) fn new( + field: impl Into>, + code: &'static str, + ) -> Self { + Self { + field: field.into(), + code, + } } } @@ -286,10 +293,7 @@ pub(crate) fn field_errors( )); } let options = ProcessOptions::of(configuration)?; - let mut errors = Vec::new(); - if let Some(code) = text_error(&configuration.name, MAXIMUM_NAME_BYTES) { - errors.push(FieldError::new("name", code)); - } + let mut errors: Vec = name_error(&configuration.name).into_iter().collect(); if kind.runs_script() { match (options.script(), options.text()) { (Some(_), Some(_)) => errors.push(FieldError::new("source", "conflict")), @@ -330,7 +334,27 @@ pub(crate) fn field_errors( if !options.execution_policy_bypass && kind != Kind::PowerShell { errors.push(FieldError::new("executionPolicyBypass", "notAllowed")); } - errors.extend(arguments_error(kind.arguments_field(), &configuration.args)); + errors.extend(arguments_and_environment_errors( + configuration, + kind.arguments_field(), + )); + Ok(errors) +} + +/// The error of a configuration name that is too long or holds NUL. +pub(crate) fn name_error(name: &str) -> Option { + text_error(name, MAXIMUM_NAME_BYTES).map(|code| FieldError::new("name", code)) +} + +/// The errors of the arguments, named by `arguments_field`, and the +/// environment every editable run has. +pub(crate) fn arguments_and_environment_errors( + configuration: &RunConfiguration, + arguments_field: &'static str, +) -> Vec { + let mut errors: Vec = arguments_error(arguments_field, &configuration.args) + .into_iter() + .collect(); if configuration .env .iter() @@ -338,7 +362,7 @@ pub(crate) fn field_errors( { errors.push(FieldError::new("environment", "invalidName")); } - Ok(errors) + errors } pub(crate) fn text_error(value: &str, maximum: usize) -> Option<&'static str> { @@ -370,13 +394,23 @@ fn program_error(field: &'static str, value: &str, platform: Platform) -> Option } fn arguments_error(field: &'static str, arguments: &[String]) -> Option { - if arguments.len() > MAXIMUM_ARGUMENTS { - return Some(FieldError::new(field, "tooLong")); + arguments_limit_error(arguments, MAXIMUM_ARGUMENTS, MAXIMUM_ARGUMENT_BYTES) + .map(|code| FieldError::new(field, code)) +} + +/// `tooLong` when there are more than `count` arguments or one is longer +/// than `bytes`, `invalidCharacter` when one holds NUL. +pub(crate) fn arguments_limit_error( + arguments: &[String], + count: usize, + bytes: usize, +) -> Option<&'static str> { + if arguments.len() > count { + return Some("tooLong"); } arguments .iter() - .find_map(|argument| text_error(argument, MAXIMUM_ARGUMENT_BYTES)) - .map(|code| FieldError::new(field, code)) + .find_map(|argument| text_error(argument, bytes)) } /// Whether a program value is a path rather than a name looked up on `PATH`. diff --git a/rust/crates/execution/src/configuration/resolve.rs b/rust/crates/execution/src/configuration/resolve.rs index 069478e6..f4de8d89 100644 --- a/rust/crates/execution/src/configuration/resolve.rs +++ b/rust/crates/execution/src/configuration/resolve.rs @@ -67,7 +67,12 @@ pub(crate) fn resolve_layers( .get("build") .and_then(|build| build.get("pluginID")) .and_then(Value::as_str) - .filter(|id| configuration.provider == "build.provider" && is_plugin_id(id)) + .filter(|id| { + matches!( + configuration.provider.as_str(), + "build.provider" | super::declared::RUN_TYPE_PROVIDER + ) && is_plugin_id(id) + }) .map(PluginDependency::named) }); if !generated_ids.contains_key(&configuration.id) { diff --git a/rust/crates/execution/src/configuration/validation.rs b/rust/crates/execution/src/configuration/validation.rs index a337d75a..86970692 100644 --- a/rust/crates/execution/src/configuration/validation.rs +++ b/rust/crates/execution/src/configuration/validation.rs @@ -109,6 +109,9 @@ pub(crate) fn validate_configuration(configuration: &RunConfiguration) -> Result )); } } + if configuration.provider == super::declared::RUN_TYPE_PROVIDER { + super::declared::validate(configuration)?; + } if super::process::is_process_provider(&configuration.provider) { super::process::validate(configuration, Platform::HOST)?; } diff --git a/rust/crates/execution/src/lib.rs b/rust/crates/execution/src/lib.rs index fc2f24b1..3f74927c 100644 --- a/rust/crates/execution/src/lib.rs +++ b/rust/crates/execution/src/lib.rs @@ -15,6 +15,7 @@ pub use configuration::*; pub use context_selection::{select_context_configuration, ContextSelectionRequest}; pub use scan::{scan_ignoring, DirectoryContext}; pub use title_action::{decide_title_action, TitleActionRequest}; +pub use types::Execution; pub mod workspace_scan; pub use workspace_scan::IgnoredPaths; diff --git a/rust/crates/execution/src/provider_runs.rs b/rust/crates/execution/src/provider_runs.rs index cf89a81d..e652372a 100644 --- a/rust/crates/execution/src/provider_runs.rs +++ b/rust/crates/execution/src/provider_runs.rs @@ -76,6 +76,7 @@ pub(super) fn configurations(runs: &[ProviderRunConfiguration]) -> Vec, T: Deserialize<'de>>( +/// read as "not translated", so a broken export cannot pass silently. Other +/// surfaces that read a translation file use it for their keys too. +pub fn present<'de, D: Deserializer<'de>, T: Deserialize<'de>>( deserializer: D, ) -> Result, D::Error> { T::deserialize(deserializer).map(Some) @@ -221,6 +222,15 @@ impl<'a> LocalizationRequest<'a> { declarations: &[SettingDeclaration], actions: &[SettingAction], ) -> (Option, Value) { + self.select_with(|text| decode(text, declarations, actions)) + } + + /// [`Self::select`] for another surface: `decode` checks one file + /// against what that surface translates. + pub fn select_with( + &self, + decode: impl Fn(&str) -> Result, + ) -> (Option, Value) { let mut chosen = None; let mut applied = Value::Null; let mut rejected = Vec::new(); @@ -228,7 +238,7 @@ impl<'a> LocalizationRequest<'a> { let Some(text) = self.files.and_then(|files| files.get(path)) else { continue; }; - match decode(text, declarations, actions) { + match decode(text) { Ok(localization) if chosen.is_none() => { chosen = Some(localization); applied = json!(path); @@ -253,9 +263,34 @@ fn rejection(field: impl Into, message: impl Into) -> PluginReje PluginRejection::at(INVALID_LOCALIZATION, field, message) } -/// A rejection of the file as a whole. -fn file_rejection(message: impl Into) -> PluginRejection { - PluginRejection::new(INVALID_LOCALIZATION, message) +/// Parses one translation file into the part a surface reads, refusing it +/// whole with `code` when it is too large, not JSON with unique keys, or not +/// in the l10n format. +pub fn parse_localization_file Deserialize<'de>>( + text: &str, + code: &'static str, +) -> Result { + if text.len() > MAX_LOCALIZATION_BYTES { + return Err(PluginRejection::new( + code, + "The translation file is larger than 1 MiB.", + )); + } + let checked = parse_unique_json(text).map_err(|_| { + PluginRejection::new(code, "The translation file is not JSON with unique keys.") + })?; + if !checked.is_object() { + return Err(PluginRejection::new( + code, + "The translation file is not a JSON object.", + )); + } + serde_json::from_value(checked).map_err(|error| { + PluginRejection::new( + code, + format!("The translation file does not match the l10n format: {error}."), + ) + }) } /// Parses and checks one translation file against the declarations it @@ -265,19 +300,7 @@ fn decode( declarations: &[SettingDeclaration], actions: &[SettingAction], ) -> Result { - if text.len() > MAX_LOCALIZATION_BYTES { - return Err(file_rejection("The translation file is larger than 1 MiB.")); - } - let checked = parse_unique_json(text) - .map_err(|_| file_rejection("The translation file is not JSON with unique keys."))?; - if !checked.is_object() { - return Err(file_rejection("The translation file is not a JSON object.")); - } - let file: LocalizationFile = serde_json::from_value(checked).map_err(|error| { - file_rejection(format!( - "The translation file does not match the l10n format: {error}." - )) - })?; + let file: LocalizationFile = parse_localization_file(text, INVALID_LOCALIZATION)?; let mut localization = SettingsLocalization::default(); for (id, text) in file.settings.0 { let field = format!("settings.{id}"); diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 789049ba..fb1c3410 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -27,6 +27,7 @@ This directory is the cross-platform source of truth: | `fixtures/ui/` | Native controls, forms, and panels, and a web panel | | `fixtures/settings/` | Plugin settings; `l10n/zh-Hans.json` translates `settings.plugin.json`, and `localization-cases.json` holds golden translation choices and rejections | | `fixtures/build-systems/` | Build systems (`build-*`: static file, command output, instance options, model producer and consumer, tool path, toolchains); `build-plans.json` holds golden build-system plans and decoded outputs | +| `fixtures/run-configuration-types/` | `run-configuration-types.plugin.json`: Go Build and Go Test kinds of run configuration with choice, text, file, directory, arguments and checkbox fields, and `l10n/zh-Hans.json` translating them | | `fixtures/build-providers/` | Build providers (`build-provider*`) and the golden cases of their configuration, run options, run and debug preparation, execution, and test protocols | | `fixtures/debug-adapters/` | Debug adapters (standalone, served by a language server, remote attach, and `debug-adapter-features` with declared features and defaults), `debug-adapter-rejections.json`, and `debug-start.json`: what `debug.decodeBackendConfiguration` returns for each `debug/start` case | | `fixtures/run/` | Run sessions and console links: `tool-reference-launch` names its runtimes by tool-definition ID and declares output link matchers; `run-start.json` holds what `run.decodeStart` returns for each case, including the rejections, and `output-link-matchers.json` the golden matches and resolutions | @@ -814,6 +815,7 @@ in `fixtures/settings/localization-cases.json`. | `settings.` | The setting's `title`, `description`, `placeholder`, and `unit`; `options.` is the title of an `enum` or `multiSelect` option | | `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` | 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 @@ -965,6 +967,7 @@ belongs to one capability: | `ui` | [`ui`](#host-owned-workbench-ui): text, [web](#web-content) and [native](#host-rendered-native-content) tool windows, commands, and [backend-only commands](#backend-only-commands) | — | Renders every kind of window and command, and serves the web bridge. | | `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`. | | `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). | @@ -1732,6 +1735,7 @@ declaration are relative, use `/`, and stay inside their base directory | `model` | `static` (a `toml` file read during detection, no process), `command` (a command whose output Core decodes; it states `executesProjectCode` and `mayUseNetwork`), or `provider`. | | `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). | | `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). | @@ -1819,9 +1823,10 @@ one condition or a list that must all hold: `projectSelected`, | `${task.name}`, `${task.property:}` | `fromModel` tasks | | `${test.suite}`, `${test.case}`, `${test.case:regex}` (regex-escaped) | `test.arguments`, guarded by `suiteSelected` / `caseSelected` | | `${optionArguments}`, `${optionArguments:}` | every command list; a whole argument that expands to all options, or one option | -| `${userArguments}` | tasks and tests; a whole argument. A task with `requiresUserArguments` must pass it | +| `${userArguments}` | tasks, tests and run configuration types; a whole argument. A task with `requiresUserArguments` must pass it | | `${pluginDir}`, `${workspaceStateDir}`, `${outputFile}` | model and dependency commands; `${outputFile}` exactly when `output` is `outputFile` | -| `${value}` | option `arguments` and `environment` | +| `${value}` | option `arguments` and `environment`, and the `arguments` of a run configuration field | +| `${field:}` | the `arguments` of a [run configuration type](#run-configuration-types); a whole argument that expands to one field's arguments | Each option's arguments are emitted once per command line: reference them either in `globalArguments` or in the command's list, and only once within a @@ -2452,6 +2457,109 @@ launch the program. Per-run option/tool overrides are ephemeral host inputs to t existing validated plan; they never mutate saved build defaults or claim that the persistent model reflects a different configuration. +### Run configuration types + +`runConfigurationTypes` adds kinds of run configuration to the Run/Debug +Configurations dialog, as IntelliJ IDEA's Go plugin adds Go Build and Go +Test. A type is data only: the fields of its editor and the command line +their values make. Core draws the editor, checks and saves the values, and +expands the command line, so a type needs no backend and the host has no +code for any type. A build system that declares types needs +`runConfigurationTypes: 0` in `requires` beside `buildSystems: 0`. Fixture: +`fixtures/run-configuration-types/`, translated by its `l10n/zh-Hans.json`. + +```json +"runConfigurationTypes": [{ + "id": "build", + "displayName": "Go Build", + "icon": { "host": "run" }, + "fields": [ + { "id": "runKind", "title": "Run kind", "kind": "choice", "default": "package", + "choices": [{ "value": "package", "title": "Package" }, { "value": "file", "title": "File" }] }, + { "id": "package", "title": "Package path", "kind": "text", "required": true, + "visibleWhen": { "field": "runKind", "equals": "package" } }, + { "id": "file", "title": "Files", "kind": "file", "required": true, + "visibleWhen": { "field": "runKind", "equals": "file" } }, + { "id": "race", "title": "Race detector", "kind": "checkbox", "arguments": ["-race"] }, + { "id": "output", "title": "Output name", "kind": "text", "arguments": ["-o", "${value}"] } + ], + "arguments": ["run", "${optionArguments}", "${field:race}", "${field:output}", + "${field:package}", "${field:file}", "${userArguments}"] +}] +``` + +| Field | Meaning | +| --- | --- | +| `id` | Unique within the build system, like a task ID; saved in every configuration of the type, so renaming it orphans them | +| `displayName`, `description` | Shown in the dialog's `+` menu and as the editor's automatic name; at most 120 and 512 bytes | +| `icon` | A [UI icon](#ui-icons) for the menu and the list; display only | +| `execution` | `application` (default) or `task`, as for a task; `service` is refused | +| `fields` | At most 16, in display order between the editor's header and the program arguments | +| `arguments` | The command line after `globalArguments`. Besides `${root}` and `${optionArguments}` it takes `${field:}`, a whole argument that expands to the arguments of one field, and `${userArguments}`, the program arguments. The editor shows its program arguments field only when `${userArguments}` appears, and it appears at most once. Conditions (`when`) are refused | + +A field has an `id` (camelCase, unique in the type), a `title`, a `kind`, and +optional `description`, `placeholder`, `default`, `required`, `visibleWhen` +and `arguments`: + +| `kind` | Value | Passed as | +| --- | --- | --- | +| `text` | One line | The value as one argument, or its `arguments` with `${value}` | +| `choice` | One of `choices` (`{value, title?}`, at most 64, required) | As `text` | +| `checkbox` | On or off | Its `arguments` (required, no `${value}`) while it is on, nothing while off | +| `file`, `directory` | A path the user picks; saved project-relative inside the project, passed absolute | As `text` | +| `arguments` | Text the user types, split like program arguments | The arguments themselves; `arguments` is refused | + +- `default` is the value of a new configuration: a string for `text` and + `choice`, a boolean for `checkbox`, a list of strings for `arguments`. + `file` and `directory` have none, since a plugin cannot know a path on the + user's machine. A `choice` starts with its first choice and a `checkbox` + off when they have none. +- `required` refuses an empty visible `text`, `file`, `directory` or + `arguments` field; a `choice` or `checkbox` always holds a value, so + `required` on one is refused. +- `visibleWhen: {field, equals}` names an earlier `choice` or `checkbox` + field and one of its values. A hidden field is not shown, saved, checked or + passed, so the Go Build fields above pass exactly one of the package and + the file. +- Every field is named exactly once as `${field:}` in the type's + `arguments`, except a field that declares no `arguments` and only controls + the visibility of others, such as `runKind`. + +An unknown, misplaced or repeated variable, or a field the command line +never names, is `plugin.template.invalid`; any other mistake is +`plugin.manifest.invalid`, with `field` naming it. + +Every editor also has the fields every configuration has: the name, *Store +as project file*, *Allow multiple instances*, the working directory, the +environment variables and the steps before launch. *Allow multiple +instances* is off by default: starting a running configuration again stops +the running process first; with it on, the host starts another process +beside it. A configuration is saved with provider `build.run-type` in +`.lithe/run/plugin/.toml` (project) or +`.local.toml` (this machine) and keeps the type and the visible +fields' values in `extensions.build`, so removing the plugin keeps the +configuration, which needs the plugin again to edit or run. + +To run one, the host calls `build.runConfigurationPlan` with the manifest, +the build system, `workspaceRoot`, the configuration ID and the detected +instances of the build system with their stored options. Core picks the +deepest instance whose root holds the configuration's working directory (or +the only instance) and returns a task plan: the global arguments, then the +type's `arguments` with the field values, the instance's options and the +program arguments, at the configuration's working directory, with its +environment over the options'. The host starts it like any build command. A +saved value that no longer fits the type, such as a choice the plugin +removed, is `plugin.build.invalidRunConfiguration` with `field: +"values."`; a type the plugin no longer declares is +`plugin.build.unavailable`. + +The type's text is translated in the package's `l10n/.json` under +`runConfigurationTypes..`: `displayName`, +`description`, and `fields.` with `title`, `description`, +`placeholder` and `options.`, chosen and checked as in +[Translations](#translations). A file that does not fit is refused whole +with `plugin.build.invalidLocalization`, and the manifest's text is shown. + ### Build providers Some tools expose their model only through their own API (the Gradle Tooling @@ -4417,6 +4525,8 @@ command payload is a Core `invalid_request` failure instead. | `plugin.build.unavailable` | Core | The plugin declares no such build system, or the build system does not declare the requested operation | | `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.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/run-configuration-types/l10n/zh-Hans.json b/shared/plugins/contract/v1/fixtures/run-configuration-types/l10n/zh-Hans.json new file mode 100644 index 00000000..50d57c80 --- /dev/null +++ b/shared/plugins/contract/v1/fixtures/run-configuration-types/l10n/zh-Hans.json @@ -0,0 +1,22 @@ +{ + "runConfigurationTypes": { + "go": { + "build": { + "displayName": "Go 构建", + "description": "构建并运行一个 Go 包、文件或目录。", + "fields": { + "runKind": { + "title": "运行种类", + "options": { "package": "软件包", "file": "文件", "directory": "目录" } + }, + "package": { "title": "软件包路径" }, + "goToolArguments": { "title": "Go 工具实参", "description": "放在软件包之前传给 go run。" }, + "race": { "title": "竞态检测" } + } + }, + "test": { + "displayName": "Go 测试" + } + } + } +} diff --git a/shared/plugins/contract/v1/fixtures/run-configuration-types/run-configuration-types.plugin.json b/shared/plugins/contract/v1/fixtures/run-configuration-types/run-configuration-types.plugin.json new file mode 100644 index 00000000..776db44c --- /dev/null +++ b/shared/plugins/contract/v1/fixtures/run-configuration-types/run-configuration-types.plugin.json @@ -0,0 +1,122 @@ +{ + "schemaVersion": 0, + "id": "dev.lithe.fixture.run-configuration-types", + "displayName": "Run Configuration Types Fixture", + "version": "0.1.0", + "pluginAPIVersion": 0, + "requires": { "buildSystems": 0, "runConfigurationTypes": 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}"] } + ], + "runConfigurationTypes": [ + { + "id": "build", + "displayName": "Go Build", + "description": "Builds and runs a Go package, file or directory.", + "icon": { "host": "run" }, + "fields": [ + { + "id": "runKind", + "title": "Run kind", + "kind": "choice", + "choices": [ + { "value": "package", "title": "Package" }, + { "value": "file", "title": "File" }, + { "value": "directory", "title": "Directory" } + ], + "default": "package" + }, + { + "id": "package", + "title": "Package path", + "kind": "text", + "placeholder": "example.com/app/cmd/server", + "required": true, + "visibleWhen": { "field": "runKind", "equals": "package" } + }, + { + "id": "file", + "title": "Files", + "kind": "file", + "required": true, + "visibleWhen": { "field": "runKind", "equals": "file" } + }, + { + "id": "directory", + "title": "Directory", + "kind": "directory", + "required": true, + "visibleWhen": { "field": "runKind", "equals": "directory" } + }, + { + "id": "goToolArguments", + "title": "Go tool arguments", + "kind": "arguments", + "description": "Passed to go run before the package." + }, + { + "id": "race", + "title": "Race detector", + "kind": "checkbox", + "arguments": ["-race"] + }, + { + "id": "output", + "title": "Output name", + "kind": "text", + "arguments": ["-o", "${value}"] + } + ], + "arguments": [ + "run", + "${optionArguments}", + "${field:goToolArguments}", + "${field:race}", + "${field:output}", + "${field:package}", + "${field:file}", + "${field:directory}", + "${userArguments}" + ] + }, + { + "id": "test", + "displayName": "Go Test", + "execution": "task", + "fields": [ + { + "id": "package", + "title": "Package", + "kind": "text", + "default": "./..." + }, + { + "id": "pattern", + "title": "Pattern", + "kind": "text", + "arguments": ["-run=${value}"] + } + ], + "arguments": ["test", "${optionArguments}", "${field:pattern}", "${field:package}"] + } + ] + } + ] +} diff --git a/shared/plugins/contract/v1/plugin-l10n.schema.json b/shared/plugins/contract/v1/plugin-l10n.schema.json index 771b708a..40961f74 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. 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 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": { @@ -24,6 +24,16 @@ "type": "object", "propertyNames": { "pattern": "^[a-z][A-Za-z0-9]*(?![\\s\\S])", "maxLength": 120 }, "additionalProperties": { "$ref": "#/$defs/actionText" } + }, + "runConfigurationTypes": { + "description": "Text of buildSystems[].runConfigurationTypes, by build system ID, then type ID.", + "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": { @@ -58,6 +68,42 @@ } } }, + "runTypeText": { + "description": "Each member replaces the field of the same name; plugin.json must have that field.", + "type": "object", + "additionalProperties": false, + "properties": { + "displayName": { "$ref": "#/$defs/label" }, + "description": { "$ref": "#/$defs/runTypeDescription" }, + "fields": { + "description": "Field text, by field ID.", + "type": "object", + "propertyNames": { "pattern": "^[a-z][A-Za-z0-9]*(?![\\s\\S])", "maxLength": 120 }, + "additionalProperties": { + "type": "object", + "additionalProperties": false, + "properties": { + "title": { "$ref": "#/$defs/label" }, + "description": { "$ref": "#/$defs/runTypeDescription" }, + "placeholder": { "$ref": "#/$defs/label" }, + "options": { + "description": "choice fields only: choice titles, by choice value.", + "type": "object", + "propertyNames": { "minLength": 1, "maxLength": 256 }, + "additionalProperties": { "$ref": "#/$defs/label" } + } + } + } + } + } + }, + "runTypeDescription": { + "description": "Not only whitespace, at most 512 bytes; may hold line breaks.", + "type": "string", + "minLength": 1, + "maxLength": 512, + "pattern": "\\S" + }, "actionText": { "description": "Each member replaces the field of the same name; plugin.json must have that field.", "type": "object", diff --git a/shared/plugins/contract/v1/plugin-manifest.schema.json b/shared/plugins/contract/v1/plugin-manifest.schema.json index 4a6951aa..480c59ff 100644 --- a/shared/plugins/contract/v1/plugin-manifest.schema.json +++ b/shared/plugins/contract/v1/plugin-manifest.schema.json @@ -9,6 +9,7 @@ "allOf": [ {"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": ["commandInstallers"]}, "then": {"required": ["permissions"], "properties": {"requires": {"required": ["commandInstallers"]}, "permissions": {"contains": {"const": "commands.install"}}}}}, {"if": {"required": ["toolchainProviders"]}, "then": {"required": ["backend"], "properties": {"requires": {"required": ["toolchainProviders", "backend"]}, "permissions": {"allOf": [{"contains": {"const": "toolchains.provide"}}, {"contains": {"const": "backend.launch"}}]}}}}, {"if": {"required": ["pluginFunctions"]}, "then": {"required": ["backend"], "properties": {"requires": {"required": ["pluginFunctions", "backend"]}}}}, @@ -39,6 +40,7 @@ "outputLinkMatchers": { "description": "Required exactly when outputLinkMatchers is non-empty.", "enum": [0] }, "packageTrust": { "description": "Required exactly when vendor.bundledSignatureRequirement is present.", "enum": [0] }, "projectGenerators": { "description": "Entries of the New Project window: fields, requirements, and steps, with tool fields that pick tool installations.", "enum": [0] }, + "runConfigurationTypes": { "description": "Required exactly when any buildSystems[].runConfigurationTypes is non-empty: kinds of run configuration the user creates in the Run/Debug Configurations dialog, drawn from declared fields and run through a declared command line. Needs buildSystems.", "enum": [0] }, "settings": { "description": "Required exactly when settings or settingActions is non-empty. Covers integer, enum, boolean, multiSelect, text, file, and directory options, scope, effect, page, section, and settingActions.", "enum": [0] }, "sourceSettings": { "description": "Required exactly when a setting action declares sourceEditor. Native-source settings projection, compiler placement, confirmed staging and read-back. Version 1 adds sidebar groups, nested sources, field sections and entry lists.", "enum": [0, 1] }, "toolDefinitions": { "enum": [0] }, @@ -2711,6 +2713,83 @@ } } }, + "runConfigurationType": { + "type": "object", + "additionalProperties": false, + "required": ["id", "displayName", "arguments"], + "description": "One kind of run configuration. Rules JSON Schema cannot express are in README.md: type IDs are unique within the build system, every field that passes a value is named exactly once as ${field:} in arguments, ${userArguments} appears at most once, and visibleWhen names an earlier field.", + "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 type in the dialog's + menu and list; display only.", "$ref": "#/$defs/uiIcon" }, + "execution": { "description": "How the started process behaves; application by default.", "enum": ["application", "task"] }, + "fields": { + "description": "The editor's fields, in display order, between the header and the program arguments.", + "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 and ${userArguments} for the program arguments, which the editor shows only when it appears.", + "$ref": "#/$defs/buildArgumentList" + } + } + }, + "runConfigurationField": { + "type": "object", + "additionalProperties": false, + "required": ["id", "title", "kind"], + "properties": { + "id": { "type": "string", "pattern": "^[a-z][A-Za-z0-9]*$", "maxLength": 120 }, + "title": { "$ref": "#/$defs/runConfigurationText" }, + "kind": { "enum": ["text", "choice", "checkbox", "file", "directory", "arguments"] }, + "description": { "$ref": "#/$defs/runConfigurationDescription" }, + "placeholder": { "$ref": "#/$defs/runConfigurationText" }, + "choices": { + "description": "choice only, and required there: the values in display order.", + "type": "array", + "minItems": 1, + "maxItems": 64, + "items": { + "type": "object", + "additionalProperties": false, + "required": ["value"], + "properties": { + "value": { "type": "string", "minLength": 1, "maxLength": 256 }, + "title": { "$ref": "#/$defs/runConfigurationText" } + } + } + }, + "default": { + "description": "The value of a new configuration: a string for text and choice, a boolean for checkbox, a list of strings for arguments. File and directory fields have none.", + "oneOf": [ + { "type": "string", "maxLength": 256 }, + { "type": "boolean" }, + { "type": "array", "maxItems": 64, "items": { "type": "string", "minLength": 1, "maxLength": 256 } } + ] + }, + "required": { "description": "A visible text, file, directory or arguments field may not be left empty.", "type": "boolean" }, + "visibleWhen": { + "description": "The field is shown, saved and passed only while an earlier choice or checkbox field holds equals.", + "type": "object", + "additionalProperties": false, + "required": ["field", "equals"], + "properties": { + "field": { "type": "string" }, + "equals": { "type": ["string", "boolean"] } + } + }, + "arguments": { + "description": "Templates that pass the value, ${value} standing for it, such as [\"-o\", \"${value}\"]; without them a value is one argument. A checkbox needs them and passes them while checked; an arguments field has none.", + "type": "array", + "maxItems": 8, + "items": { "type": "string", "minLength": 1 } + } + } + }, + "runConfigurationText": { "type": "string", "minLength": 1, "maxLength": 120, "pattern": "\\S" }, + "runConfigurationDescription": { "type": "string", "minLength": 1, "maxLength": 512, "pattern": "\\S" }, "buildSystem": { "type": "object", "additionalProperties": false, @@ -3128,6 +3207,13 @@ }, "maxItems": 128 }, + "runConfigurationTypes": { + "description": "requires.runConfigurationTypes: kinds of run configuration the user creates in the Run/Debug Configurations dialog. Core draws the declared fields, checks and saves their values, and expands arguments with them, the instance's options and the program arguments.", + "type": "array", + "minItems": 1, + "maxItems": 16, + "items": { "$ref": "#/$defs/runConfigurationType" } + }, "run": { "type": "array", "items": { diff --git a/shared/plugins/reference/api-catalog.md b/shared/plugins/reference/api-catalog.md index 1651eb3a..3bbcf922 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) | 开发指南还不完整;Lithe 桌面端未声明 `buildModelInputs` | [声明式构建](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) | 开发指南还不完整;Lithe 桌面端未声明 `buildModelInputs` 和 `runConfigurationTypes` | [声明式构建](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) | The developer guides are incomplete; the Lithe desktop client does not declare `buildModelInputs` | [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) | The developer guides are incomplete; the Lithe desktop client declares neither `buildModelInputs` nor `runConfigurationTypes` | [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 4d4e0907..7442de5b 100644 --- a/shared/plugins/reference/capabilities-and-versions.md +++ b/shared/plugins/reference/capabilities-and-versions.md @@ -52,6 +52,7 @@ Core 列以本仓库 `main` 上的 Core 源码为准([`capabilities.rs`](https | `buildProviders` `0` | `buildSystems[].provider`:[构建提供者](../contract/v1/README.md#build-providers),可以是自有进程或共享语言服务器;说 `litheBuild`,包含任务执行、测试执行与发现、运行准备、原生调试准备、原生配置、内联测试报告、语义测试选择器、类型化运行选项和注册表连接调试 | ✅ | ✅¹ | [构建提供者](domains/build-providers.md) | | `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) | | `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) | | `commandInstallers` `0` | [`commandInstallers[]`](../contract/v1/README.md#command-installers):用插件已依赖的工具安装 `systemCommand` 启动缺的裸命令,装到 Lithe 管理的目录(`managed`)或工具默认位置(`toolDefault`),用户确认后才运行 | ✅ | 未声明 | [工具链](domains/toolchains.md#安装缺失的命令) | @@ -160,6 +161,7 @@ Each row is one capability. `requires` lists **exactly** the capabilities a mani | `buildProviders` `0` | `buildSystems[].provider`: [build providers](../contract/v1/README.md#build-providers), in their own process or a shared language server; they speak `litheBuild`, which covers task execution, test execution and discovery, run preparation, native debug preparation, native configuration, inline test reports, semantic test selectors, typed run options, and registry connection debugging | ✅ | ✅¹ | [Build providers](domains/build-providers.md) | | `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 | ✅ | Not declared | [Run configuration types](../contract/v1/README.md#run-configuration-types) | | `vcsProviders` `0` | [`vcsProviders[]`](../contract/v1/README.md#vcs-providers); they speak `litheVcs` | ✅ | Not declared | [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) | | `commandInstallers` `0` | [`commandInstallers[]`](../contract/v1/README.md#command-installers): install a bare command a `systemCommand` launch lacks with a tool the plugin already requires, into a directory Lithe manages (`managed`) or the tool's default location (`toolDefault`), only after the user confirms | ✅ | Not declared | [Toolchains](domains/toolchains.md#installing-missing-commands) | diff --git a/shared/plugins/reference/domains/build-systems.md b/shared/plugins/reference/domains/build-systems.md index 17ef5d19..75209eb2 100644 --- a/shared/plugins/reference/domains/build-systems.md +++ b/shared/plugins/reference/domains/build-systems.md @@ -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`);可执行文件候选用 `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`;可执行文件候选用 `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` | @@ -34,6 +34,7 @@ | `model` | 怎么得到项目模型,见下表 | | `provider` | 没有命令能打印模型时,由[构建提供者](build-providers.md)回答模型和依赖请求 | | `tasks`、`run`、`test` | 任务目录、从模型目标或任务生成的运行入口、测试的范围、过滤器和结果文件 | +| `runConfigurationTypes` | 用户可以在运行/调试配置对话框里新建的配置类型(如 Go Build、Go Test):字段、默认值、显示条件和命令行模板;宿主按字段画编辑器,Core 校验值并展开命令行,见[运行配置类型](../../contract/v1/README.md#run-configuration-types) | | `diagnostics`、`dependencies` | 诊断的行匹配或 `litheDiagnostics`;依赖列表或依赖树的来源 | | `sync`、`layout` | 哪些文件变化会让模型过期;每个项目要作为 `excluded` 内容根加入的目录;`layout.hiddenDirectoryNames` 是插件启用期间所有工作区在任意层级隐藏的目录名(如依赖、缓存和构建输出目录),项目树、搜索、文件事件、本地历史、运行发现、构建探测和仓库发现都会跳过 | @@ -70,6 +71,7 @@ | [Optional read-only model inputs](../../contract/v1/README.md#optional-read-only-model-inputs) | 插件之间共享只读模型 | | [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` | | [Host integrations](../../contract/v1/README.md#host-integrations) | 构建系统的宿主集成(保留字段,Core 不实现) | | [Commands](../../contract/v1/README.md#commands) | `build.*` Core 命令:检测、规划、解码、同步指纹 | @@ -111,7 +113,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`); 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`; 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` | @@ -131,6 +133,7 @@ IDs of build systems, tasks, and run entries start with a lowercase letter and u | `model` | How the project model is obtained; see the table below | | `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) | | `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 | @@ -167,6 +170,7 @@ A build system's `hostIntegration` and a language server's `hostIntegration` are | [Optional read-only model inputs](../../contract/v1/README.md#optional-read-only-model-inputs) | Sharing read-only models between plugins | | [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` | | [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 42e8de22..871115e4 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -51,6 +51,7 @@ | `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) | +| `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) | | `settings` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | @@ -140,6 +141,7 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改了什么 | | --- | --- | --- | --- | --- | +| [#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`,不认识它的宿主不会安装。没有新增宿主方法或通知。 | | [#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`。没有新增宿主方法或通知。 | | [#86](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/86) | [@Mucheen](https://github.com/Mucheen) | API-29 | `buildSystems` 0 内的补充 | 构建树与选项编辑支持模型提供的默认激活项、实际激活集合和取消前缀([1lck/Lithe-IDEA#2092](https://github.com/1lck/Lithe-IDEA/issues/2092))。规范模型可报告 `optionDefaults`、`optionExcludePrefixes` 和 `optionActiveChoices`。Core 按选项指纹匹配实际激活集合,保留兄弟构建根和继承值,并在生成运行条目时解析取消前缀。清单中的 `excludePrefix` 和 `model.map.optionDefaults` 需要支持这些字段的 Core。旧 Core 可忽略规范模型新增字段。宿主方法、通知和能力版本沿用现有契约。 | | [#85](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/85) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | — | 插件清单 `schemaVersion` 0 内的补充 | 清单新增可选字段 `repository`([1lck/Lithe-IDEA#2100](https://github.com/1lck/Lithe-IDEA/issues/2100)):值是插件源码仓库的 GitHub 地址 `https://github.com/<作者>/<仓库>`,格式不对时以 `plugin.manifest.invalid`(字段 `repository`)拒绝。项目里由插件提供的 Run 配置改存 `.lithe/run/plugin/<插件 ID>.toml`(共享)和 `<插件 ID>.local.toml`(本机),文件头 `[plugin]` 记录插件 ID、名称、作者、仓库、版本、版本要求(默认 `>=保存时的版本`)、`pluginAPIVersion` 和用到的能力,作者和仓库取自 `repository`,用来区分同名插件;插件没有安装、仓库不一致或版本不满足要求时,这些配置在 Run 列表里显示为不可用并说明原因,不会让整个列表读取失败。Core 自带的脚本和程序运行(shell、PowerShell、Windows 批处理、可执行文件)不依赖任何插件。没写 `repository` 的插件照常安装,Run 文件里不记作者和仓库、也不比对仓库;清单格式和能力版本不变,没有新增宿主方法或通知。 | From 01edf2e33dc9883312792a789225b73ce2391e4d Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Wed, 18 Nov 2026 15:24:36 +0800 Subject: [PATCH 2/2] =?UTF-8?q?test(run-config):=20=E6=89=8B=E6=94=B9?= =?UTF-8?q?=E4=BF=9D=E5=AD=98=E5=80=BC=E5=90=8E=E8=A7=84=E5=88=92=EF=BC=8C?= =?UTF-8?q?=E6=8C=89=E5=AD=97=E6=AE=B5=E6=8A=A5=20plugin.build.invalidRunC?= =?UTF-8?q?onfiguration?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- rust/crates/core/src/tests/plugin_run_types.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/rust/crates/core/src/tests/plugin_run_types.rs b/rust/crates/core/src/tests/plugin_run_types.rs index 89813424..e20de4a2 100644 --- a/rust/crates/core/src/tests/plugin_run_types.rs +++ b/rust/crates/core/src/tests/plugin_run_types.rs @@ -438,6 +438,24 @@ fn saved_declared_runs_expand_into_the_types_command_line() { json!({ "configurationId": id, "instances": instances }), ); assert_eq!(foreign["data"]["status"], "rejected", "{foreign}"); + // A value edited by hand that the type does not offer is named by field. + let path = root.join(local); + let saved_text = fs::read_to_string(&path).unwrap(); + let edited = saved_text.replace("runKind = \"package\"", "runKind = \"module\""); + assert_ne!(edited, saved_text, "{saved_text}"); + fs::write(&path, edited).unwrap(); + let wrong = plan( + &root, + manifest(), + json!({ "configurationId": id, "instances": instances }), + ); + assert_eq!(wrong["data"]["status"], "rejected", "{wrong}"); + assert_eq!( + wrong["data"]["error"]["code"], + "plugin.build.invalidRunConfiguration" + ); + assert_eq!(wrong["data"]["error"]["field"], "values.runKind", "{wrong}"); + fs::write(&path, saved_text).unwrap(); // A working directory in no instance needs a single instance. let outside = plan( &root,