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
25 changes: 20 additions & 5 deletions rust/crates/build/src/manifest/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,14 @@ impl BuildSystemDeclaration {
.filter(|option| option.choices_from_model)
.map(|option| option.id.clone())
.collect();
// `optionDefaults` also reports the value a text, file or directory
// option has when the user leaves it unset.
let default_options: BTreeSet<String> = self
.options
.iter()
.filter(|option| option.choices_from_model || option.is_text_like())
.map(|option| option.id.clone())
.collect();
match &self.model {
None => {
if !model_options.is_empty() {
Expand All @@ -227,7 +235,7 @@ impl BuildSystemDeclaration {
"The model file must be relative to the build-system root.",
));
}
map.validate(&format!("{field}.map"), &model_options)
map.validate(&format!("{field}.map"), &model_options, &default_options)
}
Some(ModelSource::Command {
arguments,
Expand Down Expand Up @@ -258,7 +266,9 @@ impl BuildSystemDeclaration {
format!("{field}.map"),
"A model command with a generic format needs a map.",
)),
(_, Some(map)) => map.validate(&format!("{field}.map"), &model_options),
(_, Some(map)) => {
map.validate(&format!("{field}.map"), &model_options, &default_options)
}
}
}
Some(ModelSource::Provider) => Ok(()),
Expand Down Expand Up @@ -286,7 +296,12 @@ pub(crate) fn check_output_channel(
}

impl ModelMap {
fn validate(&self, field: &str, model_options: &BTreeSet<String>) -> Validation<()> {
fn validate(
&self,
field: &str,
model_options: &BTreeSet<String>,
default_options: &BTreeSet<String>,
) -> Validation<()> {
if self.projects.is_empty() {
return Err(invalid(
format!("{field}.projects"),
Expand Down Expand Up @@ -327,10 +342,10 @@ impl ModelMap {
}
for (id, rule) in &self.option_defaults {
let field = format!("{field}.optionDefaults.{id}");
if !model_options.contains(id) {
if !default_options.contains(id) {
return Err(invalid(
field,
"optionDefaults may only fill options declared with choicesFromModel.",
"optionDefaults may only fill choicesFromModel, text, file and directory options.",
));
}
select::validate(&rule.each, &format!("{field}.each"), false)?;
Expand Down
15 changes: 15 additions & 0 deletions rust/crates/build/src/manifest/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ use super::*;
pub(crate) struct OptionDeclaration {
pub(crate) id: String,
pub(crate) display_name: String,
/// What the option does, for the host's ⓘ next to it; display only.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) description: Option<String>,
pub(crate) kind: OptionKind,
/// Instance values belong to one detected root, never to its siblings.
#[serde(default, skip_serializing_if = "OptionScope::is_workspace")]
Expand Down Expand Up @@ -73,6 +76,15 @@ impl OptionDeclaration {
self.separator.as_deref().unwrap_or(DEFAULT_SEPARATOR)
}

/// Whether the option holds one free value (`text`, `file`, `directory`),
/// whose unset value the model may report as the tool's own.
pub(crate) fn is_text_like(&self) -> bool {
matches!(
self.kind,
OptionKind::Text | OptionKind::File | OptionKind::Directory
)
}

pub(crate) fn is_select(&self) -> bool {
matches!(
self.kind,
Expand Down Expand Up @@ -272,6 +284,9 @@ impl OptionDeclaration {
&format!("{field}.displayName"),
"display name",
)?;
if let Some(description) = &self.description {
super::run_types::check_description(description, &format!("{field}.description"))?;
}
let select = self.is_select();
if !select && (!self.choices.is_empty() || self.choices_from_model || self.allow_custom) {
return Err(invalid(
Expand Down
31 changes: 24 additions & 7 deletions rust/crates/build/src/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,9 @@ pub(crate) struct BuildModel {
pub(crate) content_roots: Vec<ModelContentRoot>,
/// Values the model offers for `choicesFromModel` options.
pub(crate) option_values: BTreeMap<String, Vec<String>>,
/// Subset of `option_values` the build tool activates when the option is unset.
/// What the build tool uses when an option is unset: the subset of
/// `option_values` it activates, or the one value of a text, file or
/// directory option.
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
pub(crate) option_defaults: BTreeMap<String, Vec<String>>,
/// Per-option prefix a `litheBuildModel` script supplies to turn a default choice off.
Expand Down Expand Up @@ -346,17 +348,25 @@ impl<'a> ModelBuilder<'a> {
}
}

/// Records a value the tool uses while `option` is unset: a choice it
/// activates, or the one value of a text, file or directory option (the
/// first reported wins, as the tool has only one).
fn add_option_default(&mut self, option: &str, value: &str) {
let accepted = self
.build_system
.option(option)
.is_some_and(|declaration| declaration.choices_from_model)
&& super::manifest::is_option_value(value);
if accepted {
let Some(declaration) = self.build_system.option(option) else {
return;
};
if !super::manifest::is_option_value(value) {
return;
}
if declaration.choices_from_model {
let values = self.option_defaults.entry(option.to_string()).or_default();
if values.len() < MAX_ITEMS {
values.insert(value.to_string());
}
} else if declaration.is_text_like() {
self.option_defaults
.entry(option.to_string())
.or_insert_with(|| BTreeSet::from([value.to_string()]));
}
}

Expand Down Expand Up @@ -477,6 +487,13 @@ impl<'a> ModelBuilder<'a> {
.option_defaults
.into_iter()
.filter_map(|(id, defaults)| {
if self
.build_system
.option(&id)
.is_some_and(|option| option.is_text_like())
{
return Some((id, defaults.into_iter().collect()));
}
let known = model.option_values.get(&id)?;
let kept: Vec<String> = defaults
.into_iter()
Expand Down
16 changes: 16 additions & 0 deletions rust/crates/build/src/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -543,6 +543,22 @@ pub(crate) fn describe_with_facts(
if option.scope == super::manifest::OptionScope::Instance {
entry["scope"] = json!("instance");
}
if let Some(description) = &option.description {
entry["description"] = json!(description);
}
if source == "unset" && option.is_text_like() {
// What the tool uses while the option is unset, as the model
// reported it (Maven's user settings file, its local
// repository). Display only: it contributes no argument, so
// the tool keeps deciding when its own configuration changes.
if let Some(value) = facts
.defaults
.and_then(|map| map.get(&option.id))
.and_then(|values| values.first())
{
entry["implicitValue"] = json!(value);
}
}
entry
})
.collect();
Expand Down
118 changes: 118 additions & 0 deletions rust/crates/core/src/tests/build_systems.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3447,6 +3447,124 @@ fn model_option_defaults_and_exclusions_round_trip_through_storage_and_plans() {
assert_eq!(after_restore["source"], "default");
}

/// A model reports what the tool uses for a text, file or directory option
/// the user left unset (Maven's user settings file and local repository), as
/// IDEA shows the effective path greyed out until the user overrides it. The
/// value is display only: it contributes no argument, and a user value or a
/// declared default replaces it.
#[test]
fn model_reports_the_implicit_value_of_unset_path_options() {
let workspace = TemporaryWorkspace::new("model-implicit-values");
let mut manifest = option_edit_fixture()["manifest"].clone();
manifest["buildSystems"][0]["options"]
.as_array_mut()
.unwrap()
.extend([
json!({"id": "settingsFile", "displayName": "User settings file", "kind": "file",
"description": "The settings.xml passed with -s.",
"arguments": ["-s", "${value}"]}),
json!({"id": "localRepository", "displayName": "Local repository", "kind": "directory",
"arguments": ["-Dmaven.repo.local=${value}"]}),
json!({"id": "threads", "displayName": "Threads", "kind": "text", "default": "1",
"arguments": ["-T", "${value}"]}),
json!({"id": "offline", "displayName": "Offline", "kind": "boolean",
"arguments": ["-o"]}),
]);
let canonical = json!({
"format": "litheBuildModel",
"version": 0,
"projects": [{"path": ".", "name": "demo"}],
"optionValues": {"profiles": ["dev"]},
"optionDefaults": {
"settingsFile": ["/home/me/.m2/settings.xml", "/ignored/second.xml"],
"localRepository": ["/home/me/.m2/repository"],
"threads": ["4"],
"offline": ["true"]
}
});
let decoded = build_decode_model_command::<Manifest>(json!({
"manifest": manifest,
"buildSystemID": "fixture",
"request": {"workspaceRoot": workspace.root(), "root": ".", "output": canonical.to_string()}
}))
.unwrap();
assert_eq!(decoded["status"], "ok", "{decoded}");
let defaults = &decoded["model"]["optionDefaults"];
// The tool has one value: the first reported is kept. A boolean option has
// no implicit value to report.
assert_eq!(
defaults["settingsFile"],
json!(["/home/me/.m2/settings.xml"]),
"{defaults}"
);
assert_eq!(
defaults["localRepository"],
json!(["/home/me/.m2/repository"])
);
assert!(defaults.get("offline").is_none(), "{defaults}");

let resolve = |options: Value| {
let resolved = build_resolve_options_command::<Manifest>(json!({
"manifest": manifest,
"buildSystemID": "fixture",
"request": {"options": options, "modelValues": decoded["model"]["optionValues"],
"modelDefaults": defaults}
}))
.unwrap();
resolved["options"]["options"].as_array().unwrap().clone()
};
let by_id = |options: &[Value], id: &str| {
options
.iter()
.find(|option| option["id"] == id)
.unwrap()
.clone()
};
let unset = resolve(json!({}));
let settings = by_id(&unset, "settingsFile");
assert_eq!(settings["source"], "unset", "{settings}");
assert_eq!(settings["value"], Value::Null);
assert_eq!(settings["implicitValue"], "/home/me/.m2/settings.xml");
assert_eq!(settings["description"], "The settings.xml passed with -s.");
assert_eq!(
by_id(&unset, "localRepository")["implicitValue"],
"/home/me/.m2/repository"
);
// A declared default is the effective value, so the model's is not shown.
let threads = by_id(&unset, "threads");
assert_eq!(threads["source"], "default");
assert!(threads.get("implicitValue").is_none(), "{threads}");
assert!(by_id(&unset, "offline").get("implicitValue").is_none());

let overridden = resolve(json!({"settingsFile": "/work/settings.xml"}));
let settings = by_id(&overridden, "settingsFile");
assert_eq!(settings["source"], "user");
assert_eq!(settings["value"], "/work/settings.xml");
assert!(settings.get("implicitValue").is_none(), "{settings}");
}

/// A model map may fill `optionDefaults` for choicesFromModel, text, file and
/// directory options only: a boolean or a declared select has no value the
/// tool picks on its own.
#[test]
fn model_map_option_defaults_name_choice_or_text_options() {
let mut manifest = fixture("build-static-file.plugin.json");
let system = &mut manifest["buildSystems"][0];
system["options"].as_array_mut().unwrap().extend([
json!({"id": "settingsFile", "displayName": "Settings", "kind": "file", "arguments": ["-s", "${value}"]}),
json!({"id": "goOffline", "displayName": "Offline", "kind": "boolean", "arguments": ["-o"]}),
]);
system["model"]["map"]["optionDefaults"] =
json!({"settingsFile": {"each": "/package", "value": "/settings"}});
let accepted = validate(manifest.clone());
assert_eq!(accepted["status"], "ok", "{accepted}");

manifest["buildSystems"][0]["model"]["map"]["optionDefaults"] =
json!({"goOffline": {"each": "/package", "value": "/offline"}});
let refused = validate(manifest);
assert_eq!(refused["status"], "rejected", "{refused}");
}

fn option_edit_fixture() -> Value {
serde_json::from_str(include_str!(
"../../../../fixtures/build/option-edit-v1.json"
Expand Down
11 changes: 8 additions & 3 deletions shared/plugins/contract/v1/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1938,7 +1938,7 @@ declaration are relative, use `/`, and stay inside their base directory
| `detection` | `markers` are file names; a directory holding one is a candidate root. Core searches at most 6 levels below the workspace root and skips the folders hidden by default (Core's own and the names enabled plugins declare, see `layout`), plus directories Git ignores: the rules come from the `.gitignore` files inside the workspace and the `info/exclude` of each repository whose root lies in it, not from directories above the workspace root, `core.excludesFile` or the index, so a tracked manifest below an ignored directory is not a candidate. Detection also skips the workspace's ignored paths, a Build option the user edits (`.gitignore` patterns stored in the team or machine-local Build options): by default every directory whose name starts with a dot, such as `.claude/worktrees`, and the user can list more or bring one back with `!`. `nesting: "outermost"` folds deeper candidates into the outer instance (Gradle builds, Maven reactors); `"separate"` (default) keeps each (Cargo packages). `priority` (0–100, default 50) decides between plugins declaring the same ID; ties go to the smaller plugin ID. |
| `invocation` | `executables` in preference order: `projectFile` (a wrapper inside the root, with `requires` files; always runs project code), `environment` (a path below a variable listed in `environmentInputs`), `command` (a bare name found on `PATH`), `runtime` (a declared runtime dependency itself). `platforms` limits a candidate. `globalArguments` precede every command. `version` probes the executable with literal `arguments` and a `pattern` whose first group is the version; `minimumVersion` needs a probe. |
| `runtimeDependencies` | Core knows no runtime by name; `node` and `go` follow the same rules as any other ID. A runtime without `executables` names the [tool definition](toolchains/README.md) with the same ID, so its `id` must be a valid tool-definition ID and it declares only `minimumVersion`: `build.invocationPlan` returns it with `version: null` and the single candidate `{ "kind": "toolchain", "toolchainID": <id>, "root": <root> }`, whose resolution checks `minimumVersion`, and `build.checkToolVersion` for it is `plugin.build.unavailable` because Core reads no version. Any other runtime describes its own `executables` and `version` probe, so the runtime list is open; a runtime whose only candidate is a `toolchain` candidate may omit the probe, since the definition checks the version. |
| `options` | Build dimensions the user chooses: `boolean`, `singleSelect`, `multiSelect`, `text`, `file`, `directory`. Each contributes `arguments` and `environment` (with `${value}`) when it has a value. Choices are declared, come from the model (`choicesFromModel`, with optional `optionDefaults` for choices the tool activates when unset), or are free (`allowCustom`); a `multiSelect` option may set `excludePrefix` (or report `optionExcludePrefixes` in `litheBuildModel`) so unchecking a default choice passes `<prefix><choice>`. |
| `options` | Build dimensions the user chooses: `boolean`, `singleSelect`, `multiSelect`, `text`, `file`, `directory`. Each contributes `arguments` and `environment` (with `${value}`) when it has a value. Choices are declared, come from the model (`choicesFromModel`, with optional `optionDefaults` for choices the tool activates when unset), or are free (`allowCustom`). A `text`, `file` or `directory` option may also get the value the tool uses while it is unset from the model's `optionDefaults` (Maven's user settings file, its local repository); `build.resolveOptions` returns it as `implicitValue` for display only, and it contributes no argument. `description` (1-512 characters) says what the option does, for the host's info icon; a `multiSelect` option may set `excludePrefix` (or report `optionExcludePrefixes` in `litheBuildModel`) so unchecking a default choice passes `<prefix><choice>`. |
| `provider` | The process that answers model and dependency requests when no command prints them; see [Build providers](#build-providers). |
| `model` | `static` (a `toml` file read during detection, no process), `command` (a command whose output Core decodes; it states `executesProjectCode` and `mayUseNetwork`), or `provider`. |
| `tasks` | The task catalog. `scopes` say what a task runs on (`workspace`, `project`, `target`); `targetTags` restrict targets; `requiresUserArguments` makes the host ask for arguments. A `fromModel` task is the template for tasks the model lists. |
Expand Down Expand Up @@ -2116,7 +2116,10 @@ for this invocation, including values activated outside the IDE's saved
options. Use an empty array if the tool reports that none are active. Omit the
entry when the tool cannot observe the active set. Report baseline defaults in
`optionDefaults`; Core restricts both sets to the available `optionValues` and
ties the observed set to the option fingerprint of the model load.
ties the observed set to the option fingerprint of the model load. For a
`text`, `file` or `directory` option, `optionDefaults: { <optionID>: [value] }`
is the value the tool uses while the option is unset; Core keeps the first
value and passes nothing for it.

Unknown fields in canonical documents are ignored, so a script may add fields
without a new version. Output that does not fit its decoder is `plugin.build.invalidOutput`.
Expand Down Expand Up @@ -2984,7 +2987,9 @@ manifest, the build-system ID, and a request, and revalidate the manifest
every time. `build.detect` walks the workspace once for all enabled plugins
and returns instances, with the model of `static` sources. `build.invocationPlan` and `build.checkToolVersion` resolve the
executable; `build.resolveOptions` checks stored option values and returns
the configuration fingerprint; `build.modelPlan`, `build.taskPlan`,
each option's value, `source` (`user`, `default` or `unset`), choices,
`description`, and, for an unset `text`, `file` or `directory` option, the
`implicitValue` the loaded model reported, with the configuration fingerprint; `build.modelPlan`, `build.taskPlan`,
`build.testPlan`, and `build.dependencyPlan` return argv plans, or provider
requests for a provider source;
`build.decodeModel`, `build.decodeTestResults`, `build.decodeDiagnostics`,
Expand Down
Loading
Loading