From 6fb61b553f8db49cf545e575ca8cf2ce1bbdc6fd Mon Sep 17 00:00:00 2001 From: lick <2188718831@qq.com> Date: Sun, 15 Nov 2026 09:17:22 -0800 Subject: [PATCH 1/3] feat(java): edit native compiler targets and local JAR dependencies --- .github/workflows/ci.yml | 52 ++ .github/workflows/release.yml | 2 +- Cargo.lock | 84 ++ backend/Cargo.toml | 6 + backend/src/launch.rs | 10 +- backend/src/lib.rs | 13 + backend/src/project_settings.rs | 792 ++++++++++++++++++ backend/src/settings_session.rs | 72 +- compiler-host.json | 6 + docs/feature-matrix.md | 9 + docs/native-settings.md | 15 + docs/releases/v2.0.0.md | 21 + .../plugin_native_source_test.go | 134 +++ .../l10n/zh-Hans.json | 12 + io.github.lithe-idea.java-support/plugin.json | 7 +- scripts/assemble-package.sh | 3 +- scripts/compiler/capture.mjs | 7 + scripts/compiler/process.mjs | 37 + scripts/compiler/process.test.mjs | 11 + scripts/compiler/test-live.mjs | 65 ++ scripts/compiler/visual.mjs | 16 + scripts/package/build-linux.mjs | 2 +- scripts/package/build-windows.mjs | 2 +- scripts/package/lsp-client.mjs | 12 +- scripts/report.mjs | 48 ++ scripts/verify-package.sh | 2 +- 26 files changed, 1423 insertions(+), 17 deletions(-) create mode 100644 backend/src/project_settings.rs create mode 100644 compiler-host.json create mode 100644 docs/native-settings.md create mode 100644 docs/releases/v2.0.0.md create mode 100644 e2e/host/desktop/internal/settingswindow/plugin_native_source_test.go create mode 100644 io.github.lithe-idea.java-support/l10n/zh-Hans.json create mode 100644 scripts/compiler/capture.mjs create mode 100644 scripts/compiler/process.mjs create mode 100644 scripts/compiler/process.test.mjs create mode 100644 scripts/compiler/test-live.mjs create mode 100644 scripts/compiler/visual.mjs create mode 100644 scripts/report.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e099980..cbf975b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -33,6 +33,8 @@ jobs: node-version: 22 - name: Test package resources run: node --test --test-timeout=60000 scripts/package/*.test.mjs + - name: Test bounded integration tool cleanup + run: node --test --test-timeout=15000 scripts/compiler/process.test.mjs - name: Check formatting run: cargo fmt --all --check - name: Lint @@ -74,6 +76,17 @@ jobs: package=$(scripts/build-package.sh --arch "$arch") scripts/archive-package.sh --package "$package" --arch "$arch" done + - name: Verify native compiler settings and JARs with JDT + run: | + package=".artifacts/package/$(uname -m)/io.github.lithe-idea.java-support" + node scripts/compiler/test-live.mjs "$package" + LITHE_JAVA_PROJECT_KIND=eclipse node scripts/compiler/test-live.mjs "$package" + - name: Upload native compiler projections + uses: actions/upload-artifact@v4 + with: + name: native-compiler-projection + path: .artifacts/compiler/visual-*.json + if-no-files-found: error - name: Upload the archives uses: actions/upload-artifact@v4 with: @@ -126,3 +139,42 @@ jobs: dist/*-linux-*.zip.sha256 if-no-files-found: error retention-days: 7 + + native-settings-visual: + name: Native compiler settings screenshots + if: github.event_name != 'pull_request' || !github.event.pull_request.draft + needs: package + runs-on: ubuntu-latest + timeout-minutes: 25 + steps: + - uses: actions/checkout@v4 + - uses: actions/download-artifact@v4 + with: + name: native-compiler-projection + path: .artifacts/compiler + - name: Read pinned host revision + id: host + run: echo "revision=$(node -p 'JSON.parse(require("fs").readFileSync("compiler-host.json")).revision')" >> "$GITHUB_OUTPUT" + - uses: actions/checkout@v4 + with: + repository: 1lck/Lithe-IDEA + ref: ${{ steps.host.outputs.revision }} + path: .artifacts/host + - uses: actions/setup-go@v5 + with: + go-version-file: .artifacts/host/desktop/go.mod + cache: false + - uses: dtolnay/rust-toolchain@master + with: + toolchain: 1.100.0 + - uses: actions/setup-node@v4 + with: + node-version: 22 + - name: Render actual compiler projections through the native host + run: node scripts/compiler/visual.mjs .artifacts/host + - uses: actions/upload-artifact@v4 + with: + name: native-compiler-settings-screenshots + path: .artifacts/compiler/visual/ + if-no-files-found: error + retention-days: 14 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index c2d061c..c09ba9c 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -3,7 +3,7 @@ name: Release # Tags must match plugin.json. Build macOS arm64/x64, Windows x64 and Linux # ARM64/x64 packages from the same revision, then upload a draft prerelease. # The maintainer verifies the downloaded assets before publishing the draft. -# Contract 0 currently requires the matching Viva preview, not stable Lithe. +# Publish only after verification and after a stable desktop supports the required capabilities. on: push: tags: ["v*"] diff --git a/Cargo.lock b/Cargo.lock index b610d42..b2b2202 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -63,6 +63,12 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -135,6 +141,20 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" +[[package]] +name = "encoding_rs" +version = "0.8.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + [[package]] name = "equivalent" version = "1.0.3" @@ -318,6 +338,26 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "java-properties" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37bf6f484471c451f2b51eabd9e66b3fa7274550c5ec4b6c3d6070840945117f" +dependencies = [ + "encoding_rs", + "lazy_static", + "regex", +] + +[[package]] +name = "jsonc-parser" +version = "0.34.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ecded084f9b9a718d39668a42657c32253663d1f6afb3fbb9134f0305f73f48" +dependencies = [ + "serde", +] + [[package]] name = "junction" version = "2.1.0" @@ -328,6 +368,12 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + [[package]] name = "libc" version = "0.2.191" @@ -346,10 +392,15 @@ version = "0.1.0" dependencies = [ "base64", "dunce", + "java-properties", + "jsonc-parser", + "libc", "lithe-java-domain", "lithe-plugin-sdk", "serde_json", + "sha2", "url", + "xmltree", "zip", ] @@ -400,6 +451,12 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + [[package]] name = "percent-encoding" version = "2.3.2" @@ -462,6 +519,12 @@ version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + [[package]] name = "scopeguard" version = "1.2.0" @@ -536,6 +599,12 @@ version = "0.3.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + [[package]] name = "smallvec" version = "1.16.4" @@ -682,6 +751,21 @@ version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" +[[package]] +name = "xml" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f45bb2c13fec6a6cb4c0f76a7e94839e110a14ec803ec2940777a94c347bc52" + +[[package]] +name = "xmltree" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cbc04313cab124e498ab1724e739720807b6dc405b9ed0edc5860164d2e4ff70" +dependencies = [ + "xml", +] + [[package]] name = "yoke" version = "0.8.4" diff --git a/backend/Cargo.toml b/backend/Cargo.toml index 8a9df07..70e272b 100644 --- a/backend/Cargo.toml +++ b/backend/Cargo.toml @@ -20,3 +20,9 @@ base64 = "0.22.1" zip.workspace = true url.workspace = true dunce = "1.0.5" + +sha2.workspace = true +java-properties = "2.0.0" +xmltree = "0.12.0" +jsonc-parser = { version = "0.34.0", features = ["cst", "serde"] } +libc = "0.2" diff --git a/backend/src/launch.rs b/backend/src/launch.rs index 0b3b0e3..b193b4e 100644 --- a/backend/src/launch.rs +++ b/backend/src/launch.rs @@ -647,7 +647,7 @@ pub fn resolve_launch_function( }; let trigger_files = trigger_files(&folders)?; context.check_cancelled()?; - let answer = resolve( + let mut answer = resolve( &request, &package_root, &fragments, @@ -655,6 +655,14 @@ pub fn resolve_launch_function( now_unix_seconds(), &report, )?; + if let Some(folder) = folders.first() { + let configuration = crate::settings_session::with_native_settings( + answer["workspaceConfiguration"].clone(), + folder, + )?; + answer["workspaceConfiguration"] = configuration.clone(); + answer["initializationOptions"]["settings"] = configuration; + } context.check_cancelled()?; Ok(answer) } diff --git a/backend/src/lib.rs b/backend/src/lib.rs index 5827f75..071af2d 100644 --- a/backend/src/lib.rs +++ b/backend/src/lib.rs @@ -50,6 +50,7 @@ pub mod class_content; pub mod launch; pub mod plugin_functions; +pub mod project_settings; pub mod run; pub mod settings_session; @@ -240,6 +241,18 @@ pub fn backend() -> Result { let run_session = Arc::clone(&run_session); move |params, context| run::rerun_function(&run_session, params, context) })?; + let projects = Arc::new(project_settings::ProjectSettings::default()); + for (function, libraries) in [("compiler.settings", false), ("libraries.settings", true)] { + let projects = Arc::clone(&projects); + let session = Arc::clone(&session); + backend.function(function, move |params, context| { + projects.snapshot(params, context, libraries, &session) + })?; + backend.suppress_success_diagnostics(function)?; + } + backend.function("compiler.prepareSettings", move |params, context| { + projects.edit(params, context) + })?; Ok(backend) } diff --git a/backend/src/project_settings.rs b/backend/src/project_settings.rs new file mode 100644 index 0000000..d7ee54d --- /dev/null +++ b/backend/src/project_settings.rs @@ -0,0 +1,792 @@ +//! Native compiler preferences and classpaths for unmanaged/Eclipse projects. +//! JDT owns project discovery and effective values. This module edits only +//! allowlisted native keys and stages replacements; the host owns publication. + +use java_properties::{LineContent, PropertiesIter, PropertiesWriter}; +use jsonc_parser::cst::{CstInputValue, CstRootNode}; +use lithe_plugin_sdk::{Context, FunctionError, PluginError, Value}; +use serde_json::json; +use sha2::{Digest, Sha256}; +use std::collections::{BTreeMap, BTreeSet}; +use std::fs::{self, OpenOptions}; +use std::io::{Read, Write}; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; +use url::Url; + +const LIMIT: u64 = 2 * 1024 * 1024; +const TARGET: &str = "org.eclipse.jdt.core.compiler.codegen.targetPlatform"; +const SOURCE: &str = "org.eclipse.jdt.core.compiler.source"; +const COMPLIANCE: &str = "org.eclipse.jdt.core.compiler.compliance"; +const RELEASE: &str = "org.eclipse.jdt.core.compiler.release"; +const NATURES: &str = "org.eclipse.jdt.ls.core.natureIds"; +const LIBRARIES: &str = "org.eclipse.jdt.ls.core.referencedLibraries"; +const PREFS: &str = ".settings/org.eclipse.jdt.core.prefs"; +const SETTINGS: &str = ".vscode/settings.json"; +const LIBRARY_KEY: &str = "java.project.referencedLibraries"; + +/// Bounded native read bindings; no configuration documents or tool models are cached. +#[derive(Default)] +pub struct ProjectSettings { + bindings: Mutex>>, +} +fn fail() -> FunctionError { + PluginError::new( + "java.nativeSettings.failed", + "Reload Java project settings and check that their native files are readable.", + ) + .into() +} +fn digest(bytes: &[u8]) -> String { + format!("sha256:{:x}", Sha256::digest(bytes)) +} +fn read(path: &Path) -> Result<(Vec, String), FunctionError> { + let info = match fs::symlink_metadata(path) { + Ok(info) => info, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + return Ok((Vec::new(), "missing".into())) + } + Err(_) => return Err(fail()), + }; + if !info.is_file() || info.len() > LIMIT { + return Err(fail()); + } + let mut bytes = Vec::new(); + fs::File::open(path) + .map_err(|_| fail())? + .take(LIMIT + 1) + .read_to_end(&mut bytes) + .map_err(|_| fail())?; + if bytes.len() as u64 > LIMIT { + return Err(fail()); + } + let revision = digest(&bytes); + Ok((bytes, revision)) +} +fn root(context: &Context) -> Result { + let workspace = context.workspace_context().ok_or_else(fail)?; + let response = context + .host() + .workspace() + .get_context(workspace) + .map_err(|_| fail())?; + let path = response["folders"][0]["path"].as_str().ok_or_else(fail)?; + dunce::canonicalize(path).map_err(|_| fail()) +} +fn command(context: &Context, name: &str, args: Value) -> Result { + context.check_cancelled()?; + let workspace = context.workspace_context().ok_or_else(fail)?; + let answer=context.host().request(crate::settings_session::REQUEST_METHOD,json!({"context":workspace.to_value(),"serverID":"java","method":"workspace/executeCommand","params":{"command":name,"arguments":args},"timeoutMilliseconds":30000})).map_err(|_|fail())?; + Ok(answer.get("value").cloned().unwrap_or(Value::Null)) +} +fn local(zh: bool, en: &str, cn: &str) -> String { + if zh { cn } else { en }.to_owned() +} +fn normalize(value: &str) -> String { + value.strip_prefix("1.").unwrap_or(value).to_owned() +} +fn properties(bytes: &[u8]) -> Result, FunctionError> { + java_properties::read(bytes) + .map(|map| map.into_iter().collect()) + .map_err(|_| fail()) +} +fn target(raw: &BTreeMap) -> Value { + raw.get(TARGET) + .map(|v| json!(normalize(v))) + .unwrap_or(Value::Null) +} +fn field( + zh: bool, + descriptor: (&str, &str, &str, &str), + raw: Value, + effective: Value, + mut options: Value, + help: &str, +) -> Value { + let (id, en, cn, kind) = descriptor; + if kind == "enum" { + for value in [&raw, &effective] { + if let Some(value) = value.as_str() { + if !options + .as_array() + .unwrap() + .iter() + .any(|option| option["value"] == value) + { + options + .as_array_mut() + .unwrap() + .push(json!({"value":value,"title":value})); + } + } + } + } + json!({"id":id,"title":local(zh,en,cn),"description":help,"kind":kind,"value":raw,"effectiveValue":effective,"effectiveSource":local(zh,"Eclipse JDT project settings","Eclipse JDT 项目生效配置"),"options":options}) +} +fn compiler_fields( + zh: bool, + raw: &BTreeMap, + effective: &Value, + module: bool, +) -> Vec { + let options: Vec<_> = (1..=26) + .map(|version| json!({"value":version.to_string(),"title":version.to_string()})) + .collect(); + let help=local(zh,"Eclipse JDT compiles unmanaged/Eclipse projects. Maven and Gradle use their own compiler pages. The project JDK is selected in Toolchains.","普通 Java 与 Eclipse 项目使用 Eclipse JDT 编译;Maven、Gradle 使用各自编译器页面。项目 JDK 在工具链中选择。"); + let mut fields = vec![field( + zh, + ("target", "Target bytecode", "目标字节码", "enum"), + target(raw), + effective[TARGET] + .as_str() + .map(|v| json!(normalize(v))) + .unwrap_or(Value::Null), + json!(options), + &help, + )]; + if !module { + fields.push(field(zh, ("release", "Use --release API restrictions", "使用 --release API 限制", "boolean"),raw.get(RELEASE).map(|v|json!(v=="enabled")).unwrap_or(Value::Null),effective[RELEASE].as_str().map(|v|json!(v=="enabled")).unwrap_or(Value::Null),json!([]),&local(zh,"For Java 9 and newer, restrict available JDK APIs as well as the generated class version.","Java 9 及更新版本同时限制可用 JDK API 和生成的 class 版本。"))); + let key = "org.eclipse.jdt.core.compiler.debug.lineNumber"; + fields.push(field( + zh, + ( + "debug", + "Generate debugging information", + "生成调试信息", + "boolean", + ), + raw.get(key) + .map(|v| json!(v == "generate")) + .unwrap_or(Value::Null), + effective[key] + .as_str() + .map(|v| json!(v == "generate")) + .unwrap_or(Value::Null), + json!([]), + "", + )); + } + fields +} + +impl ProjectSettings { + /// Projects native settings only after the declared JDT server is ready. + pub fn snapshot( + &self, + params: Value, + context: &Context, + libraries: bool, + session: &crate::settings_session::SettingsSession, + ) -> Result { + let root = root(context)?; + let zh = params["context"]["language"] + .as_str() + .unwrap_or("") + .starts_with("zh"); + if params["operation"] == "readAfterSave" { + session + .refresh_native_settings(context.workspace_context().ok_or_else(fail)?, &root) + .map_err(|_| fail())?; + } + let projects = command(context, "java.project.getAll", json!([]))?; + if params["operation"] == "readAfterSave" { + let identifiers: Vec<_> = projects + .as_array() + .ok_or_else(fail)? + .iter() + .map(|uri| json!({"uri":uri})) + .collect(); + context.host().request(crate::settings_session::NOTIFY_METHOD,json!({"context":context.workspace_context().ok_or_else(fail)?.to_value(),"serverID":"java","method":"java/projectConfigurationsUpdate","params":{"identifiers":identifiers,"force":true}})).map_err(|_|fail())?; + } + let keys = json!([ + TARGET, + SOURCE, + COMPLIANCE, + RELEASE, + "org.eclipse.jdt.core.compiler.debug.lineNumber", + NATURES, + LIBRARIES + ]); + let mut facts = Vec::new(); + for entry in projects.as_array().ok_or_else(fail)? { + context.check_cancelled()?; + let value = entry.as_str().ok_or_else(fail)?; + let path = Url::parse(value) + .ok() + .and_then(|u| u.to_file_path().ok()) + .and_then(|p| dunce::canonicalize(p).ok()) + .ok_or_else(fail)?; + if !path.starts_with(&root) { + continue; + } + let settings = command(context, "java.project.getSettings", json!([value, keys]))?; + let managed = settings[NATURES].as_array().is_some_and(|items| { + items + .iter() + .filter_map(Value::as_str) + .any(|id| id.contains("m2e") || id.contains("buildship")) + }); + if !managed { + facts.push((path, settings)); + } + } + if facts.len() > 1023 { + return Err(fail()); + } + // Global defaults come from the native global preference file, or + // from a project with no project-specific override. A module override + // is never presented as the workspace default. + let global_properties = properties(&read(&root.join(PREFS))?.0)?; + let mut global_effective = json!({}); + let mut private_bytes = 0usize; + let mut project_preferences = Vec::new(); + for (path, _) in &facts { + let (bytes, _) = read(&path.join(PREFS))?; + private_bytes += bytes.len(); + if private_bytes > 8 * 1024 * 1024 { + return Err(fail()); + } + project_preferences.push(properties(&bytes)?); + } + for key in [ + TARGET, + RELEASE, + "org.eclipse.jdt.core.compiler.debug.lineNumber", + ] { + if let Some(value) = global_properties.get(key) { + global_effective[key] = json!(value); + } else if let Some((index, _)) = project_preferences + .iter() + .enumerate() + .find(|(_, values)| !values.contains_key(key)) + { + global_effective[key] = facts[index].1[key].clone(); + } + } + let mut sources = Vec::new(); + let mut bindings = BTreeMap::new(); + let mut paths = BTreeSet::new(); + if !libraries { + let path = root.join(PREFS); + let (bytes, revision) = read(&path)?; + let raw = properties(&bytes)?; + let effective = global_effective.clone(); + let id = "defaults"; + bindings.insert(id.into(), path.clone()); + paths.insert(path); + sources.push(json!({"id":id,"group":"project","title":local(zh,"Project defaults","项目默认设置"),"path":PREFS,"revision":revision,"writable":true,"fields":compiler_fields(zh,&raw,&effective,false)})); + } + for (path, fact) in facts { + let source_path = if libraries { + if read(&path.join(".classpath"))?.1 != "missing" { + path.join(".classpath") + } else { + root.join(SETTINGS) + } + } else { + path.join(PREFS) + }; + if !paths.insert(source_path.clone()) { + continue; + } + let rel = source_path + .strip_prefix(&root) + .map_err(|_| fail())? + .to_str() + .ok_or_else(fail)? + .replace('\\', "/"); + let id = format!("source{:x}", Sha256::digest(rel.as_bytes())); + let (bytes, revision) = read(&source_path)?; + let mut fields = if libraries { + let value = if source_path.ends_with(".classpath") { + json!(classpath_libraries(&bytes)?) + } else { + library_input(&native_json(&bytes)?) + }; + let effective = fact[LIBRARIES].clone(); + vec![field(zh, ("libraries", "Referenced JAR files", "引用的 JAR 文件", "fileList"),value,effective,json!([]),&local(zh,"Eclipse projects use .classpath. Unmanaged Java uses java.project.referencedLibraries in .vscode/settings.json; lib/**/*.jar is the upstream default.","Eclipse 项目写入 .classpath;普通 Java 使用 .vscode/settings.json 的 java.project.referencedLibraries,上游默认引用 lib/**/*.jar。"))] + } else { + compiler_fields(zh, &properties(&bytes)?, &fact, true) + }; + if !libraries { + for field in &mut fields { + if field["id"] == "target" { + field["inheritedValue"] = global_effective[TARGET] + .as_str() + .map(|value| json!(normalize(value))) + .unwrap_or(Value::Null); + } + } + } + bindings.insert(id.clone(), source_path); + sources.push(json!({"id":id,"group":if libraries{"libraries"}else{"modules"},"title":path.file_name().and_then(|n|n.to_str()).unwrap_or("Java"),"path":rel,"revision":revision,"writable":true,"fields":fields})); + } + let mut all = self.bindings.lock().map_err(|_| fail())?; + if all.len() >= 32 && !all.contains_key(&root.to_string_lossy().to_string()) { + return Err(fail()); + } + all.insert(root.to_string_lossy().to_string(), bindings); + Ok( + json!({"format":"litheSettingsSources","version":0,"title":if libraries{local(zh,"Java Libraries","Java 库")}else{local(zh,"Java Compiler","Java 编译器")},"groups":if libraries{json!([{"id":"libraries","title":local(zh,"Referenced libraries","引用的库"),"layout":"form"}])}else{json!([{"id":"project","title":local(zh,"Project defaults","项目默认设置"),"layout":"form"},{"id":"modules","title":local(zh,"Per-module bytecode","按模块设置字节码"),"rowTitle":local(zh,"Module","模块"),"layout":"table"}])},"sources":sources}), + ) + } + /// Prepares only the confirmed native source; publication belongs to the host. + pub fn edit(&self, params: Value, context: &Context) -> Result { + let root = root(context)?; + let id = params["sourceID"].as_str().ok_or_else(fail)?; + let path = self + .bindings + .lock() + .map_err(|_| fail())? + .get(&root.to_string_lossy().to_string()) + .and_then(|b| b.get(id)) + .cloned() + .ok_or_else(fail)?; + let parent = path.parent().ok_or_else(fail)?; + let mut existing = parent; + while !existing.exists() { + existing = existing.parent().ok_or_else(fail)?; + } + if !dunce::canonicalize(existing) + .map_err(|_| fail())? + .starts_with(&root) + { + return Err(fail()); + } + let (bytes, revision) = read(&path)?; + if params["revision"] != revision { + return Err(fail()); + } + let values = params["values"].as_object().ok_or_else(fail)?; + let replacement = if path.ends_with(".classpath") { + edit_classpath(&bytes, values.get("libraries").ok_or_else(fail)?)? + } else if path.ends_with(SETTINGS) { + edit_json(&bytes, values.get("libraries").ok_or_else(fail)?)? + } else { + edit_properties(&bytes, values)? + }; + if replacement.len() as u64 > LIMIT { + return Err(fail()); + } + context.check_cancelled()?; + let stage = params["outputFile"].as_str().ok_or_else(fail)?; + let mut options = OpenOptions::new(); + options.write(true).truncate(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.custom_flags(libc::O_NOFOLLOW); + } + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + options.custom_flags(0x00200000); + } + let mut output = options.open(stage).map_err(|_| fail())?; + if !output.metadata().map_err(|_| fail())?.is_file() { + return Err(fail()); + } + context.check_cancelled()?; + output.write_all(&replacement).map_err(|_| fail())?; + Ok( + json!({"format":"litheSettingsSourceEdit","version":0,"sourceID":id,"revision":digest(&replacement),"changed":bytes!=replacement}), + ) + } +} + +/// Reads the actual upstream settings sources; used at startup and on every push. +pub fn native_settings(root: &Path) -> Result { + let mut settings = json!({}); + if read(&root.join(PREFS))?.1 != "missing" { + settings["settings"] = + json!({"url":Url::from_file_path(root.join(PREFS)).map_err(|_|fail())?.to_string()}); + } + let (bytes, _) = read(&root.join(SETTINGS))?; + let source = native_json(&bytes)?; + if let Some(libraries) = source.get(LIBRARY_KEY) { + settings["project"] = json!({"referencedLibraries":libraries}); + } + Ok(settings) +} +fn native_json(bytes: &[u8]) -> Result { + if bytes.is_empty() { + return Ok(json!({})); + } + let text = std::str::from_utf8(bytes).map_err(|_| fail())?; + let value: Option = + jsonc_parser::parse_to_serde_value(text, &Default::default()).map_err(|_| fail())?; + let value = value.unwrap_or(json!({})); + if !value.is_object() { + return Err(fail()); + } + Ok(value) +} +fn library_input(settings: &Value) -> Value { + match settings.get(LIBRARY_KEY) { + Some(Value::Object(object)) => object.get("include").cloned().unwrap_or(Value::Null), + Some(value) => value.clone(), + None => Value::Null, + } +} +fn edit_json(bytes: &[u8], libraries: &Value) -> Result, FunctionError> { + native_json(bytes)?; + let text = std::str::from_utf8(bytes).map_err(|_| fail())?; + let root = CstRootNode::parse(text, &Default::default()).map_err(|_| fail())?; + let object = root.object_value_or_create().ok_or_else(fail)?; + let rich = object.get(LIBRARY_KEY).and_then(|prop| prop.object_value()); + let (target, key) = rich + .map(|rich| (rich, "include")) + .unwrap_or((object, LIBRARY_KEY)); + if libraries.is_null() { + if let Some(prop) = target.get(key) { + prop.remove(); + } + } else { + let values = libraries + .as_array() + .ok_or_else(fail)? + .iter() + .map(|v| { + v.as_str() + .map(|s| CstInputValue::String(s.to_owned())) + .ok_or_else(fail) + }) + .collect::, _>>()?; + let input = CstInputValue::Array(values); + if let Some(prop) = target.get(key) { + prop.set_value(input); + } else { + target.append(key, input); + } + } + Ok(root.to_string().into_bytes()) +} +fn classpath_libraries(bytes: &[u8]) -> Result, FunctionError> { + let doc = xmltree::Element::parse(bytes).map_err(|_| fail())?; + if doc.name != "classpath" { + return Err(fail()); + } + Ok(doc + .children + .iter() + .filter_map(xmltree::XMLNode::as_element) + .filter(|e| { + e.name == "classpathentry" && e.attributes.get("kind").is_some_and(|v| v == "lib") + }) + .filter_map(|e| e.attributes.get("path").cloned()) + .collect()) +} +fn edit_classpath(bytes: &[u8], libraries: &Value) -> Result, FunctionError> { + let mut doc = xmltree::Element::parse(bytes).map_err(|_| fail())?; + if doc.name != "classpath" { + return Err(fail()); + } + let paths = libraries + .as_array() + .map(|v| { + v.iter() + .map(|p| p.as_str().map(str::to_owned).ok_or_else(fail)) + .collect::, _>>() + }) + .transpose()? + .unwrap_or_default(); + let mut retained = BTreeSet::new(); + doc.children.retain(|node| match node.as_element() { + Some(e) + if e.name == "classpathentry" + && e.attributes.get("kind").is_some_and(|v| v == "lib") => + { + e.attributes + .get("path") + .is_some_and(|path| paths.contains(path) && retained.insert(path.clone())) + } + _ => true, + }); + for path in paths.difference(&retained) { + let mut entry = xmltree::Element::new("classpathentry"); + entry.attributes.insert("kind".into(), "lib".into()); + entry.attributes.insert("path".into(), path.clone()); + doc.children.push(xmltree::XMLNode::Element(entry)); + } + // Preserve nodes outside the root too, including comments and processing + // instructions. xmltree validates each node before this serialization. + let nodes = xmltree::Element::parse_all(bytes).map_err(|_| fail())?; + let mut out = b"\n".to_vec(); + for node in nodes { + match node { + xmltree::XMLNode::Element(_) => doc + .write_with_config( + &mut out, + xmltree::EmitterConfig::new() + .perform_indent(true) + .write_document_declaration(false), + ) + .map_err(|_| fail())?, + xmltree::XMLNode::Comment(text) => { + write!(&mut out, "").map_err(|_| fail())?; + } + xmltree::XMLNode::ProcessingInstruction(name, value) => { + write!( + &mut out, + "", + value.map(|v| format!(" {v}")).unwrap_or_default() + ) + .map_err(|_| fail())?; + } + xmltree::XMLNode::Text(text) => out.extend_from_slice(text.as_bytes()), + xmltree::XMLNode::CData(_) => return Err(fail()), + } + } + Ok(out) +} +fn edit_properties( + bytes: &[u8], + values: &serde_json::Map, +) -> Result, FunctionError> { + properties(bytes)?; + let mut edits = BTreeMap::>::new(); + for (id, value) in values { + match id.as_str() { + "target" => { + let version = value.as_str(); + if version + .is_some_and(|v| v.parse::().map_or(true, |n| !(1..=26).contains(&n))) + { + return Err(fail()); + } + for key in [TARGET, SOURCE, COMPLIANCE] { + edits.insert( + key.into(), + version.map(|v| { + if v.parse::().is_ok_and(|n| n <= 8) { + format!("1.{v}") + } else { + v.into() + } + }), + ); + } + } + "release" => { + edits.insert( + RELEASE.into(), + if value.is_null() { + None + } else { + Some( + if value.as_bool().ok_or_else(fail)? { + "enabled" + } else { + "disabled" + } + .into(), + ) + }, + ); + } + "debug" => { + for key in ["lineNumber", "sourceFile", "localVariable"] { + edits.insert( + format!("org.eclipse.jdt.core.compiler.debug.{key}"), + if value.is_null() { + None + } else { + Some( + if value.as_bool().ok_or_else(fail)? { + "generate" + } else { + "do not generate" + } + .into(), + ) + }, + ); + } + } + _ => return Err(fail()), + } + } + let lines: Vec<_> = PropertiesIter::new(bytes) + .collect::>() + .map_err(|_| fail())?; + let mut offsets = vec![0]; + let mut index = 0; + while index < bytes.len() { + if bytes[index] == b'\r' { + index += 1; + if bytes.get(index) == Some(&b'\n') { + index += 1; + } + offsets.push(index); + } else if bytes[index] == b'\n' { + index += 1; + offsets.push(index); + } else { + index += 1; + } + } + let mut out = Vec::new(); + let mut cursor = 0; + for (index, line) in lines.iter().enumerate() { + if let LineContent::KVPair(key, _) = line.content() { + if edits.contains_key(key) { + let start = *offsets.get(line.line_number() - 1).ok_or_else(fail)?; + let end = lines + .get(index + 1) + .and_then(|next| offsets.get(next.line_number() - 1)) + .copied() + .unwrap_or(bytes.len()); + out.extend_from_slice(&bytes[cursor..start]); + cursor = end; + } + } + } + out.extend_from_slice(&bytes[cursor..]); + if !out.is_empty() && !out.ends_with(b"\n") && !out.ends_with(b"\r") { + out.push(b'\n'); + } + let mut writer = PropertiesWriter::new(&mut out); + for (key, value) in edits { + if let Some(value) = value { + writer.write(&key, &value).map_err(|_| fail())?; + } + } + writer.finish().map_err(|_| fail())?; + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + struct TestDirectory(PathBuf); + impl TestDirectory { + fn new() -> Self { + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + for _ in 0..32 { + let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let path = std::env::temp_dir() + .join(format!("lithe-native-settings-{}-{id}", std::process::id())); + match fs::create_dir(&path) { + Ok(()) => return Self(path), + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(error) => panic!("temporary directory: {error}"), + } + } + panic!("temporary directory collision limit"); + } + } + impl Drop for TestDirectory { + fn drop(&mut self) { + if let Err(error) = fs::remove_dir_all(&self.0) { + if !std::thread::panicking() { + panic!("temporary directory cleanup: {error}"); + } + } + } + } + #[test] + fn rich_library_configuration_keeps_excludes_sources_and_comments() { + let source = br#"{ // private comment + "java.project.referencedLibraries": { + "include": ["old.jar"], + "exclude": ["secret/**/*.jar"], + "sources": {"old.jar": "old-sources.jar"} + }, "privateToken": "untouched" + }"#; + let updated = edit_json(source, &json!(["new.jar"])).unwrap(); + let parsed = native_json(&updated).unwrap(); + assert_eq!(parsed[LIBRARY_KEY]["include"], json!(["new.jar"])); + assert_eq!(parsed[LIBRARY_KEY]["exclude"], json!(["secret/**/*.jar"])); + assert_eq!(parsed[LIBRARY_KEY]["sources"]["old.jar"], "old-sources.jar"); + assert!(String::from_utf8(updated.clone()) + .unwrap() + .contains("private comment")); + let reset = native_json(&edit_json(&updated, &Value::Null).unwrap()).unwrap(); + assert!(reset[LIBRARY_KEY].get("include").is_none()); + assert_eq!( + reset[LIBRARY_KEY]["exclude"], + parsed[LIBRARY_KEY]["exclude"] + ); + assert_eq!(reset["privateToken"], "untouched"); + } + + #[test] + fn properties_edits_preserve_comments_private_keys_and_escaped_continuations() { + let source=b"# keep this comment\r\neclipse.preferences.version=1\r\nprivateKey=private-value\r\norg.eclipse.jdt.core.compiler.codegen.targetPlatform : 1.8\r\norg.eclipse.jdt.core.compiler.sou\\\r\n rce=1.8\r\n! trailing comment\r\n"; + let updated = edit_properties(source, json!({"target":"11"}).as_object().unwrap()).unwrap(); + let text = String::from_utf8(updated.clone()).unwrap(); + assert!(text.contains("# keep this comment\r\n")); + assert!(text.contains("! trailing comment")); + assert!(text.contains("privateKey=private-value\r\n")); + let values = properties(&updated).unwrap(); + assert_eq!(values[TARGET], "11"); + assert_eq!(values[SOURCE], "11"); + assert_eq!(values[COMPLIANCE], "11"); + let inherited = + edit_properties(&updated, json!({"target":null}).as_object().unwrap()).unwrap(); + let values = properties(&inherited).unwrap(); + for key in [TARGET, SOURCE, COMPLIANCE] { + assert!(!values.contains_key(key)); + } + assert_eq!(values["privateKey"], "private-value"); + } + #[test] + fn jsonc_library_edits_preserve_comments_unknown_settings_and_spaces() { + let source=b"{ // keep comment\n \"privateToken\": \"private-value\",\n \"java.project.referencedLibraries\": [\"old.jar\"],\n}"; + let updated = edit_json(source, &json!(["C:\\Program Files\\Java\\external.jar"])).unwrap(); + assert!(String::from_utf8_lossy(&updated).contains("// keep comment")); + let value = native_json(&updated).unwrap(); + assert_eq!( + value[LIBRARY_KEY], + json!(["C:\\Program Files\\Java\\external.jar"]) + ); + assert_eq!(value["privateToken"], "private-value"); + let reset = edit_json(&updated, &Value::Null).unwrap(); + assert!(native_json(&reset).unwrap().get(LIBRARY_KEY).is_none()); + } + #[test] + fn eclipse_classpath_edits_preserve_containers_source_roots_attachments_and_comments() { + let source=br#""#; + let updated = edit_classpath(source, &json!(["keep.jar", "External Library.jar"])).unwrap(); + let text = String::from_utf8_lossy(&updated); + for item in [ + "", + "", + "", + "keep-sources.jar", + "javadoc_location", + "JRE_CONTAINER", + "kind=\"src\"", + "kind=\"output\"", + ] { + assert!(text.contains(item), "{item}: {text}"); + } + assert_eq!( + classpath_libraries(&updated).unwrap(), + vec!["keep.jar", "External Library.jar"] + ); + } + #[test] + fn complete_configuration_keeps_runtime_and_imports_when_native_keys_are_added() { + let directory = TestDirectory::new(); + let root = &directory.0; + fs::create_dir_all(root.join(".vscode")).unwrap(); + fs::write( + root.join(SETTINGS), + br#"{"java.project.referencedLibraries":["lib/**/*.jar"]}"#, + ) + .unwrap(); + let original = json!({"java":{"configuration":{"runtimes":[{"name":"JavaSE-17","path":"/selected/jdk"}]},"import":{"maven":{"enabled":true}}}}); + let updated = + crate::settings_session::with_native_settings(original.clone(), root).unwrap(); + assert_eq!( + updated["java"]["configuration"], + original["java"]["configuration"] + ); + assert_eq!(updated["java"]["import"], original["java"]["import"]); + assert_eq!( + updated["java"]["project"]["referencedLibraries"], + json!(["lib/**/*.jar"]) + ); + } +} diff --git a/backend/src/settings_session.rs b/backend/src/settings_session.rs index fef8dd0..6ed89d7 100644 --- a/backend/src/settings_session.rs +++ b/backend/src/settings_session.rs @@ -53,7 +53,9 @@ use lithe_java_domain::lsp::languages::jdt::{settings_notification, JdtJavaRunti use lithe_java_domain::lsp::languages::jdt_contributions::{ accept_answer, AcceptedSettings, Contributions, SETTINGS_CHANGED_FUNCTION, }; -use lithe_plugin_sdk::{BackendHandle, Cancellation, PluginError, Value, WorkspaceContext}; +use lithe_plugin_sdk::{ + BackendHandle, Cancellation, FunctionError, PluginError, Value, WorkspaceContext, +}; use serde_json::{json, Map}; use std::collections::HashMap; use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; @@ -118,7 +120,7 @@ pub const SESSION_CATEGORIES: &[&str] = &[ ]; /// Host method that sends a notification to a plugin-declared server. -const NOTIFY_METHOD: &str = "lithe/host/languageServer/notify"; +pub(crate) const NOTIFY_METHOD: &str = "lithe/host/languageServer/notify"; /// Host method that sends a request to a plugin-declared server. pub(crate) const REQUEST_METHOD: &str = "lithe/host/languageServer/request"; @@ -278,6 +280,7 @@ struct WorkspaceState { /// the host resolved; every push repeats them so the server keeps the /// same default runtime the host runs. java_runtimes: Vec, + native_root: Option, /// Project updates waiting for a running server. pending_projects: Vec, /// Set from the moment the server is running until its collection is @@ -294,6 +297,7 @@ impl WorkspaceState { seen: None, contributions: Contributions::default(), java_runtimes: Vec::new(), + native_root: None, pending_projects: Vec::new(), collecting: None, } @@ -507,6 +511,21 @@ pub fn java_configuration(fragments: &[Value], runtimes: &[JdtJavaRuntime]) -> V } } +/// Adds native upstream workspace sources without replacing runtimes or import +/// contributions. Only the owning plugin's allowlisted keys can be overlaid. +pub fn with_native_settings( + mut settings: Value, + root: &std::path::Path, +) -> Result { + let native = crate::project_settings::native_settings(root)?; + for (section, values) in native.as_object().into_iter().flatten() { + for (key, value) in values.as_object().into_iter().flatten() { + settings["java"][section][key] = value.clone(); + } + } + Ok(settings) +} + /// Locks `mutex` even when a panic poisoned it: the guarded data stays /// consistent because every critical section here only swaps whole values. fn lock(mutex: &Mutex) -> MutexGuard<'_, T> { @@ -623,6 +642,11 @@ impl SettingsSession { return None; } }; + if let Some(state) = self.lock_states().get_mut(workspace.context_id()) { + if state.context.generation() == workspace.generation() { + state.native_root = Some(std::path::PathBuf::from(&root)); + } + } let relay = self.host.relay(workspace); // The collection belongs to no function call, so nothing cancels it; // a provider that does not answer ends at the relay's own timeout. @@ -723,7 +747,7 @@ impl SettingsSession { /// documentation. fn flush(&self, key: &str, report: &dyn Fn(&str, u64)) { let _delivery = lock(&self.gate); - let (workspace, params, projects) = { + let (workspace, params, projects, native_root) = { let mut states = self.lock_states(); let Some(state) = states.get_mut(key) else { return; @@ -735,8 +759,20 @@ impl SettingsSession { state.context.clone(), configuration_params(&state.contributions.fragments(), &state.java_runtimes), std::mem::take(&mut state.pending_projects), + state.native_root.clone(), ) }; + let params = match native_root { + Some(root) => match with_native_settings(params["settings"].clone(), &root) { + Ok(settings) => json!({"settings":settings}), + Err(_) => { + report(SESSION_PUSH_FAILED, 1); + self.requeue_projects(key, projects); + return; + } + }, + None => params, + }; if self.host.push_configuration(&workspace, params).is_err() { report(SESSION_PUSH_FAILED, 1); // The server did not get the settings the updates build on, so @@ -755,6 +791,36 @@ impl SettingsSession { } } + /// Reloads native workspace sources after the host published them. The + /// complete current configuration retains the selected runtime and imports. + pub fn refresh_native_settings( + &self, + workspace: &WorkspaceContext, + root: &std::path::Path, + ) -> Result<(), FunctionError> { + let _delivery = lock(&self.gate); + let settings = { + let states = self.lock_states(); + let state = states.get(workspace.context_id()).ok_or_else(|| { + PluginError::new( + "java.nativeSettings.unavailable", + "The Java language server is unavailable.", + ) + })?; + java_configuration(&state.contributions.fragments(), &state.java_runtimes) + }; + let settings = with_native_settings(settings, root)?; + self.host + .push_configuration(workspace, json!({"settings":settings})) + .map_err(|_| { + PluginError::new( + "java.nativeSettings.pushFailed", + "Java project settings could not be refreshed.", + ) + })?; + Ok(()) + } + /// The contributed settings fragments known for the workspace /// `context_id`, in the order a push applies them; empty for a workspace /// the session has not seen. The launch builds its startup settings from diff --git a/compiler-host.json b/compiler-host.json new file mode 100644 index 0000000..6348c6c --- /dev/null +++ b/compiler-host.json @@ -0,0 +1,6 @@ +{ + "repository": "https://github.com/1lck/Lithe-IDEA", + "revision": "dbdee96b853b0e720167dc1ff30163b10d353aef", + "coreRevision": "5802c42b5766df7375bd427c54203db415ff72d7", + "package": "io.github.lithe-idea.java-support" +} diff --git a/docs/feature-matrix.md b/docs/feature-matrix.md index a21d72b..c89621c 100644 --- a/docs/feature-matrix.md +++ b/docs/feature-matrix.md @@ -8,3 +8,12 @@ | 真实工具/语言服务器流程 | [原生验证结果](https://github.com/Lithe-IDEA/lithe-plugin-java/pull/15/checks) | [原生验证结果](https://github.com/Lithe-IDEA/lithe-plugin-java/pull/15/checks) | `scripts/package/` 和现有集成测试 | 跨架构本地包检查通过不等于原生工作流验收。既有平台验证记录保持不变。 + +## 原生编译设置与本地 JAR + +| 能力 | macOS | Windows | 证据 | +| --- | --- | --- | --- | +| 项目默认目标、按模块字节码、继承与显式保存 | implemented / pending | implemented / pending | `scripts/compiler/` 真实引擎回归,检查 class major 52/55;原生完整 UI 验收仍 pending | +| 原生 JAR 引用与编译运行 | implemented / pending | implemented / pending | `scripts/compiler/` 编译外部 JAR 并运行引用它的程序;配置与包的只读边界见 native-settings.md | + +2026-11-15:本地 macOS 自动化已通过,不将脚本通过等同于所有交互场景验收。Windows 的实机结果另随 PR 补充。 diff --git a/docs/native-settings.md b/docs/native-settings.md new file mode 100644 index 0000000..495fc5b --- /dev/null +++ b/docs/native-settings.md @@ -0,0 +1,15 @@ +# 普通 Java 与 Eclipse 编译设置与本地 JAR + +在设置的“构建、执行、部署”中打开插件提供的编译器页,点击“读取编译设置”(构建工具会显示“使用项目工具读取编译设置”)。读取会使用项目工具,可能执行项目脚本或下载依赖。项目默认目标与模块覆盖分别显示;移除模块覆盖后继承项目配置。只有点击“保存”才写入 `.settings/org.eclipse.jdt.core.prefs`、普通项目的 `.vscode/settings.json` 或 Eclipse `.classpath`,外部修改会要求重新读取。 + +管理 JDK:在“构建、执行、部署”的工具链区使用“全局默认”,选择自动识别结果,或从磁盘添加多个 JDK,核对版本后保存;无需先打开项目。个别项目可切换到“当前项目”单独覆盖。已启动的进程需重启后采用新版本。JDK 是运行编译器的程序;目标字节码决定生成的 class 版本,两者分别设置。构建工具自己的显式 Java 环境或工具链配置仍按该工具的规则生效。 + +本地 JAR 入口在插件的语言/构建工具设置页,点击“读取本地 JAR 依赖”,选择目标模块并浏览文件后保存。每行一个路径,空格属于路径内容。JDT 的公开项目设置提供模块与实际值。JSONC、XML 和 properties 编辑器保留无关字段及注释;已有 JAR 排除和源码附件不被覆盖。Maven/Gradle 管理的项目使用各自插件的编译设置。 + +运行时状态和暂存放在宿主提供的用户状态/临时目录;插件安装包始终只读。暂存文件由一次保存拥有,完成或取消时删除,不跨工作树共享。新后端与翻译由各平台构建入口打入同一版本包并校验。 + +## Compatibility + +This version requires a desktop host advertising `sourceSettings: 0`. Older hosts retain their previous compatible plugin version. Read compiler settings under Build, Execution, Deployment; read local JAR dependencies on the language/build-system page. Save changes only the listed native sources and rejects a changed baseline. JDK selection and target bytecode are separate settings. + +Tests in `scripts/compiler/` execute the real upstream engine, inspect class-file major versions and run code using an external JAR. HTML and JUnit timing reports are written to `.artifacts/test-stability/`; tests own and clean their temporary workspaces and processes. diff --git a/docs/releases/v2.0.0.md b/docs/releases/v2.0.0.md new file mode 100644 index 0000000..96156f3 --- /dev/null +++ b/docs/releases/v2.0.0.md @@ -0,0 +1,21 @@ +# Java 2.0.0 + +## 中文 + +- 新增真实项目编译设置、项目默认目标与按模块字节码覆盖,保存后重新读取生效配置。 +- 新增本地 JAR 引用入口,保留无关的项目配置与注释。 + +### 兼容性 + +此主版本新增 `sourceSettings: 0` 宿主要求;旧宿主无法安装,应继续使用上一兼容版本或先升级桌面端。读取项目工具可能执行项目代码及下载依赖;仅明确保存才修改列出的配置文件。详见 [编译设置说明](../native-settings.md)。 + +--- + +## English + +- Add native compiler settings with project defaults, per-module bytecode overrides and effective-value readback. +- Add local JAR dependencies while preserving unrelated project configuration and comments. + +### Compatibility + +This major release requires `sourceSettings: 0`. Upgrade the desktop host first, or keep the previous compatible plugin version. Reading project tools may execute project code and download dependencies. Only explicit Save changes the displayed native sources. diff --git a/e2e/host/desktop/internal/settingswindow/plugin_native_source_test.go b/e2e/host/desktop/internal/settingswindow/plugin_native_source_test.go new file mode 100644 index 0000000..a8b3fab --- /dev/null +++ b/e2e/host/desktop/internal/settingswindow/plugin_native_source_test.go @@ -0,0 +1,134 @@ +//go:build vivahead && lithevisual + +package settingswindow + +import ( + "context" + "encoding/json" + "errors" + "os" + "path/filepath" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/marketplace" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginsettings" + "github.com/vivaui/viva/headless" +) + +// This plugin-owned overlay renders the public projection captured from its real +// engine tests. It does not publish files; native publication is tested separately. +type pluginNativeVisualSource struct { + store *pluginsettings.Store + manifest json.RawMessage + packageRoot, workspace string + sources pluginsettings.SourceEditor +} + +func (s *pluginNativeVisualSource) Load(ctx context.Context, _ string, language i18n.Language) (pluginservice.SettingsEditor, error) { + snapshot, err := s.store.LoadPresented(ctx, s.manifest, s.workspace, pluginsettings.Presentation{Package: s.packageRoot, Language: language.Code()}) + return pluginservice.SettingsEditor{Snapshot: snapshot}, err +} +func (s *pluginNativeVisualSource) Save(context.Context, pluginservice.SettingsEditor, string, []core.PluginSettingEdit) (pluginsettings.SaveResult, error) { + return pluginsettings.SaveResult{}, errors.New("visual capture never publishes") +} +func (s *pluginNativeVisualSource) Action(context.Context, pluginservice.SettingsEditor, string, bool) (pluginservice.SettingsActionResult, error) { + return pluginservice.SettingsActionResult{Plan: core.PluginSettingsActionPlan{Kind: "invoke", ActionID: "compiler", SourceEditor: true}, Sources: &s.sources}, nil +} +func (s *pluginNativeVisualSource) SaveSources(context.Context, pluginservice.SettingsEditor, string, pluginsettings.SourceEditor, []core.SourceSettingsEdits) (pluginsettings.SourceEditor, error) { + return s.sources, errors.New("visual capture never publishes") +} + +func TestPluginNativeSourceVisual(t *testing.T) { + packageRoot, input, out := os.Getenv("LITHE_NATIVE_PACKAGE"), os.Getenv("LITHE_NATIVE_SNAPSHOTS"), os.Getenv("LITHE_NATIVE_OUTPUT") + if packageRoot == "" || input == "" || out == "" { + t.Fatal("run the plugin's scripts/compiler/visual.mjs") + } + manifest, err := os.ReadFile(filepath.Join(packageRoot, "plugin.json")) + if err != nil { + t.Fatal(err) + } + var metadata struct { + ID, DisplayName, Version string + SettingActions []struct { + ID string + Page struct{ CompilerID string } + } + } + if err = json.Unmarshal(manifest, &metadata); err != nil { + t.Fatal(err) + } + admission, cancelAdmission := context.WithTimeout(context.Background(), 10*time.Second) + defer cancelAdmission() + if _, err = core.NewClient().ValidatePluginManifest(admission, manifest, pluginhost.Declared()); err != nil { + t.Fatal(err) + } + compilerID := "" + for _, action := range metadata.SettingActions { + if action.ID == "compiler" { + compilerID = action.Page.CompilerID + } + } + if compilerID == "" { + t.Fatal("compiler action missing") + } + if err = os.MkdirAll(out, 0755); err != nil { + t.Fatal(err) + } + for _, language := range []i18n.Language{i18n.Chinese, i18n.English} { + for _, theme := range []string{"dark", "light"} { + t.Run(language.Code()+"-"+theme, func(t *testing.T) { + code := "en" + if language == i18n.Chinese { + code = "zh" + } + raw, err := os.ReadFile(filepath.Join(input, "visual-"+code+".json")) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + state, err := core.NewClient().ReadSourceSettings(ctx, raw) + if err != nil { + t.Fatal(err) + } + source := &pluginNativeVisualSource{store: pluginsettings.New(core.NewClient(), t.TempDir()), manifest: manifest, packageRoot: packageRoot, workspace: t.TempDir(), sources: pluginsettings.SourceEditor{State: state}} + fetch := func(context.Context) (marketplace.Snapshot, error) { + return marketplace.Snapshot{Index: core.MarketplaceIndex{Plugins: []core.MarketplacePlugin{{ID: metadata.ID, Name: metadata.DisplayName, LatestVersion: metadata.Version}}}}, nil + } + w := newWindow(NewController(Options{Text: func() *i18n.Messages { return i18n.For(language) }, Language: func() i18n.Language { return language }, SystemLanguage: language, SystemDark: func() bool { return theme == "dark" }, PluginSettings: source, SettingsNavigation: core.NewClient().SettingsNavigation, SettingsPages: func(ctx context.Context) ([]core.SettingsPage, error) { + return core.NewClient().SettingsPages(ctx, []core.SettingsContribution{{Manifest: manifest, Owner: core.PluginSettingsOwner{PluginID: metadata.ID, Version: metadata.Version}, Enabled: true}}) + }, Marketplace: fetch, MarketplaceInstalled: fetch, PluginState: func(string) PluginState { + return PluginState{Installed: true, Enabled: true, Version: metadata.Version} + }}), Values{Theme: theme, Language: language.Code()}) + config := w.config() + config.Width, config.Height = 1120, 900 + session, err := headless.Open(config, nil, headless.Options{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(session.Close) + d := &windowDriver{t: t, w: w, driver: session.Driver()} + d.until("compiler contribution", func() bool { return len(w.dynamic.pages) > 0 }) + w.selectSettingsPage(pageBuild, "compiler:"+compilerID) + d.until("compiler read action", func() bool { return w.pluginSettings.pageKey == w.dynamicPage && w.pluginSettings.loaded }) + title := "" + for _, action := range w.pluginSettings.editor.Snapshot.State.Actions { + if action.ID == "compiler" { + title = action.Title + } + } + d.click(title) + d.until("native compiler form", func() bool { return w.pluginSettings.sources != nil }) + d.pump() + if err = session.Screenshot(filepath.Join(out, "compiler-"+language.Code()+"-"+theme+".png")); err != nil { + t.Fatal(err) + } + }) + } + } +} diff --git a/io.github.lithe-idea.java-support/l10n/zh-Hans.json b/io.github.lithe-idea.java-support/l10n/zh-Hans.json new file mode 100644 index 0000000..fde8cd0 --- /dev/null +++ b/io.github.lithe-idea.java-support/l10n/zh-Hans.json @@ -0,0 +1,12 @@ +{ + "settingActions": { + "compiler": { + "title": "读取编译设置", + "description": "读取工具的实际配置;保存时写入页面列出的原生配置文件。" + }, + "libraries": { + "title": "读取本地 JAR 依赖", + "description": "读取项目实际引用的 JAR;保存时更新页面列出的原生配置文件。" + } + } +} diff --git a/io.github.lithe-idea.java-support/plugin.json b/io.github.lithe-idea.java-support/plugin.json index e2ff51a..a00c20c 100644 --- a/io.github.lithe-idea.java-support/plugin.json +++ b/io.github.lithe-idea.java-support/plugin.json @@ -2,9 +2,9 @@ "schemaVersion": 0, "id": "io.github.lithe-idea.java-support", "displayName": "Java Support", - "version": "1.3.0", + "version": "2.0.0", "pluginAPIVersion": 0, - "requires": {"backend": 0, "debugAdapters": 0, "languages": 0, "languageServers": 0, "pluginFunctions": 0, "settings": 0, "projectGenerators": 0, "toolDefinitions": 0}, + "requires": {"backend": 0, "debugAdapters": 0, "languages": 0, "languageServers": 0, "pluginFunctions": 0, "settings": 0, "projectGenerators": 0, "toolDefinitions": 0, "sourceSettings": 0}, "requiresTools": ["java"], "vendor": { "id": "io.github.lithe-idea", @@ -485,5 +485,6 @@ {"path": "build.gradle.kts", "when": {"field": "type", "equals": "gradle-project-kotlin"}} ] } - ] + ], + "settingActions": [{"id": "compiler", "title": "Read compiler settings", "description": "Read actual Eclipse JDT project settings. Save writes the displayed native preferences or library configuration files.", "function": "compiler.settings", "sourceEditor": {"editFunction": "compiler.prepareSettings", "languageID": "java"}, "page": {"compilerID": "java"}}, {"id": "libraries", "title": "Read local JAR dependencies", "description": "Read actual Eclipse JDT project settings. Save writes the displayed native preferences or library configuration files.", "function": "libraries.settings", "sourceEditor": {"editFunction": "compiler.prepareSettings", "languageID": "java"}, "page": {"languageID": "java"}}] } diff --git a/scripts/assemble-package.sh b/scripts/assemble-package.sh index f77f0d0..1db6497 100755 --- a/scripts/assemble-package.sh +++ b/scripts/assemble-package.sh @@ -54,9 +54,10 @@ backend_path=$(/usr/bin/plutil -extract backend.launch.path raw -o - "$PLUGIN_DI jdtls_root=$(LITHE_ARCH="$ARCH" "$ROOT_DIR/scripts/prepare-jdtls.sh") language_server="$OUTPUT_DIR/language-server" -rm -rf "$language_server" "$OUTPUT_DIR/runtime" "$OUTPUT_DIR/icons" "$OUTPUT_DIR/templates" "$OUTPUT_DIR/bin" +rm -rf "$language_server" "$OUTPUT_DIR/runtime" "$OUTPUT_DIR/icons" "$OUTPUT_DIR/templates" "$OUTPUT_DIR/l10n" "$OUTPUT_DIR/bin" cp -R "$PLUGIN_DIR/icons" "$OUTPUT_DIR/icons" cp -R "$PLUGIN_DIR/templates" "$OUTPUT_DIR/templates" +cp -R "$PLUGIN_DIR/l10n" "$OUTPUT_DIR/l10n" mkdir -p "$language_server/configuration" # Only what a macOS launch reads is packaged. The wrapper scripts and the diff --git a/scripts/compiler/capture.mjs b/scripts/compiler/capture.mjs new file mode 100644 index 0000000..61c4dae --- /dev/null +++ b/scripts/compiler/capture.mjs @@ -0,0 +1,7 @@ +// Captures only the public non-sensitive projection for plugin-owned visual checks. +import {mkdirSync,writeFileSync} from 'node:fs'; +import {resolve,join} from 'node:path'; +export function capture(language,snapshot){ + const root=resolve('.artifacts/compiler');mkdirSync(root,{recursive:true}); + writeFileSync(join(root,`visual-${language}.json`),JSON.stringify(snapshot,null,2)); +} diff --git a/scripts/compiler/process.mjs b/scripts/compiler/process.mjs new file mode 100644 index 0000000..d3ae40f --- /dev/null +++ b/scripts/compiler/process.mjs @@ -0,0 +1,37 @@ +// Integration-test tools run in owned process trees with bounded output and cleanup. +import {spawn,execFile} from 'node:child_process'; +const LIMIT=2*1024*1024; +export function runTool(tool,args,{cwd,env=process.env,timeout=120000}={}) { + let command=tool,parameters=args,verbatim=false; + if(process.platform==='win32'&&/\.(cmd|bat)$/i.test(tool)) { + const quote=value=>{if(/["%\r\n]/.test(value))throw Error('Unsupported batch test argument');return `"${value}"`;}; + command=process.env.ComSpec??'cmd.exe';parameters=['/d','/v:off','/s','/c',`"${[tool,...args].map(quote).join(' ')}"`];verbatim=true; + } + return new Promise((resolve,reject)=>{ + const child=spawn(command,parameters,{cwd,env,detached:process.platform!=='win32',windowsHide:true,windowsVerbatimArguments:verbatim,stdio:['ignore','pipe','pipe']}); + let output=Buffer.alloc(0),errorOutput=Buffer.alloc(0),failure,done=false,stopping=false,cleanup; + const kill=()=>{ + if(!child.pid)return; + if(process.platform==='win32') { + if(child.exitCode!==null)return; + execFile('taskkill.exe',['/PID',String(child.pid),'/T','/F'],{timeout:5000,windowsHide:true},error=>{if(error&&child.exitCode===null)failure??=error;}); + } else {try{process.kill(-child.pid,'SIGKILL');}catch(error){if(error.code!=='ESRCH')failure??=error;}} + }; + const finish=()=>{ + if(done)return;done=true;clearTimeout(timer);clearTimeout(cleanup); + process.off('SIGINT',interrupt);process.off('SIGTERM',interrupt); + if(failure)reject(failure);else if(child.exitCode!==0)reject(Error(`Tool failed (${child.exitCode}): ${errorOutput.toString()}\n${output.toString()}`));else resolve(output); + }; + const stop=error=>{ + failure??=error;if(stopping)return;stopping=true;kill(); + cleanup=setTimeout(()=>{kill();child.stdout.destroy();child.stderr.destroy();child.unref();failure=Error('Tool cleanup timed out',{cause:failure});finish();},6000); + }; + const interrupt=()=>stop(Error('Tool interrupted')); + const timer=setTimeout(()=>stop(Error('Tool timed out')),timeout); + process.once('SIGINT',interrupt);process.once('SIGTERM',interrupt); + child.stdout.on('data',bytes=>{if(output.length+bytes.length>LIMIT)stop(Error('Tool output exceeds limit'));else output=Buffer.concat([output,bytes]);}); + child.stderr.on('data',bytes=>{if(errorOutput.length+bytes.length>LIMIT)stop(Error('Tool error output exceeds limit'));else errorOutput=Buffer.concat([errorOutput,bytes]);}); + child.once('error',error=>stop(error)); + child.once('close',()=>{kill();finish();}); + }); +} diff --git a/scripts/compiler/process.test.mjs b/scripts/compiler/process.test.mjs new file mode 100644 index 0000000..5d84b88 --- /dev/null +++ b/scripts/compiler/process.test.mjs @@ -0,0 +1,11 @@ +import {test} from 'node:test'; +import assert from 'node:assert/strict'; +import {runTool} from './process.mjs'; +test('bounded tool runner returns output and rejects a failed command',async()=>{ + assert.equal((await runTool(process.execPath,['-e','process.stdout.write("ready")'])).toString(),'ready'); + await assert.rejects(runTool(process.execPath,['-e','process.exit(3)']),/Tool failed/); +}); +test('a tool deadline terminates an owned tree including its descendant',async()=>{ + const code=`const {spawn}=require('node:child_process');spawn(process.execPath,['-e','setInterval(()=>{},1000)'],{stdio:'inherit'});setInterval(()=>{},1000);`; + await assert.rejects(runTool(process.execPath,['-e',code],{timeout:2500}),/Tool timed out/); +}); diff --git a/scripts/compiler/test-live.mjs b/scripts/compiler/test-live.mjs new file mode 100644 index 0000000..29c06f0 --- /dev/null +++ b/scripts/compiler/test-live.mjs @@ -0,0 +1,65 @@ +// Real packaged JDT + SDK backend, with bounded process ownership. This tests +// native sources reaching the engine rather than only checking RPC invocation. +import assert from 'node:assert/strict'; +import {createReport} from '../report.mjs'; +import {capture} from './capture.mjs'; +import {mkdtempSync,realpathSync,mkdirSync,rmSync,readFileSync,writeFileSync,renameSync,readdirSync,lstatSync,existsSync} from 'node:fs'; +import {tmpdir} from 'node:os'; +import {join,resolve} from 'node:path'; +import {pathToFileURL,fileURLToPath} from 'node:url'; +import {runTool} from './process.mjs'; +import {createHash} from 'node:crypto'; +import {setTimeout as delay} from 'node:timers/promises'; +import {Client} from '../package/lsp-client.mjs'; +const pkg=resolve(process.argv[2]??'.artifacts/package/arm64/io.github.lithe-idea.java-support'); +const manifest=JSON.parse(readFileSync(join(pkg,'plugin.json'))); +const stage=realpathSync(mkdtempSync(join(tmpdir(),'lithe-java-native-'))); +const root=join(stage,'workspace');mkdirSync(root);let backend,server,configuration={}; +const eclipse=process.env.LITHE_JAVA_PROJECT_KIND==='eclipse'; +const sourceFile=join(root,eclipse?'src/Main.java':'Main.java'); +if(eclipse){mkdirSync(join(root,'src'));writeFileSync(join(root,'.project'),'FixtureNativeorg.eclipse.jdt.core.javabuilderorg.eclipse.jdt.core.javanature');writeFileSync(join(root,'.classpath'),'');} +const context={contextID:'ctx-1',generation:1};let op=0; +const snapshot=root=>{const items=[];const visit=(path,label)=>{const stat=lstatSync(path);assert.equal(stat.isSymbolicLink(),false);items.push([label,stat.mode,stat.isFile()?createHash('sha256').update(readFileSync(path)).digest('hex'):null]);if(stat.isDirectory())for(const name of readdirSync(path).sort())visit(join(path,name),`${label}/${name}`);};visit(root,'');return items;}; +const baseline=snapshot(pkg); +const folders=[{rootID:'root',name:'workspace',path:root,uri:pathToFileURL(root).href}]; +const execute=(command,args=[])=>server.request('workspace/executeCommand',{command,arguments:args}); +const report=createReport(eclipse?'native-jdt-eclipse':'native-jdt-unmanaged'); +const step=report.step; +async function until(get,accept,label){const end=Date.now()+45000;let last;while(Date.now()({context,...context,folders}), + 'lithe/host/workspace/getFolders':()=>({folders}), + 'lithe/host/functions/providers':()=>({providers:[]}), + 'lithe/host/languageServer/request':async p=>({value:await server.request(p.method,p.params,p.timeoutMilliseconds??60000)}), + 'lithe/host/languageServer/notify':p=>{if(p.method==='workspace/didChangeConfiguration')configuration=p.params.settings;server.notify(p.method,p.params);return {};}, + }; + backend=new Client(join(pkg,manifest.backend.launch.path),[],{hostRequests}); + await backend.request('initialize',{processId:process.pid,rootUri:pathToFileURL(root).href,capabilities:{experimental:{litheFunctions:{versions:[0]},litheLogging:{versions:[0]}}}});backend.notify('initialized',{}); + const params={serverID:'java',platform:{os:process.platform==='darwin'?'macos':process.platform,arch:process.env.LITHE_TEST_ARCH??(process.arch==='arm64'?'arm64':'x86_64')},settings:{logLevel:'WARNING'}}; + for(const[key,name]of Object.entries({stateDirectory:'state',workspaceStateDirectory:'workspace-state',logDirectory:'logs',temporaryDirectory:'tmp'})){params[key]=join(stage,name);mkdirSync(params[key]);} + const launch=await backend.request('lithe/function/invoke',{functionID:'java.resolveLaunch',operationID:`native-${++op}`,params,context});configuration=launch.workspaceConfiguration; + server=new Client(join(pkg,launch.executable.path),launch.arguments,{env:{...process.env,...launch.environment},hostRequests:{'workspace/configuration':p=>p.items.map(item=>item.section?item.section.split('.').reduce((value,key)=>value?.[key],configuration)??null:configuration)}}); + await server.request('initialize',{processId:process.pid,rootUri:pathToFileURL(root).href,workspaceFolders:[{uri:pathToFileURL(root).href,name:'workspace'}],capabilities:{workspace:{configuration:true,workspaceFolders:true},textDocument:{publishDiagnostics:{}}},initializationOptions:launch.initializationOptions},120000);server.notify('initialized',{}); + backend.notify('lithe/host/languageServer/didChangeState',{context,serverID:'java',state:'running',generation:1}); + const invoke=(functionID,params)=>backend.request('lithe/function/invoke',{functionID,operationID:`native-${++op}`,params,context},90000); + let sources; + await step('Discover the project from the real JDT server',async()=>{await until(()=>execute('java.project.getAll'),projects=>projects.some(uri=>(process.platform==='win32'?fileURLToPath(uri).replace(/[\\/]$/,'').toLowerCase()===root.toLowerCase():fileURLToPath(uri).replace(/\/$/,'')===root)),'JDT project import');sources=await invoke('libraries.settings',{context:{language:'zh-CN',builds:[]}});assert.equal(sources.sources[0].path,eclipse?'.classpath':'.vscode/settings.json');}); + await step('Save a referenced JAR and confirm JDT resolves the actual classpath',async()=>{const source=sources.sources[0],stageFile=join(stage,'libraries-stage.json');writeFileSync(stageFile,'');await invoke('compiler.prepareSettings',{operation:'editSource',sourceID:source.id,revision:source.revision,values:{libraries:[jar]},outputFile:stageFile});mkdirSync(join(root,'.vscode'),{recursive:true});renameSync(stageFile,join(root,source.path));await invoke('libraries.settings',{operation:'readAfterSave',context:{language:'zh-CN',builds:[]}});if(!eclipse)await until(()=>execute('java.project.getSettings',[pathToFileURL(root).href,['org.eclipse.jdt.ls.core.referencedLibraries']]),value=>value['org.eclipse.jdt.ls.core.referencedLibraries']?.includes(jar),'JDT classpath refresh');}); + await step('Save native compiler target and verify real JDT effective settings',async()=>{sources=await invoke('compiler.settings',{context:{language:'zh-CN',builds:[]}});const source=sources.sources.find(s=>s.id==='defaults'),stageFile=join(stage,'compiler-stage.prefs');writeFileSync(stageFile,'');await invoke('compiler.prepareSettings',{operation:'editSource',sourceID:source.id,revision:source.revision,values:{target:'8'},outputFile:stageFile});mkdirSync(join(root,'.settings'),{recursive:true});renameSync(stageFile,join(root,source.path));await invoke('compiler.settings',{operation:'readAfterSave',context:{language:'zh-CN',builds:[]}});await until(()=>execute('java.project.getSettings',[pathToFileURL(root).href,['org.eclipse.jdt.core.compiler.codegen.targetPlatform']]),value=>value['org.eclipse.jdt.core.compiler.codegen.targetPlatform']==='1.8','JDT compiler refresh');}); + await step('Compile with JDT, inspect Java 8 bytecode and run with the external JAR',async()=>{ + const result=await execute('vscode.java.buildWorkspace',[JSON.stringify({mainClass:'Main',filePath:sourceFile,isFullBuild:true})]);assert.equal(result,1); + const paths=await execute('vscode.java.resolveClasspath',['Main','']); + const classes=paths.flat().find(path=>typeof path==='string'&&existsSync(join(path,'Main.class')));assert.ok(classes,JSON.stringify(paths)); + assert.equal(readFileSync(join(classes,'Main.class')).readUInt16BE(6),52); + const output=await runTool(process.env.LITHE_TEST_JAVA??'java',['-cp',classes+(process.platform==='win32'?';':':')+jar,'Main'],{timeout:30000});assert.equal(output.toString(),'jar-ok'); + }); + capture('zh',await invoke('compiler.settings',{context:{language:'zh-CN',builds:[]}}));capture('en',await invoke('compiler.settings',{context:{language:'en',builds:[]}})); + assert.deepEqual(snapshot(pkg),baseline,'Native settings and server startup must never mutate the installed package'); + await server.request('shutdown',null);server.notify('exit',null); +}finally{ + try{if(server)await server.close();}finally{try{if(backend)await backend.close();}finally{report.write();rmSync(stage,{recursive:true,force:true});}} +} diff --git a/scripts/compiler/visual.mjs b/scripts/compiler/visual.mjs new file mode 100644 index 0000000..d612300 --- /dev/null +++ b/scripts/compiler/visual.mjs @@ -0,0 +1,16 @@ +// Plugin-owned tests are injected through a Go overlay; no test or plugin data +// is copied into the host repository. Pass an explicit host checkout to validate. +import {readFileSync,writeFileSync,mkdirSync} from 'node:fs'; +import {resolve,join} from 'node:path'; +import {fileURLToPath} from 'node:url'; +import {runTool} from './process.mjs'; +const root=fileURLToPath(new URL('../..',import.meta.url)); +const host=resolve(process.argv[2]??'');if(!process.argv[2])throw Error('Usage: node scripts/compiler/visual.mjs '); +const manifest=JSON.parse(readFileSync(join(root,'compiler-host.json'))); +const stage=join(root,'.artifacts/compiler');mkdirSync(stage,{recursive:true}); +const target=join(host,'desktop/internal/settingswindow/plugin_native_source_test.go'); +const overlay=join(stage,'overlay.json');writeFileSync(overlay,JSON.stringify({Replace:{[target]:join(root,'e2e/host/desktop/internal/settingswindow/plugin_native_source_test.go')}})); +const revision=(await runTool('git',['-C',host,'rev-parse','HEAD'])).toString().trim(); +writeFileSync(join(stage,'visual-host.json'),JSON.stringify({repository:manifest.repository,revision,core:process.env.LITHE_CORE_RUST_DIR??'host pin'},null,2)); +const result=await runTool(process.env.LITHE_TEST_BASH??'bash',['scripts/desktop/desktop-go.sh','test','-overlay',overlay,'-tags','vivahead lithevisual','./internal/settingswindow','-run','^TestPluginNativeSourceVisual$','-count=1','-timeout=120s'],{cwd:host,env:{...process.env,LITHE_NATIVE_PACKAGE:join(root,manifest.package),LITHE_NATIVE_SNAPSHOTS:stage,LITHE_NATIVE_OUTPUT:join(stage,'visual')},timeout:1200000}); +process.stdout.write(result); diff --git a/scripts/package/build-linux.mjs b/scripts/package/build-linux.mjs index edb8867..2523e68 100644 --- a/scripts/package/build-linux.mjs +++ b/scripts/package/build-linux.mjs @@ -37,7 +37,7 @@ function verify(directory){ try{ mkdirSync(pkg); cpSync(join(root,id,'plugin.json'),join(pkg,'plugin.json')); - for(const name of ['icons','templates'])cpSync(join(root,id,name),join(pkg,name),{recursive:true}); + for(const name of ['icons','templates','l10n'])cpSync(join(root,id,name),join(pkg,name),{recursive:true}); mkdirSync(join(pkg,'runtime'));cpSync(runtime,join(pkg,'runtime',target.runtime),{recursive:true}); const language=join(pkg,'language-server');mkdirSync(language); for(const name of ['plugins','features','lombok','java-debug','java-test','manifest.json','LICENSE-EPL-2.0.txt'])cpSync(join(jdt,name),join(language,name),{recursive:true}); diff --git a/scripts/package/build-windows.mjs b/scripts/package/build-windows.mjs index c5c9d60..7ff13cf 100644 --- a/scripts/package/build-windows.mjs +++ b/scripts/package/build-windows.mjs @@ -75,7 +75,7 @@ try { if (!/^JAVA_VERSION="21\./m.test(release)) throw new Error('The pinned runtime must be Java 21.'); await mkdir(join(packageRoot, 'runtime'), { recursive: true }); await cp(runtime, join(packageRoot, 'runtime/x86_64'), { recursive: true }); - for (const name of ['icons', 'templates']) await cp(join(root, id, name), join(packageRoot, name), { recursive: true }); + for (const name of ['icons', 'templates', 'l10n']) await cp(join(root, id, name), join(packageRoot, name), { recursive: true }); const languageServer = join(packageRoot, 'language-server'); await mkdir(languageServer); for (const name of ['plugins', 'features', 'lombok', 'java-debug', 'java-test', 'manifest.json', 'LICENSE-EPL-2.0.txt']) { diff --git a/scripts/package/lsp-client.mjs b/scripts/package/lsp-client.mjs index fafe9e3..07a2b00 100644 --- a/scripts/package/lsp-client.mjs +++ b/scripts/package/lsp-client.mjs @@ -1,10 +1,11 @@ // Bounded integration-test client. Each child owns a process group; cleanup // runs after success, protocol failure, and request timeout. -import {spawn} from 'node:child_process'; +import {spawn,execFileSync} from 'node:child_process'; export class Client { constructor(executable,args=[],options={}){ + this.hostRequests=options.hostRequests??{};const {hostRequests,...spawnOptions}=options; this.next=1;this.pending=new Map();this.buffer=Buffer.alloc(0);this.stderr=''; - this.child=spawn(executable,args,{...options,detached:true,stdio:['pipe','pipe','pipe']}); + this.child=spawn(executable,args,{...spawnOptions,detached:true,stdio:['pipe','pipe','pipe']}); this.exited=new Promise(resolve=>{this.child.once('exit',(code,signal)=>{this.fail(Error(`Process exited: ${code}/${signal}: ${this.stderr}`));resolve();});this.child.once('error',error=>{this.fail(error);resolve();});}); this.child.stdin.on('error',error=>this.fail(error)); this.child.stderr.on('data',bytes=>{this.stderr=(this.stderr+bytes).slice(-65536);}); @@ -18,8 +19,9 @@ export class Client { if(this.buffer.length({})):null; - this.send({id:message.id,result}); + const handler=this.hostRequests[message.method]; + if(handler){Promise.resolve().then(()=>handler(message.params)).then(result=>this.send({id:message.id,result}),error=>this.send({id:message.id,error:{code:-32603,message:error.message}}));} + else{const result=message.method==='workspace/configuration'?(message.params?.items??[]).map(()=>({})):null;this.send({id:message.id,result});} }else if(message.id!==undefined){const item=this.pending.get(message.id);if(item){this.pending.delete(message.id);clearTimeout(item.timer);message.error?item.reject(Error(JSON.stringify(message.error))):item.resolve(message.result);}} } }catch(error){this.fail(error);} @@ -37,7 +39,7 @@ export class Client { } async close(){ this.fail(Error('Client closed')); - if(this.child.pid){try{process.kill(-this.child.pid,'SIGKILL');}catch(error){if(error.code!=='ESRCH')throw error;}} + if(this.child.pid){try{if(process.platform==='win32'){if(this.child.exitCode===null)execFileSync('taskkill.exe',['/PID',String(this.child.pid),'/T','/F'],{timeout:5000,windowsHide:true,stdio:'ignore'});}else process.kill(-this.child.pid,'SIGKILL');}catch(error){if(error.code!=='ESRCH')throw error;}} let timer;try{await Promise.race([this.exited,new Promise((_,reject)=>{timer=setTimeout(()=>reject(Error('Process cleanup timed out')),5000);})]);}finally{clearTimeout(timer);} } } diff --git a/scripts/report.mjs b/scripts/report.mjs new file mode 100644 index 0000000..75bfb9b --- /dev/null +++ b/scripts/report.mjs @@ -0,0 +1,48 @@ +// Dependency-free per-step reports for packaging and the Maven integration lane. +import { mkdirSync, writeFileSync } from "node:fs"; +import { join, resolve } from "node:path"; +import { performance } from "node:perf_hooks"; + +const escape = (value) => String(value).replace(/[&<>"']/g, (char) => ({ + "&": "&", "<": "<", ">": ">", '"': """, "'": "'", +})[char]); + +export function createReport(lane) { + const started = performance.now(); + const tests = []; + const step = async (name, body) => { + const before = performance.now(); + const test = { name, suite: lane, status: "passed", durationMs: 0 }; + tests.push(test); + try { return await body(); } + catch (error) { + test.status = "failed"; + test.details = error.stack ?? String(error); + throw error; + } finally { + test.durationMs = performance.now() - before; + console.log(`${test.status === "passed" ? "✓" : "✗"} ${name} (${test.durationMs.toFixed(1)} ms)`); + } + }; + const write = () => { + const directory = resolve(process.env.LITHE_REPORT_DIR ?? ".artifacts/test-stability"); + mkdirSync(directory, { recursive: true }); + const durationMs = performance.now() - started; + const failures = tests.filter((test) => test.status === "failed").length; + const errors = tests.filter((test) => test.status === "error").length; + const report = { schemaVersion: 1, runner: "node", lane, warnMs: 1_000, maxMs: 610_000, durationMs, tests }; + writeFileSync(join(directory, `${lane}.json`), `${JSON.stringify(report, null, 2)}\n`); + const cases = tests.map((test) => { + const tag = test.status === "error" ? "error" : "failure"; + return ` ${test.details ? `<${tag} message="step failed">${escape(test.details)}` : ""}`; + }); + writeFileSync(join(directory, `${lane}.junit.xml`), `\n\n${cases.join("\n")}\n\n`); + const rows = tests.map((test) => `${escape(test.name)}${test.durationMs.toFixed(1)}${test.status}${test.details ? `
${escape(test.details)}
` : ""}`); + writeFileSync(join(directory, `${lane}.html`), `${escape(lane)}

${escape(lane)}

${tests.length} steps, ${failures} failures, ${errors} errors, ${durationMs.toFixed(1)} ms total

${rows.join("\n")}
StepDuration (ms)Result
\n`); + console.log(`Timing reports: ${join(directory, `${lane}.html`)} (JSON, JUnit alongside)`); + }; + const failure = (name, error) => { + tests.push({ name, suite: lane, status: "error", durationMs: 0, details: error.stack ?? String(error) }); + }; + return { step, write, failure }; +} diff --git a/scripts/verify-package.sh b/scripts/verify-package.sh index 48c6b50..2477b0e 100755 --- a/scripts/verify-package.sh +++ b/scripts/verify-package.sh @@ -53,7 +53,7 @@ for notice in LICENSE NOTICE; do done node "$ROOT_DIR/scripts/package/collect-notices.mjs" --verify "$PACKAGE" -allowed=(plugin.json bin icons templates language-server runtime LICENSE NOTICE licenses) +allowed=(plugin.json bin icons templates l10n language-server runtime LICENSE NOTICE licenses) for entry in "$PACKAGE"/*(DN); do (( ${allowed[(Ie)${entry:t}]} )) || fail "undeclared top-level entry ${entry:t}" done From ae5b4ed273cf5f3119700e50a02c9082d4e63fb4 Mon Sep 17 00:00:00 2001 From: lick <2188718831@qq.com> Date: Sun, 15 Nov 2026 09:54:39 -0800 Subject: [PATCH 2/3] test(settings): normalize native Windows project paths and update host pin --- compiler-host.json | 2 +- scripts/compiler/test-live.mjs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/compiler-host.json b/compiler-host.json index 6348c6c..ff84420 100644 --- a/compiler-host.json +++ b/compiler-host.json @@ -1,6 +1,6 @@ { "repository": "https://github.com/1lck/Lithe-IDEA", - "revision": "dbdee96b853b0e720167dc1ff30163b10d353aef", + "revision": "e9ce7781f1a9635ced8a090b45a159af4f5ce959", "coreRevision": "5802c42b5766df7375bd427c54203db415ff72d7", "package": "io.github.lithe-idea.java-support" } diff --git a/scripts/compiler/test-live.mjs b/scripts/compiler/test-live.mjs index 29c06f0..b55592f 100644 --- a/scripts/compiler/test-live.mjs +++ b/scripts/compiler/test-live.mjs @@ -13,7 +13,7 @@ import {setTimeout as delay} from 'node:timers/promises'; import {Client} from '../package/lsp-client.mjs'; const pkg=resolve(process.argv[2]??'.artifacts/package/arm64/io.github.lithe-idea.java-support'); const manifest=JSON.parse(readFileSync(join(pkg,'plugin.json'))); -const stage=realpathSync(mkdtempSync(join(tmpdir(),'lithe-java-native-'))); +const stage=realpathSync.native(mkdtempSync(join(tmpdir(),'lithe-java-native-'))); const root=join(stage,'workspace');mkdirSync(root);let backend,server,configuration={}; const eclipse=process.env.LITHE_JAVA_PROJECT_KIND==='eclipse'; const sourceFile=join(root,eclipse?'src/Main.java':'Main.java'); From 57e71a7f682d32cbcabc2284051486f09f4e6fa5 Mon Sep 17 00:00:00 2001 From: lick <2188718831@qq.com> Date: Sun, 15 Nov 2026 10:11:16 -0800 Subject: [PATCH 3/3] test(java): compare JDT Windows library paths case insensitively --- scripts/compiler/test-live.mjs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/scripts/compiler/test-live.mjs b/scripts/compiler/test-live.mjs index b55592f..9b9ca10 100644 --- a/scripts/compiler/test-live.mjs +++ b/scripts/compiler/test-live.mjs @@ -19,6 +19,7 @@ const eclipse=process.env.LITHE_JAVA_PROJECT_KIND==='eclipse'; const sourceFile=join(root,eclipse?'src/Main.java':'Main.java'); if(eclipse){mkdirSync(join(root,'src'));writeFileSync(join(root,'.project'),'FixtureNativeorg.eclipse.jdt.core.javabuilderorg.eclipse.jdt.core.javanature');writeFileSync(join(root,'.classpath'),'');} const context={contextID:'ctx-1',generation:1};let op=0; +const samePath=(left,right)=>process.platform==='win32'?resolve(left).toLowerCase()===resolve(right).toLowerCase():resolve(left)===resolve(right); const snapshot=root=>{const items=[];const visit=(path,label)=>{const stat=lstatSync(path);assert.equal(stat.isSymbolicLink(),false);items.push([label,stat.mode,stat.isFile()?createHash('sha256').update(readFileSync(path)).digest('hex'):null]);if(stat.isDirectory())for(const name of readdirSync(path).sort())visit(join(path,name),`${label}/${name}`);};visit(root,'');return items;}; const baseline=snapshot(pkg); const folders=[{rootID:'root',name:'workspace',path:root,uri:pathToFileURL(root).href}]; @@ -48,7 +49,7 @@ try{ const invoke=(functionID,params)=>backend.request('lithe/function/invoke',{functionID,operationID:`native-${++op}`,params,context},90000); let sources; await step('Discover the project from the real JDT server',async()=>{await until(()=>execute('java.project.getAll'),projects=>projects.some(uri=>(process.platform==='win32'?fileURLToPath(uri).replace(/[\\/]$/,'').toLowerCase()===root.toLowerCase():fileURLToPath(uri).replace(/\/$/,'')===root)),'JDT project import');sources=await invoke('libraries.settings',{context:{language:'zh-CN',builds:[]}});assert.equal(sources.sources[0].path,eclipse?'.classpath':'.vscode/settings.json');}); - await step('Save a referenced JAR and confirm JDT resolves the actual classpath',async()=>{const source=sources.sources[0],stageFile=join(stage,'libraries-stage.json');writeFileSync(stageFile,'');await invoke('compiler.prepareSettings',{operation:'editSource',sourceID:source.id,revision:source.revision,values:{libraries:[jar]},outputFile:stageFile});mkdirSync(join(root,'.vscode'),{recursive:true});renameSync(stageFile,join(root,source.path));await invoke('libraries.settings',{operation:'readAfterSave',context:{language:'zh-CN',builds:[]}});if(!eclipse)await until(()=>execute('java.project.getSettings',[pathToFileURL(root).href,['org.eclipse.jdt.ls.core.referencedLibraries']]),value=>value['org.eclipse.jdt.ls.core.referencedLibraries']?.includes(jar),'JDT classpath refresh');}); + await step('Save a referenced JAR and confirm JDT resolves the actual classpath',async()=>{const source=sources.sources[0],stageFile=join(stage,'libraries-stage.json');writeFileSync(stageFile,'');await invoke('compiler.prepareSettings',{operation:'editSource',sourceID:source.id,revision:source.revision,values:{libraries:[jar]},outputFile:stageFile});mkdirSync(join(root,'.vscode'),{recursive:true});renameSync(stageFile,join(root,source.path));await invoke('libraries.settings',{operation:'readAfterSave',context:{language:'zh-CN',builds:[]}});if(!eclipse)await until(()=>execute('java.project.getSettings',[pathToFileURL(root).href,['org.eclipse.jdt.ls.core.referencedLibraries']]),value=>value['org.eclipse.jdt.ls.core.referencedLibraries']?.some(path=>samePath(path,jar)),'JDT classpath refresh');}); await step('Save native compiler target and verify real JDT effective settings',async()=>{sources=await invoke('compiler.settings',{context:{language:'zh-CN',builds:[]}});const source=sources.sources.find(s=>s.id==='defaults'),stageFile=join(stage,'compiler-stage.prefs');writeFileSync(stageFile,'');await invoke('compiler.prepareSettings',{operation:'editSource',sourceID:source.id,revision:source.revision,values:{target:'8'},outputFile:stageFile});mkdirSync(join(root,'.settings'),{recursive:true});renameSync(stageFile,join(root,source.path));await invoke('compiler.settings',{operation:'readAfterSave',context:{language:'zh-CN',builds:[]}});await until(()=>execute('java.project.getSettings',[pathToFileURL(root).href,['org.eclipse.jdt.core.compiler.codegen.targetPlatform']]),value=>value['org.eclipse.jdt.core.compiler.codegen.targetPlatform']==='1.8','JDT compiler refresh');}); await step('Compile with JDT, inspect Java 8 bytecode and run with the external JAR',async()=>{ const result=await execute('vscode.java.buildWorkspace',[JSON.stringify({mainClass:'Main',filePath:sourceFile,isFullBuild:true})]);assert.equal(result,1);