diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 5bcabdf3..70f4fd8c 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -517,6 +517,7 @@ or removing a command fails until the table changes in the same commit. | `outputLinks.match` | Find the links plugin `outputLinkMatchers` declare in Run or Test console lines, as UTF-16 ranges with candidate paths or a backend function to resolve them, and the web addresses the lines print, as `url` links the host opens in the browser | | `outputLinks.decodeResolution` | Check a matcher's `resolve` function reply and return the 1-based file location to open, or `null` | | `build.detect` | Find every build-system instance the enabled plugins declare in a workspace, with models that need no process | +| `build.localizeOptions` | Return the enabled build plugins' manifests with their option text in the interface language, naming the translation files to read first | | `build.projectOptions` | Validate a native team's persisted Build options | | `build.resolveStoredOptions` | Merge checked team and machine-local Build preferences without I/O | | `build.editStoredOption` | Edit one declared option in a machine-local Build document without I/O | @@ -5285,6 +5286,7 @@ user to trust the workspace before an action the user started. | Command | Request | Result | | --- | --- | --- | | `build.detect` | `{ workspaceRoot, plugins: [{ manifest }], options?: { : { : value } }, instanceOptions?: { : { : { : value } } }, instanceDefaults?: { : { : value } }, emptySelections?: { : { : [optionID] } }, ignoredPaths?: [pattern] }` | `detection`: `{ instances, rejected: [{ index, error }], shadowed: [{ pluginID, buildSystemID, by }] }`; each instance is `{ id, pluginID, buildSystemID, displayName, root, markers, modelSource, optionFingerprint, options, droppedOptions }` plus `model` or `modelError` for `static` and `hostIntegration` sources; a `provider` source has neither. `options` contains accepted stored values after Core scope/root merging, including explicit empty selections; `droppedOptions` names rejected stored values without rewriting the source document. The scan does not enter a directory `ignoredPaths` names; omitted (or `null`), it is Core's default `[".*"]`, every directory whose name starts with a dot, and `[]` ignores nothing beyond the shared scan policy. Hosts pass `storage.ignoredPaths.patterns` from `build.resolveStoredOptions`. An unusable list rejects with `plugin.build.invalidIgnoredPath` (see `build.editIgnoredPaths`). | +| `build.localizeOptions` | `{ language?, plugins: [{ manifest, localizations? }] }`, without the standard manifest/build-system wrapper | `{ manifests, localizations }`: one manifest per plugin in request order, with the `buildOptions` part of the first accepted translation file applied to `buildSystems[].options[]` (`displayName`, `description`, choice `title`), else as sent; one report per plugin that declares a build option when `language` is set, `{ pluginID, language, candidates, maximumBytes, readRequired, applied, rejected }` as in `plugins.settings`. Hosts send it without `localizations`, read the named candidates from the installed package, send it again with them, and detect with the returned manifests. A file that does not fit is refused whole as `plugin.build.invalidLocalization` | | `build.projectOptions` | `{ document }`, host-read persisted v1 Build options, without a manifest | `document`: validated storage with version 1, systems and optional `ignoredPaths`; options, instance defaults, root values, explicit empty selections and saved custom choices are retained. Missing system fields normalize to empty maps; malformed, unsupported or oversized documents reject with `plugin.build.invalidOptionsDocument`. This pure operation never reads or writes a file and does not replace declared option resolution. | | `build.resolveStoredOptions` | `{ document, local: { version: 1, document, emptySelections?: { : { : [optionID] } } } }`, without a manifest | `storage: { document, local, emptySelections, ignoredPaths: { patterns, source } }`: checked team/local merge; local values override matching keys, unrelated systems/roots/choices stay intact. `ignoredPaths` is the list `build.detect` uses: a local list replaces the team's whole (`source: "local"`), then the team's (`"team"`), then Core's default `[".*"]` (`"default"`). No filesystem I/O. Local documents are machine/workspace preferences, not team files or plugin-native configuration. Their storage syntax is [build-local-options-v1.schema.json](build-local-options-v1.schema.json), with additional cross-field membership and byte limits checked by Core. | | `build.editStoredOption` | `{ document, local, root, optionID, value?, selectedChoices?, modelValues?, modelDefaults?, modelExcludePrefixes?, modelSelection? }` in the standard manifest/build-system envelope | `edit: { local, options }`: changes one declared local preference. Pass exactly one of raw `value` or positive `selectedChoices` for a multi-select. Explicit `value: null` removes the local override. When the checked set equals the defaults, Core clears the local override only if the edited root would inherit those defaults and sibling-only selections and empty markers would survive. See [the option edit fixture](../fixtures/build/option-edit-v1.json). Invalid or partially accepted edits reject before persistence. Workspace multi-selections preserve sibling-only values; explicit per-root empty markers apply only to workspace multi-select declarations. Platforms compare both native source revisions, atomically write only the local document and read back. | @@ -5292,7 +5294,7 @@ user to trust the workspace before an action the user started. | `build.invocationPlan` | `{ root, platform: "macos" \| "linux" \| "windows" }` | `invocation`: `{ buildSystemID, root, executables, environmentInputs, runtimeDependencies, version, minimumVersion }` with project-file paths joined to `root`; every runtime dependency with a known probe, host-managed ones included, carries `version: { arguments }` | | `build.checkToolVersion` | `{ runtime?, output }` | `version`: `{ satisfied, version? }`; `runtime` checks that runtime dependency instead of the tool | | `build.resolveModelInputs` | `{revision, sources: [{manifest, instances: [{buildSystemID, root, state, model?, options?}]}]}` from installed enabled current-workspace sources | `modelInputs`: version 1 public snapshot with exact optional producer slots, state, normalized projects/targets/content roots, configuration fingerprint and explicitly shared options; no tasks/run/settings/private functions; see the [plugin contract](../../shared/plugins/contract/v1/README.md#optional-read-only-model-inputs) | -| `build.resolveOptions` | `{ options?, inheritedOptions?, selectedChoices?, modelValues?, modelDefaults?, modelExcludePrefixes?, modelSelection? }` | `options`: `{ options: [{ id, displayName, kind, scope?, value, selectedChoices?, source, choices: [{ value, title?, fromModel?, custom?, defaultActive? }], allowCustom }], dropped, fingerprint }` | +| `build.resolveOptions` | `{ options?, inheritedOptions?, selectedChoices?, modelValues?, modelDefaults?, modelExcludePrefixes?, modelSelection? }` | `options`: `{ options: [{ id, displayName, description?, kind, scope?, value, selectedChoices?, source, implicitValue?, choices: [{ value, title?, fromModel?, custom?, defaultActive? }], allowCustom }], dropped, fingerprint }`; `implicitValue` is the value a model reported in `optionDefaults` for a `text`, `file` or `directory` option without a declared `default`, display only | | `build.configurationPlan` | plan fields and optional host-selected `tool` | `plan.provider` for `lithe/build/configuration`; no mutation, project or output-file parameters | | `build.decodeConfiguration` | `{ result }` | `configuration`: bounded `litheBuildConfiguration` v1 native sources/fields; see the plugin contract | | `build.configurationEditPlan` | `{ root, options?, workspaceStateDirectory, outputFile, snapshot, edits: { sourceID, revision, values }, tool? }` | Provider request `lithe/build/editConfiguration`; existing private staging only, no document bytes | diff --git a/rust/crates/build/src/lib.rs b/rust/crates/build/src/lib.rs index de03b8a3..c3675481 100644 --- a/rust/crates/build/src/lib.rs +++ b/rust/crates/build/src/lib.rs @@ -25,6 +25,7 @@ mod invocation; mod manifest; mod model; mod model_inputs; +mod option_text; mod options; mod outputs; mod plans; @@ -46,6 +47,7 @@ pub use manifest::{ activation_event, programs, validate_declarations, BuildSystemDeclaration, DeclarationContext, ProviderProcess, }; +pub use option_text::build_localize_options_command; pub use project_options::project_options_command; pub use run_start::run_decode_start_command; pub use run_types::{declared_run_types, RunTypePlugin, RunTypePlugins}; diff --git a/rust/crates/build/src/option_text.rs b/rust/crates/build/src/option_text.rs new file mode 100644 index 00000000..5343c10b --- /dev/null +++ b/rust/crates/build/src/option_text.rs @@ -0,0 +1,272 @@ +//! Translated text of build options: `build.localizeOptions`. +//! +//! A build plugin's options are named in its manifest, in the plugin's +//! language. The host shows them in the option dialogs, the run +//! configuration editor, the toolbar toggles and the tree's option nodes, +//! all read from the manifest of the detected instance. So the translation +//! is applied to the manifest itself, before detection: the host sends the +//! enabled build plugins' manifests with the interface language, Core names +//! the translation files each may read (`l10n/.json`, as for +//! settings and run configuration types), the host reads them from the +//! installed package and asks again, and Core returns every manifest with +//! the option text of its `buildOptions` section replaced. +//! +//! A translation replaces only text the manifest has: an option's +//! `displayName`, its `description` and the titles of its declared choices. +//! It never renames, adds or reorders anything, and every text keeps the +//! manifest's limits, so a translated manifest validates and plans exactly +//! as the original. A file that does not fit is refused whole and reported; +//! the manifest keeps its wording. + +use super::manifest::{check_description, check_text, BuildSystemDeclaration, OptionDeclaration}; +use super::BuildManifest; +use lithe_plugin_model::settings::{parse_localization_file, present, LocalizationRequest}; +use lithe_plugin_model::{PluginRejection, Validation}; +use lithe_protocol::json_document::UniqueMap; +use lithe_protocol::{CoreError, ErrorCode}; +use serde::Deserialize; +use serde_json::{json, Value}; +use std::collections::BTreeMap; + +/// Error code of a translation file Core did not apply. +const INVALID_LOCALIZATION: &str = "plugin.build.invalidLocalization"; +/// Most plugins one request may name. +const MAX_PLUGINS: usize = 512; + +/// The `build.localizeOptions` request: the enabled build plugins and the +/// interface language. +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct LocalizeOptionsRequest { + /// Interface language; absent returns the manifests unchanged. + #[serde(default)] + language: Option, + plugins: Vec, +} + +/// One enabled plugin. +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct OptionPlugin { + manifest: Value, + /// The translation files the native adapter read, by package-relative + /// path; absent until it has read the candidates a report names. + #[serde(default)] + localizations: Option>, +} + +/// `build.localizeOptions`: `{manifests, localizations}`. `manifests` has +/// one entry per plugin, in request order: the manifest with its option text +/// translated, or as sent when there is nothing to translate or it does not +/// validate (detection skips such a manifest anyway). `localizations` has +/// one report per plugin that declares a build option, when a language is +/// named: `{pluginID, language, candidates, maximumBytes, readRequired, +/// applied, rejected}`, the report of `plugins.settings`. +pub fn build_localize_options_command( + payload: Value, +) -> Result { + let request: LocalizeOptionsRequest = + lithe_plugin_model::decode_payload(payload, "build.localizeOptions")?; + if request.plugins.len() > MAX_PLUGINS { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Too many plugins in the build option localization request", + )); + } + let mut manifests = Vec::with_capacity(request.plugins.len()); + let mut reports = Vec::new(); + for plugin in request.plugins { + let localization = + LocalizationRequest::new(request.language.as_deref(), plugin.localizations.as_ref()) + .map_err(|message| { + CoreError::new( + ErrorCode::InvalidRequest, + "Invalid build option localization request", + ) + .with_details(message) + })?; + let Some(localization) = localization else { + manifests.push(plugin.manifest); + continue; + }; + let Ok(validated) = M::validate(plugin.manifest.clone()) else { + manifests.push(plugin.manifest); + continue; + }; + let systems: Vec<&BuildSystemDeclaration> = validated + .build_systems() + .iter() + .filter(|system| !system.options.is_empty()) + .collect(); + if systems.is_empty() { + manifests.push(plugin.manifest); + continue; + } + let (chosen, mut report) = localization.select_with(|text| decode_file(text, &systems)); + report["pluginID"] = json!(validated.id()); + reports.push(report); + let mut manifest = plugin.manifest; + if let Some(texts) = chosen { + apply(&mut manifest, &texts); + } + manifests.push(manifest); + } + Ok(json!({ "manifests": manifests, "localizations": reports })) +} + +/// The part of a translation file this module reads: +/// `buildOptions..`. Other top-level keys belong to +/// other surfaces. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct LocalizationFile { + #[serde(default)] + build_options: UniqueMap>, +} + +/// Translated text of one option, by the manifest field it replaces. +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct OptionText { + #[serde(default, deserialize_with = "present")] + display_name: Option, + #[serde(default, deserialize_with = "present")] + description: Option, + /// Choice titles by declared choice value. + #[serde(default, deserialize_with = "present")] + choices: Option>, +} + +/// Checked option text of one plugin, by build system and option ID. +type OptionTexts = BTreeMap<(String, String), OptionText>; + +/// Parses one translation file and checks it against the declarations: it +/// names only declared build systems, options and choices, translates only +/// text the manifest has, and every text fits the manifest's limits. +fn decode_file(text: &str, systems: &[&BuildSystemDeclaration]) -> Validation { + let file: LocalizationFile = parse_localization_file(text, INVALID_LOCALIZATION)?; + let mut texts = OptionTexts::new(); + for (system_id, options) in file.build_options.0 { + let field = format!("buildOptions.{system_id}"); + let system = systems + .iter() + .find(|system| system.id == system_id) + .ok_or_else(|| { + rejection( + &field, + "The plugin declares no build system with options under this ID.", + ) + })?; + for (option_id, text) in options.0 { + let field = format!("{field}.{option_id}"); + let declaration = system.option(&option_id).ok_or_else(|| { + rejection(&field, "The build system declares no option with this ID.") + })?; + check_option_text(&text, declaration, &field)?; + texts.insert((system_id.clone(), option_id), text); + } + } + Ok(texts) +} + +fn check_option_text( + text: &OptionText, + declaration: &OptionDeclaration, + field: &str, +) -> Validation<()> { + if let Some(name) = &text.display_name { + relabel(check_text( + name, + &format!("{field}.displayName"), + "display name", + ))?; + } + if let Some(description) = &text.description { + let field = format!("{field}.description"); + if declaration.description.is_none() { + return Err(rejection( + field, + "The manifest has no text here to translate.", + )); + } + relabel(check_description(description, &field))?; + } + for (value, title) in text.choices.iter().flat_map(|choices| &choices.0) { + let field = format!("{field}.choices.{value}"); + if !declaration + .choices + .iter() + .any(|choice| &choice.value == value) + { + return Err(rejection( + &field, + "The option declares no choice with this value.", + )); + } + relabel(check_text(title, &field, "title"))?; + } + Ok(()) +} + +/// Replaces the option text of `manifest` in place. The manifest validated, +/// so its build systems and options are the objects the checks read. +fn apply(manifest: &mut Value, texts: &OptionTexts) { + let Some(systems) = manifest + .get_mut("buildSystems") + .and_then(Value::as_array_mut) + else { + return; + }; + for system in systems { + let Some(system_id) = system.get("id").and_then(Value::as_str).map(str::to_owned) else { + continue; + }; + let Some(options) = system.get_mut("options").and_then(Value::as_array_mut) else { + continue; + }; + for option in options { + let Some(option_id) = option.get("id").and_then(Value::as_str) else { + continue; + }; + let Some(text) = texts.get(&(system_id.clone(), option_id.to_owned())) else { + continue; + }; + if let Some(name) = &text.display_name { + option["displayName"] = json!(name); + } + if let Some(description) = &text.description { + option["description"] = json!(description); + } + let Some(titles) = &text.choices else { + continue; + }; + for choice in option + .get_mut("choices") + .and_then(Value::as_array_mut) + .into_iter() + .flatten() + { + let title = choice + .get("value") + .and_then(Value::as_str) + .and_then(|value| titles.0.get(value)) + .cloned(); + if let Some(title) = title { + choice["title"] = json!(title); + } + } + } + } +} + +/// A manifest check's rejection, as a rejection of the translation file. +fn relabel(result: Validation<()>) -> Validation<()> { + result.map_err(|error| PluginRejection { + code: INVALID_LOCALIZATION, + ..error + }) +} + +fn rejection(field: impl Into, message: impl Into) -> PluginRejection { + PluginRejection::at(INVALID_LOCALIZATION, field, message) +} diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 00c235ec..bfca6d85 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -436,6 +436,8 @@ pub enum ToolchainsCommand { pub enum BuildCommand { /// Finds the build-system instances of a workspace (`build.detect`). Detect, + /// Translates the option text of build plugins' manifests (`build.localizeOptions`). + LocalizeOptions, /// Validates a native team's persisted Build options (`build.projectOptions`). ProjectOptions, /// Merges checked team and machine-local Build preferences without I/O. @@ -1186,6 +1188,7 @@ impl CoreCommand { "outputLinks.match" => Some(Self::OutputLinksMatch), "outputLinks.decodeResolution" => Some(Self::OutputLinksDecodeResolution), "build.detect" => Some(Self::Build(BuildCommand::Detect)), + "build.localizeOptions" => Some(Self::Build(BuildCommand::LocalizeOptions)), "build.projectOptions" => Some(Self::Build(BuildCommand::ProjectOptions)), "build.resolveStoredOptions" => Some(Self::Build(BuildCommand::ResolveStoredOptions)), "build.editStoredOption" => Some(Self::Build(BuildCommand::EditStoredOption)), diff --git a/rust/crates/core/src/runtime/dispatcher/build.rs b/rust/crates/core/src/runtime/dispatcher/build.rs index 3b4e0056..9e6ed791 100644 --- a/rust/crates/core/src/runtime/dispatcher/build.rs +++ b/rust/crates/core/src/runtime/dispatcher/build.rs @@ -12,6 +12,11 @@ pub(super) fn dispatch(command: BuildCommand, id: Option, payload: Value BuildCommand::Detect => { plugin_response(id, payload, crate::build::build_detect_command::) } + BuildCommand::LocalizeOptions => plugin_response( + id, + payload, + crate::build::build_localize_options_command::, + ), BuildCommand::ProjectOptions => { plugin_response(id, payload, crate::build::project_options_command) } diff --git a/rust/crates/core/src/tests/build_systems.rs b/rust/crates/core/src/tests/build_systems.rs index a563aecb..220210fe 100644 --- a/rust/crates/core/src/tests/build_systems.rs +++ b/rust/crates/core/src/tests/build_systems.rs @@ -3566,6 +3566,120 @@ fn model_map_option_defaults_name_choice_or_text_options() { assert_eq!(refused["status"], "rejected", "{refused}"); } +/// A plugin's translation file names its build options in the interface +/// language: Core names the files to read, then returns the manifest with +/// the option text replaced, so every surface that reads the manifest shows +/// it. A file that names an undeclared option or adds text the manifest +/// lacks is refused whole, and the manifest keeps its wording. +#[test] +fn build_option_text_is_translated_in_the_manifest() { + use crate::build::build_localize_options_command; + let mut manifest = option_edit_fixture()["manifest"].clone(); + manifest["buildSystems"][0]["options"] + .as_array_mut() + .unwrap() + .extend([ + json!({"id": "settingsFile", "displayName": "Settings File", "kind": "file", + "description": "The user settings file passed with -s.", + "arguments": ["-s", "${value}"]}), + json!({"id": "checksums", "displayName": "Checksums", "kind": "singleSelect", + "choices": [{"value": "warn", "title": "Warn"}, {"value": "fail", "title": "Fail"}], + "arguments": ["--checksums=${value}"]}), + ]); + let localize = |localizations: Option| { + let mut plugin = json!({"manifest": manifest}); + if let Some(files) = localizations { + plugin["localizations"] = files; + } + build_localize_options_command::( + json!({"language": "zh-Hans", "plugins": [plugin]}), + ) + .unwrap() + }; + let option = |result: &Value, id: &str| { + result["manifests"][0]["buildSystems"][0]["options"] + .as_array() + .unwrap() + .iter() + .find(|option| option["id"] == id) + .unwrap() + .clone() + }; + + let first = localize(None); + let report = &first["localizations"][0]; + assert_eq!( + report["pluginID"], "dev.lithe.test.build-option-edit", + "{first}" + ); + assert_eq!(report["readRequired"], true); + assert_eq!( + first["manifests"][0], manifest, + "nothing is translated before the files are read" + ); + let path = report["candidates"][0].as_str().unwrap().to_string(); + + let file = json!({"buildOptions": {"fixture": { + "settingsFile": {"displayName": "用户设置文件", "description": "用 -s 传入的用户设置文件。"}, + "checksums": {"displayName": "校验和", "choices": {"fail": "失败"}} + }}}); + let translated = localize(Some(json!({ &path: file.to_string() }))); + assert_eq!( + translated["localizations"][0]["applied"], + json!(path), + "{translated}" + ); + let settings = option(&translated, "settingsFile"); + assert_eq!(settings["displayName"], "用户设置文件"); + assert_eq!(settings["description"], "用 -s 传入的用户设置文件。"); + let checksums = option(&translated, "checksums"); + assert_eq!(checksums["displayName"], "校验和"); + assert_eq!( + checksums["choices"], + json!([{"value": "warn", "title": "Warn"}, {"value": "fail", "title": "失败"}]) + ); + // The translated manifest is still a valid manifest with the same options. + let validated = validate(translated["manifests"][0].clone()); + assert_eq!(validated["status"], "ok", "{validated}"); + + for (broken, what) in [ + ( + json!({"buildOptions": {"fixture": {"unknown": {"displayName": "x"}}}}), + "an undeclared option", + ), + ( + json!({"buildOptions": {"fixture": {"profiles": {"description": "x"}}}}), + "text the manifest lacks", + ), + ( + json!({"buildOptions": {"fixture": {"checksums": {"choices": {"skip": "x"}}}}}), + "an undeclared choice", + ), + ( + json!({"buildOptions": {"other": {"profiles": {"displayName": "x"}}}}), + "an undeclared build system", + ), + ] { + let refused = localize(Some(json!({ &path: broken.to_string() }))); + let report = &refused["localizations"][0]; + assert_eq!(report["applied"], Value::Null, "{what}: {refused}"); + assert_eq!( + report["rejected"][0]["error"]["code"], "plugin.build.invalidLocalization", + "{what}" + ); + assert_eq!( + refused["manifests"][0], manifest, + "{what} changed the manifest" + ); + } + + // Without a language the manifests come back as sent and nothing is read. + let plain = + build_localize_options_command::(json!({"plugins": [{"manifest": manifest}]})) + .unwrap(); + assert_eq!(plain, json!({"manifests": [manifest], "localizations": []})); +} + fn option_edit_fixture() -> Value { serde_json::from_str(include_str!( "../../../../fixtures/build/option-edit-v1.json" diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 0afb32da..4e7f6194 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -852,6 +852,7 @@ in `fixtures/settings/localization-cases.json`. | `settingRegions.` | `keywords`: 1–32 search words added to the region's declared ones. The view's own text is not translated here: each view event carries the interface language. | | `runConfigurationTypes..` | A [run configuration type](#run-configuration-types)'s `displayName` and `description`, and `fields.` with a field's `title`, `description`, `placeholder`, and `options.`; refused as `plugin.build.invalidLocalization` | | `beforeLaunchTasks..` | A [before-launch task](#before-launch-tasks)'s text, shaped like `runConfigurationTypes`; refused as `plugin.build.invalidLocalization` | +| `buildOptions..` | A [build option](#build-systems)'s `displayName` and `description`, and `choices.` with a declared choice's `title`; Core applies it to the manifest before detection (`build.localizeOptions`), so the option dialogs, toolbar toggles and tree nodes show it; refused as `plugin.build.invalidLocalization` | Every member is optional, and text a file leaves out stays as `plugin.json` writes it. IDs, option values and their order, stored values, and the grouping @@ -1938,7 +1939,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": , "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 `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 ``. | +| `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; `displayName`, `description` and choice titles are translated through the `buildOptions` part of a [translation file](#translations); a `multiSelect` option may set `excludePrefix` (or report `optionExcludePrefixes` in `litheBuildModel`) so unchecking a default choice passes ``. | | `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. | @@ -2986,7 +2987,7 @@ The `build.*` Core commands (see `rust/contracts/rust-core-api.md`) take the 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 +executable; `build.localizeOptions` applies the `buildOptions` translations to the manifests before detection; `build.resolveOptions` checks stored option values and returns each option's value, `source` (`user`, `default` or `unset`), choices, `description`, and, for a `text`, `file` or `directory` option without a declared `default`, the `implicitValue` the loaded model reported (also while @@ -4866,7 +4867,7 @@ command payload is a Core `invalid_request` failure instead. | `plugin.build.untrustedWorkspace` | Core | The plan would run project code and the user has not trusted the workspace; see [Workspace trust](#workspace-trust) | | `plugin.build.invalidRunConfiguration` | Core | A saved configuration of a [run configuration type](#run-configuration-types) holds a value the type no longer accepts; `field` is `values.` | | `plugin.build.invalidBeforeLaunchTask` | Core | A step of a [before-launch task](#before-launch-tasks) holds a value the task no longer accepts; `field` is `values.` | -| `plugin.build.invalidLocalization` | Core | The `runConfigurationTypes` or `beforeLaunchTasks` part of a [translation file](#translations) does not fit the declarations; the host shows the next candidate or the manifest text | +| `plugin.build.invalidLocalization` | Core | The `runConfigurationTypes`, `beforeLaunchTasks` or `buildOptions` part of a [translation file](#translations) does not fit the declarations; the host shows the next candidate or the manifest text | | `plugin.launch.invalidRequest` | Core | A launch plan request has an unusable directory or an unknown architecture | | `plugin.launch.notBackend` | Core | `decodeLaunch` named a language server that the plugin backend does not launch | | `plugin.launch.invalidResult` | Core | A [backend-resolved launch](#backend-resolved-launch) answer is malformed, unknown in a field, or over a bound | diff --git a/shared/plugins/contract/v1/plugin-l10n.schema.json b/shared/plugins/contract/v1/plugin-l10n.schema.json index f34c253c..aa810126 100644 --- a/shared/plugins/contract/v1/plugin-l10n.schema.json +++ b/shared/plugins/contract/v1/plugin-l10n.schema.json @@ -61,6 +61,16 @@ "propertyNames": { "pattern": "^[a-z][a-z0-9-]*(?![\\s\\S])", "maxLength": 64 }, "additionalProperties": { "$ref": "#/$defs/runTypeText" } } + }, + "buildOptions": { + "description": "Text of buildSystems[].options, by build system ID, then option ID. Core applies it to the manifest (build.localizeOptions), so every surface that shows an option shows it translated.", + "type": "object", + "propertyNames": { "pattern": "^[a-z][a-z0-9-]*(?![\\s\\S])", "maxLength": 64 }, + "additionalProperties": { + "type": "object", + "propertyNames": { "pattern": "^[a-z][A-Za-z0-9]*(?![\\s\\S])", "maxLength": 120 }, + "additionalProperties": { "$ref": "#/$defs/optionText" } + } } }, "$defs": { @@ -131,6 +141,21 @@ "maxLength": 512, "pattern": "\\S" }, + "optionText": { + "description": "Each member replaces the field of the same name; plugin.json must have that field.", + "type": "object", + "additionalProperties": false, + "properties": { + "displayName": { "$ref": "#/$defs/label" }, + "description": { "$ref": "#/$defs/runTypeDescription" }, + "choices": { + "description": "Titles of declared choices, by choice value.", + "type": "object", + "propertyNames": { "minLength": 1, "maxLength": 256 }, + "additionalProperties": { "$ref": "#/$defs/label" } + } + } + }, "actionText": { "description": "Each member replaces the field of the same name; plugin.json must have that field.", "type": "object", diff --git a/shared/plugins/reference/domains/build-systems.md b/shared/plugins/reference/domains/build-systems.md index 8ab5ee5c..b093a93e 100644 --- a/shared/plugins/reference/domains/build-systems.md +++ b/shared/plugins/reference/domains/build-systems.md @@ -57,7 +57,7 @@ - **选项范围。** 选项可以声明 `scope: "instance"`,按检测到的每个根目录分别保存:改动或重置 `a` 不会影响 `b`。省略范围(或 `"workspace"`)使用工作区和构建系统存储。显式的 `false`、`""`、`[]` 仍然是用户保存的值。实例值不能覆盖工作区选项,工作区值也不能悄悄覆盖实例选项。示例:`build-instance-options`。 - **可执行文件解析。** `invocation.executables` 按偏好顺序列出来源:`projectFile`(项目里的包装脚本,总是运行项目代码)、`environment`、`command`(`PATH` 上的命令名)、`runtime`、`setting`(引用声明为 `file` 的全局设置)和 `toolchain`(工具定义 ID)。可以用 `id`、`priority`、`insertBefore`、`insertAfter` 调整同一个候选集内的顺序。用户配置的路径失败是终止性的,不会回退到后面的候选或提供者自己的查找。示例:`build-tool-path`(`setting`)、`build-toolchains`(`toolchain`)。规则见[可执行文件解析](../../contract/v1/README.md#executable-resolution)。 -- **展示。** 每个启用的构建系统有自己的工具窗口,由宿主按模型绘制;`options[].presentation` 把布尔选项放到工具栏(`toolbar`,需要 `icon`)或把多选选项放成树顶部的清单(`tree`),`tasks[].category` 给任务归类。模型可以通过 `optionDefaults` 给出未设置时默认激活的多选候选,并通过 `options[].excludePrefix` 或 `litheBuildModel` 的 `optionExcludePrefixes` 声明取消默认激活项的前缀(如 `"-"`),Core 负责把勾选集合编码成存储值并在树顶生成 `option` 与 `optionChoice` 节点。`text`、`file`、`directory` 选项也可以由模型在 `optionDefaults` 里报告未设置时工具实际使用的值(如 Maven 的用户设置文件和本地仓库),`build.resolveOptions` 以 `implicitValue` 返回,宿主只用来显示“实际生效值”,不会据此传参数;选项的 `description` 是宿主 ⓘ 里的说明。树由 Core 统一排布:项目按 `parentID` 嵌套,每个项目下依次是它的任务文件夹、依赖、目标和子项目;只作用于整个工作区的任务、依赖和测试在根项目旁边只出现一次;只有一个根项目时,它的内容直接作为构建系统的内容,任务仍在根项目上运行。 +- **展示。** 每个启用的构建系统有自己的工具窗口,由宿主按模型绘制;`options[].presentation` 把布尔选项放到工具栏(`toolbar`,需要 `icon`)或把多选选项放成树顶部的清单(`tree`),`tasks[].category` 给任务归类。模型可以通过 `optionDefaults` 给出未设置时默认激活的多选候选,并通过 `options[].excludePrefix` 或 `litheBuildModel` 的 `optionExcludePrefixes` 声明取消默认激活项的前缀(如 `"-"`),Core 负责把勾选集合编码成存储值并在树顶生成 `option` 与 `optionChoice` 节点。`text`、`file`、`directory` 选项也可以由模型在 `optionDefaults` 里报告未设置时工具实际使用的值(如 Maven 的用户设置文件和本地仓库),`build.resolveOptions` 以 `implicitValue` 返回,宿主只用来显示“实际生效值”,不会据此传参数;选项的 `description` 是宿主 ⓘ 里的说明。选项的 `displayName`、`description` 和固定选项值的标题可以在包内翻译文件的 `buildOptions.<构建系统 ID>.<选项 ID>` 里翻译,宿主在检测前经 `build.localizeOptions` 换到清单里,所以选项对话框、工具栏开关和构建树都显示译文。树由 Core 统一排布:项目按 `parentID` 嵌套,每个项目下依次是它的任务文件夹、依赖、目标和子项目;只作用于整个工作区的任务、依赖和测试在根项目旁边只出现一次;只有一个根项目时,它的内容直接作为构建系统的内容,任务仍在根项目上运行。 - **项目准备任务。** 项目任务可以声明 `preparation: { purpose, sourceRoles }`,按用途(如 `run`)和内容根角色绑定运行前要执行的任务;宿主从当前模型选出最深的所属项目和内容根,要求恰好一个匹配的声明,不猜任务名,也不回退到约定的任务 ID。示例:`build-providers/build-provider-preparation`。 - **只读模型输入。** 生产者用 `modelSharing: { options: [...] }` 公开规范化的项目、目标和内容根(以及明确列出的普通选项的有效值),消费者用 `modelInputs: [{ pluginID, buildSystemID }]` 读取,最多 8 个槽位。缺失、被禁用或不公开的生产者只会让该槽位 `unavailable`,从不被自动安装或激活;一个生产者不能同时是消费者。示例:`build-model-producer`、`build-model-consumer`。 @@ -159,7 +159,7 @@ A build system's `hostIntegration` and a language server's `hostIntegration` are - **Option scope.** An option may declare `scope: "instance"`, stored separately per detected root: changing or resetting `a` cannot change `b`. Omitting the scope (or `"workspace"`) uses the workspace and build-system storage. Explicit `false`, `""`, and `[]` remain stored user values. Instance values cannot override workspace options, and workspace values cannot silently override an instance option. Example: `build-instance-options`. - **Executable resolution.** `invocation.executables` lists sources in preference order: `projectFile` (a wrapper inside the project; always runs project code), `environment`, `command` (a bare name on `PATH`), `runtime`, `setting` (references a declared global `file` setting), and `toolchain` (a tool-definition ID). `id`, `priority`, `insertBefore`, and `insertAfter` reorder candidates within one candidate set. A configured path that fails is terminal and never falls back to later candidates or to the provider's own lookup. Examples: `build-tool-path` (`setting`) and `build-toolchains` (`toolchain`). The rules are in [Executable resolution](../../contract/v1/README.md#executable-resolution). -- **Presentation.** Every enabled build system gets a tool window of its own, drawn by the host from the model; `options[].presentation` puts a boolean option on the toolbar (`toolbar`, needs an `icon`) or a multiSelect option as a checklist at the top of the tree (`tree`), and `tasks[].category` files a task under headings. A model may also report choices active when the option is unset (`optionDefaults`) and a prefix that turns a default choice off (`options[].excludePrefix` or `optionExcludePrefixes` in `litheBuildModel`, such as `"-"`), so Core encodes the checked set and places `option` and `optionChoice` nodes at the top of the tree. A `text`, `file` or `directory` option may also have the value the tool uses while it is unset reported in `optionDefaults` (Maven's user settings file and local repository); `build.resolveOptions` returns it as `implicitValue`, which the host shows as the effective value and never passes as an argument. An option's `description` is the text of the host's info icon. Core lays out the tree the same way for every tool: projects nest by `parentID`, and each project lists its task folders, its dependencies, its targets and then its child projects; tasks, dependencies and tests that act on the whole workspace appear once, beside the root projects. With a single root project, its contents become the build system's own, and its tasks still run on the root project. +- **Presentation.** Every enabled build system gets a tool window of its own, drawn by the host from the model; `options[].presentation` puts a boolean option on the toolbar (`toolbar`, needs an `icon`) or a multiSelect option as a checklist at the top of the tree (`tree`), and `tasks[].category` files a task under headings. A model may also report choices active when the option is unset (`optionDefaults`) and a prefix that turns a default choice off (`options[].excludePrefix` or `optionExcludePrefixes` in `litheBuildModel`, such as `"-"`), so Core encodes the checked set and places `option` and `optionChoice` nodes at the top of the tree. A `text`, `file` or `directory` option may also have the value the tool uses while it is unset reported in `optionDefaults` (Maven's user settings file and local repository); `build.resolveOptions` returns it as `implicitValue`, which the host shows as the effective value and never passes as an argument. An option's `description` is the text of the host's info icon. An option's `displayName`, `description` and declared choice titles may be translated under `buildOptions..` in the package's translation files; the host applies them to the manifest through `build.localizeOptions` before detection, so the option dialogs, toolbar toggles and tree show them. Core lays out the tree the same way for every tool: projects nest by `parentID`, and each project lists its task folders, its dependencies, its targets and then its child projects; tasks, dependencies and tests that act on the whole workspace appear once, beside the root projects. With a single root project, its contents become the build system's own, and its tasks still run on the root project. - **Project preparation tasks.** A project task may declare `preparation: { purpose, sourceRoles }`, binding the task to run first by purpose (such as `run`) and content-root role. The host selects the deepest owning project and content root from the current model, requires exactly one matching declaration, never guesses a task name, and never falls back to a conventional task ID. Example: `build-providers/build-provider-preparation`. - **Read-only model inputs.** A producer publishes normalized projects, targets, and content roots (and the effective values of explicitly listed ordinary options) with `modelSharing: { options: [...] }`; a consumer reads them with `modelInputs: [{ pluginID, buildSystemID }]`, up to 8 slots. A missing, disabled, or non-public producer only makes that slot `unavailable` and is never installed or activated automatically; a producer cannot also be a consumer. Examples: `build-model-producer` and `build-model-consumer`. diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index c07637d9..5bf19364 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -150,6 +150,7 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改了什么 | | --- | --- | --- | --- | --- | +| [#122](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/122) | [@1lck](https://github.com/1lck) | API-29、API-37 | `buildSystems` 0 内的补充 | 包内翻译文件新增 `buildOptions..`,可翻译构建选项的 `displayName`、`description` 和固定选项值的 `title`,规则与 `runConfigurationTypes` 相同,不合规时整份拒绝,错误码 `plugin.build.invalidLocalization`。新 Core 命令 `build.localizeOptions` 接收已启用构建插件的清单和界面语言,采用两阶段读取翻译文件(与 `runConfig.configurationTypes` 相同),返回替换了选项文字的清单,宿主用它检测,选项对话框、工具栏开关和构建树都显示译文。插件清单、宿主方法、通知和能力版本都不变;旧 Core 会忽略翻译文件中的 `buildOptions`。见 [1lck/Lithe-IDEA#2204](https://github.com/1lck/Lithe-IDEA/issues/2204)。 | | [#121](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/121) | [@1lck](https://github.com/1lck) | API-29 | `buildSystems` 0 内的行为修正 | `build.resolveOptions` 对没有声明 `default` 的 `text`、`file`、`directory` 选项,用户覆盖时也返回 `implicitValue`,作为撤销覆盖后回到的值,宿主据此保留“覆盖”复选框。没有新增字段、版本号、宿主方法或通知。见 [1lck/Lithe-IDEA#2152](https://github.com/1lck/Lithe-IDEA/issues/2152)。 | | [#120](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/120) | [@1lck](https://github.com/1lck) | API-29 | `buildSystems` 0 内的补充 | 清单的 `options[]` 新增 `description`(1–512 字符),作为宿主 ⓘ 中的说明,只用于显示。`litheBuildModel` 和 `model.map` 的 `optionDefaults` 除 `choicesFromModel` 选项外,也可以填 `text`、`file`、`directory` 选项,值是选项未设置时工具实际使用的那一个(如 Maven 的用户设置文件和本地仓库),Core 只保留第一个值。`build.resolveOptions` 对未设置的这类选项返回 `implicitValue`,并返回 `description`。`implicitValue` 只用于显示,不生成参数,也不进入选项指纹。旧 Core 会拒绝声明了 `description` 或给路径选项填 `optionDefaults` 的清单。没有新增版本号、宿主方法、通知或 SDK 版本。见 [1lck/Lithe-IDEA#2152](https://github.com/1lck/Lithe-IDEA/issues/2152)、[#2204](https://github.com/1lck/Lithe-IDEA/issues/2204)。 | | [#118](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/118) | [@1lck](https://github.com/1lck) | — | `buildSystems` 0 内的行为补充 | 契约新增 [Workspace trust](../contract/v1/README.md#workspace-trust) 一节,取代“Lithe 没有工作区信任状态”的说法。构建计划请求新增 `projectCodeAllowed`;工作区未受信任时,Core 以新错误码 `plugin.build.untrustedWorkspace` 拒绝所有任务、测试、运行、调试准备,以及声明了 `executesProjectCode: true` 的模型、依赖命令和构建提供者请求。声明 `false` 的模型和依赖命令在安全模式下照常加载。插件清单和后端协议都不变;宿主必须在计划请求里传入信任,否则会运行项目代码的计划都会被拒绝。没有新增版本号、宿主方法、通知或 SDK 版本。见 [1lck/Lithe-IDEA#2201](https://github.com/1lck/Lithe-IDEA/issues/2201)。 |