diff --git a/rust/contracts/run-configuration-v2.schema.json b/rust/contracts/run-configuration-v2.schema.json index 779fd6f9..9eca040d 100644 --- a/rust/contracts/run-configuration-v2.schema.json +++ b/rust/contracts/run-configuration-v2.schema.json @@ -21,6 +21,18 @@ }, "additionalProperties": true }, + "arrangement": { + "type": "object", + "description": "Machine-local order of the run configuration list. Stored only in the local layer; omitted means sorted by name.", + "properties": { + "sortAlphabetically": { "type": "boolean" }, + "order": { + "type": "array", "maxItems": 4096, "uniqueItems": true, + "items": { "type": "string", "minLength": 1, "maxLength": 4096 } + } + }, + "additionalProperties": false + }, "configurations": { "type": "array", "items": { "$ref": "#/$defs/configuration" } @@ -181,6 +193,11 @@ "properties": { "id": { "type": "string", "minLength": 1 }, "name": { "type": "string", "minLength": 1 }, + "folder": { + "type": "string", "minLength": 1, "maxLength": 256, + "pattern": "^[^\\s\\p{Cc}](?:[^\\p{Cc}]*[^\\s\\p{Cc}])?$", + "description": "Folder the configuration is listed in within its kind; display only." + }, "provider": { "type": "string", "pattern": "^[a-z][a-z0-9-]*\\.[a-z][a-z0-9-]*$" diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index d624e2e2..b5a886e7 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -717,6 +717,8 @@ 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.copyConfiguration` | Return the file changes that save a copy of any configuration under a new name | +| `runConfig.arrange` | Return the file changes that move configurations between folders and save the list order | | `runConfig.beforeLaunch` | Expand the built-in process runs a configuration starts first, and say whether the user must confirm them | | `runConfig.createLaunchPlan` | Project one effective configuration into a platform-neutral Run or Debug plan | | `runConfig.providerLaunchInputs` | Resolve user choices for a provider-owned launch | @@ -3965,6 +3967,47 @@ 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. +`runConfig.copyConfiguration` accepts `{root, configurationId, name, plugins?}` +and replies `{id, changes}`: the copy's new `user:` ID and the changes that +save it. The copy is the resolved configuration with every saved choice, its +folder included, under the new ID and `name` (trimmed, 1 to 256 bytes). It is +saved in the project layer when the original is a user configuration defined +there without a local override, and in the local layer otherwise, so local +choices never reach the team. A saved `build.provider` run supersedes the +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. + +#### Folders and order + +A configuration may name a `folder`, the folder it is listed in within its +kind (IntelliJ IDEA's `folderName`): 1 to 256 bytes, without surrounding +whitespace or control characters. A folder is display metadata saved in the +configuration, so a project configuration carries its folder to the team, and +a local entry `{id, folder}` overrides it like any other key; launching +ignores it. An invalid folder makes the configuration unavailable +(`invalidConfiguration`). + +The order of the list and whether it is sorted by name are this machine's +choice, saved only in the local Lithe document under `arrangement: +{sortAlphabetically?: boolean, order?: string[]}`. The default sorts by name, +ignoring case. `runConfig.resolve` returns the configurations in the order the +list shows them and adds `sortAlphabetically`: by name when sorted, otherwise in +the saved `order`, with the configurations it does not name after it by name; +IDs that no longer resolve are skipped. A malformed `arrangement` is ignored +and reported as the `invalidArrangement` diagnostic. + +`runConfig.arrange` accepts `{root, folders?, order?, sortAlphabetically?, +plugins?}` and returns `{changes}`. `folders` maps configuration IDs to the +folder each moves to, or `null` to take it out of its folder; each ID must +resolve. The folder is written to the layer that defines the configuration: +the project layer for a configuration saved there, otherwise the local layer, +where a generated configuration gets a sparse `{id, folder}` entry, and the +other layer's folder for it is removed. `order` replaces the whole saved order +(at most 4,096 IDs, repeats dropped) and `sortAlphabetically` the sort choice; +an omitted field keeps the saved value, and saving the defaults removes +`arrangement`. Nothing to change returns no changes. + #### Steps before launch A configuration of any provider may name `beforeLaunch`, an ordered list of at diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 44b9d8a6..82764638 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -744,6 +744,10 @@ pub enum RunConfigCommand { SaveConfiguration, /// Removes a user-authored run configuration (`runConfig.deleteConfiguration`). DeleteConfiguration, + /// Saves a copy of a configuration under a new name (`runConfig.copyConfiguration`). + CopyConfiguration, + /// Moves configurations between folders and saves the list order (`runConfig.arrange`). + Arrange, /// Expands the steps run before a configuration starts (`runConfig.beforeLaunch`). BeforeLaunch, /// Produces the process plan for one configuration (`runConfig.createLaunchPlan`). @@ -1440,6 +1444,10 @@ impl CoreCommand { "runConfig.deleteConfiguration" => { Some(Self::RunConfig(RunConfigCommand::DeleteConfiguration)) } + "runConfig.copyConfiguration" => { + Some(Self::RunConfig(RunConfigCommand::CopyConfiguration)) + } + "runConfig.arrange" => Some(Self::RunConfig(RunConfigCommand::Arrange)), "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 3ed33b21..59b933d9 100644 --- a/rust/crates/core/src/runtime/dispatcher/run_config.rs +++ b/rust/crates/core/src/runtime/dispatcher/run_config.rs @@ -247,6 +247,36 @@ pub(super) fn dispatch( Err(error) => CoreResponse::failure(id, error), } } + RunConfigCommand::CopyConfiguration => { + match serde_json::from_value::(payload) + .map_err(|error| { + CoreError::new( + ErrorCode::InvalidRequest, + "Invalid run configuration copy request", + ) + .with_details(error.to_string()) + }) + .and_then(crate::execution::copy_configuration) + { + Ok(data) => CoreResponse::success(id, data), + Err(error) => CoreResponse::failure(id, error), + } + } + RunConfigCommand::Arrange => { + match serde_json::from_value::(payload) + .map_err(|error| { + CoreError::new( + ErrorCode::InvalidRequest, + "Invalid run configuration arrange request", + ) + .with_details(error.to_string()) + }) + .and_then(crate::execution::arrange) + { + Ok(data) => CoreResponse::success(id, data), + Err(error) => CoreResponse::failure(id, error), + } + } RunConfigCommand::ProviderLaunchInputs => { match serde_json::from_value::(payload) .map_err(|error| { diff --git a/rust/crates/core/src/tests/mod.rs b/rust/crates/core/src/tests/mod.rs index 52455479..62b9cf2f 100644 --- a/rust/crates/core/src/tests/mod.rs +++ b/rust/crates/core/src/tests/mod.rs @@ -61,6 +61,7 @@ mod remote_sessions; mod request_events; mod row_selection; mod run_configuration; +mod run_configuration_arrangement; pub(crate) mod support; mod toolchain_definitions; mod toolchain_pins; diff --git a/rust/crates/core/src/tests/run_configuration_arrangement.rs b/rust/crates/core/src/tests/run_configuration_arrangement.rs new file mode 100644 index 00000000..8a88a515 --- /dev/null +++ b/rust/crates/core/src/tests/run_configuration_arrangement.rs @@ -0,0 +1,301 @@ +//! Issue 1lck/Lithe-IDEA#2100: the run configuration list has folders, a +//! manual order and an alphabetical sort, and any configuration can be +//! copied. A folder is saved in the configuration, the order only locally. + +use super::support::{ + apply_run_changes, changed_run_document, changed_run_paths, temporary_root, write_run_document, + Cleanup, +}; +use crate::execute_json; +use serde_json::{json, Value}; +use std::fs; + +const PROJECT: &str = ".lithe/run/configurations.yaml"; +const LOCAL: &str = ".lithe/run/local.yaml"; + +fn reply(command: &str, payload: Value) -> Value { + serde_json::from_str(&execute_json( + &json!({ "id": command, "command": command, "payload": payload }).to_string(), + )) + .unwrap() +} + +fn call(command: &str, payload: Value) -> Value { + let reply = reply(command, payload); + assert_eq!(reply["ok"], true, "{command}: {reply}"); + reply["data"].clone() +} + +fn executable(id: &str, name: &str) -> Value { + json!({ + "id": id, "name": name, "provider": "process.executable", + "confidence": "declared", "extensions": {"process": {"program": "tool"}} + }) +} + +fn names(resolved: &Value) -> Vec { + resolved["configurations"] + .as_array() + .unwrap() + .iter() + .map(|item| item["name"].as_str().unwrap().to_string()) + .collect() +} + +fn entry<'a>(document: &'a Value, id: &str) -> &'a Value { + document["configurations"] + .as_array() + .unwrap() + .iter() + .find(|item| item["id"] == id) + .unwrap_or_else(|| panic!("{id} is not in {document}")) +} + +#[test] +fn folders_are_saved_in_the_defining_layer_and_the_order_only_locally() { + let root = temporary_root("run-arrangement"); + let _cleanup = Cleanup(root.clone()); + write_run_document( + &root, + PROJECT, + &json!({"version": 2, "configurations": [executable("user:serve", "serve")]}), + ); + write_run_document( + &root, + LOCAL, + &json!({"version": 2, "configurations": [ + executable("user:Build", "Build"), executable("user:check", "check") + ]}), + ); + // Sorted by name, ignoring case, before anything is arranged. + let resolved = call("runConfig.resolve", json!({"root": root})); + assert_eq!(names(&resolved), ["Build", "check", "serve"]); + assert_eq!(resolved["sortAlphabetically"], true); + + // A project configuration takes its folder to the team; a local one + // keeps it in the local layer. + let arranged = call( + "runConfig.arrange", + json!({"root": root, "folders": {"user:serve": "Servers", "user:check": "Checks"}}), + ); + assert_eq!(changed_run_paths(&arranged), [PROJECT, LOCAL]); + let project = changed_run_document(&arranged, PROJECT).unwrap(); + assert_eq!(entry(&project, "user:serve")["folder"], "Servers"); + let local = changed_run_document(&arranged, LOCAL).unwrap(); + assert_eq!(entry(&local, "user:check")["folder"], "Checks"); + assert!(local.get("arrangement").is_none()); + apply_run_changes(&root, &arranged); + + // A manual order is local only and takes effect once sorting is off. + let ordered = call( + "runConfig.arrange", + json!({"root": root, "order": ["user:serve", "gone", "user:check"], "sortAlphabetically": false}), + ); + assert_eq!(changed_run_paths(&ordered), [LOCAL]); + let local = changed_run_document(&ordered, LOCAL).unwrap(); + assert_eq!( + local["arrangement"], + json!({"sortAlphabetically": false, "order": ["user:serve", "gone", "user:check"]}) + ); + apply_run_changes(&root, &ordered); + let resolved = call("runConfig.resolve", json!({"root": root})); + // Configurations the order does not name follow it by name. + assert_eq!(names(&resolved), ["serve", "check", "Build"]); + assert_eq!(resolved["sortAlphabetically"], false); + let serve = entry(&resolved, "user:serve"); + assert_eq!(serve["folder"], "Servers"); + + // Sorting again keeps the saved order for later. + let sorted = call( + "runConfig.arrange", + json!({"root": root, "sortAlphabetically": true}), + ); + let local = changed_run_document(&sorted, LOCAL).unwrap(); + assert_eq!(local["arrangement"]["order"][0], "user:serve"); + apply_run_changes(&root, &sorted); + assert_eq!( + names(&call("runConfig.resolve", json!({"root": root}))), + ["Build", "check", "serve"] + ); + + // `null` takes a configuration out of its folder. + let out = call( + "runConfig.arrange", + json!({"root": root, "folders": {"user:serve": null}}), + ); + assert_eq!(changed_run_paths(&out), [PROJECT]); + let project = changed_run_document(&out, PROJECT).unwrap(); + assert!(entry(&project, "user:serve").get("folder").is_none()); + + // Nothing to change writes nothing. + let unchanged = call( + "runConfig.arrange", + json!({"root": root, "folders": {"user:check": "Checks"}}), + ); + assert_eq!(unchanged["changes"], json!([])); +} + +#[test] +fn a_local_folder_override_wins_and_a_bad_request_changes_nothing() { + let root = temporary_root("run-arrangement-override"); + let _cleanup = Cleanup(root.clone()); + let mut serve = executable("user:serve", "serve"); + serve["folder"] = json!("Team"); + write_run_document( + &root, + PROJECT, + &json!({"version": 2, "configurations": [serve]}), + ); + write_run_document( + &root, + LOCAL, + &json!({"version": 2, "configurations": [{"id": "user:serve", "folder": "Mine"}]}), + ); + let resolved = call("runConfig.resolve", json!({"root": root})); + assert_eq!(entry(&resolved, "user:serve")["folder"], "Mine"); + + // Moving it writes the defining project entry and drops the local + // override that would hide the choice. + let moved = call( + "runConfig.arrange", + json!({"root": root, "folders": {"user:serve": "Servers"}}), + ); + let project = changed_run_document(&moved, PROJECT).unwrap(); + assert_eq!(entry(&project, "user:serve")["folder"], "Servers"); + let local = changed_run_document(&moved, LOCAL).unwrap(); + assert_eq!(local["configurations"], json!([])); + + for (payload, message) in [ + ( + json!({"root": root, "folders": {"user:missing": "A"}}), + "Run configuration was not found", + ), + ( + json!({"root": root, "folders": {"user:serve": " padded"}}), + "Invalid run configuration folder", + ), + ( + json!({"root": root, "folders": {"user:serve": "a\nb"}}), + "Invalid run configuration folder", + ), + ( + json!({"root": root, "order": [""]}), + "Invalid run configuration order", + ), + ] { + let failed = reply("runConfig.arrange", payload); + assert_eq!(failed["ok"], false, "{failed}"); + assert_eq!(failed["error"]["message"], message, "{failed}"); + } + + // A hand-edited arrangement that cannot be read is reported and ignored. + write_run_document( + &root, + LOCAL, + &json!({"version": 2, "configurations": [], "arrangement": {"order": "user:serve"}}), + ); + let resolved = call("runConfig.resolve", json!({"root": root})); + assert_eq!(resolved["sortAlphabetically"], true); + assert!(resolved["diagnostics"] + .as_array() + .unwrap() + .iter() + .any(|diagnostic| diagnostic["code"] == "invalidArrangement")); + // So is a folder name no folder can have. + let mut bad = executable("user:bad", "bad"); + bad["folder"] = json!(""); + write_run_document( + &root, + LOCAL, + &json!({"version": 2, "configurations": [bad]}), + ); + let resolved = call("runConfig.resolve", json!({"root": root})); + assert_eq!( + entry(&resolved, "user:bad")["availability"]["code"], + "invalidConfiguration" + ); +} + +#[test] +fn copies_keep_every_choice_and_never_hide_the_original() { + let root = temporary_root("run-copy"); + let _cleanup = Cleanup(root.clone()); + fs::create_dir_all(root.join("app")).unwrap(); + let mut serve = executable("user:serve", "serve"); + serve["folder"] = json!("Servers"); + serve["args"] = json!(["--port", "8080"]); + write_run_document( + &root, + PROJECT, + &json!({"version": 2, "configurations": [serve]}), + ); + + // A project configuration is copied into the project layer, folder + // and arguments included. + let copied = call( + "runConfig.copyConfiguration", + json!({"root": root, "configurationId": "user:serve", "name": "serve (1)"}), + ); + assert_eq!(copied["id"], "user:serve-1"); + assert_eq!(changed_run_paths(&copied), [PROJECT]); + let project = changed_run_document(&copied, PROJECT).unwrap(); + let copy = entry(&project, "user:serve-1"); + assert_eq!(copy["name"], "serve (1)"); + assert_eq!(copy["folder"], "Servers"); + assert_eq!(copy["args"], json!(["--port", "8080"])); + assert!(copy.get("source").is_none()); + apply_run_changes(&root, &copied); + + // A generated build provider run stays listed next to its copy, which + // is saved in the plugin's local document. + let reference = json!({ + "pluginID": "dev.example.engine", "buildSystemID": "engine", "root": "app", + "run": "serve", "projectID": "opaque/project", "targetID": "opaque/target", + "execution": "service" + }); + call( + "runConfig.generate", + json!({"root": root, "providerRuns": [ + {"projectPath": "app", "name": "Engine", "reference": reference} + ]}), + ); + let resolved = call("runConfig.resolve", json!({"root": root})); + let generated = resolved["configurations"] + .as_array() + .unwrap() + .iter() + .find(|item| item["provider"] == "build.provider") + .unwrap()["id"] + .as_str() + .unwrap() + .to_string(); + let copied = call( + "runConfig.copyConfiguration", + json!({"root": root, "configurationId": generated, "name": "Engine (1)"}), + ); + let plugin = ".lithe/run/plugin/dev.example.engine.local.toml"; + assert_eq!(changed_run_paths(&copied), [plugin]); + apply_run_changes(&root, &copied); + let resolved = call("runConfig.resolve", json!({"root": root})); + assert_eq!( + names(&resolved), + ["Engine", "Engine (1)", "serve", "serve (1)"] + ); + let copy = entry(&resolved, copied["id"].as_str().unwrap()); + assert_eq!(copy["extensions"]["build"]["targetID"], "opaque/target"); + assert_eq!(entry(&resolved, &generated)["source"], "local"); + + let failed = reply( + "runConfig.copyConfiguration", + json!({"root": root, "configurationId": "user:missing", "name": "x"}), + ); + assert_eq!( + failed["error"]["message"], + "Run configuration was not found" + ); + let failed = reply( + "runConfig.copyConfiguration", + json!({"root": root, "configurationId": "user:serve", "name": " "}), + ); + assert_eq!(failed["error"]["message"], "Invalid run configuration name"); +} diff --git a/rust/crates/execution/src/configuration.rs b/rust/crates/execution/src/configuration.rs index 2581480a..cf9dc39b 100644 --- a/rust/crates/execution/src/configuration.rs +++ b/rust/crates/execution/src/configuration.rs @@ -16,7 +16,9 @@ use std::collections::{BTreeMap, BTreeSet}; use std::fs; use std::path::{Path, PathBuf}; +mod arrangement; mod before_launch; +mod copying; mod document; mod editing; mod form; @@ -31,7 +33,10 @@ mod resolve; mod storage; mod validation; +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 document::*; pub use editing::*; pub use form::{ diff --git a/rust/crates/execution/src/configuration/arrangement.rs b/rust/crates/execution/src/configuration/arrangement.rs new file mode 100644 index 00000000..59119160 --- /dev/null +++ b/rust/crates/execution/src/configuration/arrangement.rs @@ -0,0 +1,298 @@ +//! How the run configuration list is arranged: folders and order. +//! +//! A folder is display metadata saved in the configuration itself, the way +//! IntelliJ IDEA saves `folderName`, so a configuration in the project layer +//! carries its folder to the team. The order and whether the list is sorted +//! by name are this machine's choice and live only in the local Lithe +//! document, under `arrangement`: +//! +//! ```yaml +//! arrangement: +//! sortAlphabetically: false +//! order: [user:build, user:serve] +//! ``` +//! +//! Resolution returns the configurations in this order, so every list a host +//! draws agrees. Launching ignores both. + +use super::*; + +/// Longest folder name, in bytes. +const MAXIMUM_FOLDER_BYTES: usize = 256; + +/// Most configuration ids one saved order holds. +const MAXIMUM_ORDER_LENGTH: usize = 4096; + +/// Longest configuration id a saved order may name, in bytes. +const MAXIMUM_ID_BYTES: usize = 4096; + +/// Whether `folder` can name a folder: not empty, without surrounding +/// whitespace or control characters, and at most 256 bytes. +pub(crate) fn valid_folder(folder: &str) -> bool { + !folder.is_empty() + && folder.len() <= MAXIMUM_FOLDER_BYTES + && folder.trim() == folder + && !folder.chars().any(char::is_control) +} + +/// The arrangement the local layer saves, with its defaults: sorted by name +/// and no manual order. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct Arrangement { + /// List by name instead of the manual order. + pub(crate) sort_alphabetically: bool, + /// Configuration ids in the order the user placed them. Ids that no + /// longer resolve are skipped; configurations it does not name follow. + pub(crate) order: Vec, +} + +impl Default for Arrangement { + fn default() -> Self { + Self { + sort_alphabetically: true, + order: Vec::new(), + } + } +} + +impl Arrangement { + /// The arrangement of `local`, the local layer's document. A malformed + /// value is reported and the defaults are used, so a hand-edited file + /// never hides the list. + pub(crate) fn read(local: &Value, diagnostics: &mut Vec) -> Self { + let Some(value) = local.get("arrangement").filter(|value| !value.is_null()) else { + return Self::default(); + }; + match Self::parse(value) { + Some(arrangement) => arrangement, + None => { + diagnostics.push(json!({ + "code": "invalidArrangement", + "path": ".lithe/run/local.yaml", + "message": "The saved run configuration order is invalid and is ignored" + })); + Self::default() + } + } + } + + fn parse(value: &Value) -> Option { + let object = value.as_object()?; + let mut arrangement = Self::default(); + if let Some(sort) = object.get("sortAlphabetically") { + arrangement.sort_alphabetically = sort.as_bool()?; + } + if let Some(order) = object.get("order") { + let ids = order + .as_array()? + .iter() + .map(|id| id.as_str().map(str::to_string)) + .collect::>>()?; + arrangement.order = valid_order(ids).ok()?; + } + Some(arrangement) + } + + /// Orders `configurations` as the list shows them: by name, ignoring + /// case, when sorted; otherwise as the saved order places them, with the + /// configurations it does not name after it by name. + pub(crate) fn apply(&self, configurations: &mut [RunConfiguration]) { + let positions = if self.sort_alphabetically { + BTreeMap::new() + } else { + self.order + .iter() + .enumerate() + .map(|(index, id)| (id.as_str(), index)) + .collect() + }; + configurations.sort_by_cached_key(|configuration| { + ( + positions + .get(configuration.id.as_str()) + .copied() + .unwrap_or(usize::MAX), + configuration.name.to_lowercase(), + configuration.name.clone(), + configuration.id.clone(), + ) + }); + } + + /// Saves the arrangement in `local`, the local layer's document; the + /// defaults remove the key so an untouched project writes nothing. + fn write(&self, local: &mut Value) { + let object = local.as_object_mut().expect("validated layers are objects"); + if *self == Self::default() { + object.remove("arrangement"); + return; + } + let mut saved = serde_json::Map::new(); + saved.insert( + "sortAlphabetically".to_string(), + json!(self.sort_alphabetically), + ); + if !self.order.is_empty() { + saved.insert("order".to_string(), json!(self.order)); + } + object.insert("arrangement".to_string(), Value::Object(saved)); + } +} + +/// `ids` without repeats, or an error when it is too long or names an +/// impossible id. +fn valid_order(ids: Vec) -> Result, CoreError> { + if ids.len() > MAXIMUM_ORDER_LENGTH + || ids + .iter() + .any(|id| id.is_empty() || id.len() > MAXIMUM_ID_BYTES || id.contains('\0')) + { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Invalid run configuration order", + )); + } + let mut seen = BTreeSet::new(); + Ok(ids + .into_iter() + .filter(|id| seen.insert(id.clone())) + .collect()) +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +/// Request to move configurations between folders and to save the order. +pub struct ArrangeRequest { + /// Canonical workspace root. + pub root: String, + /// The folder each listed configuration moves to; `null` takes it out of + /// its folder. Configurations not listed keep theirs. + #[serde(default)] + pub folders: BTreeMap>, + /// The whole manual order, replacing the saved one; omitted keeps it. + #[serde(default)] + pub order: Option>, + /// Whether the list is sorted by name; omitted keeps the saved choice. + #[serde(default)] + pub sort_alphabetically: Option, + /// The installed plugins, whose identity a written plugin document records. + #[serde(default)] + pub plugins: Option>, +} + +/// The changes that move configurations into folders and save the order. +/// +/// A folder is written to the layer that defines the configuration: the +/// project layer for a configuration saved there, otherwise the local +/// layer, where a generated configuration gets a sparse `{id, folder}` +/// override. The other layer's folder for it is removed, so the choice is +/// the one that shows. The order and the sort choice are written to the +/// local layer only. +pub fn arrange(request: ArrangeRequest) -> Result { + let root = existing_root(&request.root)?; + let layers = read_layers(&root, None, None)?; + let mut project = layers.project.document.clone(); + let mut local = layers.local.document.clone(); + if !request.folders.is_empty() { + let resolved = resolve_layers(&root, &layers, None)?; + let listed = resolved["configurations"] + .as_array() + .into_iter() + .flatten() + .filter_map(|item| item["id"].as_str()) + .collect::>(); + for (id, folder) in &request.folders { + if !listed.contains(id.as_str()) { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Run configuration was not found", + ) + .with_details(id)); + } + if folder + .as_deref() + .is_some_and(|folder| !valid_folder(folder)) + { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Invalid run configuration folder", + ) + .with_details(id)); + } + set_folder(&mut project, &mut local, id, folder.as_deref())?; + } + } + if request.order.is_some() || request.sort_alphabetically.is_some() { + let mut arrangement = Arrangement::read(&local, &mut Vec::new()); + if let Some(order) = request.order { + arrangement.order = valid_order(order)?; + } + if let Some(sort) = request.sort_alphabetically { + arrangement.sort_alphabetically = sort; + } + arrangement.write(&mut local); + } + let writing = write_context(&root, request.plugins.as_deref()); + let mut changes = layers.project.changes(&project, &writing.context())?; + changes.extend(layers.local.changes(&local, &writing.context())?); + Ok(json!({ "changes": changes })) +} + +/// Puts configuration `id` in `folder`, or out of every folder for `None`, +/// in the two saved layer documents. +fn set_folder( + project: &mut Value, + local: &mut Value, + id: &str, + folder: Option<&str>, +) -> Result<(), CoreError> { + let defined_in_project = entries(project)? + .iter() + .any(|item| item["id"] == id && item.get("provider").is_some()); + let (target, other) = if defined_in_project { + (project, local) + } else { + (local, project) + }; + let items = entries(other)?; + for item in items.iter_mut().filter(|item| item["id"] == id) { + if let Some(object) = item.as_object_mut() { + object.remove("folder"); + } + } + // An override left holding only its id changes nothing. + items.retain(|item| item["id"] != id || item.as_object().is_none_or(|object| object.len() > 1)); + let items = entries(target)?; + match items.iter_mut().find(|item| item["id"] == id) { + Some(item) => { + let object = item.as_object_mut().ok_or_else(|| { + CoreError::new( + ErrorCode::ParseFailed, + "Run configuration must be an object", + ) + })?; + match folder { + Some(folder) => { + object.insert("folder".to_string(), json!(folder)); + } + None => { + object.remove("folder"); + } + } + } + None => { + if let Some(folder) = folder { + items.push(json!({ "id": id, "folder": folder })); + items.sort_by(|left, right| left["id"].as_str().cmp(&right["id"].as_str())); + } + } + } + items.retain(|item| item["id"] != id || item.as_object().is_none_or(|object| object.len() > 1)); + Ok(()) +} + +fn entries(document: &mut Value) -> Result<&mut Vec, CoreError> { + document["configurations"] + .as_array_mut() + .ok_or_else(|| CoreError::new(ErrorCode::ParseFailed, "configurations must be an array")) +} diff --git a/rust/crates/execution/src/configuration/copying.rs b/rust/crates/execution/src/configuration/copying.rs new file mode 100644 index 00000000..3e2890fe --- /dev/null +++ b/rust/crates/execution/src/configuration/copying.rs @@ -0,0 +1,125 @@ +//! Copying a run configuration under a new name. + +use super::*; + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +/// Request to save a copy of a configuration as a user configuration. +pub struct CopyConfigurationRequest { + /// Canonical workspace root. + pub root: String, + /// The resolved configuration to copy, of any kind. + pub configuration_id: String, + /// Display name of the copy. + pub name: String, + /// The installed plugins, whose identity a written plugin document records. + #[serde(default)] + pub plugins: Option>, +} + +/// Replies `{id, changes}`: the copy's new `user:` id and the changes that +/// save it. +/// +/// The copy is the resolved configuration with every saved choice, its folder +/// included, under a new id and name. It is saved in the project layer when +/// the original is a user configuration defined there with no local +/// override, so local choices never reach the team, and in the local layer +/// otherwise. +/// +/// A saved build provider run supersedes the generated run with the same +/// target, so copying a generated one would hide the original. The original +/// is then also saved whole in the local layer under its own id, which keeps +/// both listed; it stops following later name changes of the build model. +pub fn copy_configuration(request: CopyConfigurationRequest) -> Result { + let root = existing_root(&request.root)?; + let name = request.name.trim(); + if name.is_empty() || name.len() > 256 || name.contains('\0') { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Invalid run configuration name", + )); + } + let layers = read_layers(&root, None, None)?; + let resolved = resolve_layers(&root, &layers, None)?; + let original = resolved["configurations"] + .as_array() + .into_iter() + .flatten() + .find(|item| item["id"] == request.configuration_id) + .cloned() + .ok_or_else(|| { + CoreError::new(ErrorCode::InvalidRequest, "Run configuration was not found") + })?; + let original = saved_form(original); + let id = unique_user_configuration_id(name, &existing_ids(&root, &layers)); + let mut copy = original.clone(); + copy["id"] = json!(id); + copy["name"] = json!(name); + let typed: RunConfiguration = serde_json::from_value(copy.clone()) + .map_err(|_| CoreError::new(ErrorCode::ParseFailed, "Invalid saved run configuration"))?; + validate_configuration(&typed)?; + let has_entry = |document: &Value, defining: bool| { + document["configurations"] + .as_array() + .into_iter() + .flatten() + .any(|item| { + item["id"] == request.configuration_id + && (!defining || item.get("provider").is_some()) + }) + }; + let user = request.configuration_id.starts_with("user:"); + let target = if user + && has_entry(&layers.project.document, true) + && !has_entry(&layers.local.document, false) + { + Scope::Project + } else { + Scope::Local + }; + let mut project = layers.project.document.clone(); + let mut local = layers.local.document.clone(); + if !user && typed.provider == "build.provider" { + replace_entry(&mut local, original)?; + } + match target { + Scope::Project => replace_entry(&mut project, copy)?, + Scope::Local => replace_entry(&mut local, copy)?, + } + let writing = write_context(&root, request.plugins.as_deref()); + let mut changes = layers.project.changes(&project, &writing.context())?; + changes.extend(layers.local.changes(&local, &writing.context())?); + Ok(json!({ "id": id, "changes": changes })) +} + +/// A resolved configuration as a layer saves it: without the values +/// resolution computes and without empty defaults. +fn saved_form(mut configuration: Value) -> Value { + if let Some(object) = configuration.as_object_mut() { + for key in ["source", "plugin", "availability", "disabled"] { + object.remove(key); + } + for key in ["args", "env", "toolchains", "members", "extensions"] { + let empty = match object.get(key) { + Some(Value::Array(items)) => items.is_empty(), + Some(Value::Object(entries)) => entries.is_empty(), + _ => false, + }; + if empty { + object.remove(key); + } + } + } + configuration +} + +/// Puts `entry` in `document` in place of any entry with its id, in id order. +fn replace_entry(document: &mut Value, entry: Value) -> Result<(), CoreError> { + let items = document["configurations"] + .as_array_mut() + .ok_or_else(|| CoreError::new(ErrorCode::ParseFailed, "configurations must be an array"))?; + items.retain(|item| item["id"] != entry["id"]); + items.push(entry); + items.sort_by(|left, right| left["id"].as_str().cmp(&right["id"].as_str())); + Ok(()) +} diff --git a/rust/crates/execution/src/configuration/document.rs b/rust/crates/execution/src/configuration/document.rs index 88c6570a..e4050c09 100644 --- a/rust/crates/execution/src/configuration/document.rs +++ b/rust/crates/execution/src/configuration/document.rs @@ -161,6 +161,10 @@ pub struct RunConfiguration { pub id: String, /// Display name shown in the Run list. pub name: String, + /// Folder the entry is listed in within its kind; display only, launching + /// ignores it (`runConfig.arrange`). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub folder: Option, /// Open namespaced discriminator, e.g. `build.provider`. /// Deliberately not an enum: new ecosystems must not require a contract change. pub provider: String, diff --git a/rust/crates/execution/src/configuration/form.rs b/rust/crates/execution/src/configuration/form.rs index 2f3f83cc..27c823ab 100644 --- a/rust/crates/execution/src/configuration/form.rs +++ b/rust/crates/execution/src/configuration/form.rs @@ -765,6 +765,7 @@ impl Draft { let configuration = RunConfiguration { id: "user:draft".into(), name: stored.name.clone(), + folder: None, provider: self.kind.provider().into(), execution: Execution::default(), category: Default::default(), diff --git a/rust/crates/execution/src/configuration/resolve.rs b/rust/crates/execution/src/configuration/resolve.rs index 0f499952..069478e6 100644 --- a/rust/crates/execution/src/configuration/resolve.rs +++ b/rust/crates/execution/src/configuration/resolve.rs @@ -133,6 +133,8 @@ pub(crate) fn resolve_layers( } } configurations.retain(|configuration| !configuration.disabled); + let arrangement = Arrangement::read(local, &mut diagnostics); + arrangement.apply(&mut configurations); let runnable = |id: &str| { configurations .iter() @@ -163,6 +165,7 @@ pub(crate) fn resolve_layers( "configurations": configurations, "diagnostics": diagnostics, "defaultRunConfiguration": default_run_configuration, + "sortAlphabetically": arrangement.sort_alphabetically, "toolchain": global_toolchain, "localToolchains": local_toolchains })) diff --git a/rust/crates/execution/src/configuration/validation.rs b/rust/crates/execution/src/configuration/validation.rs index f05b9589..a337d75a 100644 --- a/rust/crates/execution/src/configuration/validation.rs +++ b/rust/crates/execution/src/configuration/validation.rs @@ -62,6 +62,16 @@ pub(crate) fn validate_configuration(configuration: &RunConfiguration) -> Result "Run configuration id and name are required", )); } + if configuration + .folder + .as_deref() + .is_some_and(|folder| !valid_folder(folder)) + { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Invalid run configuration folder", + )); + } super::before_launch::validate_shape(configuration)?; if !valid_provider(&configuration.provider) { return Err(CoreError::new( diff --git a/rust/crates/execution/src/provider_runs.rs b/rust/crates/execution/src/provider_runs.rs index b862645e..cf89a81d 100644 --- a/rust/crates/execution/src/provider_runs.rs +++ b/rust/crates/execution/src/provider_runs.rs @@ -56,6 +56,7 @@ pub(super) fn configurations(runs: &[ProviderRunConfiguration]) -> Vec