Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions rust/contracts/rust-core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.<fieldID>` 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.<fieldID>` 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.<fieldID>` 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.<fieldID>` 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`. |
Expand Down
88 changes: 71 additions & 17 deletions rust/crates/build/src/run_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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.
Expand Down Expand Up @@ -442,9 +446,9 @@ pub(crate) struct RunConfigurationPlanRequest {
/// `runConfig.launchPlan`.
#[serde(default)]
pub(crate) local_document: Option<Value>,
/// 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<RunTypeInstance>,
/// Absolute installed plugin directory, for `${pluginDir}`.
#[serde(default)]
Expand Down Expand Up @@ -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(),
Expand Down Expand Up @@ -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<Option<String>> {
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::<Option<Vec<_>>>();
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<impl FnOnce() -> io::Result<Option<String>>>,
) -> Validation<&'a RunTypeInstance> {
if instances.is_empty() {
return Err(invalid_selection(
Expand All @@ -704,12 +750,11 @@ fn instance_of<'a>(
.iter()
.map(|instance| decode::request_path(&instance.root, "root"))
.collect::<Validation<Vec<_>>>()?;
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
Expand All @@ -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))
}
134 changes: 133 additions & 1 deletion rust/crates/core/src/tests/plugin_run_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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");
Expand Down
Loading
Loading