From 11d1b72b6014c77b82e90ac20bb8f7ca3125281b Mon Sep 17 00:00:00 2001 From: lick <2188718831@qq.com> Date: Tue, 17 Nov 2026 18:33:21 -0800 Subject: [PATCH] =?UTF-8?q?feat(run-config):=20=E8=BF=90=E8=A1=8C=E9=85=8D?= =?UTF-8?q?=E7=BD=AE=E7=9A=84=E5=90=AF=E5=8A=A8=E5=89=8D=E6=AD=A5=E9=AA=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 运行配置新增 beforeLaunch,引用内置进程运行,按顺序在配置启动前运行。 Core 展开嵌套步骤、校验引用并对项目文件列出的步骤给出确认指纹; 编辑器表单新增 beforeLaunch 字段,updateOptions 可修改步骤列表。 Refs 1lck/Lithe-IDEA#1616 Co-Authored-By: Claude Opus 5.5 --- .../run-configuration-v2.schema.json | 13 + rust/contracts/rust-core-api.md | 52 +++ rust/crates/core/src/protocol/command.rs | 3 + .../core/src/runtime/dispatcher/run_config.rs | 15 + .../core/src/tests/before_launch_steps.rs | 291 ++++++++++++++ rust/crates/core/src/tests/mod.rs | 1 + .../core/src/tests/run_configuration.rs | 3 +- rust/crates/execution/src/configuration.rs | 2 + .../src/configuration/before_launch.rs | 359 ++++++++++++++++++ .../execution/src/configuration/document.rs | 5 + .../execution/src/configuration/editing.rs | 33 ++ .../execution/src/configuration/form.rs | 49 ++- .../execution/src/configuration/requests.rs | 5 + .../execution/src/configuration/validation.rs | 1 + rust/crates/execution/src/provider_runs.rs | 1 + 15 files changed, 825 insertions(+), 8 deletions(-) create mode 100644 rust/crates/core/src/tests/before_launch_steps.rs create mode 100644 rust/crates/execution/src/configuration/before_launch.rs diff --git a/rust/contracts/run-configuration-v2.schema.json b/rust/contracts/run-configuration-v2.schema.json index 9119deff..779fd6f9 100644 --- a/rust/contracts/run-configuration-v2.schema.json +++ b/rust/contracts/run-configuration-v2.schema.json @@ -211,6 +211,19 @@ "propertyNames": { "type": "string", "pattern": "^[a-z][a-z0-9-]*$" }, "additionalProperties": { "type": "object" } }, + "beforeLaunch": { + "type": "array", + "maxItems": 16, + "description": "Built-in process runs started in order before this one; each must exit with 0 first. A layer replaces the whole list.", + "items": { + "type": "object", + "required": ["configuration"], + "properties": { + "configuration": { "type": "string", "minLength": 1, "maxLength": 256 } + }, + "additionalProperties": false + } + }, "disabled": { "type": "boolean" }, "source": { "type": "string" } }, diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 0609c797..f261cc29 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -715,6 +715,7 @@ or removing a command fails until the table changes in the same commit. | `runConfig.editorForm` | Describe the editor fields and current values of a built-in 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.beforeLaunch` | Expand the built-in process runs a configuration starts first, and say whether the user must confirm them | | `runConfig.createLaunchPlan` | Project one effective configuration into a platform-neutral Run or Debug plan | | `runConfig.providerLaunchInputs` | Resolve user choices for a provider-owned launch | | `git.status` | Resolve the repository, current branch, and working-tree changes | @@ -3885,6 +3886,57 @@ extension namespaces the editor does not show are kept. returns `{changes}` that remove the saved `user:` configuration from every layer. Generated entries cannot be deleted. +#### Steps before launch + +A configuration of any provider may name `beforeLaunch`, an ordered list of at +most 16 `{configuration}` steps. Each step is the ID of a built-in process run +of the same project, which starts and must exit with 0 before the next step, +and the configuration itself, starts (IntelliJ IDEA's "Before launch: Run +Another Configuration"). A shell script that compiles a module or a program +that generates sources is saved as a process run and named as a step, so a step +has the interpreter, arguments, working directory, environment and launch plan +a process run already has. A layer replaces the whole list: an empty list in the +local layer hides the steps the project layer names. A step that names the +configuration itself makes the configuration unavailable +(`invalidConfiguration`); a step whose target is missing or cannot run is +reported when the configuration starts, so the list still resolves. + +`runConfig.beforeLaunch` accepts `{root, configurationId, localDocument?}` and +replies `{status: "ok", steps, confirmation}` or `{status: "rejected", refusal: +{code, configurationId}}`. `steps` are the runs to start, in order, each +`{configurationId, name, summary}`; `summary` is one line naming what it starts +(the program or script and its arguments) for the confirmation. A step whose run +names steps of its own starts them first, as starting that run alone would; at +most 32 steps are expanded. `refusal.code` is `notFound` (no such +configuration), `notAllowed` (not a built-in process run), `unavailable` (the +run cannot start, see its `availability`), `cycle` (a step leads back to a +configuration being started) or `tooLong`; `configurationId` names the step. + +`confirmation` is `{fingerprint}` when the project layer names any of the +expanded lists, and `null` otherwise. Those steps run code from the repository +that nobody chose on this machine, so the host asks the user before running +them, showing each step's name and summary, and remembers the fingerprint per +project in its own storage, never in the project. The fingerprint is a SHA-256 +over the lists and the definitions of the runs they start, so changing either +asks again; it does not cover the contents of a script file a step runs. A list +the local layer names, including one that starts runs the project defines, was +chosen on this machine and needs no confirmation. The host runs each step +through `runConfig.createLaunchPlan`, writes its output to the console of the +configuration that starts, stops it with that configuration, and does not start +the configuration when a step fails or is stopped. Run and Debug both run the +steps. + +`runConfig.editorForm` adds a `beforeLaunch` field to every process run with +`candidates: [{id, name}]`, the runnable process runs other than the edited one; +its value is the list of IDs. `runConfig.saveConfiguration` checks it like +`runConfig.beforeLaunch` and reports `{field: "beforeLaunch", code}` with +`notFound`, `notAllowed`, `unavailable`, `conflict` (a cycle) or `tooLong`. +`runConfig.updateOptions` and `runConfig.saveEditorChanges` accept an optional +`beforeLaunch` list of IDs for any configuration: omission keeps the saved +steps, an empty list removes them from the edited layer (and in the local layer +hides the project's), and a list that cannot run is `invalid_request` with +`beforeLaunch: ` in the details. + `runConfig.createLaunchPlan` accepts `root`, `configurationId`, optional `localDocument` and optional `inlineScriptBase`. It resolves the configuration through the same layers and rejects a missing, disabled or unavailable one. diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 72b194cb..4f7e9f84 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -740,6 +740,8 @@ pub enum RunConfigCommand { SaveConfiguration, /// Removes a user-authored run configuration (`runConfig.deleteConfiguration`). DeleteConfiguration, + /// Expands the steps run before a configuration starts (`runConfig.beforeLaunch`). + BeforeLaunch, /// Produces the process plan for one configuration (`runConfig.createLaunchPlan`). CreateLaunchPlan, /// Resolves user choices for a provider-owned launch (`runConfig.providerLaunchInputs`). @@ -1427,6 +1429,7 @@ impl CoreCommand { "runConfig.deleteConfiguration" => { Some(Self::RunConfig(RunConfigCommand::DeleteConfiguration)) } + "runConfig.beforeLaunch" => Some(Self::RunConfig(RunConfigCommand::BeforeLaunch)), "runConfig.createLaunchPlan" => { Some(Self::RunConfig(RunConfigCommand::CreateLaunchPlan)) } diff --git a/rust/crates/core/src/runtime/dispatcher/run_config.rs b/rust/crates/core/src/runtime/dispatcher/run_config.rs index 652766f8..3ed33b21 100644 --- a/rust/crates/core/src/runtime/dispatcher/run_config.rs +++ b/rust/crates/core/src/runtime/dispatcher/run_config.rs @@ -217,6 +217,21 @@ pub(super) fn dispatch( Err(error) => CoreResponse::failure(id, error), } } + RunConfigCommand::BeforeLaunch => { + match serde_json::from_value::(payload) + .map_err(|error| { + CoreError::new( + ErrorCode::InvalidRequest, + "Invalid run configuration before launch request", + ) + .with_details(error.to_string()) + }) + .and_then(crate::execution::before_launch) + { + Ok(data) => CoreResponse::success(id, data), + Err(error) => CoreResponse::failure(id, error), + } + } RunConfigCommand::DeleteConfiguration => { match serde_json::from_value::(payload) .map_err(|error| { diff --git a/rust/crates/core/src/tests/before_launch_steps.rs b/rust/crates/core/src/tests/before_launch_steps.rs new file mode 100644 index 00000000..1bfacf75 --- /dev/null +++ b/rust/crates/core/src/tests/before_launch_steps.rs @@ -0,0 +1,291 @@ +//! Issue 1lck/Lithe-IDEA#1616: a run configuration names built-in process runs +//! to start first. Core checks and expands the references and says whether a +//! project file named them, so the host confirms them before running. + +use super::support::{apply_run_changes, temporary_root, write_run_document, Cleanup}; +use crate::execute_json; +use serde_json::{json, Value}; +use std::fs; + +fn call(command: &str, payload: Value) -> Value { + let reply: Value = serde_json::from_str(&execute_json( + &json!({ "id": command, "command": command, "payload": payload }).to_string(), + )) + .unwrap(); + assert_eq!(reply["ok"], true, "{command}: {reply}"); + reply["data"].clone() +} + +fn executable(id: &str, program: &str, steps: &[&str]) -> Value { + let mut entry = json!({ + "id": id, "name": id.trim_start_matches("user:"), "provider": "process.executable", + "confidence": "declared", "extensions": {"process": {"program": program}} + }); + if !steps.is_empty() { + entry["beforeLaunch"] = json!(steps + .iter() + .map(|step| json!({ "configuration": step })) + .collect::>()); + } + entry +} + +fn step_ids(reply: &Value) -> Vec { + reply["steps"] + .as_array() + .unwrap_or_else(|| panic!("no steps in {reply}")) + .iter() + .map(|step| step["configurationId"].as_str().unwrap().to_string()) + .collect() +} + +#[test] +fn steps_expand_nested_runs_first_and_project_lists_need_confirmation() { + let root = temporary_root("before-launch-expand"); + let _cleanup = Cleanup(root.clone()); + fs::create_dir_all(root.join("scripts")).unwrap(); + fs::write( + root.join("scripts/compile.sh"), + "#!/bin/sh\necho compiled\n", + ) + .unwrap(); + let project = ".lithe/run/configurations.yaml"; + let local = ".lithe/run/local.yaml"; + let compile = json!({ + "id": "user:compile", "name": "compile", "provider": "process.shell", + "confidence": "declared", "args": ["--fast"], + "extensions": {"process": {"script": "scripts/compile.sh"}} + }); + write_run_document( + &root, + project, + &json!({"version": 2, "configurations": [ + executable("user:app", "echo", &["user:gen"]), compile + ]}), + ); + write_run_document( + &root, + local, + &json!({"version": 2, "configurations": [executable("user:gen", "echo", &["user:compile"])]}), + ); + + // The app starts gen, which starts compile first; a project file names the + // app's list, so the user confirms it. + let app = call( + "runConfig.beforeLaunch", + json!({"root": root, "configurationId": "user:app"}), + ); + assert_eq!(app["status"], "ok", "{app}"); + assert_eq!(step_ids(&app), ["user:compile", "user:gen"]); + assert_eq!(app["steps"][0]["name"], "compile"); + assert_eq!(app["steps"][0]["summary"], "scripts/compile.sh --fast"); + assert_eq!(app["steps"][1]["summary"], "echo"); + let fingerprint = app["confirmation"]["fingerprint"] + .as_str() + .unwrap() + .to_string(); + assert_eq!(fingerprint.len(), 64); + + // gen's own list is this machine's, so it runs without asking. + let gen = call( + "runConfig.beforeLaunch", + json!({"root": root, "configurationId": "user:gen"}), + ); + assert_eq!(step_ids(&gen), ["user:compile"]); + assert!(gen["confirmation"].is_null(), "{gen}"); + // A run that names no steps has none. + let none = call( + "runConfig.beforeLaunch", + json!({"root": root, "configurationId": "user:compile"}), + ); + assert_eq!( + none, + json!({"status": "ok", "steps": [], "confirmation": null}) + ); + + // Changing what a step starts asks again. + let mut changed: Value = + serde_json::from_str(&fs::read_to_string(root.join(project)).unwrap()).unwrap(); + changed["configurations"][1]["args"] = json!(["--clean"]); + write_run_document(&root, project, &changed); + let again = call( + "runConfig.beforeLaunch", + json!({"root": root, "configurationId": "user:app"}), + ); + assert_ne!(again["confirmation"]["fingerprint"], json!(fingerprint)); + + // An empty local list hides the project's steps. + let cleared = call( + "runConfig.updateOptions", + json!({"root": root, "scope": "local", "configurationId": "user:app", "beforeLaunch": []}), + ); + apply_run_changes(&root, &cleared); + let local_document: Value = serde_yaml_value(&fs::read_to_string(root.join(local)).unwrap()); + let entry = local_document["configurations"] + .as_array() + .unwrap() + .iter() + .find(|entry| entry["id"] == "user:app") + .cloned() + .unwrap(); + assert_eq!(entry["beforeLaunch"], json!([]), "{local_document}"); + let app = call( + "runConfig.beforeLaunch", + json!({"root": root, "configurationId": "user:app"}), + ); + assert_eq!( + app, + json!({"status": "ok", "steps": [], "confirmation": null}) + ); + + // A list set on this machine runs without asking, even though it starts + // runs a project file defines. + let local_list = call( + "runConfig.updateOptions", + json!({"root": root, "scope": "local", "configurationId": "user:app", "beforeLaunch": ["user:compile"]}), + ); + apply_run_changes(&root, &local_list); + let app = call( + "runConfig.beforeLaunch", + json!({"root": root, "configurationId": "user:app"}), + ); + assert_eq!(step_ids(&app), ["user:compile"]); + assert!(app["confirmation"].is_null(), "{app}"); +} + +#[test] +fn steps_that_cannot_run_are_refused_by_code() { + let root = temporary_root("before-launch-refused"); + let _cleanup = Cleanup(root.clone()); + let local = ".lithe/run/local.yaml"; + write_run_document( + &root, + local, + &json!({"version": 2, "configurations": [ + executable("user:a", "echo", &["user:missing"]), + executable("user:b", "echo", &["user:c"]), + executable("user:c", "echo", &["user:b"]), + executable("user:self", "echo", &["user:self"]), + ]}), + ); + let refusal = |id: &str| { + let reply = call( + "runConfig.beforeLaunch", + json!({"root": root, "configurationId": id}), + ); + assert_eq!(reply["status"], "rejected", "{reply}"); + reply["refusal"].clone() + }; + assert_eq!( + refusal("user:a"), + json!({"code": "notFound", "configurationId": "user:missing"}) + ); + assert_eq!( + refusal("user:b"), + json!({"code": "cycle", "configurationId": "user:b"}) + ); + + // A configuration that names itself is unavailable, and the list still resolves. + let resolved = call("runConfig.resolve", json!({"root": root})); + let configurations = resolved["configurations"].as_array().unwrap(); + assert_eq!(configurations.len(), 4, "{resolved}"); + let own = configurations + .iter() + .find(|entry| entry["id"] == "user:self") + .unwrap(); + assert_eq!(own["availability"]["code"], "invalidConfiguration", "{own}"); + assert_eq!(refusal("user:a")["code"], "notFound"); + assert_eq!( + call( + "runConfig.beforeLaunch", + json!({"root": root, "configurationId": "user:b"}) + )["refusal"]["code"], + "cycle" + ); + + // updateOptions refuses a list that cannot run and writes nothing. + let reply: Value = serde_json::from_str(&execute_json( + &json!({"id": "u", "command": "runConfig.updateOptions", "payload": { + "root": root, "scope": "local", "configurationId": "user:a", "beforeLaunch": ["user:a"] + }}) + .to_string(), + )) + .unwrap(); + assert_eq!(reply["ok"], false, "{reply}"); + assert!( + reply["error"]["details"] + .as_str() + .unwrap() + .contains("notAllowed"), + "{reply}" + ); +} + +#[test] +fn the_editor_form_lists_candidates_and_checks_the_steps_it_saves() { + let root = temporary_root("before-launch-form"); + let _cleanup = Cleanup(root.clone()); + let local = ".lithe/run/local.yaml"; + write_run_document( + &root, + local, + &json!({"version": 2, "configurations": [ + executable("user:prepare", "echo", &[]), + executable("user:serve", "echo", &["user:prepare"]), + ]}), + ); + let form = call( + "runConfig.editorForm", + json!({"root": root, "configurationId": "user:prepare"}), + ); + assert_eq!(form["values"]["beforeLaunch"], json!([])); + let field = form["fields"] + .as_array() + .unwrap() + .iter() + .find(|field| field["id"] == "beforeLaunch") + .cloned() + .unwrap(); + assert_eq!(field["kind"], "beforeLaunch"); + assert_eq!( + field["candidates"], + json!([{"id": "user:serve", "name": "serve"}]) + ); + let serve = call( + "runConfig.editorForm", + json!({"root": root, "configurationId": "user:serve"}), + ); + assert_eq!(serve["values"]["beforeLaunch"], json!(["user:prepare"])); + + // prepare -> serve -> prepare would never start. + let mut values = form["values"].as_object().unwrap().clone(); + values.insert("beforeLaunch".into(), json!(["user:serve"])); + let cycle = call( + "runConfig.saveConfiguration", + json!({"root": root, "provider": "process.executable", "configurationId": "user:prepare", "values": values}), + ); + assert_eq!(cycle["status"], "invalid", "{cycle}"); + assert_eq!( + cycle["errors"], + json!([{"field": "beforeLaunch", "code": "conflict"}]) + ); + + // A new run may start an existing one first; the list is saved in its entry. + let created = call( + "runConfig.saveConfiguration", + json!({"root": root, "provider": "process.executable", "values": { + "name": "deploy", "program": "echo", "beforeLaunch": ["user:serve"] + }}), + ); + assert_eq!(created["status"], "saved", "{created}"); + apply_run_changes(&root, &created); + let deploy = call( + "runConfig.beforeLaunch", + json!({"root": root, "configurationId": "user:deploy"}), + ); + assert_eq!(step_ids(&deploy), ["user:prepare", "user:serve"]); +} + +fn serde_yaml_value(text: &str) -> Value { + serde_yaml_ng::from_str(text).expect("run documents are YAML") +} diff --git a/rust/crates/core/src/tests/mod.rs b/rust/crates/core/src/tests/mod.rs index a0037b35..52455479 100644 --- a/rust/crates/core/src/tests/mod.rs +++ b/rust/crates/core/src/tests/mod.rs @@ -1,3 +1,4 @@ +mod before_launch_steps; mod build_configuration; mod build_model_tree; mod build_project_options; diff --git a/rust/crates/core/src/tests/run_configuration.rs b/rust/crates/core/src/tests/run_configuration.rs index c0b082d8..429fdc87 100644 --- a/rust/crates/core/src/tests/run_configuration.rs +++ b/rust/crates/core/src/tests/run_configuration.rs @@ -2053,7 +2053,8 @@ fn powershell_and_program_editors_store_their_own_choices() { "program", "programArguments", "workingDirectory", - "environment" + "environment", + "beforeLaunch" ] ); let save_program = |program: &str| { diff --git a/rust/crates/execution/src/configuration.rs b/rust/crates/execution/src/configuration.rs index 571f43e9..2581480a 100644 --- a/rust/crates/execution/src/configuration.rs +++ b/rust/crates/execution/src/configuration.rs @@ -16,6 +16,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::fs; use std::path::{Path, PathBuf}; +mod before_launch; mod document; mod editing; mod form; @@ -30,6 +31,7 @@ mod resolve; mod storage; mod validation; +pub use before_launch::{before_launch, BeforeLaunchRequest, BeforeLaunchStep}; pub use document::*; pub use editing::*; pub use form::{ diff --git a/rust/crates/execution/src/configuration/before_launch.rs b/rust/crates/execution/src/configuration/before_launch.rs new file mode 100644 index 00000000..2f1257f9 --- /dev/null +++ b/rust/crates/execution/src/configuration/before_launch.rs @@ -0,0 +1,359 @@ +//! Steps run before a configuration starts (IDEA's "Before launch"). +//! +//! A configuration may name, in order, built-in process runs to start first: +//! a shell script that compiles a module, a program that generates sources. +//! Each step must exit with 0 before the next one, and before the +//! configuration itself, starts. A step reuses everything a process run +//! already has (interpreter, arguments, working directory, environment and +//! launch plan), so a step is a reference to such a run, not a second command +//! format. A referenced run that names steps of its own runs them first, as +//! starting it on its own would. +//! +//! Core checks the references, expands them into one ordered list, and says +//! whether the list needs the user's confirmation: steps a project file names +//! run code from the repository the user did not choose on this machine, so +//! the host asks before running a list it has not seen. The host runs each +//! step through `runConfig.createLaunchPlan`. + +use super::process::{self, ProcessOptions}; +use super::*; +use sha2::{Digest, Sha256}; + +/// Most steps one configuration names. +pub(crate) const MAXIMUM_STEPS: usize = 16; +/// Most steps one start runs once referenced runs are expanded. +const MAXIMUM_EXPANDED_STEPS: usize = 32; +/// Longest configuration ID a step names. +const MAXIMUM_ID_BYTES: usize = 256; + +/// One step of `beforeLaunch`: the run configuration to start first. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct BeforeLaunchStep { + /// ID of a built-in process run of the same project. + pub configuration: String, +} + +/// Checks the shape of a configuration's own steps: their number, and IDs +/// that are not empty, not too long and not the configuration itself. Whether +/// a step names a runnable process run is checked when it starts, so a +/// removed step target never hides the configuration from the list. +pub(crate) fn validate_shape(configuration: &RunConfiguration) -> Result<(), CoreError> { + let steps = &configuration.before_launch; + if steps.len() > MAXIMUM_STEPS { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "A run configuration names at most 16 steps before launch", + )); + } + for step in steps { + let id = step.configuration.as_str(); + if id.trim().is_empty() || id.len() > MAXIMUM_ID_BYTES || id == configuration.id { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "A step before launch names another run configuration", + ) + .with_details(id.to_string())); + } + } + Ok(()) +} + +/// Why a list of steps cannot run, for the field or the step it names. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct StepRefusal { + /// `notFound`, `notAllowed`, `unavailable`, `cycle` or `tooLong`. + pub(crate) code: &'static str, + /// The configuration the refusal is about. + pub(crate) configuration: String, +} + +/// The resolved configurations by ID. +pub(crate) struct Resolved { + by_id: BTreeMap, +} + +impl Resolved { + pub(crate) fn read(root: &Path, layers: &Layers) -> Result { + let resolved = resolve_layers(root, layers, None)?; + let configurations: Vec = + serde_json::from_value(resolved["configurations"].clone()).map_err(|error| { + CoreError::new(ErrorCode::ParseFailed, "Invalid resolved run configuration") + .with_details(error.to_string()) + })?; + Ok(Self { + by_id: configurations + .into_iter() + .map(|configuration| (configuration.id.clone(), configuration)) + .collect(), + }) + } + + /// The configurations a step of `owner` may name: every runnable built-in + /// process run but `owner`, in name order. + pub(crate) fn candidates(&self, owner: Option<&str>) -> Vec { + let mut candidates = self + .by_id + .values() + .filter(|configuration| { + Some(configuration.id.as_str()) != owner + && process::is_process_provider(&configuration.provider) + && configuration.availability.is_none() + }) + .map(|configuration| json!({ "id": configuration.id, "name": configuration.name })) + .collect::>(); + candidates.sort_by(|left, right| { + (left["name"].as_str(), left["id"].as_str()) + .cmp(&(right["name"].as_str(), right["id"].as_str())) + }); + candidates + } + + /// Expands `steps`, the steps `owner` would have, into the runs they + /// start, nested steps first. `owner` may be a configuration being + /// created, which nothing names yet. + pub(crate) fn expand( + &self, + owner: &str, + steps: &[BeforeLaunchStep], + ) -> Result { + let mut expansion = Expansion::default(); + let mut stack = vec![owner.to_string()]; + self.expand_into(steps, &mut stack, &mut expansion)?; + expansion.owners.insert(0, owner.to_string()); + Ok(expansion) + } + + fn expand_into( + &self, + steps: &[BeforeLaunchStep], + stack: &mut Vec, + expansion: &mut Expansion, + ) -> Result<(), StepRefusal> { + if steps.len() > MAXIMUM_STEPS { + return Err(StepRefusal { + code: "tooLong", + configuration: stack.last().cloned().unwrap_or_default(), + }); + } + for step in steps { + let id = &step.configuration; + let refuse = |code| StepRefusal { + code, + configuration: id.clone(), + }; + if stack.contains(id) { + return Err(refuse("cycle")); + } + let target = self.by_id.get(id).ok_or_else(|| refuse("notFound"))?; + if !process::is_process_provider(&target.provider) { + return Err(refuse("notAllowed")); + } + if target.availability.is_some() { + return Err(refuse("unavailable")); + } + if !target.before_launch.is_empty() { + stack.push(id.clone()); + expansion.owners.push(id.clone()); + self.expand_into(&target.before_launch, stack, expansion)?; + stack.pop(); + } + if expansion.steps.len() >= MAXIMUM_EXPANDED_STEPS { + return Err(refuse("tooLong")); + } + expansion.steps.push(target.clone()); + } + Ok(()) + } +} + +/// Steps expanded for one start. +#[derive(Default)] +pub(crate) struct Expansion { + /// The runs to start, in order. + pub(crate) steps: Vec, + /// The configurations whose step lists were read: the one that starts, + /// then each referenced run that names steps of its own. + pub(crate) owners: Vec, +} + +/// A step that refused to expand, in the shape the host shows. +fn refusal_value(refusal: &StepRefusal) -> Value { + json!({ "code": refusal.code, "configurationId": refusal.configuration }) +} + +/// The steps a list of configuration IDs names, read from an editor. +pub(crate) fn steps_of(ids: &[String]) -> Vec { + ids.iter() + .map(|id| BeforeLaunchStep { + configuration: id.trim().to_string(), + }) + .collect() +} + +/// The layer a configuration's own step list was read from: the local layer +/// when it names `beforeLaunch` there, else the project layer. +fn list_from_project(layers: &Layers, id: &str) -> bool { + let names_steps = |document: &Value| { + document["configurations"] + .as_array() + .into_iter() + .flatten() + .any(|item| item["id"] == id && item.get("beforeLaunch").is_some()) + }; + if names_steps(&layers.local.document) { + return false; + } + names_steps(&layers.project.document) +} + +/// A one-line description of what a process run starts, for the +/// confirmation that lists the steps. +fn summary(configuration: &RunConfiguration) -> String { + let options = ProcessOptions::of(configuration).unwrap_or_default(); + let mut words = Vec::new(); + if let Some(program) = options.program() { + words.push(program.to_string()); + } else if let Some(script) = options.script() { + if let Some(interpreter) = options.interpreter() { + words.push(interpreter.to_string()); + } + words.push(script.to_string()); + } else if let Some(text) = options.text() { + let first = text + .lines() + .find(|line| !line.trim().is_empty()) + .unwrap_or(""); + let more = text.lines().filter(|line| !line.trim().is_empty()).count() > 1; + words.push(if more { + format!("{} …", first.trim()) + } else { + first.trim().to_string() + }); + } + if !configuration.args.is_empty() { + words.push( + crate::format_argument_text(crate::ArgumentTextRequest { + argument_lists: vec![configuration.args.clone()], + }) + .remove(0), + ); + } + words.join(" ") +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +/// Request for the steps a configuration runs before it starts. +pub struct BeforeLaunchRequest { + /// Canonical workspace root. + pub root: String, + /// The configuration that starts. + pub configuration_id: String, + /// Host-owned replacement for the machine-local layer. + #[serde(default)] + pub local_document: Option, +} + +/// `runConfig.beforeLaunch`: the runs to start, in order, before +/// configuration `configurationId` starts. +/// +/// Replies `{status: "ok", steps, confirmation}` with each step's +/// `{configurationId, name, summary}` and, when a project file names any of +/// the step lists, `confirmation: {fingerprint}`. The fingerprint covers the +/// lists and the runs they start; the host asks once per fingerprint before +/// running them. A list that cannot run replies `{status: "rejected", refusal: +/// {code, configurationId}}` with `notFound`, `notAllowed` (not a built-in +/// process run), `unavailable`, `cycle` or `tooLong`. +pub fn before_launch(request: BeforeLaunchRequest) -> Result { + let root = existing_root(&request.root)?; + let layers = read_layers(&root, None, request.local_document)?; + let resolved = Resolved::read(&root, &layers)?; + let configuration = resolved + .by_id + .get(&request.configuration_id) + .ok_or_else(|| { + CoreError::new(ErrorCode::InvalidRequest, "Run configuration was not found") + })?; + let expansion = match resolved.expand(&configuration.id, &configuration.before_launch) { + Ok(expansion) => expansion, + Err(refusal) => { + return Ok(json!({ "status": "rejected", "refusal": refusal_value(&refusal) })) + } + }; + let steps = expansion + .steps + .iter() + .map(|step| { + json!({ "configurationId": step.id, "name": step.name, "summary": summary(step) }) + }) + .collect::>(); + let from_project = expansion + .owners + .iter() + .any(|owner| list_from_project(&layers, owner)); + let confirmation = (from_project && !steps.is_empty()) + .then(|| json!({ "fingerprint": fingerprint(&resolved, &expansion) })); + Ok(json!({ "status": "ok", "steps": steps, "confirmation": confirmation })) +} + +/// Identity of what the steps start: each list and each run's definition. +/// Changing a list or a run the steps start asks the user again. +fn fingerprint(resolved: &Resolved, expansion: &Expansion) -> String { + let lists = expansion + .owners + .iter() + .map(|owner| { + let steps = resolved + .by_id + .get(owner) + .map(|configuration| configuration.before_launch.clone()) + .unwrap_or_default(); + json!({ "owner": owner, "steps": steps }) + }) + .collect::>(); + let runs = expansion + .steps + .iter() + .map(|step| { + json!({ + "id": step.id, + "provider": step.provider, + "args": step.args, + "cwd": step.cwd, + "env": step.env, + "process": step.extensions.get("process"), + }) + }) + .collect::>(); + let bytes = serde_json::to_vec(&json!({ "lists": lists, "runs": runs })) + .expect("fingerprint input encodes"); + format!("{:x}", Sha256::digest(bytes)) +} + +/// Checks the steps an editor names for configuration `owner` against the +/// saved configurations; the code of the first that is wrong. +pub(crate) fn check_edit( + root: &Path, + layers: &Layers, + owner: &str, + ids: &[String], +) -> Result, CoreError> { + if ids.len() > MAXIMUM_STEPS { + return Ok(Some("tooLong")); + } + if ids + .iter() + .any(|id| id.trim().is_empty() || id.trim() == owner) + { + return Ok(Some("notAllowed")); + } + let resolved = Resolved::read(root, layers)?; + Ok(resolved + .expand(owner, &steps_of(ids)) + .err() + .map(|refusal| match refusal.code { + "cycle" => "conflict", + code => code, + })) +} diff --git a/rust/crates/execution/src/configuration/document.rs b/rust/crates/execution/src/configuration/document.rs index 3fa10df6..a4b0de94 100644 --- a/rust/crates/execution/src/configuration/document.rs +++ b/rust/crates/execution/src/configuration/document.rs @@ -197,6 +197,11 @@ pub struct RunConfiguration { /// Provider-specific payload keyed by namespace, such as `build`. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub extensions: BTreeMap, + /// Built-in process runs started in order before this one, each of which + /// must exit with 0 first (`runConfig.beforeLaunch`). A layer replaces the + /// whole list, so an empty list clears the steps of a lower layer. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub before_launch: Vec, /// Hidden from the resolved list; set by a user or when the working directory is missing. #[serde(default)] pub disabled: bool, diff --git a/rust/crates/execution/src/configuration/editing.rs b/rust/crates/execution/src/configuration/editing.rs index 7881d434..fb045f35 100644 --- a/rust/crates/execution/src/configuration/editing.rs +++ b/rust/crates/execution/src/configuration/editing.rs @@ -193,6 +193,29 @@ fn update_configuration_options( request.working_directory.trim(), )?) }; + if let Some(ids) = &request.before_launch { + if let Some(code) = + super::before_launch::check_edit(root, layers, &request.configuration_id, ids)? + { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "A step before launch cannot run", + ) + .with_details(format!("beforeLaunch: {code}"))); + } + } + // An empty local list must still hide a list the project names. + let project_names_steps = layers.project.document["configurations"] + .as_array() + .into_iter() + .flatten() + .any(|item| { + item["id"] == request.configuration_id + && item["beforeLaunch"] + .as_array() + .is_some_and(|steps| !steps.is_empty()) + }); + let local_layer = request.scope == "local"; let configurations = document["configurations"] .as_array_mut() .ok_or_else(|| CoreError::new(ErrorCode::ParseFailed, "configurations must be an array"))?; @@ -204,6 +227,13 @@ fn update_configuration_options( patch["cwd"] = json!(working_directory); } patch["args"] = json!(split_arguments(&request.arguments)); + let mut drop_steps = false; + match request.before_launch.as_deref() { + None => {} + Some([]) if local_layer && project_names_steps => patch["beforeLaunch"] = json!([]), + Some([]) => drop_steps = true, + Some(ids) => patch["beforeLaunch"] = json!(super::before_launch::steps_of(ids)), + } if provider == "build.provider" { if let Some(options) = &request.provider_run_options { patch["extensions"] = json!({"build-run":options}); @@ -222,6 +252,9 @@ fn update_configuration_options( if working_directory.is_none() { target.remove("cwd"); } + if drop_steps { + target.remove("beforeLaunch"); + } for (key, value) in patch.as_object_mut().expect("patch is an object") { if key == "extensions" { merge_extensions(target, value)?; diff --git a/rust/crates/execution/src/configuration/form.rs b/rust/crates/execution/src/configuration/form.rs index 74a4c8af..7d1bf171 100644 --- a/rust/crates/execution/src/configuration/form.rs +++ b/rust/crates/execution/src/configuration/form.rs @@ -7,6 +7,7 @@ //! know, and sends back value keys it does not know unchanged, so a later //! Core can add fields without a host change. +use super::before_launch::{check_edit, steps_of, Resolved}; use super::process::{self, FieldError, Kind, ProcessOptions}; use super::*; @@ -50,9 +51,9 @@ pub struct EditorFormRequest { /// The fields, values and automatic values of a process 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() { Some(id) => { - let layers = read_layers(&root, None, None)?; let saved = SavedEntry::find(&layers, id)?; let kind = saved.kind()?; if request @@ -74,12 +75,14 @@ pub fn editor_form(request: EditorFormRequest) -> Result { }; 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()); Ok(json!({ "formVersion": FORM_VERSION, "provider": kind.provider(), "configurationId": request.configuration_id, "values": values, - "fields": fields(kind, &root, &draft), + "fields": fields(kind, &root, &draft, candidates), })) } @@ -126,14 +129,17 @@ pub fn save_configuration(request: SaveConfigurationRequest) -> Result None, }; let draft = Draft::read(kind, &request.values)?; - let (stored, errors) = draft.store(&root); - if !errors.is_empty() { - return Ok(json!({ "status": "invalid", "errors": errors })); - } + let (stored, mut errors) = draft.store(&root); 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)? { + errors.push(FieldError::new("beforeLaunch", code)); + } + if !errors.is_empty() { + return Ok(json!({ "status": "invalid", "errors": errors })); + } let mut entry = saved .as_ref() .map(|saved| saved.merged.clone()) @@ -166,6 +172,11 @@ pub fn save_configuration(request: SaveConfigurationRequest) -> Result>()), ); + values.insert( + "beforeLaunch".into(), + json!(configuration + .before_launch + .iter() + .map(|step| step.configuration.clone()) + .collect::>()), + ); if kind.runs_script() { let text = options.script().is_none() && options.text.is_some(); values.insert("source".into(), json!(if text { "text" } else { "file" })); @@ -419,6 +438,7 @@ fn default_values(kind: Kind) -> serde_json::Map { values.insert(kind.arguments_field().into(), json!("")); values.insert("workingDirectory".into(), json!(".")); values.insert("environment".into(), json!([])); + values.insert("beforeLaunch".into(), json!([])); if kind.runs_script() { values.insert("interpreter".into(), json!("")); values.insert("interpreterArguments".into(), json!("")); @@ -437,7 +457,7 @@ fn argument_text(arguments: &[String]) -> String { } /// The fields of `kind`'s editor, with automatic values for `draft`. -fn fields(kind: Kind, root: &Path, draft: &Draft) -> Vec { +fn fields(kind: Kind, root: &Path, draft: &Draft, candidates: Vec) -> Vec { let platform = Platform::HOST; let options = draft.options(); let mut fields = vec![ @@ -496,6 +516,7 @@ fn fields(kind: Kind, root: &Path, draft: &Draft) -> Vec { field("environment", "environment"), ]); } + fields.push(field("beforeLaunch", "beforeLaunch").candidates(candidates)); fields.into_iter().map(|field| field.0).collect() } @@ -536,6 +557,12 @@ impl Field { self } + /// The run configurations a `beforeLaunch` field may name, `{id, name}`. + fn candidates(mut self, candidates: Vec) -> Self { + self.0["candidates"] = json!(candidates); + self + } + /// A short explanation key, such as `windowsOnly`. fn note(mut self, note: &str) -> Self { self.0["note"] = json!(note); @@ -564,6 +591,8 @@ struct Draft { 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. @@ -619,6 +648,11 @@ impl Draft { 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()) + .map_err(|_| invalid_value("beforeLaunch"))?, + }, }) } @@ -741,6 +775,7 @@ impl Draft { "process".to_string(), serde_json::to_value(&stored.options).expect("process options encode"), )]), + before_launch: Vec::new(), disabled: false, source: None, plugin: None, diff --git a/rust/crates/execution/src/configuration/requests.rs b/rust/crates/execution/src/configuration/requests.rs index 012d4e5b..8d642a4f 100644 --- a/rust/crates/execution/src/configuration/requests.rs +++ b/rust/crates/execution/src/configuration/requests.rs @@ -134,6 +134,11 @@ pub struct UpdateOptionsRequest { /// into the local layer instead of patching one configuration. #[serde(default)] pub toolchain: Option, + /// IDs of the built-in process runs to start first, in order. Omission + /// keeps the saved steps; an empty list removes them from this layer and, + /// in the local layer, also hides the project's. + #[serde(default)] + pub before_launch: Option>, /// Host-owned local layer used to resolve the configuration first. A /// local edit is refused while it is set: only files can be changed. #[serde(default)] diff --git a/rust/crates/execution/src/configuration/validation.rs b/rust/crates/execution/src/configuration/validation.rs index 00a16689..f05b9589 100644 --- a/rust/crates/execution/src/configuration/validation.rs +++ b/rust/crates/execution/src/configuration/validation.rs @@ -62,6 +62,7 @@ pub(crate) fn validate_configuration(configuration: &RunConfiguration) -> Result "Run configuration id and name are required", )); } + super::before_launch::validate_shape(configuration)?; if !valid_provider(&configuration.provider) { return Err(CoreError::new( ErrorCode::NotSupported, diff --git a/rust/crates/execution/src/provider_runs.rs b/rust/crates/execution/src/provider_runs.rs index 654a8711..b862645e 100644 --- a/rust/crates/execution/src/provider_runs.rs +++ b/rust/crates/execution/src/provider_runs.rs @@ -73,6 +73,7 @@ pub(super) fn configurations(runs: &[ProviderRunConfiguration]) -> Vec