diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 696a3dbd..40a46a0e 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -5509,8 +5509,8 @@ user to trust the workspace before an action the user started. | `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?, projectCodeAllowed?}` | `plan` as `build.taskPlan` returns it plus `runType: {pluginID, buildSystemID, type}`: the global arguments, then the type's `arguments` with the saved field values, the instance's options and the configuration's program arguments, at the configuration's working directory, with its environment over the options'. The instance is the deepest one whose root holds the working directory, or the only one; `plugin.build.invalidSelection` when several exist and none holds it or the configuration belongs to another plugin or build system, `plugin.build.unavailable` when the type is no longer declared, `plugin.build.invalidRunConfiguration` with `field: values.` when a saved value no longer fits. A configuration that is missing, disabled, unavailable or of another provider fails the call | -| `build.beforeLaunchTaskPlan` | `manifest`, `buildSystemID`, required `workspaceRoot`, and `request: {task, workingDirectory, instances: [{root, options?, modelInputs?}], pluginDirectory?, workspaceStateDirectory?, projectCodeAllowed?}`, with `task` and `workingDirectory` as `runConfig.beforeLaunch` returned the step | `plan` as `build.taskPlan` returns it plus `beforeLaunchTask: {pluginID, buildSystemID, type}`: the global arguments, then the task's `arguments` with the saved field values and the instance's options, at the step's working directory with the options' environment, as a `task` execution. The instance is chosen as for `build.runConfigurationPlan`; `plugin.build.invalidSelection` when several exist and none holds the working directory or the task belongs to another plugin or build system, `plugin.build.unavailable` when the task is no longer declared, `plugin.build.invalidBeforeLaunchTask` with `field: values.` when a saved value no longer fits. A working directory outside the workspace fails the call | +| `build.runConfigurationPlan` | `manifest`, `buildSystemID`, required `workspaceRoot`, and `request: {configurationId, localDocument?, instances: [{root, options?, modelInputs?}], pluginDirectory?, workspaceStateDirectory?, projectCodeAllowed?}` | `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 deepest enclosing instance is selected by the working directory, then by the resolved target of the sole active file field if it is a file inside the workspace, the working directory resolves lexically to the workspace root, and no instance contains that directory. A sole instance works without a path match. The working directory is preserved. `plugin.build.invalidSelection` when no instance can be selected or the configuration belongs to another plugin or build system, `plugin.build.unavailable` when the type is no longer declared, `plugin.build.invalidRunConfiguration` with `field: values.` when a saved value no longer fits. A configuration that is missing, disabled, unavailable or of another provider fails the call | +| `build.beforeLaunchTaskPlan` | `manifest`, `buildSystemID`, required `workspaceRoot`, and `request: {task, workingDirectory, instances: [{root, options?, modelInputs?}], pluginDirectory?, workspaceStateDirectory?, projectCodeAllowed?}`, with `task` and `workingDirectory` as `runConfig.beforeLaunch` returned the step | `plan` as `build.taskPlan` returns it plus `beforeLaunchTask: {pluginID, buildSystemID, type}`: the global arguments, then the task's `arguments` with the saved field values and the instance's options, at the step's working directory with the options' environment, as a `task` execution. The instance is the deepest enclosing the working directory, or the only one. `plugin.build.invalidSelection` when several exist and none holds the working directory or the task belongs to another plugin or build system, `plugin.build.unavailable` when the task is no longer declared, `plugin.build.invalidBeforeLaunchTask` with `field: values.` when a saved value no longer fits. A working directory outside the workspace fails the call | | `build.testPlan` | plan fields plus `project?`, `target?`, `suite?`, `case?`, `userArguments?`, `projects?` (the model's project directories) | command plan or `provider: {method: "lithe/build/test", params}`, plus `results`: `null`, `{ decoder, reports }` with workspace-relative globs (for the selected project, or for the root and every listed project when none is selected), or command-only `{ decoder: "hostIntegration" }`. Command filters that templates cannot place, such as a case without its suite when the tool only addresses `Suite#case`, are `plugin.build.invalidSelection`; Provider filters remain separate typed values and must be declared supported | | `build.testDiscoveryPlan` | Common plan fields, plus a fresh absolute `outputFile` for `test.discoveryCommand`, or optional `refresh` and `tool` for `test.discovery: true`. No project selection. | Command plan with argv, environment, instance working directory, `output: "outputFile"`, `decoder: "litheTestDiscovery"` and effect metadata, or `plan.provider` for `lithe/build/discoverTests` with the effective options. | | `build.decodeTestDiscovery` | Original common plan fields plus the same `outputFile` for a completed command or canonical inline `result` for a Provider. | `discovery.tests` with validated `{id, suite, case, project?, target?}` selectors. Bounded at 10,000 items and 32 MiB, deterministic and exactly runnable. Malformed results reject in full with `plugin.build.invalidOutput`. | diff --git a/rust/crates/build/src/run_types.rs b/rust/crates/build/src/run_types.rs index ef0bc940..924ac4a5 100644 --- a/rust/crates/build/src/run_types.rs +++ b/rust/crates/build/src/run_types.rs @@ -31,9 +31,11 @@ use lithe_plugin_model::settings::{parse_localization_file, present, Localizatio use lithe_plugin_model::{PluginRejection, Validation}; use lithe_protocol::json_document::UniqueMap; use lithe_protocol::{CoreError, ErrorCode}; +use lithe_workspace::fs; use serde::Deserialize; use serde_json::{json, Map, Value}; use std::collections::BTreeMap; +use std::io; use std::path::Path; /// Error code of a translation file Core did not apply. @@ -46,6 +48,8 @@ const INVALID_BEFORE_LAUNCH_TASK: &str = "plugin.build.invalidBeforeLaunchTask"; const MAX_PLUGINS: usize = 512; /// Most build-system instances one plan request may name. const MAX_INSTANCES: usize = 4_096; +const NO_MATCHING_INSTANCE: &str = + "The working directory is outside every project of this build system; choose one inside a project."; /// The installed plugins whose run configuration types and before-launch /// tasks the editor offers. @@ -442,9 +446,9 @@ pub(crate) struct RunConfigurationPlanRequest { /// `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. + /// The detected instances of the build system, with their stored options. + /// Selection uses the working directory first and can fall back to the + /// run's file when the workspace root has no instance. pub(crate) instances: Vec, /// Absolute installed plugin directory, for `${pluginDir}`. #[serde(default)] @@ -624,7 +628,9 @@ fn declared_plan( .expect("launch values name declared fields"); field_arguments.push((id.clone(), field_value_arguments(field, value)?)); } - let instance = instance_of(sources.instances, &launch.working_directory)?; + let file_directory = (role.role == RunTypeRole::Configuration) + .then_some(|| sole_file_directory(workspace_root, declaration, &values)); + let instance = instance_of(sources.instances, &launch.working_directory, file_directory)?; let base = PlanBase { model_inputs: instance.model_inputs.clone(), root: instance.root.clone(), @@ -684,13 +690,53 @@ fn field_value_arguments( } } -/// 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. +/// The workspace-relative parent of the sole active file's resolved target. +/// Resolving both paths keeps aliases inside the workspace usable and prevents +/// a link to an external file from choosing an instance. +fn sole_file_directory( + workspace_root: &Path, + declaration: &RunTypeDeclaration, + values: &[(String, DeclaredValue)], +) -> io::Result> { + let mut files = values.iter().filter_map(|(id, value)| { + let DeclaredValue::Text(path) = value else { + return None; + }; + declaration + .fields + .iter() + .any(|field| field.id == *id && field.kind == RunFieldKind::File) + .then_some(path) + }); + let (Some(file), None) = (files.next(), files.next()) else { + return Ok(None); + }; + let workspace_root = fs::canonicalize(workspace_root)?; + let file = fs::canonicalize(file)?; + let Some(directory) = file + .parent() + .and_then(|parent| parent.strip_prefix(&workspace_root).ok()) + else { + return Ok(None); + }; + if !fs::is_file(&file)? { + return Ok(None); + } + let components = directory + .iter() + .map(|component| component.to_str()) + .collect::>>(); + Ok(components.and_then(|parts| decode::request_path(&parts.join("/"), "file directory").ok())) +} + +/// Picks the deepest project that contains the working directory. When no +/// root holds it, a run at the workspace root can supply a file's directory +/// to select the instance while keeping the configured working directory. +/// A lone instance can run from outside its project. fn instance_of<'a>( instances: &'a [RunTypeInstance], working_directory: &str, + file_directory: Option io::Result>>, ) -> Validation<&'a RunTypeInstance> { if instances.is_empty() { return Err(invalid_selection( @@ -704,12 +750,11 @@ fn instance_of<'a>( .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| { + let holding = |directory: &str| { roots .iter() .enumerate() - .filter(|(_, root)| decode::contains(root, &directory)) + .filter(|(_, root)| decode::contains(root, directory)) .max_by_key(|(_, root)| { if *root == "." { 0 @@ -718,11 +763,20 @@ fn instance_of<'a>( } }) .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.", - )), + }; + let directory = decode::request_path(working_directory, "working directory").ok(); + match (directory.as_deref().and_then(holding), instances) { + (Some(instance), _) | (None, [instance]) => return Ok(instance), + (None, _) => {} + } + if let Some(resolve_file_directory) = + file_directory.filter(|_| directory.as_deref() == Some(".")) + { + let resolved = + resolve_file_directory().map_err(|_| invalid_selection(NO_MATCHING_INSTANCE))?; + if let Some(instance) = resolved.as_deref().and_then(holding) { + return Ok(instance); + } } + Err(invalid_selection(NO_MATCHING_INSTANCE)) } diff --git a/rust/crates/core/src/tests/plugin_run_types.rs b/rust/crates/core/src/tests/plugin_run_types.rs index b374d4a6..8f7bf01f 100644 --- a/rust/crates/core/src/tests/plugin_run_types.rs +++ b/rust/crates/core/src/tests/plugin_run_types.rs @@ -3,7 +3,10 @@ //! 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 super::support::{ + apply_run_changes, changed_run_document, changed_run_paths, edit_plugin_run_document, + temporary_root, Cleanup, +}; use crate::execute_json; use serde_json::{json, Value}; use std::collections::BTreeMap; @@ -65,6 +68,23 @@ fn plan(root: &std::path::Path, manifest: Value, request: Value) -> Value { ) } +fn save_file_run(root: &std::path::Path, name: &str, directory: &str) -> Value { + let saved = call( + "runConfig.saveConfiguration", + json!({ + "root": root, "provider": "build.run-type", "runType": run_type("build"), + "runTypePlugins": plugins(), + "values": { + "name": name, "workingDirectory": directory, + "field:runKind": "file", "field:file": "apps/worker/main.go", + }, + }), + ); + assert_eq!(saved["data"]["status"], "saved", "{saved}"); + apply_run_changes(root, &saved["data"]); + saved["data"].clone() +} + #[test] fn declared_types_follow_the_built_in_kinds_with_translated_text() { let plain = call( @@ -518,6 +538,118 @@ fn saved_declared_runs_expand_into_the_types_command_line() { assert_eq!(planned["data"]["plan"]["root"], "."); } +/// A file run at the workspace root can resolve the one project that contains +/// that file. An explicit working directory still chooses its own instance. +#[test] +fn file_run_uses_its_project_when_the_workspace_root_has_no_instance() { + let root = temporary_root("run-types-file-project"); + let _cleanup = Cleanup(root.clone()); + fs::create_dir_all(root.join("apps/worker")).unwrap(); + fs::create_dir_all(root.join("tools")).unwrap(); + fs::write(root.join("apps/worker/main.go"), "package main\n").unwrap(); + + for (name, directory, expected_instance) in [ + ("default", "", "apps/worker"), + ("explicit", "tools", "tools"), + ] { + let saved = save_file_run(&root, name, directory); + let planned = plan( + &root, + manifest(), + json!({ + "configurationId": saved["id"], + "instances": [{"root": "apps"}, {"root": "apps/worker"}, {"root": "tools"}], + }), + ); + assert_eq!(planned["data"]["status"], "ok", "{planned}"); + assert_eq!(planned["data"]["plan"]["root"], expected_instance); + let expected_directory = if directory.is_empty() { "." } else { directory }; + assert_eq!( + planned["data"]["plan"]["workingDirectory"], + expected_directory + ); + } +} + +#[test] +fn file_run_accepts_an_equivalent_saved_workspace_root() { + let root = temporary_root("run-types-root-alias"); + let _cleanup = Cleanup(root.clone()); + fs::create_dir_all(root.join("apps/worker")).unwrap(); + fs::create_dir_all(root.join("tools")).unwrap(); + fs::write(root.join("apps/worker/main.go"), "package main\n").unwrap(); + let saved = save_file_run(&root, "root alias", ""); + let plugin_document = changed_run_paths(&saved) + .into_iter() + .find(|path| path.ends_with(".toml")) + .expect("a declared run is saved in a plugin TOML document"); + edit_plugin_run_document(&root, &plugin_document, |document| { + document["configurations"][0]["cwd"] = json!("./"); + }); + + let planned = plan( + &root, + manifest(), + json!({ + "configurationId": saved["id"], + "instances": [{"root": "apps/worker"}, {"root": "tools"}], + }), + ); + assert_eq!(planned["data"]["status"], "ok", "{planned}"); + assert_eq!(planned["data"]["plan"]["root"], "apps/worker"); + assert_eq!(planned["data"]["plan"]["workingDirectory"], "./"); +} + +#[cfg(unix)] +fn plan_file_run_after_script_becomes_link(target: &str) -> Value { + let fixture = temporary_root("run-types-linked-file"); + let _cleanup = Cleanup(fixture.clone()); + let root = fixture.join("workspace"); + fs::create_dir_all(root.join("apps/worker")).unwrap(); + fs::create_dir_all(root.join("tools")).unwrap(); + let script = root.join("apps/worker/main.go"); + fs::write(&script, "package main\n").unwrap(); + let target = fixture.join(target); + fs::write(&target, "package main\n").unwrap(); + let saved = save_file_run(&root, "linked script", ""); + fs::remove_file(&script).unwrap(); + std::os::unix::fs::symlink(target, script).unwrap(); + + plan( + &root, + manifest(), + json!({ + "configurationId": saved["id"], + "instances": [ + {"root": "apps/worker", "options": {"tags": "worker"}}, + {"root": "tools", "options": {"tags": "tools"}}, + ], + }), + ) +} + +#[cfg(unix)] +#[test] +fn file_run_selects_the_project_of_its_link_target() { + let planned = plan_file_run_after_script_becomes_link("workspace/tools/main.go"); + assert_eq!(planned["data"]["status"], "ok", "{planned}"); + assert_eq!(planned["data"]["plan"]["root"], "tools"); + assert_eq!(planned["data"]["plan"]["workingDirectory"], "."); + assert_eq!(planned["data"]["plan"]["arguments"][1], "-tags"); + assert_eq!(planned["data"]["plan"]["arguments"][2], "tools"); +} + +#[cfg(unix)] +#[test] +fn file_run_cannot_infer_a_project_from_a_link_to_an_external_file() { + let planned = plan_file_run_after_script_becomes_link("outside.go"); + assert_eq!(planned["data"]["status"], "rejected", "{planned}"); + assert_eq!( + planned["data"]["error"]["code"], + "plugin.build.invalidSelection" + ); +} + #[test] fn a_type_without_program_arguments_stores_none() { let root = temporary_root("run-types-no-arguments"); diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 2d0aa87b..660be0cf 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -3008,8 +3008,14 @@ 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 +deepest instance whose root contains the configuration's working directory. +When that directory is the workspace root and no instance contains it, Core +can instead use the deepest instance containing the parent of the sole active +file field's resolved target, provided the target is a file inside the +workspace. Equivalent spellings of the workspace root, such as `./`, qualify +for this fallback. If neither path selects an instance, a single detected +instance still works. This choice does not change +the working directory. Core 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 @@ -3070,8 +3076,9 @@ it, without that configuration's program arguments or environment. To run one, the host calls `build.beforeLaunchTaskPlan` with the manifest, the build system, `workspaceRoot`, the step and its working directory as `runConfig.beforeLaunch` returned them, and the detected instances of the -build system with their stored options. Core picks the instance as for a run -configuration and returns a task plan: the global arguments, then the task's +build system with their stored options. Core picks the deepest instance +containing the step's working directory, or the only instance, and returns +a task plan: the global arguments, then the task's `arguments` with the field values and the instance's options. A saved value that no longer fits the task is `plugin.build.invalidBeforeLaunchTask` with `field: "values."`; a task the plugin no longer declares is diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 9ce86726..25911950 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -15,6 +15,7 @@ ## 待合入 - [#151](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/151),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`pluginAPIVersion` 0 内的补充(API-05、API-35、API-40):远程工作区上下文的 `authority` 新增 `platform: { os, arch }`,取值同托管运行时(`os` 为 `linux`,`arch` 为 `arm64` 或 `x86_64`),本地上下文没有这个字段。新增宿主方法 `workspace/getHostPaths`:返回远程上下文的根目录在远端主机上的绝对 POSIX 路径 `hostPath`,可选的 `rootIDs`(1–256 个不重复的根目录 ID)决定返回哪些根目录和顺序;它是 `workspace.metadata` 下单独的方法授权,本地上下文返回 `plugin.host.authorityUnsupported`,未知根目录返回 `plugin.host.notFound`;声明 `workspace.metadata` 的插件,启动计划的 `backend.hostServices` 因此多出 `lithe/host/workspace/getHostPaths`,宿主传给 `lsp.startServer` 时去掉自己没有注册处理器的方法授权,后端调用它们得到 `plugin.host.permissionDenied`。新增失败码 `plugin.host.remoteDisconnected`(`-32078`,操作进行中与远端主机断开)和 `plugin.host.platformUnavailable`(`-32079`,插件没有适合远端平台的程序包或托管运行时)。插件函数中转不再拒绝远程工作区的上下文,导出的 `context: "workspace"` 指两种来源的工作区,Core 不读也不改写参数和结果里的路径。四个官方 SDK 新增远端平台读取、`getHostPaths`、按来源选择进程所用路径的辅助方法和两个失败码,`path` 与 `hostPath` 是不同类型。没有新增能力版本、通知或 SDK 版本。 +- [#150](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/150),[@Mucheen](https://github.com/Mucheen),`runConfigurationTypes` 0 内的行为修正(API-29)。`build.runConfigurationPlan` 在工作目录为工作区根且没有匹配实例时,用唯一生效的文件字段解析后的工作区内目标定位最深的构建实例。`./` 等价于工作区根,指向工作区外的链接不参与定位。进程工作目录和执行前任务选择规则保持原样。没有新增宿主方法、通知或协议版本。 ## 按协议查首次出现