Skip to content

Commit 44d62e4

Browse files
authored
Merge pull request #112 from Lithe-IDEA/codex/2122-command-test-discovery
feat(build): 支持命令式测试发现
2 parents 509c2be + 6d7a59a commit 44d62e4

24 files changed

Lines changed: 600 additions & 108 deletions

File tree

‎rust/contracts/rust-core-api.md‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -538,8 +538,8 @@ or removing a command fails until the table changes in the same commit.
538538
| `build.decodeConfiguration` | Validate native source identities, raw/effective values and XML bindings |
539539
| `build.prepareRunPlan` | Plan Provider-owned application/service/task preparation from a model target |
540540
| `build.decodeRunPreparation` | Validate portable launch data before the native Run host starts a process |
541-
| `build.testDiscoveryPlan` | Plan opt-in Provider test discovery for an instance |
542-
| `build.decodeTestDiscovery` | Validate, deduplicate and order Provider test selectors |
541+
| `build.testDiscoveryPlan` | Plan opt-in command or Provider test discovery for an instance |
542+
| `build.decodeTestDiscovery` | Validate, deduplicate and order discovered test selectors |
543543
| `build.runEntrypointsPlan` | Plan a Provider request for the run entrypoints of one source file (`buildProviders` 1) |
544544
| `build.decodeRunEntrypoints` | Validate and deduplicate the run entrypoints a Provider named |
545545
| `build.dependencyPlan` | Expand the command that prints a project's dependency tree, or the request a build provider answers |
@@ -5281,8 +5281,8 @@ and the directories are absolute host paths used only as substitution text.
52815281
| `build.runConfigurationPlan` | `manifest`, `buildSystemID`, required `workspaceRoot`, and `request: {configurationId, localDocument?, instances: [{root, options?, modelInputs?}], pluginDirectory?, workspaceStateDirectory?}` | `plan` as `build.taskPlan` returns it plus `runType: {pluginID, buildSystemID, type}`: the global arguments, then the type's `arguments` with the saved field values, the instance's options and the configuration's program arguments, at the configuration's working directory, with its environment over the options'. The instance is the deepest one whose root holds the working directory, or the only one; `plugin.build.invalidSelection` when several exist and none holds it or the configuration belongs to another plugin or build system, `plugin.build.unavailable` when the type is no longer declared, `plugin.build.invalidRunConfiguration` with `field: values.<fieldID>` when a saved value no longer fits. A configuration that is missing, disabled, unavailable or of another provider fails the call |
52825282
| `build.beforeLaunchTaskPlan` | `manifest`, `buildSystemID`, required `workspaceRoot`, and `request: {task, workingDirectory, instances: [{root, options?, modelInputs?}], pluginDirectory?, workspaceStateDirectory?}`, 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 |
52835283
| `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 |
5284-
| `build.testDiscoveryPlan` | common plan fields plus `refresh?`, `tool?`; no project/output file | `plan.provider` for `lithe/build/discoverTests`, only with `test.discovery: true`, using the same effective options and effect metadata |
5285-
| `build.decodeTestDiscovery` | common plan fields plus canonical `result` | `discovery.tests` with validated `{id, suite, case, project?, target?}` selectors; bounded at 10,000 items/32 MiB, deterministic and exactly runnable; malformed replies reject in full |
5284+
| `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. |
5285+
| `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`. |
52865286
| `build.runEntrypointsPlan` | common plan fields plus `file` (workspace-relative, inside the instance), `refresh?`, `tool?`; no project/output file | `plan.provider` for `lithe/build/runEntrypoints` with `file`, only when a run declares `entrypoints: true`; decoder `litheRunEntrypoints` |
52875287
| `build.decodeRunEntrypoints` | common plan fields plus canonical `result` | `entrypoints.entrypoints`: `[{run, name, entrypoint, project:{name, path}}]` in the provider's order without exact duplicates; at most 64; each names an entrypoint run, a 1–256 byte name, a 1–4,096 byte entrypoint and a project inside the instance; malformed replies reject in full with `plugin.build.invalidOutput` |
52885288
| `build.prepareRunPlan` | common plan fields, `run`, required `project`, `target` (required for a target run, refused for an entrypoint run), `userArguments?`, `optionOverrides?`, `launchOptions?`, `workspaceRoot?` (required for an explicit launch cwd); no output file | `plan.provider` for `lithe/build/prepareRun`, selected declaration/tags/paths/options validated; typed launch options must match the run's declared execution kind, a service or task run requires them, and an entrypoint run requires `launchOptions.entrypoint` and sends no `target` |
@@ -6935,6 +6935,7 @@ a code has one meaning across every contribution with that lifecycle:
69356935
| `debugAdapter/start` | `debugAdapters[]` | process start |
69366936
| `lithe/build/model` | `buildSystems[].model` command source | command run |
69376937
| `lithe/build/dependencies` | `buildSystems[].dependencies` command source | command run |
6938+
| `lithe/build/discoverTests` | `buildSystems[].test.discoveryCommand` | command run |
69386939
| `commandInstaller/install` | `commandInstallers[]` installation the user confirmed; `decode` when a provided command is missing after a successful exit | command run |
69396940

69406941
| `stage` | Process start | Command run |

‎rust/crates/build/src/commands.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -302,7 +302,7 @@ pub fn build_test_plan_command<M: BuildManifest>(payload: Value) -> Result<Value
302302
)
303303
}
304304

305-
/// `build.testDiscoveryPlan`: a typed request for provider-owned test discovery.
305+
/// `build.testDiscoveryPlan`: a command plan or provider request for test discovery.
306306
pub fn build_test_discovery_plan_command<M: BuildManifest>(
307307
payload: Value,
308308
) -> Result<Value, CoreError> {

‎rust/crates/build/src/decode.rs‎

Lines changed: 49 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
use lithe_plugin_model::{PluginRejection, Validation};
1010
use lithe_workspace::{self as workspace, fs};
1111
use serde_json::Value;
12+
use std::io::Read;
1213
use std::path::{Component, Path, PathBuf};
1314
use std::time::UNIX_EPOCH;
1415

@@ -62,24 +63,41 @@ fn first_line(text: &str) -> &str {
6263

6364
/// Reads a UTF-8 file up to the output bound.
6465
pub(crate) fn read_bounded(path: &Path) -> Validation<String> {
66+
String::from_utf8(read_file_bytes(path)?)
67+
.map_err(|_| invalid_output("The build tool output is not UTF-8."))
68+
}
69+
70+
/// Bytes of a file up to the output bound, or `None` when it is absent, not
71+
/// a regular file, or too large.
72+
pub(crate) fn read_bytes_bounded(path: &Path) -> Option<Vec<u8>> {
73+
// Sync fingerprints treat an unreadable input as absent.
74+
read_file_bytes(path).ok()
75+
}
76+
77+
fn read_file_bytes(path: &Path) -> Validation<Vec<u8>> {
6578
let metadata = fs::metadata(path)
6679
.map_err(|_| invalid_output("The build tool did not write its output file."))?;
6780
if !metadata.is_file() || metadata.len() > MAX_OUTPUT_BYTES as u64 {
6881
return Err(invalid_output(
6982
"The build tool output file is missing or too large.",
7083
));
7184
}
72-
fs::read_to_string(path).map_err(|_| invalid_output("The build tool output is not UTF-8."))
85+
let file = fs::File::open(path)
86+
.map_err(|_| invalid_output("The build tool output file could not be opened."))?;
87+
read_output(file, metadata.len() as usize)
7388
}
7489

75-
/// Bytes of a file up to the output bound, or `None` when it is absent, not
76-
/// a regular file, or too large.
77-
pub(crate) fn read_bytes_bounded(path: &Path) -> Option<Vec<u8>> {
78-
let metadata = fs::metadata(path).ok()?;
79-
if !metadata.is_file() || metadata.len() > MAX_OUTPUT_BYTES as u64 {
80-
return None;
90+
fn read_output(reader: impl Read, observed_size: usize) -> Validation<Vec<u8>> {
91+
let mut bytes = Vec::with_capacity(observed_size + 1);
92+
// The opened file may have grown since the metadata check.
93+
reader
94+
.take(MAX_OUTPUT_BYTES as u64 + 1)
95+
.read_to_end(&mut bytes)
96+
.map_err(|_| invalid_output("The build tool output file could not be read."))?;
97+
if bytes.len() > MAX_OUTPUT_BYTES {
98+
return Err(invalid_output("The build tool output is too large."));
8199
}
82-
fs::read(path).ok()
100+
Ok(bytes)
83101
}
84102

85103
/// Bounds a host-provided output text before it is parsed line by line.
@@ -428,6 +446,29 @@ fn is_current(path: &Path, not_before_millis: Option<u64>) -> bool {
428446
mod tests {
429447
use super::*;
430448

449+
#[test]
450+
fn output_read_enforces_the_limit_even_if_the_file_grows() {
451+
let limit = MAX_OUTPUT_BYTES as u64;
452+
let at_limit = std::io::repeat(b'x').take(limit);
453+
assert_eq!(
454+
read_output(at_limit, MAX_OUTPUT_BYTES).unwrap().len(),
455+
MAX_OUTPUT_BYTES
456+
);
457+
458+
// Metadata reported an in-budget size, but the stream contains more.
459+
let mut over_limit = std::io::repeat(b'x').take(limit + 2);
460+
let rejected = match read_output(&mut over_limit, MAX_OUTPUT_BYTES) {
461+
Ok(bytes) => panic!("accepted an oversized output of {} bytes", bytes.len()),
462+
Err(error) => error,
463+
};
464+
assert_eq!(rejected.code, "plugin.build.invalidOutput");
465+
assert_eq!(
466+
over_limit.limit(),
467+
1,
468+
"read past the extra byte needed to detect overflow"
469+
);
470+
}
471+
431472
#[test]
432473
fn wildcards_match_within_a_segment() {
433474
assert!(wildcard("TEST-*.xml", "TEST-demo.OrderTest.xml"));

‎rust/crates/build/src/manifest/checks.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,9 @@ fn program(build_system: &BuildSystemDeclaration) -> Value {
122122
review["source"] = json!("provider");
123123
}
124124
if test.discovery { review["discovery"] = json!(true); }
125+
if let Some(command) = &test.discovery_command {
126+
review["discoveryCommand"] = json!(command);
127+
}
125128
review
126129
}),
127130
"model": model,

‎rust/crates/build/src/manifest/options.rs‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -232,6 +232,12 @@ impl BuildSystemDeclaration {
232232
}
233233
if let Some(test) = &self.test {
234234
lists.push((format!("{field}.test.arguments"), &test.arguments));
235+
if let Some(command) = &test.discovery_command {
236+
lists.push((
237+
format!("{field}.test.discoveryCommand.arguments"),
238+
&command.arguments,
239+
));
240+
}
235241
}
236242
if let Some(ModelSource::Command { arguments, .. }) = &self.model {
237243
lists.push((format!("{field}.model.arguments"), arguments));

‎rust/crates/build/src/manifest/testing.rs‎

Lines changed: 52 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -33,11 +33,29 @@ pub(crate) struct TestDeclaration {
3333
/// The provider can enumerate exact selectors for the native test tree.
3434
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
3535
pub(crate) discovery: bool,
36+
/// A separate discovery command that writes a canonical selector document.
37+
#[serde(default, skip_serializing_if = "Option::is_none")]
38+
pub(crate) discovery_command: Option<TestDiscoveryCommand>,
3639
pub(crate) arguments: Vec<BuildArgument>,
3740
#[serde(default, skip_serializing_if = "Option::is_none")]
3841
pub(crate) results: Option<TestResultsSource>,
3942
}
4043

44+
impl TestDeclaration {
45+
pub(crate) fn discovers_tests(&self) -> bool {
46+
self.discovery || self.discovery_command.is_some()
47+
}
48+
}
49+
50+
/// Command input plus the effect facts the host needs before launch.
51+
#[derive(Debug, Clone, Deserialize, Serialize)]
52+
#[serde(rename_all = "camelCase", deny_unknown_fields)]
53+
pub(crate) struct TestDiscoveryCommand {
54+
pub(crate) arguments: Vec<BuildArgument>,
55+
pub(crate) executes_project_code: bool,
56+
pub(crate) may_use_network: bool,
57+
}
58+
4159
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Deserialize, Serialize)]
4260
#[serde(rename_all = "camelCase")]
4361
pub(crate) enum TestFilter {
@@ -62,6 +80,13 @@ pub(crate) enum TestResultsSource {
6280
}
6381

6482
impl BuildSystemDeclaration {
83+
/// Whether the declaration needs buildSystems 1 for command-based discovery.
84+
pub fn has_test_discovery_command(&self) -> bool {
85+
self.test
86+
.as_ref()
87+
.is_some_and(|test| test.discovery_command.is_some())
88+
}
89+
6590
pub(crate) fn validate_test(
6691
&mut self,
6792
field: &str,
@@ -95,16 +120,39 @@ impl BuildSystemDeclaration {
95120
test.selector_kinds.sort();
96121
test.filters.sort();
97122
test.filters.dedup();
98-
if test.discovery
99-
&& (test.source != TaskSource::Provider
100-
|| !test.filters.contains(&TestFilter::Suite)
123+
if test.discovers_tests()
124+
&& (!test.filters.contains(&TestFilter::Suite)
101125
|| !test.filters.contains(&TestFilter::Case))
102126
{
103127
return Err(invalid(
104128
&field,
105-
"Test discovery requires a provider and suite/case filters.",
129+
"Test discovery requires suite and case filters.",
106130
));
107131
}
132+
if test.discovery
133+
&& (test.source != TaskSource::Provider || test.discovery_command.is_some())
134+
{
135+
return Err(invalid(
136+
&field,
137+
"Provider test discovery requires provider tests and no discoveryCommand.",
138+
));
139+
}
140+
if let Some(command) = &test.discovery_command {
141+
let field = format!("{field}.discoveryCommand");
142+
let arguments = format!("{field}.arguments");
143+
check_argument_count(&command.arguments, &arguments)?;
144+
template::validate_arguments(
145+
&command.arguments,
146+
&Allowed {
147+
root: true,
148+
host_directories: true,
149+
options: Some(options),
150+
..Allowed::none()
151+
},
152+
&arguments,
153+
)?;
154+
check_output_channel(OutputChannel::OutputFile, &command.arguments, &field)?;
155+
}
108156
if test.source == TaskSource::Provider {
109157
if !test.arguments.is_empty() {
110158
return Err(invalid(&field, "Provider tests require empty arguments."));

‎rust/crates/build/src/outputs.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ fn message_text(value: &str) -> Option<String> {
6666
}
6767

6868
/// The text a finished command left: its stdout, or the file it wrote.
69-
fn command_output(
69+
pub(crate) fn command_output(
7070
channel: OutputChannel,
7171
output: Option<&str>,
7272
output_file: Option<&str>,

0 commit comments

Comments
 (0)