diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c5e1545..1555e44 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -67,6 +67,13 @@ jobs: with: path: .artifacts/jdtls-downloads key: third-party-${{ hashFiles('third_party/*/manifest.json') }} + # The package ships no JDK. This one compiles the plugin's own JDT LS + # extension bundle while packaging, and the integration tests run the + # tested JDT LS release on it, as a user's JDK 21+ would. + - uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: "21" - name: Build, verify and archive both architectures run: | set -euo pipefail @@ -74,17 +81,12 @@ jobs: package=$(scripts/build-package.sh --arch "$arch") scripts/archive-package.sh --package "$package" --arch "$arch" done - # The package ships no JDK; the integration tests run the tested JDT LS - # release on this one, as a user's JDK 21+ would. - - uses: actions/setup-java@v5 - with: - distribution: temurin - java-version: "21" - name: Verify native compiler settings and JARs with the user's JDT LS 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" + node scripts/compiler/test-project-models.mjs "$package" - name: Upload native compiler projections uses: actions/upload-artifact@v4 with: @@ -139,6 +141,12 @@ jobs: run: node scripts/package/build-linux.mjs "${{ matrix.arch }}" - name: Start the packaged backend and the user's language server run: node scripts/package/smoke-linux.mjs dist/*-linux-${{ matrix.arch }}.zip + - name: Compile legacy and cross-IDE project models with the user's language server + run: | + package=$(mktemp -d) + unzip -q dist/*-linux-${{ matrix.arch }}.zip -d "$package" + node scripts/compiler/test-project-models.mjs "$package/io.github.lithe-idea.java-support" + rm -rf "$package" - uses: actions/upload-artifact@v4 with: name: java-linux-${{ matrix.arch }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 2e51b99..605b30d 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -98,6 +98,12 @@ jobs: echo "::error::Tag $GITHUB_REF_NAME does not match plugin.json version $version" exit 1 fi + # Packaging compiles the plugin's own JDT LS extension bundle, which + # needs javac 21 or later (scripts/package/project-model-bundle.mjs). + - uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: "21" - name: Build and verify both architectures run: | set -euo pipefail diff --git a/README.md b/README.md index 89536a9..2151e64 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,9 @@ # Java Support for Lithe +> **3.0.1 识别旧式与跨 IDE 工程**:没有 Maven/Gradle 的项目,插件只读识别 Eclipse WTP/MyEclipse 容器 +> (Web App Libraries、EAR Libraries、Server Runtime)、IntelliJ IDEA 的模块与库,以及传统 Web 的 `WEB-INF/lib`, +> 在内存中补全类路径并自动找到 Tomcat 等 Servlet 容器,不修改项目文件,详见 [docs/project-models.md](docs/project-models.md)。 +> > **3.0.0 起使用你自己的 JDT LS**:插件包不再附带 Eclipse JDT Language Server 和运行它的 JDK(包从约 250 MB 降到约 11 MB), > 做法和 Go 插件使用你自己的 `gopls` 一样。需要先安装 JDT LS(例如 `brew install jdtls`)和 JDK 21 或更新版本, > 详见下文[语言服务器与 JDK](#语言服务器与-jdk)。 diff --git a/backend/src/launch.rs b/backend/src/launch.rs index 7b09325..a54e128 100644 --- a/backend/src/launch.rs +++ b/backend/src/launch.rs @@ -52,6 +52,7 @@ use crate::jdtls::{ self, SearchEnvironment, ServerInstallation, LAUNCH_SERVER_INVALID, LAUNCH_SERVER_MISSING, SERVER_HOME_SETTING, }; +use crate::project_model::{ModelOptions, ProjectModel}; use crate::run::file_uri; use crate::settings_session::{java_configuration, jdt_settings, SettingsSession, SERVER_ID}; use lithe_java_domain::jdt_integration::launch_resources::{bundles_in, missing_resource_message}; @@ -121,10 +122,22 @@ pub const LAUNCH_CONFIGURATION_CLEANUP_FAILED: &str = "launch.configuration_clea /// launch names no `triggerFiles` and JDT LS falls back to the first opened /// file to lay out a workspace without a build file. pub const LAUNCH_WORKSPACE_FOLDERS_UNAVAILABLE: &str = "launch.workspace_folders_unavailable"; +/// The project needs servlet container libraries (a web module, a Server +/// Runtime container) and none was found, so `javax.servlet` stays +/// unresolved until the user configures one. +pub const LAUNCH_SERVLET_CONTAINER_MISSING: &str = "launch.servlet_container_missing"; +/// Libraries the project model declares could not be added; the count is +/// how many. The Java libraries settings page lists them. +pub const LAUNCH_PROJECT_MODEL_UNRESOLVED: &str = "launch.project_model_unresolved"; +/// The project model scan stopped at its budget; deeper layouts were not read. +pub const LAUNCH_PROJECT_MODEL_TRUNCATED: &str = "launch.project_model_truncated"; /// Every degraded-diagnostic category `java.resolveLaunch` reports. pub const LAUNCH_CATEGORIES: &[&str] = &[ LAUNCH_CONFIGURATION_CLEANUP_FAILED, LAUNCH_WORKSPACE_FOLDERS_UNAVAILABLE, + LAUNCH_SERVLET_CONTAINER_MISSING, + LAUNCH_PROJECT_MODEL_UNRESOLVED, + LAUNCH_PROJECT_MODEL_TRUNCATED, ]; /// Most `.java` files named as `triggerFiles`. JDT LS uses the first one @@ -180,11 +193,13 @@ pub const EXTENSIONS_DIRECTORY: &str = "jdtls-extensions"; /// Package path of the Lombok agent JDT LS runs with. pub const LOMBOK_AGENT: &str = "jdtls-extensions/lombok/lombok.jar"; /// Package directories whose JAR files JDT LS loads as extension bundles, in -/// this order and then by file name: the Java Debug Server, then the Java -/// Test extensions. +/// this order and then by file name: the Java Debug Server, the Java Test +/// extensions, then the plugin's own project model bundle, built from +/// `jdtls-extension/project-model` by `scripts/package/project-model-bundle.mjs`. pub const EXTENSION_BUNDLE_DIRECTORIES: &[&str] = &[ "jdtls-extensions/java-debug", "jdtls-extensions/java-test/extensions", + "jdtls-extensions/project-model", ]; /// Package path of the Java Test runner JAR the test flow adds to the class /// path of TestNG launches; JDT LS itself does not load it. @@ -196,6 +211,7 @@ pub const PACKAGE_LAYOUT: &[&str] = &[ LOMBOK_AGENT, EXTENSION_BUNDLE_DIRECTORIES[0], EXTENSION_BUNDLE_DIRECTORIES[1], + EXTENSION_BUNDLE_DIRECTORIES[2], TEST_RUNNER, ]; /// Directory under `workspaceStateDirectory` passed to JDT LS as `-data`. @@ -238,6 +254,8 @@ pub struct LaunchRequest { /// with that JDK, so the server must compile for it. Empty when the host /// found none, which leaves the server on the runtimes it already knows. pub java_runtimes: Vec, + /// `settings.projectModelDetection` and `settings.servletContainerHome`. + pub model_options: ModelOptions, } /// The files of a JDT LS launch, absolute. @@ -301,6 +319,7 @@ pub fn parse_launch_params(params: &Value) -> Result } }, }; + let model_options = crate::project_model::parse_options(&settings).map_err(invalid_params)?; Ok(LaunchRequest { os: os.to_string(), architecture: architecture.to_string(), @@ -313,6 +332,7 @@ pub fn parse_launch_params(params: &Value) -> Result server_home, server_runtime_version: host_tool_version(params, SERVER_RUNTIME_TOOL), java_runtimes: jdt_java_runtimes(&host_java_tool(params)), + model_options, }) } @@ -651,6 +671,22 @@ fn now_unix_seconds() -> u64 { .map_or(0, |elapsed| elapsed.as_secs()) } +/// Reports what detection could not do for the project; the launch stands. +pub fn report_model(model: &ProjectModel, report: &dyn Fn(&str, u64)) { + if model.needs_servlet && model.servlet.runtime.is_none() { + report(LAUNCH_SERVLET_CONTAINER_MISSING, 1); + } + if !model.unresolved.is_empty() { + report( + LAUNCH_PROJECT_MODEL_UNRESOLVED, + model.unresolved.len() as u64, + ); + } + if model.truncated { + report(LAUNCH_PROJECT_MODEL_TRUNCATED, 1); + } +} + /// Runs a call of `java.resolveLaunch`. /// /// The workspace comes from the call's `context`. The settings are the ones @@ -681,8 +717,10 @@ pub fn resolve_launch_function( }; let (fragments, folders) = match context.workspace_context() { Some(workspace) => { - // The pushes after this start repeat the runtimes it configures. + // The pushes after this start repeat the runtimes and the + // project model settings it configures. session.set_java_runtimes(workspace, request.java_runtimes.clone()); + session.set_model_options(workspace, request.model_options.clone()); let folders = match workspace_folders(context.host(), workspace) { Ok(folders) => folders, Err(_) => { @@ -708,10 +746,12 @@ pub fn resolve_launch_function( &report, )?; if let Some(folder) = folders.first() { - let configuration = crate::settings_session::with_native_settings( + let (configuration, model) = crate::settings_session::with_native_model( answer["workspaceConfiguration"].clone(), folder, + &request.model_options, )?; + report_model(&model, &report); answer["workspaceConfiguration"] = configuration.clone(); answer["initializationOptions"]["settings"] = configuration; } diff --git a/backend/src/lib.rs b/backend/src/lib.rs index b378783..0be709b 100644 --- a/backend/src/lib.rs +++ b/backend/src/lib.rs @@ -51,7 +51,9 @@ pub mod class_content; pub mod jdtls; pub mod launch; +pub mod library_settings; pub mod plugin_functions; +pub mod project_model; pub mod project_settings; pub mod run; pub mod settings_session; @@ -253,7 +255,7 @@ pub fn backend() -> Result { backend.suppress_success_diagnostics(function)?; } backend.function("compiler.prepareSettings", move |params, context| { - projects.edit(params, context) + projects.edit(params, context, &session) })?; Ok(backend) } diff --git a/backend/src/library_settings.rs b/backend/src/library_settings.rs new file mode 100644 index 0000000..8c10d10 --- /dev/null +++ b/backend/src/library_settings.rs @@ -0,0 +1,834 @@ +//! The Java libraries settings page beyond the native sources it edits: the +//! detected project model, what Lithe adds in memory, the servlet container, +//! and what JDT made of Eclipse containers. These rows are read-only sources +//! bound to the model's own descriptor files (`.idea/modules.xml`, +//! `.project`, `WEB-INF/web.xml`), so the host's revision checks still hold. +//! The `.vscode/settings.json` source gains source folders and an explicit +//! "save detected entries" choice; nothing is written without Save. + +use crate::project_model::servlet::ServletSource; +use crate::project_model::{ + Explicit, ModelKind, Origin, ProjectModel, UnresolvedKind, UPSTREAM_DEFAULT_LIBRARIES, +}; +use serde_json::{json, Value}; +use std::path::{Path, PathBuf}; + +/// Field IDs of the `.vscode/settings.json` source. +pub const LIBRARIES_FIELD: &str = "libraries"; +pub const SOURCE_PATHS_FIELD: &str = "source-paths"; +pub const STORE_DETECTED_FIELD: &str = "store-detected"; +/// JDT LS project setting with the absolute source folders of a project. +pub const SOURCE_PATHS_FACT: &str = "org.eclipse.jdt.ls.core.sourcePaths"; +/// The project model bundle's command (`DescribeCommandHandler`). +pub const DESCRIBE_COMMAND: &str = "lithe.java.projectModel.describe"; +/// Most lines of one read-only list; the host shows at most 256. +const MAX_LINES: usize = 256; +/// The contract's bound of an effective-source label. +const MAX_LABEL_BYTES: usize = 1024; +/// The contract's bound of one list item. +const MAX_ITEM_BYTES: usize = 4096; + +fn text(zh: bool, en: &str, cn: &str) -> String { + if zh { cn } else { en }.to_owned() +} + +/// What the page knows when it projects the model. +pub struct Page<'a> { + pub zh: bool, + pub root: &'a Path, + pub model: &'a ProjectModel, + pub explicit: &'a Explicit, + /// The bundle's describe answer, when JDT LS gave one. + pub described: Option<&'a Value>, +} + +impl Page<'_> { + /// Detected includes that may be saved to a shared file: everything but + /// the machine's servlet container. + pub fn storable(&self) -> Vec { + if !self.model.enabled || self.model.kind.managed() { + return Vec::new(); + } + self.model + .libraries + .iter() + .map(|item| item.pattern.clone()) + .collect() + } + + /// IDEA source folders a save would write when none are explicit. + fn storable_source_paths(&self) -> &[String] { + if self.model.enabled && self.model.kind == ModelKind::Idea { + &self.model.source_paths + } else { + &[] + } + } + + /// Whether the file already holds every storable entry. + fn stored(&self) -> bool { + let include = self.explicit.include(); + self.explicit.libraries.is_some() + && self + .storable() + .iter() + .all(|pattern| include.contains(pattern)) + && (self.storable_source_paths().is_empty() || self.explicit.source_paths.is_some()) + } + + /// The fields of the unmanaged folder's `.vscode/settings.json` source. + /// `fact` is JDT's project settings answer for the folder. + pub fn settings_fields(&self, fact: &Value, libraries: Value) -> Vec { + let zh = self.zh; + let detected = crate::project_model::detected_include(self.model).len(); + let library_source = if detected > 0 { + if zh { + format!("JDT 实际生效,含自动识别的 {detected} 项") + } else { + format!("Effective in JDT, including {detected} detected entries") + } + } else { + text( + zh, + "Eclipse JDT project settings", + "Eclipse JDT 项目生效配置", + ) + }; + let mut fields = vec![json!({ + "id": LIBRARIES_FIELD, + "title": text(zh, "Referenced JAR files", "引用的 JAR 文件"), + "description": text(zh, + "java.project.referencedLibraries in .vscode/settings.json; lib/** is the upstream default. Lithe also adds the libraries listed under Project model in memory, without writing this file.", + "写入 .vscode/settings.json 的 java.project.referencedLibraries,上游默认引用 lib/**。Lithe 还会在内存中加入“工程模型”里列出的库,无需写入此文件。"), + "kind": "fileList", + "value": libraries, + "effectiveValue": fact[crate::project_settings::LIBRARIES_FACT].clone(), + "effectiveSource": library_source, + })]; + let explicit_sources = self.explicit.source_paths.clone().filter(Value::is_array); + let inherited = self.storable_source_paths(); + let effective_source = if explicit_sources.is_some() { + ".vscode/settings.json".to_string() + } else if !inherited.is_empty() { + text(zh, "IntelliJ IDEA modules", "IntelliJ IDEA 模块") + } else { + text( + zh, + "Inferred by JDT from package declarations", + "JDT 按 package 声明推断", + ) + }; + fields.push(json!({ + "id": SOURCE_PATHS_FIELD, + "title": text(zh, "Source folders", "源码文件夹"), + "description": text(zh, + "java.project.sourcePaths of a folder without a build file. Empty uses the IntelliJ IDEA modules' source folders, else JDT infers them from the package declarations of Java files. Saved to .vscode/settings.json; JDT applies a change after the language server restarts.", + "无构建文件的文件夹的源码根(java.project.sourcePaths)。留空时使用 IntelliJ IDEA 模块中的源码文件夹,否则由 JDT 根据 Java 文件的 package 声明推断。保存到 .vscode/settings.json;修改在语言服务器重启后生效。"), + "kind": "stringList", + "value": explicit_sources.unwrap_or(Value::Null), + "effectiveValue": relative_list(self.root, &fact[SOURCE_PATHS_FACT]), + "inheritedValue": if inherited.is_empty() { Value::Null } else { json!(inherited) }, + "effectiveSource": effective_source, + })); + if !self.storable().is_empty() || !self.storable_source_paths().is_empty() { + let stored = self.stored(); + fields.push(json!({ + "id": STORE_DETECTED_FIELD, + "title": text(zh, "Save detected entries to this file", "将识别结果保存到此文件"), + "description": text(zh, + "Checked and saved, writes the detected libraries (not this machine's servlet container) and IntelliJ IDEA source folders into .vscode/settings.json, so other editors and teammates get the same classpath. Unchecked and saved, removes them again. Lithe uses them either way.", + "勾选并保存后,把自动识别的库(不含本机 Servlet 容器路径)和 IntelliJ IDEA 源码文件夹写入 .vscode/settings.json,供 VS Code 等其他编辑器和团队成员使用;取消勾选并保存则移除这些条目。无论是否保存,Lithe 都会使用它们。"), + "kind": "boolean", + "value": stored, + "effectiveValue": stored, + "effectiveSource": ".vscode/settings.json", + })); + } + fields + } + + /// The effective-source label of an Eclipse project's `.classpath`. + pub fn classpath_label(&self, project: &Path) -> String { + let zh = self.zh; + let mut label = text( + zh, + "Eclipse JDT project settings", + "Eclipse JDT 项目生效配置", + ); + let lines = self.container_lines(project, true); + if !lines.is_empty() { + label.push_str(if zh { ";容器:" } else { "; containers: " }); + label.push_str(&lines.join(if zh { "," } else { ", " })); + } + truncate(label, MAX_LABEL_BYTES) + } + + /// Read-only sources of the model. `taken` holds the paths of the + /// writable sources, which a read-only row must not reuse. + pub fn model_sources(&self, taken: &[PathBuf]) -> Vec<(String, PathBuf, Vec)> { + let zh = self.zh; + let mut sources = Vec::new(); + let Some(descriptor) = &self.model.descriptor else { + return sources; + }; + let path = self.root.join(descriptor); + if taken.contains(&path) { + return sources; + } + let mut fields = vec![read_only( + zh, + "model", + text(zh, "Project model", "工程模型"), + text(zh, + "Who provides the classpath, in this order: Maven or Gradle build files, Eclipse .project files, an IntelliJ IDEA .idea folder, legacy web folders (WEB-INF/lib), then a plain folder. Detection only reads project files. Turn it off with Project model detection in the Java settings.", + "按以下顺序决定由谁提供类路径:Maven/Gradle 构建文件、Eclipse .project、IntelliJ IDEA 的 .idea、传统 Web 目录(WEB-INF/lib)、普通文件夹。识别只读取项目文件。可在 Java 设置的“自动识别工程模型”中关闭。"), + json!(self.model_title()), + "text", + )]; + let detected: Vec = self.detected_lines(); + if !detected.is_empty() { + fields.push(read_only( + zh, + "detected", + text(zh, "Detected libraries", "自动识别的库"), + text(zh, + "Lithe adds these to the classpath in memory; project files stay unchanged. To share them with other editors, check Save detected entries to this file under Referenced libraries.", + "Lithe 在内存中把这些库加入类路径,不修改项目文件。若要与其他编辑器共享,在“引用的库”中勾选“将识别结果保存到此文件”。"), + json!(detected), + "stringList", + )); + } + if self.model.enabled + && self.model.kind == ModelKind::Idea + && !self.model.source_paths.is_empty() + { + fields.push(read_only( + zh, + "source-folders", + text(zh, "IntelliJ IDEA source folders", "IntelliJ IDEA 源码文件夹"), + text(zh, + "Production and test source folders of the IDEA modules. JDT treats test folders as ordinary source folders in a folder without a build file.", + "IDEA 模块的生产与测试源码文件夹。无构建文件时 JDT 把测试文件夹当作普通源码文件夹处理。"), + json!(self.model.source_paths.iter().take(MAX_LINES).collect::>()), + "stringList", + )); + } + if self.model.needs_servlet { + fields.push(read_only( + zh, + "servlet", + text(zh, "Servlet container", "Servlet 容器"), + text(zh, + "Web projects get javax.servlet and the other server APIs from a servlet container, as Eclipse's Server Runtime and IDEA's application server libraries do. Automatic uses the Servlet container folder of the Java settings, then CATALINA_HOME or TOMCAT_HOME, then standard installation folders, preferring the version the project names.", + "Web 项目的 javax.servlet 等服务器 API 由 Servlet 容器提供,对应 Eclipse 的 Server Runtime 和 IDEA 的应用服务器库。自动:依次使用 Java 设置中的“Servlet 容器文件夹”、CATALINA_HOME 或 TOMCAT_HOME、常见安装位置,并优先选择项目指定的版本。"), + json!(self.servlet_text()), + "text", + )); + } + let unresolved = self.unresolved_lines(); + if !unresolved.is_empty() { + fields.push(read_only( + zh, + "unresolved", + text(zh, "Not resolved", "未能解析"), + text(zh, + "Libraries the project declares but Lithe cannot add. Add their JAR files under Referenced JAR files.", + "项目声明了但 Lithe 无法加入的库。请在“引用的 JAR 文件”中添加对应的 JAR。"), + json!(unresolved), + "stringList", + )); + } + sources.push(("model".to_string(), path, fields)); + sources + } + + /// Read-only rows of Eclipse projects with containers, variables or + /// missing libraries, bound to each project's `.project`. + pub fn eclipse_sources(&self, taken: &[PathBuf]) -> Vec<(String, PathBuf, Vec)> { + let zh = self.zh; + let mut sources = Vec::new(); + for project in self.described_projects() { + let Some(location) = project["location"].as_str().map(PathBuf::from) else { + continue; + }; + let location = dunce::canonicalize(&location).unwrap_or(location); + if !location.starts_with(self.root) { + continue; + } + let path = location.join(".project"); + let lines = self.container_lines(&location, false); + if lines.is_empty() + || taken.contains(&path) + || sources.iter().any(|(_, known, _)| known == &path) + { + continue; + } + let id = format!("eclipse-{}", project["name"].as_str().unwrap_or_default()); + sources.push(( + id, + path, + vec![read_only( + zh, + "containers", + text(zh, "Containers and variables", "容器与变量"), + text(zh, + "Eclipse WTP and MyEclipse containers resolved by Lithe inside JDT from project files, without changing .classpath: Web App Libraries is WEB-INF/lib and the utility modules deployed there, EAR Libraries is the library folder of each EAR that bundles the module, Server Runtime and Java EE libraries come from the servlet container. TOMCAT_HOME and CATALINA_HOME point at the servlet container.", + "Eclipse WTP 与 MyEclipse 的容器由 Lithe 在 JDT 内根据项目文件解析,不修改 .classpath:Web App Libraries 是 WEB-INF/lib 及部署到其中的工具模块;EAR Libraries 是引用此模块的 EAR 的库目录;Server Runtime 与 Java EE 库来自 Servlet 容器。TOMCAT_HOME、CATALINA_HOME 指向 Servlet 容器。"), + json!(lines), + "stringList", + )], + )); + } + sources + } + + fn described_projects(&self) -> Vec<&Value> { + self.described + .and_then(|value| value["projects"].as_array()) + .map(|projects| projects.iter().collect()) + .unwrap_or_default() + } + + /// One line per container, variable and missing library of the project + /// at `location`. `brief` keeps only the containers this plugin resolves. + fn container_lines(&self, location: &Path, brief: bool) -> Vec { + let zh = self.zh; + let Some(project) = self.described_projects().into_iter().find(|project| { + project["location"].as_str().is_some_and(|value| { + let path = PathBuf::from(value); + dunce::canonicalize(&path).unwrap_or(path) == location + }) + }) else { + return Vec::new(); + }; + let mut lines = Vec::new(); + for entry in project["entries"].as_array().into_iter().flatten() { + let kind = entry["containerKind"].as_str().unwrap_or("other"); + let status = entry["status"].as_str().unwrap_or("unbound"); + let ours = entry["kind"] == "container" && kind != "other"; + if brief && !ours { + continue; + } + if entry["kind"] == "container" && kind == "other" && status != "unbound" { + continue; + } + let name = entry["description"] + .as_str() + .or_else(|| entry["path"].as_str()) + .unwrap_or_default(); + let libraries = entry["libraries"].as_u64().unwrap_or(0); + let projects = entry["projects"].as_u64().unwrap_or(0); + let state = match status { + "resolved" if entry["kind"] == "variable" => entry["resolvedPath"] + .as_str() + .unwrap_or_default() + .to_string(), + "resolved" if projects > 0 => { + if zh { + format!("{libraries} 个 JAR,{projects} 个项目") + } else { + format!( + "{}, {}", + count(libraries, "JAR"), + count(projects, "project") + ) + } + } + "resolved" => { + if zh { + format!("{libraries} 个 JAR") + } else { + count(libraries, "JAR") + } + } + "empty" if kind == "serverRuntime" || kind == "javaEE" => { + text(zh, "no servlet container found", "未找到 Servlet 容器") + } + "empty" => text(zh, "empty", "为空"), + "missing" => text(zh, "file does not exist", "文件不存在"), + "disabled" => text(zh, "detection is off", "自动识别已关闭"), + _ if entry["path"].as_str().is_some_and(|path| { + path.starts_with(crate::project_model::eclipse::USER_LIBRARY) + }) => + { + text( + zh, + "user library defined in an Eclipse workspace; add its JARs to .classpath", + "用户库定义在 Eclipse 工作区,请把其 JAR 加入 .classpath", + ) + } + _ => text(zh, "cannot be resolved", "无法解析"), + }; + lines.push( + format!( + "{name}{}{state}", + if brief { + if zh { + "(" + } else { + " (" + } + } else { + " — " + } + ) + if brief { + if zh { + ")" + } else { + ")" + } + } else { + "" + }, + ); + if lines.len() >= MAX_LINES { + break; + } + } + lines + } + + fn model_title(&self) -> String { + let zh = self.zh; + let model = self.model; + let mut title = match model.kind { + ModelKind::Maven => text( + zh, + "Maven project (imported by Maven)", + "Maven 项目(由 Maven 导入)", + ), + ModelKind::Gradle => text( + zh, + "Gradle project (imported by Gradle)", + "Gradle 项目(由 Gradle 导入)", + ), + ModelKind::Eclipse if zh => { + format!("Eclipse 项目({} 个 .project)", model.eclipse_projects) + } + ModelKind::Eclipse => format!( + "Eclipse project ({} .project files)", + model.eclipse_projects + ), + ModelKind::Idea if zh => format!( + "IntelliJ IDEA 项目({} 个模块,只读导入)", + model.idea_modules + ), + ModelKind::Idea => format!( + "IntelliJ IDEA project ({} modules, imported read-only)", + model.idea_modules + ), + ModelKind::LegacyWeb => text( + zh, + "Legacy web project (no build file)", + "传统 Web 项目(无构建文件)", + ), + ModelKind::Plain => text(zh, "Plain Java folder", "普通 Java 文件夹"), + }; + if !model.enabled { + title.push_str(if zh { + " · 自动识别已关闭" + } else { + " · detection is off" + }); + } + if model.truncated { + title.push_str(if zh { + " · 文件过多,只识别了前面的部分" + } else { + " · too many files, only the first part was read" + }); + } + title + } + + fn detected_lines(&self) -> Vec { + let zh = self.zh; + if self.model.kind.managed() || !self.model.enabled { + return Vec::new(); + } + let mut lines: Vec = self + .model + .libraries + .iter() + .take(MAX_LINES) + .map(|item| { + let origin = match item.origin { + Origin::WebLibraries => text(zh, "Web app libraries", "Web 应用库"), + Origin::EarLibraries => text(zh, "EAR libraries", "EAR 库"), + Origin::ManifestClassPath => "MANIFEST Class-Path".to_string(), + Origin::IdeaModuleLibrary => text(zh, "IDEA module library", "IDEA 模块库"), + Origin::IdeaProjectLibrary => text(zh, "IDEA project library", "IDEA 项目库"), + Origin::ServletContainer => text(zh, "Servlet container", "Servlet 容器"), + }; + if zh { + format!( + "{} — {origin}({},{} 个 JAR)", + item.pattern, item.label, item.count + ) + } else { + format!( + "{} — {origin} ({}, {})", + item.pattern, + item.label, + count(item.count as u64, "JAR") + ) + } + }) + .collect(); + if let Some(runtime) = &self.model.servlet.runtime { + if lines.len() < MAX_LINES { + lines.push(if zh { + format!( + "Servlet 容器 — {}({} 个 JAR)", + runtime.name, + runtime.libraries.len() + ) + } else { + format!( + "Servlet container — {} ({})", + runtime.name, + count(runtime.libraries.len() as u64, "JAR") + ) + }); + } + } + lines + } + + fn servlet_text(&self) -> String { + let zh = self.zh; + match &self.model.servlet.runtime { + // Name and origin first, the folder last: a long folder is + // what the field cuts off. + Some(runtime) => { + let (name, home) = (&runtime.name, runtime.home.display()); + match (&runtime.source, zh) { + (ServletSource::Setting, true) => format!("{name}(Java 设置)— {home}"), + (ServletSource::Setting, false) => format!("{name} (Java settings) — {home}"), + (ServletSource::Environment(variable), true) => format!("自动:{name}(来自 {variable})— {home}"), + (ServletSource::Environment(variable), false) => format!("Automatic: {name} (from {variable}) — {home}"), + (ServletSource::Installed, true) => format!("自动:{name} — {home}"), + (ServletSource::Installed, false) => format!("Automatic: {name} — {home}"), + } + } + None if self.model.servlet.setting_invalid => text( + zh, + "The Servlet container folder in the Java settings has no servlet API library (lib/servlet-api.jar); choose the folder of a Tomcat or Jetty installation.", + "Java 设置中的“Servlet 容器文件夹”没有 Servlet API 库(lib/servlet-api.jar),请选择 Tomcat 或 Jetty 的安装文件夹。", + ), + None => text( + zh, + "Automatic (not found): choose a Tomcat or Jetty folder as Servlet container folder in the Java settings, or set CATALINA_HOME.", + "自动(未找到):在 Java 设置的“Servlet 容器文件夹”中选择 Tomcat 或 Jetty 的安装文件夹,或设置 CATALINA_HOME。", + ), + } + } + + fn unresolved_lines(&self) -> Vec { + let zh = self.zh; + self.model + .unresolved + .iter() + .take(MAX_LINES) + .map(|item| { + let reason = match item.kind { + UnresolvedKind::MissingFile => text(zh, "file does not exist", "文件不存在"), + UnresolvedKind::MissingLibrary => { + text(zh, "project library is not defined", "项目库未定义") + } + UnresolvedKind::IdeLibrary => text( + zh, + "IDEA global or application library, kept outside the project", + "IDEA 全局库或应用库,不在项目内", + ), + UnresolvedKind::ClassFolder => text( + zh, + "class folder; JDT accepts only JAR files", + "类文件夹,JDT 只接受 JAR", + ), + UnresolvedKind::UnknownMacro => text( + zh, + "path variable known only to IDEA", + "路径变量只有 IDEA 知道", + ), + UnresolvedKind::OutsideWorkspace => text( + zh, + "source folder outside the workspace", + "源码文件夹在工作区之外", + ), + UnresolvedKind::UserLibrary => text( + zh, + "Eclipse user library, defined in an Eclipse workspace", + "Eclipse 用户库,定义在 Eclipse 工作区", + ), + }; + format!("{} — {reason}", item.name) + }) + .collect() + } +} + +/// `n` English things, singular for one. +fn count(n: u64, thing: &str) -> String { + if n == 1 { + format!("1 {thing}") + } else { + format!("{n} {thing}s") + } +} + +/// A read-only field whose value is also its effective value. List items +/// and text are cut to the contract's bounds. +fn read_only( + zh: bool, + id: &str, + title: String, + description: String, + value: Value, + kind: &str, +) -> Value { + let value = match value { + Value::Array(items) => Value::Array( + items + .into_iter() + .take(MAX_LINES) + .filter_map(|item| { + item.as_str() + .map(|line| json!(truncate(line.to_string(), MAX_ITEM_BYTES))) + }) + .collect(), + ), + Value::String(line) => json!(truncate(line, MAX_ITEM_BYTES)), + other => other, + }; + json!({ + "id": id, + "title": title, + "description": description, + "kind": kind, + "value": value, + "effectiveValue": value, + "effectiveSource": text(zh, "Detected from project files", "根据项目文件识别"), + }) +} + +/// Absolute JDT paths as workspace-relative ones where possible. +fn relative_list(root: &Path, value: &Value) -> Value { + match value.as_array() { + Some(items) => json!(items + .iter() + .filter_map(Value::as_str) + .map(|item| { + let path = PathBuf::from(item); + let path = dunce::canonicalize(&path).unwrap_or(path); + crate::project_model::relative_or_absolute(root, &path) + }) + .collect::>()), + None => Value::Null, + } +} + +fn truncate(mut text: String, bytes: usize) -> String { + if text.len() > bytes { + let mut end = bytes.saturating_sub(3); + while !text.is_char_boundary(end) { + end -= 1; + } + text.truncate(end); + text.push_str("..."); + } + text +} + +/// The new include list and source folders after saving +/// [`STORE_DETECTED_FIELD`] as `store`, from the file's current `explicit` +/// values. `None` leaves a key as it is. +pub fn stored_entries(page: &Page<'_>, store: bool) -> (Option, Option>) { + let storable = page.storable(); + let mut include = page.explicit.include(); + let had = page.explicit.libraries.is_some(); + if store { + if !had { + include.push(UPSTREAM_DEFAULT_LIBRARIES.to_string()); + } + for pattern in &storable { + if !include.contains(pattern) { + include.push(pattern.clone()); + } + } + } else { + include.retain(|pattern| !storable.contains(pattern)); + } + let libraries = (store || had).then(|| json!(include)); + let sources = page.storable_source_paths(); + let source_paths = if sources.is_empty() { + None + } else if store && page.explicit.source_paths.is_none() { + Some(Some(json!(sources))) + } else if !store && page.explicit.source_paths.as_ref() == Some(&json!(sources)) { + Some(None) + } else { + None + }; + (libraries, source_paths) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::project_model::servlet::{ServletResolution, ServletRuntime}; + use crate::project_model::{Detected, Unresolved}; + + fn model(kind: ModelKind) -> ProjectModel { + ProjectModel { + kind, + enabled: true, + descriptor: Some(".idea/modules.xml".into()), + idea_modules: 2, + eclipse_projects: 0, + libraries: vec![Detected { + pattern: "web/WEB-INF/lib/*.jar".into(), + origin: Origin::WebLibraries, + label: "web".into(), + count: 3, + }], + source_paths: vec!["src".into(), "test".into()], + unresolved: vec![Unresolved { + kind: UnresolvedKind::IdeLibrary, + name: "Global".into(), + }], + needs_servlet: true, + servlet: ServletResolution { + runtime: Some(ServletRuntime { + home: PathBuf::from("/opt/tomcat"), + libraries: vec![PathBuf::from("/opt/tomcat/lib/servlet-api.jar")], + name: "Apache Tomcat 9.0.98".into(), + version: Some("9.0.98".into()), + source: ServletSource::Installed, + }), + setting_invalid: false, + }, + truncated: false, + } + } + + #[test] + fn saving_detected_entries_keeps_the_upstream_default_and_removing_them_restores_the_file() { + let model = model(ModelKind::Idea); + let explicit = Explicit::default(); + let page = Page { + zh: false, + root: Path::new("/w"), + model: &model, + explicit: &explicit, + described: None, + }; + let (libraries, sources) = stored_entries(&page, true); + assert_eq!(libraries, Some(json!(["lib/**", "web/WEB-INF/lib/*.jar"]))); + assert_eq!(sources, Some(Some(json!(["src", "test"])))); + let explicit = Explicit::from_document(&json!({ + "java.project.referencedLibraries": ["lib/**", "web/WEB-INF/lib/*.jar", "own.jar"], + "java.project.sourcePaths": ["src", "test"], + })); + let page = Page { + zh: false, + root: Path::new("/w"), + model: &model, + explicit: &explicit, + described: None, + }; + assert!(page.stored()); + let (libraries, sources) = stored_entries(&page, false); + assert_eq!(libraries, Some(json!(["lib/**", "own.jar"]))); + assert_eq!(sources, Some(None)); + } + + #[test] + fn the_model_rows_show_detection_servlet_container_and_unresolved_entries() { + let model = model(ModelKind::Idea); + let explicit = Explicit::default(); + let page = Page { + zh: true, + root: Path::new("/w"), + model: &model, + explicit: &explicit, + described: None, + }; + let sources = page.model_sources(&[]); + assert_eq!(sources.len(), 1); + let (_, path, fields) = &sources[0]; + assert_eq!(path, &PathBuf::from("/w/.idea/modules.xml")); + let ids: Vec<_> = fields + .iter() + .map(|field| field["id"].as_str().unwrap()) + .collect(); + assert_eq!( + ids, + vec![ + "model", + "detected", + "source-folders", + "servlet", + "unresolved" + ] + ); + assert_eq!( + fields[0]["value"], + "IntelliJ IDEA 项目(2 个模块,只读导入)" + ); + assert_eq!( + fields[3]["value"], + "自动:Apache Tomcat 9.0.98 — /opt/tomcat" + ); + assert_eq!( + fields[4]["value"], + json!(["Global — IDEA 全局库或应用库,不在项目内"]) + ); + assert!(page + .model_sources(&[PathBuf::from("/w/.idea/modules.xml")]) + .is_empty()); + } + + #[test] + fn eclipse_rows_and_labels_come_from_what_jdt_resolved() { + let model = ProjectModel { + kind: ModelKind::Eclipse, + ..model(ModelKind::Eclipse) + }; + let explicit = Explicit::default(); + let root = std::env::temp_dir(); + let root = dunce::canonicalize(&root).unwrap(); + let described = json!({"projects": [{"name": "app", "location": root.join("app").to_str().unwrap(), "entries": [ + {"kind": "container", "containerKind": "other", "path": "org.eclipse.jdt.launching.JRE_CONTAINER", "status": "resolved", "libraries": 1}, + {"kind": "container", "containerKind": "webApp", "path": "org.eclipse.jst.j2ee.internal.web.container", "description": "Web App Libraries", "status": "resolved", "libraries": 37, "projects": 0}, + {"kind": "container", "containerKind": "serverRuntime", "path": "org.eclipse.jst.server.core.container/t/Tomcat", "description": "Server Runtime [Tomcat]", "status": "empty"}, + {"kind": "container", "containerKind": "other", "path": "org.eclipse.jdt.USER_LIBRARY/Libs", "status": "unbound"}, + {"kind": "variable", "path": "TOMCAT_HOME/lib/servlet-api.jar", "status": "resolved", "resolvedPath": "/opt/tomcat/lib/servlet-api.jar"}, + {"kind": "library", "path": "D:/old/x.jar", "status": "missing"} + ]}]}); + let page = Page { + zh: false, + root: &root, + model: &model, + explicit: &explicit, + described: Some(&described), + }; + assert_eq!( + page.classpath_label(&root.join("app")), + "Eclipse JDT project settings; containers: Web App Libraries (37 JARs), Server Runtime [Tomcat] (no servlet container found)" + ); + let rows = page.eclipse_sources(&[]); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].1, root.join("app/.project")); + assert_eq!( + rows[0].2[0]["value"], + json!([ + "Web App Libraries — 37 JARs", + "Server Runtime [Tomcat] — no servlet container found", + "org.eclipse.jdt.USER_LIBRARY/Libs — user library defined in an Eclipse workspace; add its JARs to .classpath", + "TOMCAT_HOME/lib/servlet-api.jar — /opt/tomcat/lib/servlet-api.jar", + "D:/old/x.jar — file does not exist" + ]) + ); + } +} diff --git a/backend/src/project_model/eclipse.rs b/backend/src/project_model/eclipse.rs new file mode 100644 index 0000000..f38e09f --- /dev/null +++ b/backend/src/project_model/eclipse.rs @@ -0,0 +1,109 @@ +//! Facts from Eclipse `.classpath` files that the backend needs before JDT LS +//! has imported anything: whether a servlet container must be configured and +//! which servlet container version the project names. Resolving the +//! containers themselves is the job of the JDT LS extension bundle. + +use super::{read_bounded, servlet::ServletHint, xml}; +use std::path::{Path, PathBuf}; + +/// Container IDs (first path segment) the bundle fills from the servlet +/// container. Must match `ContainerKind` of the bundle. +pub const SERVLET_CONTAINERS: &[&str] = &[ + "org.eclipse.jst.server.core.container", + "com.genuitec.eclipse.j2eedt.core.J2EE13_CONTAINER", + "com.genuitec.eclipse.j2eedt.core.J2EE14_CONTAINER", + "melibrary.com.genuitec.eclipse.j2eedt.core.MYECLIPSE_JAVAEE_5_CONTAINER", + "melibrary.com.genuitec.eclipse.j2eedt.core.MYECLIPSE_JAVAEE_6_CONTAINER", + "melibrary.com.genuitec.eclipse.j2eedt.core.MYECLIPSE_JAVAEE_7_CONTAINER", + "com.genuitec.runtime.library", +]; +/// Classpath variables the bundle binds to the servlet container's folder. +pub const SERVLET_VARIABLES: &[&str] = &["TOMCAT_HOME", "CATALINA_HOME"]; +/// User libraries live in an Eclipse workspace, not in the project. +pub const USER_LIBRARY: &str = "org.eclipse.jdt.USER_LIBRARY"; + +/// What the `.classpath` files of the scanned Eclipse projects say. +#[derive(Debug, Default, Clone, PartialEq, Eq)] +pub struct EclipseFacts { + pub needs_servlet: bool, + pub hints: Vec, + /// Names of user libraries the projects reference. + pub user_libraries: Vec, +} + +pub fn read(projects: &[PathBuf]) -> EclipseFacts { + let mut facts = EclipseFacts::default(); + for project in projects { + read_project(project, &mut facts); + } + facts +} + +fn read_project(project: &Path, facts: &mut EclipseFacts) { + let Some(document) = + read_bounded(&project.join(".classpath")).and_then(|bytes| xml::parse(&bytes)) + else { + return; + }; + for entry in xml::children(&document, "classpathentry") { + let path = xml::attribute(entry, "path").unwrap_or_default(); + let mut segments = path.split('/'); + let first = segments.next().unwrap_or_default(); + match xml::attribute(entry, "kind") { + Some("con") if SERVLET_CONTAINERS.contains(&first) => { + facts.needs_servlet = true; + if let Some(hint) = path.rsplit('/').next().and_then(ServletHint::from_name) { + facts.hints.push(hint); + } + } + Some("con") if first == USER_LIBRARY => { + if let Some(name) = segments.next().filter(|name| !name.is_empty()) { + if !facts.user_libraries.iter().any(|known| known == name) { + facts.user_libraries.push(name.to_string()); + } + } + } + Some("var") if SERVLET_VARIABLES.contains(&first) => facts.needs_servlet = true, + _ => {} + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::project_model::tests::Tree; + + #[test] + fn server_runtime_containers_variables_and_user_libraries_are_recognized() { + let tree = Tree::new(&[ + ( + "app/.classpath", + r#" + + + + + "#, + ), + ( + "tool/.classpath", + r#""#, + ), + ( + "plain/.classpath", + r#""#, + ), + ]); + let facts = read(&[tree.root.join("plain")]); + assert!(!facts.needs_servlet); + let facts = read(&[ + tree.root.join("app"), + tree.root.join("tool"), + tree.root.join("missing"), + ]); + assert!(facts.needs_servlet); + assert_eq!(facts.hints, vec![ServletHint::Major(8)]); + assert_eq!(facts.user_libraries, vec!["Shared Libs"]); + } +} diff --git a/backend/src/project_model/idea.rs b/backend/src/project_model/idea.rs new file mode 100644 index 0000000..f53ad8f --- /dev/null +++ b/backend/src/project_model/idea.rs @@ -0,0 +1,551 @@ +//! Read-only import of IntelliJ IDEA project models: `.idea/modules.xml` (or a +//! file-based `.ipr`), each module's `.iml` source folders and libraries, and +//! the project libraries in `.idea/libraries`. No IDEA file is ever written. +//! Libraries IDEA keeps outside the project (application and global +//! libraries) cannot be read and are reported as unresolved. + +use super::servlet::ServletHint; +use super::{ + read_bounded, relative_inside, relative_or_absolute, xml, Detected, Origin, Unresolved, + UnresolvedKind, +}; +use std::collections::BTreeMap; +use std::fs; +use std::path::{Path, PathBuf}; +use xmltree::Element; + +/// Most modules imported from one project. +pub const MAX_MODULES: usize = 512; +/// Most project library files read from `.idea/libraries`. +pub const MAX_LIBRARY_FILES: usize = 512; +/// Most library roots imported in total. +pub const MAX_LIBRARY_ROOTS: usize = 4096; + +/// Folders the IDEA path macros stand for. +pub struct Macros { + pub project_dir: PathBuf, + pub user_home: Option, + pub maven_repository: Option, +} + +/// What an IDEA project contributes. +#[derive(Debug, Default, Clone, PartialEq, Eq)] +pub struct IdeaFacts { + /// Workspace-relative path of the descriptor that was read. + pub descriptor: String, + pub modules: usize, + /// Workspace-relative production source folders, then test ones. + pub source_paths: Vec, + pub test_source_paths: Vec, + pub libraries: Vec, + pub unresolved: Vec, + /// Web roots declared by web facets. + pub web_roots: Vec, + /// A module is a web module or uses application server libraries. + pub needs_servlet: bool, + pub hints: Vec, + pub truncated: bool, +} + +/// Reads the IDEA project at `root`, or None when there is none. +pub fn read(root: &Path, ipr_files: &[PathBuf], macros: &Macros) -> Option { + let directory = root.join(".idea"); + let (descriptor, modules_document, mut project_libraries) = if let Some(document) = + read_bounded(&directory.join("modules.xml")).and_then(|bytes| xml::parse(&bytes)) + { + ( + ".idea/modules.xml".to_string(), + document, + directory_libraries(&directory.join("libraries")), + ) + } else { + let ipr = ipr_files.first()?; + let document = read_bounded(ipr).and_then(|bytes| xml::parse(&bytes))?; + let libraries = component(&document, "libraryTable") + .map(named_libraries) + .unwrap_or_default(); + (relative_or_absolute(root, ipr), document, libraries) + }; + let mut facts = IdeaFacts { + descriptor, + ..IdeaFacts::default() + }; + let mut module_files = Vec::new(); + if let Some(manager) = component(&modules_document, "ProjectModuleManager") { + for module in xml::descendants(manager, "module") { + let declared = xml::attribute(module, "filepath") + .or_else(|| xml::attribute(module, "fileurl")) + .unwrap_or_default(); + if let Some(path) = expand(declared, macros, ¯os.project_dir) { + module_files.push(path); + } + } + } + if module_files.len() > MAX_MODULES { + module_files.truncate(MAX_MODULES); + facts.truncated = true; + } + let mut roots = 0usize; + for file in module_files { + let Some(document) = read_bounded(&file).and_then(|bytes| xml::parse(&bytes)) else { + facts.unresolved.push(Unresolved { + kind: UnresolvedKind::MissingFile, + name: relative_or_absolute(root, &file), + }); + continue; + }; + facts.modules += 1; + let module_dir = file + .parent() + .map(Path::to_path_buf) + .unwrap_or_else(|| root.to_path_buf()); + let module_name = file + .file_stem() + .and_then(|name| name.to_str()) + .unwrap_or("module") + .to_string(); + let module_macros = Macros { + project_dir: macros.project_dir.clone(), + user_home: macros.user_home.clone(), + maven_repository: macros.maven_repository.clone(), + }; + read_module( + root, + &document, + &module_dir, + &module_name, + &module_macros, + &mut project_libraries, + &mut facts, + &mut roots, + ); + } + Some(facts) +} + +#[allow(clippy::too_many_arguments)] +fn read_module( + root: &Path, + document: &Element, + module_dir: &Path, + module_name: &str, + macros: &Macros, + project_libraries: &mut BTreeMap, + facts: &mut IdeaFacts, + roots: &mut usize, +) { + if let Some(manager) = component(document, "FacetManager") { + for facet in xml::descendants(manager, "facet") { + if xml::attribute(facet, "type") == Some("web") { + facts.needs_servlet = true; + for web_root in xml::descendants(facet, "root") { + if let Some(path) = xml::attribute(web_root, "url") + .and_then(|url| expand(url, macros, module_dir)) + { + if !facts.web_roots.contains(&path) { + facts.web_roots.push(path); + } + } + } + } + } + } + let Some(manager) = component(document, "NewModuleRootManager") else { + return; + }; + for content in xml::children(manager, "content") { + for folder in xml::children(content, "sourceFolder") { + if xml::attribute(folder, "type").is_some_and(|kind| kind.contains("resource")) { + continue; + } + let Some(path) = + xml::attribute(folder, "url").and_then(|url| expand(url, macros, module_dir)) + else { + continue; + }; + let Some(relative) = relative_inside(root, &path) else { + facts.unresolved.push(Unresolved { + kind: UnresolvedKind::OutsideWorkspace, + name: path.to_string_lossy().to_string(), + }); + continue; + }; + let target = if xml::attribute(folder, "isTestSource") == Some("true") { + &mut facts.test_source_paths + } else { + &mut facts.source_paths + }; + if !target.contains(&relative) { + target.push(relative); + } + } + } + for entry in xml::children(manager, "orderEntry") { + match xml::attribute(entry, "type") { + Some("module-library") => { + if let Some(library) = xml::children(entry, "library").next() { + let name = xml::attribute(library, "name") + .unwrap_or(module_name) + .to_string(); + add_library( + root, + library, + &name, + Origin::IdeaModuleLibrary, + macros, + module_dir, + facts, + roots, + ); + } + } + Some("library") => { + let name = xml::attribute(entry, "name") + .unwrap_or_default() + .to_string(); + match xml::attribute(entry, "level") { + Some("project") => match project_libraries.get(&name).cloned() { + Some(library) => { + add_library( + root, + &library, + &name, + Origin::IdeaProjectLibrary, + macros, + ¯os.project_dir, + facts, + roots, + ); + // A project library shared by many modules is imported once. + project_libraries.remove(&name); + } + None if facts.libraries.iter().any(|item| item.label == name) => {} + None => facts.unresolved.push(Unresolved { + kind: UnresolvedKind::MissingLibrary, + name, + }), + }, + Some("application_server_libraries") => { + facts.needs_servlet = true; + if let Some(hint) = ServletHint::from_name(&name) { + facts.hints.push(hint); + } + } + _ => { + if !facts.unresolved.iter().any(|item| item.name == name) { + facts.unresolved.push(Unresolved { + kind: UnresolvedKind::IdeLibrary, + name, + }); + } + } + } + } + _ => {} + } + } +} + +#[allow(clippy::too_many_arguments)] +fn add_library( + root: &Path, + library: &Element, + name: &str, + origin: Origin, + macros: &Macros, + base: &Path, + facts: &mut IdeaFacts, + roots: &mut usize, +) { + for classes in xml::children(library, "CLASSES") { + for entry in xml::children(classes, "root") { + if *roots >= MAX_LIBRARY_ROOTS { + facts.truncated = true; + return; + } + *roots += 1; + let url = xml::attribute(entry, "url").unwrap_or_default(); + let Some(path) = expand(url, macros, base) else { + facts.unresolved.push(Unresolved { + kind: UnresolvedKind::UnknownMacro, + name: url.to_string(), + }); + continue; + }; + if path.is_dir() { + facts.unresolved.push(Unresolved { + kind: UnresolvedKind::ClassFolder, + name: relative_or_absolute(root, &path), + }); + continue; + } + if !path.is_file() { + facts.unresolved.push(Unresolved { + kind: UnresolvedKind::MissingFile, + name: relative_or_absolute(root, &path), + }); + continue; + } + push(facts, relative_or_absolute(root, &path), origin, name, 1); + } + } + for directory in xml::children(library, "jarDirectory") { + let Some(path) = xml::attribute(directory, "url").and_then(|url| expand(url, macros, base)) + else { + continue; + }; + let count = super::web::count_libraries(&path); + if count == 0 && xml::attribute(directory, "recursive") != Some("true") { + continue; + } + let glob = if xml::attribute(directory, "recursive") == Some("true") { + "**/*.jar" + } else { + "*.jar" + }; + push( + facts, + format!("{}/{glob}", relative_or_absolute(root, &path)), + origin, + name, + count.max(1), + ); + } +} + +fn push(facts: &mut IdeaFacts, pattern: String, origin: Origin, label: &str, count: usize) { + if !facts.libraries.iter().any(|item| item.pattern == pattern) { + facts.libraries.push(Detected { + pattern, + origin, + label: label.to_string(), + count, + }); + } +} + +/// The `` of a module or project document. +fn component<'a>(document: &'a Element, name: &str) -> Option<&'a Element> { + xml::children(document, "component").find(|item| xml::attribute(item, "name") == Some(name)) +} + +fn directory_libraries(directory: &Path) -> BTreeMap { + let mut libraries = BTreeMap::new(); + let Ok(entries) = fs::read_dir(directory) else { + return libraries; + }; + let mut files: Vec = entries + .filter_map(Result::ok) + .map(|entry| entry.path()) + .filter(|path| path.extension().is_some_and(|extension| extension == "xml")) + .collect(); + files.sort(); + files.truncate(MAX_LIBRARY_FILES); + for file in files { + if let Some(document) = read_bounded(&file).and_then(|bytes| xml::parse(&bytes)) { + libraries.extend(named_libraries(&document)); + } + } + libraries +} + +fn named_libraries(table: &Element) -> BTreeMap { + xml::descendants(table, "library") + .into_iter() + .filter_map(|library| { + xml::attribute(library, "name").map(|name| (name.to_string(), library.clone())) + }) + .collect() +} + +/// Expands `file://`/`jar://…!/` URLs and the path macros IDEA writes, with +/// `$MODULE_DIR$` meaning `module_dir`. +/// Unknown macros (path variables, the IDE's own folder) give None. +fn expand(value: &str, macros: &Macros, module_dir: &Path) -> Option { + let mut text = value + .trim() + .trim_start_matches("jar://") + .trim_start_matches("file://") + .trim_end_matches("!/") + .to_string(); + let replacements: [(&str, Option<&Path>); 4] = [ + ("$MODULE_DIR$", Some(module_dir)), + ("$PROJECT_DIR$", Some(¯os.project_dir)), + ("$USER_HOME$", macros.user_home.as_deref()), + ("$MAVEN_REPOSITORY$", macros.maven_repository.as_deref()), + ]; + for (name, folder) in replacements { + if text.contains(name) { + text = text.replace(name, &folder?.to_string_lossy()); + } + } + if text.contains('$') || text.is_empty() { + return None; + } + // A Windows drive path keeps its form; IDEA always writes '/'. + let path = PathBuf::from(text.replace('/', std::path::MAIN_SEPARATOR_STR)); + Some(normalize(&path)) +} + +/// Removes `.` and `..` components without touching the file system. +fn normalize(path: &Path) -> PathBuf { + let mut out = PathBuf::new(); + for component in path.components() { + match component { + std::path::Component::CurDir => {} + std::path::Component::ParentDir => { + out.pop(); + } + other => out.push(other.as_os_str()), + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::project_model::tests::Tree; + + fn macros(tree: &Tree) -> Macros { + Macros { + project_dir: tree.root.clone(), + user_home: Some(tree.root.join("home")), + maven_repository: Some(tree.root.join("home/.m2/repository")), + } + } + + #[test] + fn modules_source_folders_and_libraries_are_imported_read_only() { + let tree = Tree::new(&[ + ( + ".idea/modules.xml", + r#" + + + + "#, + ), + ( + "app.iml", + r#" + + + + + + + + + + + + + + + + + + + + + + "#, + ), + ( + "core/core.iml", + r#" + + + "#, + ), + ( + ".idea/libraries/shared.xml", + r#" + + "#, + ), + ("home/.m2/repository/org/acme/shared/1.0/shared-1.0.jar", ""), + ("lib/local.jar", ""), + ("classes-folder/A.class", ""), + ("web/WEB-INF/lib/w.jar", ""), + ]); + let facts = read(&tree.root, &[], ¯os(&tree)).unwrap(); + assert_eq!(facts.descriptor, ".idea/modules.xml"); + assert_eq!(facts.modules, 2); + assert_eq!(facts.source_paths, vec!["src", "core/java"]); + assert_eq!(facts.test_source_paths, vec!["test"]); + let libraries: Vec<_> = facts + .libraries + .iter() + .map(|item| (item.pattern.as_str(), item.origin, item.label.as_str())) + .collect(); + let shared = tree + .root + .join("home/.m2/repository/org/acme/shared/1.0/shared-1.0.jar"); + assert_eq!( + libraries, + vec![ + ("lib/local.jar", Origin::IdeaModuleLibrary, "app"), + ("web/WEB-INF/lib/*.jar", Origin::IdeaModuleLibrary, "app"), + ( + "home/.m2/repository/org/acme/shared/1.0/shared-1.0.jar", + Origin::IdeaProjectLibrary, + "shared" + ), + ] + ); + assert!(shared.is_file()); + let unresolved: Vec<_> = facts + .unresolved + .iter() + .map(|item| (item.kind, item.name.as_str())) + .collect(); + assert_eq!( + unresolved, + vec![ + ( + UnresolvedKind::OutsideWorkspace, + tree.root + .parent() + .unwrap() + .join("outside") + .to_str() + .unwrap() + ), + (UnresolvedKind::MissingFile, "lib/missing.jar"), + (UnresolvedKind::ClassFolder, "classes-folder"), + (UnresolvedKind::UnknownMacro, "jar://$TOOLS_DIR$/x.jar!/"), + (UnresolvedKind::IdeLibrary, "Global Utils"), + (UnresolvedKind::MissingLibrary, "absent"), + (UnresolvedKind::MissingFile, "gone.iml"), + ] + ); + assert!(facts.needs_servlet); + assert_eq!(facts.hints, vec![ServletHint::Major(9)]); + assert_eq!(facts.web_roots, vec![tree.root.join("web")]); + } + + #[test] + fn a_file_based_project_reads_its_ipr() { + let tree = Tree::new(&[ + ( + "Legacy.ipr", + r#" + + + "#, + ), + ( + "Legacy.iml", + r#""#, + ), + ("lib/a.jar", ""), + ]); + let facts = read(&tree.root, &[tree.root.join("Legacy.ipr")], ¯os(&tree)).unwrap(); + assert_eq!(facts.descriptor, "Legacy.ipr"); + assert_eq!(facts.source_paths, vec!["source"]); + assert_eq!(facts.libraries[0].pattern, "lib/a.jar"); + assert!(read(&tree.root.join("lib"), &[], ¯os(&tree)).is_none()); + } +} diff --git a/backend/src/project_model/mod.rs b/backend/src/project_model/mod.rs new file mode 100644 index 0000000..2028af8 --- /dev/null +++ b/backend/src/project_model/mod.rs @@ -0,0 +1,703 @@ +//! The Java project model of a workspace folder, and what the plugin adds to +//! JDT LS for the folders JDT imports as a plain ("invisible") project. +//! +//! JDT LS owns import: Maven and Gradle build files win, then Eclipse +//! `.project` files, and only a folder with neither becomes an invisible +//! project, whose classpath comes from `java.project.referencedLibraries` +//! and `java.project.sourcePaths` alone. For those folders this module reads +//! the layouts other tools leave behind (IntelliJ IDEA modules, legacy web +//! roots with `WEB-INF/lib`, exploded EARs) and adds what they declare to the +//! two settings **in memory**: the user's own `.vscode/settings.json` values +//! stay first and in charge, and no project file is written unless the user +//! saves through the settings page. Eclipse WTP containers are resolved inside +//! JDT LS by the plugin's extension bundle (`jdtls-extension/project-model`), +//! which receives the servlet container under `java.lithe.projectModel`. +//! +//! Everything here is bounded: one walk ([`scan`]), fixed descriptor paths, +//! 2 MiB per descriptor, and item limits in each reader. + +pub mod eclipse; +mod idea; +mod scan; +pub mod servlet; +mod web; +mod xml; + +use serde_json::{json, Value}; +use servlet::{ServletEnvironment, ServletResolution}; +use std::fs; +use std::io::Read; +use std::path::{Path, PathBuf}; + +/// Plugin setting that turns detection (and the bundle's containers) off. +pub const DETECTION_SETTING: &str = "projectModelDetection"; +/// Plugin setting naming the servlet container folder; empty is automatic. +pub const SERVLET_HOME_SETTING: &str = "servletContainerHome"; +/// The upstream default of `java.project.referencedLibraries`. Setting the key +/// replaces the default, so an overlay without an explicit value keeps it. +pub const UPSTREAM_DEFAULT_LIBRARIES: &str = "lib/**"; +/// Largest descriptor file read. +pub const MAX_DESCRIPTOR_BYTES: u64 = 2 * 1024 * 1024; + +/// The plugin settings that steer detection, from a launch's `settings`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ModelOptions { + pub detection: bool, + pub servlet_home: Option, +} + +impl Default for ModelOptions { + fn default() -> Self { + Self { + detection: true, + servlet_home: None, + } + } +} + +/// Reads [`DETECTION_SETTING`] and [`SERVLET_HOME_SETTING`]; absent values +/// are the manifest defaults. +pub fn parse_options(settings: &Value) -> Result { + let detection = match settings.get(DETECTION_SETTING) { + None | Some(Value::Null) => true, + Some(Value::Bool(value)) => *value, + Some(_) => return Err("The project model detection setting is not a boolean."), + }; + let servlet_home = match settings.get(SERVLET_HOME_SETTING) { + None | Some(Value::Null) => None, + Some(Value::String(text)) if text.is_empty() => None, + Some(Value::String(text)) if Path::new(text).is_absolute() => Some(PathBuf::from(text)), + Some(_) => return Err("The servlet container folder setting is not a folder."), + }; + Ok(ModelOptions { + detection, + servlet_home, + }) +} + +/// Which JDT importer takes the folder, and which layout fed the overlay. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ModelKind { + Maven, + Gradle, + Eclipse, + Idea, + LegacyWeb, + Plain, +} + +impl ModelKind { + /// Whether a JDT importer other than the invisible project owns the + /// classpath; overlays of `java.project.*` then have no effect. + pub fn managed(self) -> bool { + matches!(self, Self::Maven | Self::Gradle | Self::Eclipse) + } +} + +/// Where a detected library comes from. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Origin { + WebLibraries, + EarLibraries, + ManifestClassPath, + IdeaModuleLibrary, + IdeaProjectLibrary, + ServletContainer, +} + +/// One `referencedLibraries` include the model adds. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Detected { + /// Workspace-relative glob or file (slash separated), or an absolute path. + pub pattern: String, + pub origin: Origin, + /// Module, library or folder name shown with the entry. + pub label: String, + /// Number of JAR files the entry stands for (displayed only). + pub count: usize, +} + +/// Why a declared library could not be added. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum UnresolvedKind { + /// A declared file does not exist. + MissingFile, + /// A project library a module uses is not defined. + MissingLibrary, + /// An IDEA application or global library, kept outside the project. + IdeLibrary, + /// A class folder; JDT's referenced libraries accept only JAR files. + ClassFolder, + /// A path variable whose value only the other IDE knows. + UnknownMacro, + /// A source folder outside the workspace folder. + OutsideWorkspace, + /// An Eclipse user library, defined in an Eclipse workspace. + UserLibrary, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Unresolved { + pub kind: UnresolvedKind, + pub name: String, +} + +/// The detected model of one workspace folder. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ProjectModel { + pub kind: ModelKind, + pub enabled: bool, + /// Workspace-relative descriptor that identifies the model, if any. + pub descriptor: Option, + pub idea_modules: usize, + pub eclipse_projects: usize, + /// Libraries for the invisible project; empty for managed kinds. + pub libraries: Vec, + /// IDEA source folders, production before test. + pub source_paths: Vec, + pub unresolved: Vec, + /// The project needs servlet container libraries. + pub needs_servlet: bool, + /// Resolved only when [`Self::needs_servlet`]. + pub servlet: ServletResolution, + /// A scan or reader limit cut detection short. + pub truncated: bool, +} + +/// What detection may read beyond the workspace: the user's home for IDEA +/// macros and the servlet container search. +pub struct Environment { + pub servlet: ServletEnvironment, + pub user_home: Option, +} + +impl Environment { + /// The process environment of this platform. + pub fn current() -> Self { + let os = match std::env::consts::OS { + "macos" => "macos", + "windows" => "windows", + _ => "linux", + }; + let user_home = std::env::var_os(if os == "windows" { + "USERPROFILE" + } else { + "HOME" + }) + .map(PathBuf::from) + .filter(|path| path.is_absolute()); + Self { + servlet: ServletEnvironment::current(os), + user_home, + } + } +} + +/// Detects the model of the folder `root`. +pub fn detect(root: &Path, options: &ModelOptions, environment: &Environment) -> ProjectModel { + let found = scan::scan(root); + let mut model = ProjectModel { + kind: ModelKind::Plain, + enabled: options.detection, + descriptor: None, + idea_modules: 0, + eclipse_projects: found.eclipse_projects.len(), + libraries: Vec::new(), + source_paths: Vec::new(), + unresolved: Vec::new(), + needs_servlet: false, + servlet: ServletResolution::default(), + truncated: found.truncated, + }; + let mut hints = Vec::new(); + if let Some(build) = found.build_files.first() { + let maven = found + .build_files + .iter() + .any(|file| file.ends_with("pom.xml")); + model.kind = if maven { + ModelKind::Maven + } else { + ModelKind::Gradle + }; + let descriptor = found + .build_files + .iter() + .find(|file| !maven || file.ends_with("pom.xml")) + .unwrap_or(build); + model.descriptor = Some(relative_or_absolute(root, descriptor)); + return model; + } + if let Some(project) = found.eclipse_projects.first() { + model.kind = ModelKind::Eclipse; + model.descriptor = Some(relative_or_absolute(root, &project.join(".project"))); + if options.detection { + let facts = eclipse::read(&found.eclipse_projects); + model.needs_servlet = facts.needs_servlet; + hints.extend(facts.hints); + model + .unresolved + .extend(facts.user_libraries.into_iter().map(|name| Unresolved { + kind: UnresolvedKind::UserLibrary, + name, + })); + } + } else { + let macros = idea::Macros { + project_dir: root.to_path_buf(), + user_home: environment.user_home.clone(), + maven_repository: environment + .user_home + .as_ref() + .map(|home| home.join(".m2/repository")), + }; + let idea = idea::read(root, &found.ipr_files, ¯os); + let mut web_roots = found.web_roots.clone(); + if let Some(idea) = &idea { + model.kind = ModelKind::Idea; + model.descriptor = Some(idea.descriptor.clone()); + model.idea_modules = idea.modules; + for web_root in &idea.web_roots { + if !web_roots.contains(web_root) && web_root.join("WEB-INF").is_dir() { + web_roots.push(web_root.clone()); + } + } + } else if let Some(web_root) = web_roots.first() { + model.kind = ModelKind::LegacyWeb; + model.descriptor = Some(relative_or_absolute( + root, + &web_root.join("WEB-INF/web.xml"), + )); + } else if let Some(ear_root) = found.ear_roots.first() { + model.kind = ModelKind::LegacyWeb; + model.descriptor = Some(relative_or_absolute( + root, + &ear_root.join("META-INF/application.xml"), + )); + } + if !options.detection { + return model; + } + if let Some(idea) = idea { + model.source_paths = idea + .source_paths + .into_iter() + .chain(idea.test_source_paths) + .collect(); + model.libraries = idea.libraries; + model.unresolved = idea.unresolved; + model.needs_servlet = idea.needs_servlet; + model.truncated |= idea.truncated; + hints.extend(idea.hints); + } + let web = web::read(root, &web_roots, &found.ear_roots); + if let Some(namespace) = web.namespace { + hints.push(servlet::ServletHint::Namespace(namespace)); + } + for library in web.libraries { + if !model + .libraries + .iter() + .any(|known| known.pattern == library.pattern) + { + model.libraries.push(library); + } + } + model.needs_servlet |= !web_roots.is_empty(); + } + if model.needs_servlet { + model.servlet = servlet::resolve( + options.servlet_home.as_deref(), + &hints, + &environment.servlet, + ); + } + model +} + +/// The `java.project.*` values of a `.vscode/settings.json` document. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Explicit { + /// `referencedLibraries`: an include array or the rich object form. + pub libraries: Option, + pub source_paths: Option, + pub output_path: Option, +} + +impl Explicit { + pub fn from_document(document: &Value) -> Self { + Self { + libraries: document.get("java.project.referencedLibraries").cloned(), + source_paths: document.get("java.project.sourcePaths").cloned(), + output_path: document.get("java.project.outputPath").cloned(), + } + } + + /// The explicit include patterns, from either form. + pub fn include(&self) -> Vec { + let list = match &self.libraries { + Some(Value::Object(object)) => object.get("include"), + other => other.as_ref(), + }; + strings(list) + } +} + +/// Every include the model adds: detected libraries, then the servlet +/// container's libraries. Empty for managed kinds and when disabled. +pub fn detected_include(model: &ProjectModel) -> Vec { + if !model.enabled || model.kind.managed() { + return Vec::new(); + } + let mut include: Vec = model + .libraries + .iter() + .map(|item| item.pattern.clone()) + .collect(); + if let Some(runtime) = &model.servlet.runtime { + include.extend( + runtime + .libraries + .iter() + .map(|path| path.to_string_lossy().to_string()), + ); + } + include +} + +/// The effective `referencedLibraries`: the explicit value (or the upstream +/// default) with the detected includes appended, keeping its excludes and +/// source attachments. None when neither exists: JDT LS rebuilds its +/// preferences from every push, so an absent key is the upstream default. +pub fn effective_libraries(model: &ProjectModel, explicit: &Explicit) -> Option { + let detected = detected_include(model); + if detected.is_empty() { + return explicit.libraries.clone(); + } + let mut include = match &explicit.libraries { + Some(_) => explicit.include(), + None => vec![UPSTREAM_DEFAULT_LIBRARIES.to_string()], + }; + for pattern in detected { + if !include.contains(&pattern) { + include.push(pattern); + } + } + Some(match &explicit.libraries { + Some(Value::Object(object)) => { + let mut object = object.clone(); + object.insert("include".into(), json!(include)); + Value::Object(object) + } + _ => json!(include), + }) +} + +/// The effective `sourcePaths`: explicit, else the IDEA source folders. +pub fn effective_source_paths(model: &ProjectModel, explicit: &Explicit) -> Option { + if explicit.source_paths.is_some() { + return explicit.source_paths.clone(); + } + (model.enabled && model.kind == ModelKind::Idea && !model.source_paths.is_empty()) + .then(|| json!(model.source_paths)) +} + +/// The `java` settings sections the plugin overlays for `model`: +/// `{project: {...}, lithe: {projectModel: {...}}}`, each only with keys +/// that differ from what JDT LS and the bundle assume when a key is absent. +pub fn overlay(model: &ProjectModel, explicit: &Explicit) -> Value { + let mut project = json!({}); + if let Some(libraries) = effective_libraries(model, explicit) { + project["referencedLibraries"] = libraries; + } + if let Some(paths) = effective_source_paths(model, explicit) { + project["sourcePaths"] = paths; + } + if let Some(output) = &explicit.output_path { + project["outputPath"] = output.clone(); + } + let runtime = model.servlet.runtime.as_ref(); + if model.enabled && runtime.is_none() { + return json!({"project": project}); + } + json!({ + "project": project, + "lithe": {"projectModel": { + "enabled": model.enabled, + "serverRuntimeHome": runtime.map(|runtime| runtime.home.to_string_lossy().to_string()).unwrap_or_default(), + "serverRuntimeLibraries": runtime.map(|runtime| runtime.libraries.iter().map(|path| path.to_string_lossy().to_string()).collect::>()).unwrap_or_default(), + "serverRuntimeName": runtime.map(|runtime| runtime.name.clone()).unwrap_or_default(), + }}, + }) +} + +fn strings(value: Option<&Value>) -> Vec { + value + .and_then(Value::as_array) + .map(|items| { + items + .iter() + .filter_map(Value::as_str) + .map(str::to_string) + .collect() + }) + .unwrap_or_default() +} + +/// The bytes of a regular file of at most [`MAX_DESCRIPTOR_BYTES`]. +pub(crate) fn read_bounded(path: &Path) -> Option> { + let info = fs::metadata(path).ok()?; + if !info.is_file() || info.len() > MAX_DESCRIPTOR_BYTES { + return None; + } + let mut bytes = Vec::new(); + fs::File::open(path) + .ok()? + .take(MAX_DESCRIPTOR_BYTES + 1) + .read_to_end(&mut bytes) + .ok()?; + (bytes.len() as u64 <= MAX_DESCRIPTOR_BYTES).then_some(bytes) +} + +/// `path` relative to `root` with `/` separators, or None outside it. +pub(crate) fn relative_inside(root: &Path, path: &Path) -> Option { + let relative = path.strip_prefix(root).ok()?; + let parts: Vec<_> = relative + .components() + .map(|part| part.as_os_str().to_string_lossy().to_string()) + .collect(); + Some(if parts.is_empty() { + ".".to_string() + } else { + parts.join("/") + }) +} + +/// `path` relative to `root` when inside it, else the absolute path. +pub(crate) fn relative_or_absolute(root: &Path, path: &Path) -> String { + relative_inside(root, path).unwrap_or_else(|| path.to_string_lossy().to_string()) +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + use std::sync::atomic::{AtomicU64, Ordering}; + + /// A temporary folder tree removed on drop; `root` is canonical. + pub struct Tree { + pub root: PathBuf, + } + + impl Tree { + pub fn new(files: &[(&str, &str)]) -> Self { + static NEXT: AtomicU64 = AtomicU64::new(0); + let base = std::env::temp_dir().join(format!( + "lithe-project-model-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + let _ = fs::remove_dir_all(&base); + fs::create_dir_all(base.join("workspace")).unwrap(); + let tree = Self { + root: dunce::canonicalize(base.join("workspace")).unwrap(), + }; + for (path, content) in files { + tree.write(path, content); + } + tree + } + + pub fn write(&self, path: &str, content: &str) { + let file = self.root.join(path); + fs::create_dir_all(file.parent().unwrap()).unwrap(); + fs::write(file, content).unwrap(); + } + } + + impl Drop for Tree { + fn drop(&mut self) { + if let Some(base) = self.root.parent() { + if let Err(error) = fs::remove_dir_all(base) { + if !std::thread::panicking() { + panic!("temporary tree cleanup: {error}"); + } + } + } + } + } + + fn environment(tree: &Tree) -> Environment { + Environment { + servlet: ServletEnvironment { + variables: vec![], + search: vec![(tree.root.join("servers"), None)], + }, + user_home: Some(tree.root.join("home")), + } + } + + fn tomcat(tree: &Tree) -> PathBuf { + tree.write("servers/apache-tomcat-9.0.98/lib/servlet-api.jar", ""); + tree.write("servers/apache-tomcat-9.0.98/lib/jsp-api.jar", ""); + tree.root.join("servers/apache-tomcat-9.0.98") + } + + #[test] + fn a_legacy_web_folder_keeps_the_upstream_default_and_adds_web_libraries_and_the_servlet_container( + ) { + let tree = Tree::new(&[ + ("project/WebContent/WEB-INF/lib/a.jar", ""), + ("project/src/demo/A.java", ""), + ]); + let home = tomcat(&tree); + let model = detect(&tree.root, &ModelOptions::default(), &environment(&tree)); + assert_eq!(model.kind, ModelKind::LegacyWeb); + assert_eq!( + model.descriptor.as_deref(), + Some("project/WebContent/WEB-INF/web.xml") + ); + let value = overlay(&model, &Explicit::default()); + assert_eq!( + value["project"]["referencedLibraries"], + json!([ + "lib/**", + "project/WebContent/WEB-INF/lib/*.jar", + home.join("lib/jsp-api.jar").to_str().unwrap(), + home.join("lib/servlet-api.jar").to_str().unwrap(), + ]) + ); + assert!(value["project"].get("sourcePaths").is_none()); + assert_eq!( + value["lithe"]["projectModel"]["serverRuntimeName"], + "Apache Tomcat 9.0.98" + ); + assert_eq!( + value["lithe"]["projectModel"]["serverRuntimeHome"], + home.to_str().unwrap() + ); + } + + #[test] + fn explicit_values_stay_first_and_keep_excludes_and_sources() { + let tree = Tree::new(&[("WebRoot/WEB-INF/lib/a.jar", "")]); + let model = detect(&tree.root, &ModelOptions::default(), &environment(&tree)); + let explicit = Explicit::from_document(&json!({ + "java.project.referencedLibraries": {"include": ["vendor/x.jar"], "exclude": ["WebRoot/WEB-INF/lib/bad.jar"], "sources": {"vendor/x.jar": "vendor/x-src.jar"}}, + "java.project.sourcePaths": ["src/java"], + "java.project.outputPath": "out", + })); + let value = overlay(&model, &explicit); + assert_eq!( + value["project"]["referencedLibraries"]["include"], + json!(["vendor/x.jar", "WebRoot/WEB-INF/lib/*.jar"]) + ); + assert_eq!( + value["project"]["referencedLibraries"]["exclude"], + json!(["WebRoot/WEB-INF/lib/bad.jar"]) + ); + assert_eq!( + value["project"]["referencedLibraries"]["sources"]["vendor/x.jar"], + "vendor/x-src.jar" + ); + assert_eq!(value["project"]["sourcePaths"], json!(["src/java"])); + assert_eq!(value["project"]["outputPath"], "out"); + // No servlet container is installed, so the bundle keeps its defaults. + assert!(value.get("lithe").is_none()); + } + + #[test] + fn idea_projects_set_source_paths_and_build_files_win_over_every_layout() { + let tree = Tree::new(&[ + ( + ".idea/modules.xml", + r#""#, + ), + ( + "a.iml", + r#""#, + ), + ]); + let model = detect(&tree.root, &ModelOptions::default(), &environment(&tree)); + assert_eq!(model.kind, ModelKind::Idea); + let value = overlay(&model, &Explicit::default()); + assert_eq!(value["project"]["sourcePaths"], json!(["java", "tests"])); + assert!(value["project"].get("referencedLibraries").is_none()); + assert!(value.get("lithe").is_none()); + tree.write("module/build.gradle", ""); + let model = detect(&tree.root, &ModelOptions::default(), &environment(&tree)); + assert_eq!( + (model.kind, model.descriptor.as_deref()), + (ModelKind::Gradle, Some("module/build.gradle")) + ); + assert_eq!(overlay(&model, &Explicit::default())["project"], json!({})); + } + + #[test] + fn eclipse_projects_only_configure_the_servlet_container_for_the_bundle() { + let tree = Tree::new(&[ + ("app/.project", ""), + ( + "app/.classpath", + r#""#, + ), + ("app/WebContent/WEB-INF/lib/a.jar", ""), + ]); + let home = tomcat(&tree); + let model = detect(&tree.root, &ModelOptions::default(), &environment(&tree)); + assert_eq!( + (model.kind, model.descriptor.as_deref()), + (ModelKind::Eclipse, Some("app/.project")) + ); + assert_eq!( + model.unresolved, + vec![Unresolved { + kind: UnresolvedKind::UserLibrary, + name: "Libs".into() + }] + ); + let value = overlay(&model, &Explicit::default()); + assert_eq!(value["project"], json!({})); + assert_eq!( + value["lithe"]["projectModel"]["serverRuntimeHome"], + home.to_str().unwrap() + ); + } + + #[test] + fn disabling_detection_changes_nothing_but_tells_the_bundle() { + let tree = Tree::new(&[("WebContent/WEB-INF/lib/a.jar", "")]); + tomcat(&tree); + let options = ModelOptions { + detection: false, + servlet_home: None, + }; + let model = detect(&tree.root, &options, &environment(&tree)); + assert_eq!(model.kind, ModelKind::LegacyWeb); + let value = overlay(&model, &Explicit::default()); + assert_eq!(value["project"], json!({})); + assert_eq!(value["lithe"]["projectModel"]["enabled"], false); + } + + #[test] + fn options_are_parsed_strictly() { + assert_eq!(parse_options(&json!({})), Ok(ModelOptions::default())); + let folder = if cfg!(windows) { + r"C:\tomcat" + } else { + "/opt/tomcat" + }; + assert_eq!( + parse_options(&json!({DETECTION_SETTING: false, SERVLET_HOME_SETTING: folder})), + Ok(ModelOptions { + detection: false, + servlet_home: Some(PathBuf::from(folder)) + }) + ); + assert_eq!( + parse_options(&json!({SERVLET_HOME_SETTING: ""})), + Ok(ModelOptions::default()) + ); + assert!(parse_options(&json!({SERVLET_HOME_SETTING: "relative"})).is_err()); + assert!(parse_options(&json!({DETECTION_SETTING: "yes"})).is_err()); + } +} diff --git a/backend/src/project_model/scan.rs b/backend/src/project_model/scan.rs new file mode 100644 index 0000000..f1bdd56 --- /dev/null +++ b/backend/src/project_model/scan.rs @@ -0,0 +1,169 @@ +//! One bounded walk of a workspace folder that finds every file the project +//! model readers need. It never follows symbolic links, skips hidden, +//! dependency and build output trees, and reads at most +//! [`SCAN_ENTRY_BUDGET`] entries, so a huge workspace costs a bounded delay. + +use std::collections::VecDeque; +use std::fs; +use std::path::{Path, PathBuf}; + +/// How deep below the workspace folder the walk descends. Legacy layouts keep +/// web roots at most a few levels down (`module/WebRoot/WEB-INF`). +pub const SCAN_DEPTH: usize = 6; +/// Most directory entries one walk reads. +pub const SCAN_ENTRY_BUDGET: usize = 20_000; +/// Most items of each kind the walk records. +pub const SCAN_ITEM_LIMIT: usize = 256; +/// Directories never entered: dependency and build output trees, and the +/// descriptor folders whose few known children are read directly. +pub const SKIPPED_DIRECTORIES: &[&str] = &[ + "node_modules", + "target", + "build", + "bin", + "out", + "dist", + "vendor", + "classes", + "WEB-INF", + "META-INF", + "archetype-resources", +]; +/// Files whose presence makes JDT LS import the folder with Maven or Gradle. +pub const BUILD_FILES: &[&str] = &[ + "pom.xml", + "build.gradle", + "build.gradle.kts", + "settings.gradle", + "settings.gradle.kts", +]; + +/// What one walk found, in walk order (breadth first, names sorted). +#[derive(Debug, Default, Clone, PartialEq, Eq)] +pub struct Scan { + /// Maven and Gradle build files. + pub build_files: Vec, + /// Folders holding an Eclipse `.project`. + pub eclipse_projects: Vec, + /// Folders holding a `WEB-INF` directory: deployed web application roots. + pub web_roots: Vec, + /// Exploded EAR roots: folders holding `META-INF/application.xml`, and + /// WTP's `EarContent` folders. + pub ear_roots: Vec, + /// IntelliJ IDEA file-based project descriptors at the folder's top. + pub ipr_files: Vec, + /// The budget or an item limit stopped the walk early. + pub truncated: bool, +} + +/// Walks `root`; an unreadable directory contributes nothing. +pub fn scan(root: &Path) -> Scan { + let mut found = Scan::default(); + let mut budget = SCAN_ENTRY_BUDGET; + let mut pending = VecDeque::from([(root.to_path_buf(), 0usize)]); + while let Some((directory, depth)) = pending.pop_front() { + // An unreadable directory contributes nothing to the model. + let Ok(entries) = fs::read_dir(&directory) else { + continue; + }; + let mut entries: Vec<_> = entries.filter_map(Result::ok).collect(); + entries.sort_by_key(|entry| entry.file_name()); + for entry in entries { + if budget == 0 { + found.truncated = true; + return found; + } + budget -= 1; + let name = entry.file_name(); + let Some(name) = name.to_str() else { + continue; + }; + let Ok(kind) = entry.file_type() else { + continue; + }; + let path = entry.path(); + if kind.is_dir() { + if name == "WEB-INF" { + push( + &mut found.web_roots, + directory.clone(), + &mut found.truncated, + ); + } else if name == "META-INF" && path.join("application.xml").is_file() { + push( + &mut found.ear_roots, + directory.clone(), + &mut found.truncated, + ); + } else if name == "EarContent" { + push(&mut found.ear_roots, path.clone(), &mut found.truncated); + } + let skipped = name.starts_with('.') || SKIPPED_DIRECTORIES.contains(&name); + if depth < SCAN_DEPTH && !skipped { + pending.push_back((path, depth + 1)); + } + } else if kind.is_file() { + if BUILD_FILES.contains(&name) { + push(&mut found.build_files, path, &mut found.truncated); + } else if name == ".project" { + push( + &mut found.eclipse_projects, + directory.clone(), + &mut found.truncated, + ); + } else if depth == 0 && name.ends_with(".ipr") { + push(&mut found.ipr_files, path, &mut found.truncated); + } + } + } + } + found.ear_roots.sort(); + found.ear_roots.dedup(); + found +} + +fn push(items: &mut Vec, item: PathBuf, truncated: &mut bool) { + if items.len() >= SCAN_ITEM_LIMIT { + *truncated = true; + } else if !items.contains(&item) { + items.push(item); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::project_model::tests::Tree; + + #[test] + fn finds_build_files_eclipse_projects_web_and_ear_roots_but_skips_build_trees() { + let tree = Tree::new(&[ + ("pom.xml", ""), + ("legacy/.project", ""), + ("legacy/WebContent/WEB-INF/lib/a.jar", ""), + ("ear/EarContent/lib/b.jar", ""), + ("exploded/META-INF/application.xml", ""), + ("target/dep/pom.xml", ""), + ("target/x/WEB-INF/lib/c.jar", ""), + ("lib/META-INF/maven/pom.xml", ""), + (".hidden/pom.xml", ""), + ("Demo.ipr", ""), + ]); + let found = scan(&tree.root); + assert_eq!(found.build_files, vec![tree.root.join("pom.xml")]); + assert_eq!(found.eclipse_projects, vec![tree.root.join("legacy")]); + assert_eq!(found.web_roots, vec![tree.root.join("legacy/WebContent")]); + assert_eq!( + found.ear_roots, + vec![tree.root.join("ear/EarContent"), tree.root.join("exploded")] + ); + assert_eq!(found.ipr_files, vec![tree.root.join("Demo.ipr")]); + assert!(!found.truncated); + } + + #[test] + fn a_missing_folder_is_an_empty_scan() { + let tree = Tree::new(&[]); + assert_eq!(scan(&tree.root.join("missing")), Scan::default()); + } +} diff --git a/backend/src/project_model/servlet.rs b/backend/src/project_model/servlet.rs new file mode 100644 index 0000000..3ed7a11 --- /dev/null +++ b/backend/src/project_model/servlet.rs @@ -0,0 +1,474 @@ +//! The servlet container whose libraries stand in for the "Server Runtime" a +//! web project was written against. Precedence: the plugin setting, then +//! `CATALINA_HOME`/`TOMCAT_HOME`, then installations in the standard places, +//! choosing the one closest to what the project names (an Eclipse runtime +//! "Apache Tomcat v8.5", an IDEA "Tomcat 9.0.98" library, a javax or jakarta +//! web.xml). Only directory listings and two small text files are read. + +use super::read_bounded; +use super::web::ServletNamespace; +use std::fs; +use std::path::{Path, PathBuf}; + +/// Most libraries taken from one installation. +pub const MAX_RUNTIME_LIBRARIES: usize = 256; +/// Environment variables naming a servlet container folder, in order. +pub const HOME_VARIABLES: &[&str] = &["CATALINA_HOME", "TOMCAT_HOME"]; +/// Folder name prefixes of servlet container installations. +const INSTALLATION_PREFIXES: &[&str] = &["apache-tomcat", "tomcat", "jetty"]; + +/// A preference for one installation over another, read from the project. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ServletHint { + /// The Tomcat major version the project names. + Major(u32), + /// The API namespace the project's descriptors or containers imply. + Namespace(ServletNamespace), +} + +impl ServletHint { + /// The hint in a runtime or library name: "Apache Tomcat v8.5" is Tomcat + /// 8, "MYECLIPSE_JAVAEE_6_CONTAINER" is javax. + pub fn from_name(name: &str) -> Option { + let lower = name.to_ascii_lowercase(); + if let Some(index) = lower.find("tomcat") { + let digits: String = lower[index + 6..] + .chars() + .skip_while(|c| !c.is_ascii_digit()) + .take_while(char::is_ascii_digit) + .collect(); + if let Ok(major) = digits.parse() { + return Some(Self::Major(major)); + } + } + if lower.contains("javaee") || lower.contains("j2ee") || lower.contains("generic_") { + return Some(Self::Namespace(ServletNamespace::Javax)); + } + None + } +} + +/// Where the installation in use came from. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ServletSource { + /// The plugin's servlet container setting. + Setting, + /// One of [`HOME_VARIABLES`]. + Environment(&'static str), + /// Found in a standard installation folder. + Installed, +} + +/// A servlet container installation and the libraries it provides. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ServletRuntime { + pub home: PathBuf, + pub libraries: Vec, + /// Display name such as "Apache Tomcat 9.0.98". + pub name: String, + pub version: Option, + pub source: ServletSource, +} + +/// The outcome of resolving the servlet container. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct ServletResolution { + pub runtime: Option, + /// The setting names a folder that is not a servlet container; nothing + /// else is tried, so the user sees their choice is not in use. + pub setting_invalid: bool, +} + +/// What the resolution may read: environment variables and the folders +/// searched for installations. Tests supply their own. +pub struct ServletEnvironment { + pub variables: Vec<(&'static str, PathBuf)>, + /// Folders whose children named like an installation are candidates, + /// each with the subfolder holding the installation (Homebrew's `libexec`). + pub search: Vec<(PathBuf, Option<&'static str>)>, +} + +impl ServletEnvironment { + /// The process environment and the standard folders of `os`. + pub fn current(os: &str) -> Self { + let variables = HOME_VARIABLES + .iter() + .filter_map(|name| std::env::var_os(name).map(|value| (*name, PathBuf::from(value)))) + .filter(|(_, path)| path.is_absolute()) + .collect(); + let home = std::env::var_os(if os == "windows" { + "USERPROFILE" + } else { + "HOME" + }) + .map(PathBuf::from); + let mut search: Vec<(PathBuf, Option<&'static str>)> = match os { + "macos" => vec![ + (PathBuf::from("/opt/homebrew/opt"), Some("libexec")), + (PathBuf::from("/usr/local/opt"), Some("libexec")), + (PathBuf::from("/Library"), None), + (PathBuf::from("/usr/local"), None), + (PathBuf::from("/opt"), None), + ], + "windows" => vec![ + ( + PathBuf::from(r"C:\Program Files\Apache Software Foundation"), + None, + ), + (PathBuf::from(r"C:\"), None), + ], + _ => vec![ + (PathBuf::from("/usr/share"), None), + (PathBuf::from("/opt"), None), + (PathBuf::from("/usr/local"), None), + ], + }; + if let Some(home) = home { + search.push((home, None)); + } + Self { variables, search } + } +} + +/// Resolves the servlet container for a project with `hints`. +pub fn resolve( + setting: Option<&Path>, + hints: &[ServletHint], + environment: &ServletEnvironment, +) -> ServletResolution { + if let Some(folder) = setting { + return match inspect(folder, ServletSource::Setting) { + Some(runtime) => ServletResolution { + runtime: Some(runtime), + setting_invalid: false, + }, + None => ServletResolution { + runtime: None, + setting_invalid: true, + }, + }; + } + for (name, folder) in &environment.variables { + if let Some(runtime) = inspect(folder, ServletSource::Environment(name)) { + return ServletResolution { + runtime: Some(runtime), + setting_invalid: false, + }; + } + } + let mut installed = Vec::new(); + for (folder, suffix) in &environment.search { + let Ok(entries) = fs::read_dir(folder) else { + continue; + }; + let mut names: Vec<_> = entries + .filter_map(Result::ok) + .map(|entry| entry.path()) + .collect(); + names.sort(); + for path in names { + let Some(name) = path.file_name().and_then(|name| name.to_str()) else { + continue; + }; + let lower = name.to_ascii_lowercase(); + if !INSTALLATION_PREFIXES + .iter() + .any(|prefix| lower.starts_with(prefix)) + { + continue; + } + let home = suffix.map_or_else(|| path.clone(), |suffix| path.join(suffix)); + if let Some(runtime) = inspect(&home, ServletSource::Installed) { + if !installed + .iter() + .any(|known: &ServletRuntime| known.home == runtime.home) + { + installed.push(runtime); + } + } + } + } + let best = installed.into_iter().max_by(|left, right| { + score(left, hints) + .cmp(&score(right, hints)) + // Equal scores keep the first found, which is the most standard place. + .then(std::cmp::Ordering::Greater) + }); + ServletResolution { + runtime: best, + setting_invalid: false, + } +} + +/// Orders installations: the named major version, then the implied +/// namespace, then the newest version. +fn score(runtime: &ServletRuntime, hints: &[ServletHint]) -> (bool, bool, Vec) { + let version: Vec = runtime + .version + .as_deref() + .unwrap_or_default() + .split('.') + .filter_map(|part| part.parse().ok()) + .collect(); + let major = version.first().copied(); + let tomcat = runtime.name.contains("Tomcat"); + let exact = hints + .iter() + .any(|hint| matches!(hint, ServletHint::Major(wanted) if tomcat && Some(*wanted) == major)); + let namespace = if tomcat && major.is_some_and(|major| major >= 10) + || runtime + .libraries + .iter() + .any(|library| library.to_string_lossy().contains("jakarta")) + { + ServletNamespace::Jakarta + } else { + ServletNamespace::Javax + }; + // The namespace web.xml declares outranks one implied by a version name. + let wanted = hints + .iter() + .find_map(|hint| match hint { + ServletHint::Namespace(namespace) => Some(*namespace), + ServletHint::Major(_) => None, + }) + .or_else(|| { + hints.iter().find_map(|hint| match hint { + ServletHint::Major(major) if *major >= 10 => Some(ServletNamespace::Jakarta), + ServletHint::Major(_) => Some(ServletNamespace::Javax), + ServletHint::Namespace(_) => None, + }) + }); + ( + exact, + wanted.is_none_or(|wanted| wanted == namespace), + version, + ) +} + +/// The installation at `home`, if its `lib` (Tomcat 5.5: `common/lib`) holds +/// a servlet API library. +pub fn inspect(home: &Path, source: ServletSource) -> Option { + let mut libraries = Vec::new(); + for directory in ["lib", "common/lib"] { + let Ok(entries) = fs::read_dir(home.join(directory)) else { + continue; + }; + let mut found: Vec = entries + .filter_map(Result::ok) + .filter(|entry| entry.file_type().is_ok_and(|kind| kind.is_file())) + .map(|entry| entry.path()) + .filter(|path| { + path.extension() + .is_some_and(|extension| extension.eq_ignore_ascii_case("jar")) + }) + .collect(); + found.sort(); + libraries.extend(found); + } + libraries.truncate(MAX_RUNTIME_LIBRARIES); + let has_api = libraries.iter().any(|library| { + library + .file_name() + .and_then(|name| name.to_str()) + .is_some_and(|name| name.contains("servlet-api") || name.contains("servlet.api")) + }); + if !has_api { + return None; + } + let (name, version) = describe(home); + Some(ServletRuntime { + home: home.to_path_buf(), + libraries, + name, + version, + source, + }) +} + +/// The display name and version: Tomcat's RELEASE-NOTES, Jetty's +/// VERSION.txt, else the version in the folder's name. +fn describe(home: &Path) -> (String, Option) { + if let Some(bytes) = read_bounded(&home.join("RELEASE-NOTES")) { + let text = String::from_utf8_lossy(&bytes); + if let Some(version) = text + .find("Apache Tomcat Version") + .and_then(|index| leading_version(&text[index + 21..])) + { + return (format!("Apache Tomcat {version}"), Some(version)); + } + } + if let Some(bytes) = read_bounded(&home.join("VERSION.txt")) { + let text = String::from_utf8_lossy(&bytes); + if let Some(version) = text + .find("jetty-") + .and_then(|index| leading_version(&text[index + 6..])) + { + return (format!("Eclipse Jetty {version}"), Some(version)); + } + } + let folder = home + .components() + .rev() + .map(|part| part.as_os_str().to_string_lossy().to_string()) + .find(|part| part != "libexec") + .unwrap_or_default(); + let version = leading_version(&folder); + let product = if folder.to_ascii_lowercase().contains("jetty") { + "Eclipse Jetty" + } else { + "Apache Tomcat" + }; + match version { + Some(version) => (format!("{product} {version}"), Some(version)), + None => (folder, None), + } +} + +/// The first dotted number in `text`, such as "9.0.98". +fn leading_version(text: &str) -> Option { + let start = text.find(|c: char| c.is_ascii_digit())?; + let version: String = text[start..] + .chars() + .take_while(|c| c.is_ascii_digit() || *c == '.') + .collect(); + let version = version.trim_end_matches('.').to_string(); + (!version.is_empty()).then_some(version) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::project_model::tests::Tree; + + fn tomcat(tree: &Tree, folder: &str, version: &str) -> PathBuf { + tree.write(&format!("{folder}/lib/servlet-api.jar"), ""); + tree.write(&format!("{folder}/lib/catalina.jar"), ""); + tree.write( + &format!("{folder}/RELEASE-NOTES"), + &format!(" Apache Tomcat Version {version}\n Release Notes\n"), + ); + tree.root.join(folder) + } + + #[test] + fn the_setting_wins_and_an_invalid_setting_is_reported_without_falling_back() { + let tree = Tree::new(&[]); + let chosen = tomcat(&tree, "chosen", "8.5.100"); + let environment = ServletEnvironment { + variables: vec![("CATALINA_HOME", tomcat(&tree, "env", "9.0.1"))], + search: vec![], + }; + let resolved = resolve(Some(&chosen), &[], &environment); + let runtime = resolved.runtime.unwrap(); + assert_eq!( + (runtime.name.as_str(), runtime.source), + ("Apache Tomcat 8.5.100", ServletSource::Setting) + ); + assert_eq!( + runtime.libraries, + vec![ + chosen.join("lib/catalina.jar"), + chosen.join("lib/servlet-api.jar") + ] + ); + let invalid = resolve(Some(&tree.root.join("missing")), &[], &environment); + assert_eq!( + invalid, + ServletResolution { + runtime: None, + setting_invalid: true + } + ); + let from_environment = resolve(None, &[], &environment).runtime.unwrap(); + assert_eq!( + from_environment.source, + ServletSource::Environment("CATALINA_HOME") + ); + } + + #[test] + fn installations_are_chosen_by_named_major_then_namespace_then_newest() { + let tree = Tree::new(&[]); + tomcat(&tree, "opt/tomcat@9/libexec", "9.0.98"); + tomcat(&tree, "opt/tomcat@10/libexec", "10.1.30"); + tomcat(&tree, "opt/tomcat/libexec", "11.0.2"); + tree.write("opt/tomcat-broken/libexec/lib/other.jar", ""); + tree.write("opt/unrelated/lib/servlet-api.jar", ""); + let environment = ServletEnvironment { + variables: vec![], + search: vec![(tree.root.join("opt"), Some("libexec"))], + }; + let pick = |hints: &[ServletHint]| { + resolve(None, hints, &environment) + .runtime + .unwrap() + .version + .unwrap() + }; + assert_eq!(pick(&[]), "11.0.2"); + assert_eq!(pick(&[ServletHint::Major(10)]), "10.1.30"); + assert_eq!( + pick(&[ServletHint::Namespace(ServletNamespace::Javax)]), + "9.0.98" + ); + assert_eq!(pick(&[ServletHint::Major(8)]), "9.0.98"); + assert_eq!( + resolve( + None, + &[], + &ServletEnvironment { + variables: vec![], + search: vec![] + } + ), + ServletResolution::default() + ); + } + + #[test] + fn names_carry_hints() { + assert_eq!( + ServletHint::from_name("Apache Tomcat v8.5"), + Some(ServletHint::Major(8)) + ); + assert_eq!( + ServletHint::from_name("Tomcat 10.1.30"), + Some(ServletHint::Major(10)) + ); + assert_eq!( + ServletHint::from_name("MYECLIPSE_JAVAEE_6_CONTAINER"), + Some(ServletHint::Namespace(ServletNamespace::Javax)) + ); + assert_eq!(ServletHint::from_name("Shared Libs"), None); + } + + #[test] + fn jetty_and_folder_names_describe_installations() { + let tree = Tree::new(&[ + ("jetty/lib/servlet-api-3.1.jar", ""), + ( + "jetty/VERSION.txt", + "jetty-9.4.54.v20240208 - 08 February 2024\n", + ), + ("apache-tomcat-7.0.109/lib/servlet-api.jar", ""), + ("old/common/lib/servlet-api.jar", ""), + ]); + assert_eq!( + inspect(&tree.root.join("jetty"), ServletSource::Installed) + .unwrap() + .name, + "Eclipse Jetty 9.4.54" + ); + assert_eq!( + inspect( + &tree.root.join("apache-tomcat-7.0.109"), + ServletSource::Installed + ) + .unwrap() + .name, + "Apache Tomcat 7.0.109" + ); + assert!(inspect(&tree.root.join("old"), ServletSource::Installed).is_some()); + } +} diff --git a/backend/src/project_model/web.rs b/backend/src/project_model/web.rs new file mode 100644 index 0000000..9d5e3e9 --- /dev/null +++ b/backend/src/project_model/web.rs @@ -0,0 +1,230 @@ +//! Libraries of legacy web and enterprise layouts without a build file: +//! `WEB-INF/lib` of every web root, the library directory of every exploded +//! EAR, and the manifest `Class-Path` of those modules. Only fixed paths below +//! roots the scan found are read. + +use super::{read_bounded, relative_or_absolute, xml, Detected, Origin}; +use std::fs; +use std::path::{Path, PathBuf}; + +/// Most JAR files counted in one directory; the count is only displayed. +pub const MAX_COUNTED_LIBRARIES: usize = 4096; + +/// Which servlet API a web module's descriptor declares. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ServletNamespace { + /// `java.sun.com`/`xmlns.jcp.org` descriptors: Java EE, `javax.servlet`. + Javax, + /// `jakarta.ee` descriptors: Jakarta EE 9+, `jakarta.servlet`. + Jakarta, +} + +/// What the web and EAR roots contribute. +#[derive(Debug, Default, Clone, PartialEq, Eq)] +pub struct WebFacts { + pub libraries: Vec, + /// The namespace of the first web.xml that declares one. + pub namespace: Option, +} + +/// Reads the libraries of `web_roots` and `ear_roots` below `root`. +pub fn read(root: &Path, web_roots: &[PathBuf], ear_roots: &[PathBuf]) -> WebFacts { + let mut facts = WebFacts::default(); + for web_root in web_roots { + let lib = web_root.join("WEB-INF/lib"); + add_directory(root, &lib, Origin::WebLibraries, &mut facts.libraries); + if facts.namespace.is_none() { + facts.namespace = namespace(&web_root.join("WEB-INF/web.xml")); + } + } + for ear_root in ear_roots { + let directory = ear_root.join(ear_library_directory(ear_root)); + add_directory(root, &directory, Origin::EarLibraries, &mut facts.libraries); + } + // A module's manifest names archives relative to where the module sits + // when deployed: the EAR's root, or beside the module itself. + for web_root in web_roots { + let mut bases: Vec<&Path> = ear_roots.iter().map(PathBuf::as_path).collect(); + if let Some(parent) = web_root.parent() { + bases.push(parent); + } + for entry in manifest_class_path(web_root) { + for base in &bases { + let file = base.join(&entry); + if file.is_file() { + let pattern = relative_or_absolute(root, &file); + if !facts.libraries.iter().any(|item| item.pattern == pattern) { + facts.libraries.push(Detected { + pattern, + origin: Origin::ManifestClassPath, + label: relative_or_absolute(root, web_root), + count: 1, + }); + } + break; + } + } + } + } + facts +} + +/// Adds `/*.jar` when the directory holds at least one JAR. +fn add_directory(root: &Path, directory: &Path, origin: Origin, libraries: &mut Vec) { + let count = count_libraries(directory); + if count == 0 { + return; + } + let pattern = format!("{}/*.jar", relative_or_absolute(root, directory)); + if !libraries.iter().any(|item| item.pattern == pattern) { + libraries.push(Detected { + pattern, + origin, + label: relative_or_absolute(root, directory), + count, + }); + } +} + +/// The number of JAR files directly inside `directory`, at most +/// [`MAX_COUNTED_LIBRARIES`]. +pub fn count_libraries(directory: &Path) -> usize { + let Ok(entries) = fs::read_dir(directory) else { + return 0; + }; + entries + .filter_map(Result::ok) + .filter(|entry| { + entry.file_type().is_ok_and(|kind| kind.is_file()) + && entry + .file_name() + .to_str() + .is_some_and(|name| name.to_ascii_lowercase().ends_with(".jar")) + }) + .take(MAX_COUNTED_LIBRARIES) + .count() +} + +/// application.xml's ``, else the Java EE 5 default `lib`. +pub fn ear_library_directory(ear_root: &Path) -> String { + let declared = read_bounded(&ear_root.join("META-INF/application.xml")) + .and_then(|bytes| xml::parse(&bytes)) + .and_then(|document| { + xml::descendants(&document, "library-directory") + .first() + .and_then(|element| element.get_text()) + .map(|text| text.trim().trim_matches('/').to_string()) + }); + match declared { + Some(directory) if !directory.is_empty() && !directory.contains("..") => directory, + _ => "lib".to_string(), + } +} + +/// The relative `Class-Path` entries of `/META-INF/MANIFEST.MF`. +pub fn manifest_class_path(module_root: &Path) -> Vec { + let Some(bytes) = read_bounded(&module_root.join("META-INF/MANIFEST.MF")) else { + return Vec::new(); + }; + let text = String::from_utf8_lossy(&bytes); + // Manifest lines continue on the next line when it starts with a space. + let mut joined = String::new(); + for line in text.lines() { + if let Some(rest) = line.strip_prefix(' ') { + joined.push_str(rest); + } else { + joined.push('\n'); + joined.push_str(line); + } + } + joined + .lines() + .find_map(|line| line.strip_prefix("Class-Path:")) + .map(|value| { + value + .split_whitespace() + .filter(|entry| !entry.contains("..") && !entry.contains(':')) + .map(str::to_string) + .collect() + }) + .unwrap_or_default() +} + +fn namespace(web_xml: &Path) -> Option { + let bytes = read_bounded(web_xml)?; + let text = String::from_utf8_lossy(&bytes); + if text.contains("jakarta.ee/xml/ns/jakartaee") { + Some(ServletNamespace::Jakarta) + } else if text.contains("java.sun.com/xml/ns") + || text.contains("xmlns.jcp.org/xml/ns") + || text.contains("java.sun.com/dtd/web-app") + { + Some(ServletNamespace::Javax) + } else { + None + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::project_model::tests::Tree; + + #[test] + fn web_inf_ear_and_manifest_libraries_are_found_with_counts() { + let tree = Tree::new(&[ + ("web/WebContent/WEB-INF/lib/a.jar", ""), + ("web/WebContent/WEB-INF/lib/b.jar", ""), + ("web/WebContent/WEB-INF/lib/readme.txt", ""), + ( + "web/WebContent/WEB-INF/web.xml", + r#""#, + ), + ( + "web/WebContent/META-INF/MANIFEST.MF", + "Manifest-Version: 1.0\nClass-Path: shared.jar lib/co\n mmon.jar ../escape.jar\n", + ), + ( + "ear/META-INF/application.xml", + "APP-INF/lib", + ), + ("ear/APP-INF/lib/c.jar", ""), + ("ear/shared.jar", ""), + ("web/lib/common.jar", ""), + ]); + let facts = read( + &tree.root, + &[tree.root.join("web/WebContent")], + &[tree.root.join("ear")], + ); + let patterns: Vec<_> = facts + .libraries + .iter() + .map(|item| (item.pattern.as_str(), item.origin, item.count)) + .collect(); + assert_eq!( + patterns, + vec![ + ("web/WebContent/WEB-INF/lib/*.jar", Origin::WebLibraries, 2), + ("ear/APP-INF/lib/*.jar", Origin::EarLibraries, 1), + ("ear/shared.jar", Origin::ManifestClassPath, 1), + ("web/lib/common.jar", Origin::ManifestClassPath, 1), + ] + ); + assert_eq!(facts.namespace, Some(ServletNamespace::Javax)); + } + + #[test] + fn an_empty_web_inf_lib_contributes_nothing_and_jakarta_is_recognized() { + let tree = Tree::new(&[ + ("WebRoot/WEB-INF/lib/.keep", ""), + ( + "WebRoot/WEB-INF/web.xml", + r#""#, + ), + ]); + let facts = read(&tree.root, &[tree.root.join("WebRoot")], &[]); + assert!(facts.libraries.is_empty()); + assert_eq!(facts.namespace, Some(ServletNamespace::Jakarta)); + } +} diff --git a/backend/src/project_model/xml.rs b/backend/src/project_model/xml.rs new file mode 100644 index 0000000..2a2fc15 --- /dev/null +++ b/backend/src/project_model/xml.rs @@ -0,0 +1,43 @@ +//! Small helpers over `xmltree` for the model descriptors. Names are matched +//! by local name, so namespaced and plain descriptors read the same. The +//! parser never fetches a DTD or external entity. + +use xmltree::{Element, XMLNode}; + +/// The document element of `bytes`, or None when it is not well formed. +pub fn parse(bytes: &[u8]) -> Option { + Element::parse(bytes).ok() +} + +/// The element children of `element` named `name`. +pub fn children<'a>(element: &'a Element, name: &'a str) -> impl Iterator + 'a { + element + .children + .iter() + .filter_map(XMLNode::as_element) + .filter(move |child| child.name == name) +} + +/// Every descendant of `element` named `name`, depth first in document order. +pub fn descendants<'a>(element: &'a Element, name: &str) -> Vec<&'a Element> { + let mut found = Vec::new(); + let mut stack: Vec<&Element> = vec![element]; + while let Some(current) = stack.pop() { + if current.name == name && !std::ptr::eq(current, element) { + found.push(current); + } + let mut nested: Vec<&Element> = current + .children + .iter() + .filter_map(XMLNode::as_element) + .collect(); + nested.reverse(); + stack.extend(nested); + } + found +} + +/// The value of attribute `name`. +pub fn attribute<'a>(element: &'a Element, name: &str) -> Option<&'a str> { + element.attributes.get(name).map(String::as_str) +} diff --git a/backend/src/project_settings.rs b/backend/src/project_settings.rs index d7ee54d..38042d4 100644 --- a/backend/src/project_settings.rs +++ b/backend/src/project_settings.rs @@ -14,16 +14,19 @@ use std::path::{Path, PathBuf}; use std::sync::Mutex; use url::Url; +use crate::project_model::{self, Environment, Explicit, ModelOptions, ProjectModel}; + 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"; +pub(crate) const LIBRARIES_FACT: &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"; +const SOURCE_PATHS_KEY: &str = "java.project.sourcePaths"; /// Bounded native read bindings; no configuration documents or tool models are cached. #[derive(Default)] @@ -205,7 +208,8 @@ impl ProjectSettings { RELEASE, "org.eclipse.jdt.core.compiler.debug.lineNumber", NATURES, - LIBRARIES + LIBRARIES_FACT, + crate::library_settings::SOURCE_PATHS_FACT ]); let mut facts = Vec::new(); for entry in projects.as_array().ok_or_else(fail)? { @@ -263,6 +267,35 @@ impl ProjectSettings { global_effective[key] = facts[index].1[key].clone(); } } + // The libraries page also projects the detected project model and + // what the project model bundle made of Eclipse containers. A JDT LS + // without the bundle (an older user installation) has no describe + // command; the page then shows only what the backend detected. + let model = if libraries { + let workspace = context.workspace_context().ok_or_else(fail)?; + let options = session.model_options(workspace.context_id()); + let explicit = Explicit::from_document(&native_json(&read(&root.join(SETTINGS))?.0)?); + let model = project_model::detect(&root, &options, &Environment::current()); + let described = command( + context, + crate::library_settings::DESCRIBE_COMMAND, + json!([]), + ) + .ok(); + Some((model, explicit, described)) + } else { + None + }; + let page = + model.as_ref().map( + |(model, explicit, described)| crate::library_settings::Page { + zh, + root: &root, + model, + explicit, + described: described.as_ref(), + }, + ); let mut sources = Vec::new(); let mut bindings = BTreeMap::new(); let mut paths = BTreeSet::new(); @@ -297,14 +330,15 @@ impl ProjectSettings { .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)?) + let mut fields = if let Some(page) = &page { + if source_path.ends_with(".classpath") { + let effective = fact[LIBRARIES_FACT].clone(); + let mut field = field(zh, ("libraries", "Referenced JAR files", "引用的 JAR 文件", "fileList"),json!(classpath_libraries(&bytes)?),effective,json!([]),&local(zh,"Libraries of this Eclipse project, written to its .classpath. Containers such as Web App Libraries and Server Runtime stay in .classpath and are resolved by Lithe; see Project model.","此 Eclipse 项目的库,写入其 .classpath。Web App Libraries、Server Runtime 等容器保留在 .classpath 中,由 Lithe 解析,详见“工程模型”。")); + field["effectiveSource"] = json!(page.classpath_label(&path)); + vec![field] } 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。"))] + page.settings_fields(&fact, library_input(&native_json(&bytes)?)) + } } else { compiler_fields(zh, &properties(&bytes)?, &fact, true) }; @@ -321,17 +355,71 @@ impl ProjectSettings { 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 groups = if libraries { + vec![ + json!({"id":"libraries","title":local(zh,"Referenced libraries","引用的库"),"layout":"form"}), + ] + } else { + vec![ + json!({"id":"project","title":local(zh,"Project defaults","项目默认设置"),"layout":"form"}), + json!({"id":"modules","title":local(zh,"Per-module bytecode","按模块设置字节码"),"rowTitle":local(zh,"Module","模块"),"layout":"table"}), + ] + }; + if let Some(page) = &page { + let taken: Vec = paths.iter().cloned().collect(); + let mut model_sources: Vec<(PathBuf, Value)> = Vec::new(); + let mut rows = page.model_sources(&taken); + rows.extend(page.eclipse_sources(&taken)); + for (id, path, fields) in rows { + // An Eclipse project's container rows share its `.project` + // with the model rows; one source holds both. + if let Some(source) = model_sources.iter_mut().find(|(known, _)| known == &path) { + let existing = source.1["fields"].as_array_mut().ok_or_else(fail)?; + existing.extend( + fields + .into_iter() + .take(32usize.saturating_sub(existing.len())), + ); + continue; + } + if sources.len() + model_sources.len() >= 1024 || !paths.insert(path.clone()) { + continue; + } + let rel = project_model::relative_inside(&root, &path).ok_or_else(fail)?; + let title = if id == "model" { + local(zh, "Project model", "工程模型") + } else { + path.parent() + .and_then(|p| p.file_name()) + .and_then(|n| n.to_str()) + .unwrap_or("Eclipse") + .to_string() + }; + let (_, revision) = read(&path)?; + let id = format!("model{:x}", Sha256::digest(rel.as_bytes())); + model_sources.push((path, json!({"id":id,"group":"model","title":title,"path":rel,"revision":revision,"writable":false,"fields":fields}))); + } + sources.extend(model_sources.into_iter().map(|(_, source)| source)); + if sources.iter().any(|source| source["group"] == "model") { + groups.push(json!({"id":"model","title":local(zh,"Project model","工程模型"),"layout":"form"})); + } + } 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}), + json!({"format":"litheSettingsSources","version":0,"title":if libraries{local(zh,"Java Libraries","Java 库")}else{local(zh,"Java Compiler","Java 编译器")},"groups":groups,"sources":sources}), ) } /// Prepares only the confirmed native source; publication belongs to the host. - pub fn edit(&self, params: Value, context: &Context) -> Result { + pub fn edit( + &self, + params: Value, + context: &Context, + session: &crate::settings_session::SettingsSession, + ) -> Result { let root = root(context)?; let id = params["sourceID"].as_str().ok_or_else(fail)?; let path = self @@ -359,9 +447,14 @@ impl ProjectSettings { } 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)?)? + match values.get("libraries") { + Some(libraries) => edit_classpath(&bytes, libraries)?, + None => bytes.clone(), + } } else if path.ends_with(SETTINGS) { - edit_json(&bytes, values.get("libraries").ok_or_else(fail)?)? + let workspace = context.workspace_context().ok_or_else(fail)?; + let options = session.model_options(workspace.context_id()); + edit_settings(&root, &bytes, values, &options)? } else { edit_properties(&bytes, values)? }; @@ -394,19 +487,31 @@ impl ProjectSettings { } } -/// Reads the actual upstream settings sources; used at startup and on every push. -pub fn native_settings(root: &Path) -> Result { +/// Reads the actual upstream settings sources and overlays the detected +/// project model; used at startup and on every push. Returns the `java` +/// sections to overlay and the model they came from. +pub fn native_settings( + root: &Path, + options: &ModelOptions, +) -> Result<(Value, ProjectModel), FunctionError> { 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}); + let explicit = Explicit::from_document(&native_json(&bytes)?); + let model = project_model::detect(root, options, &Environment::current()); + let overlay = project_model::overlay(&model, &explicit); + for section in ["project", "lithe"] { + if overlay + .get(section) + .is_some_and(|value| value != &json!({})) + { + settings[section] = overlay[section].clone(); + } } - Ok(settings) + Ok((settings, model)) } fn native_json(bytes: &[u8]) -> Result { if bytes.is_empty() { @@ -428,15 +533,64 @@ fn library_input(settings: &Value) -> Value { None => Value::Null, } } -fn edit_json(bytes: &[u8], libraries: &Value) -> Result, FunctionError> { +/// Applies the confirmed fields of the `.vscode/settings.json` source in +/// order: libraries, source folders, then saving or removing the detected +/// entries against the file as the first two left it. +fn edit_settings( + root: &Path, + bytes: &[u8], + values: &serde_json::Map, + options: &ModelOptions, +) -> Result, FunctionError> { + use crate::library_settings::{LIBRARIES_FIELD, SOURCE_PATHS_FIELD, STORE_DETECTED_FIELD}; + let mut document = bytes.to_vec(); + if let Some(libraries) = values.get(LIBRARIES_FIELD) { + document = edit_json(&document, LIBRARY_KEY, libraries)?; + } + if let Some(paths) = values.get(SOURCE_PATHS_FIELD) { + document = edit_json(&document, SOURCE_PATHS_KEY, paths)?; + } + if let Some(store) = values.get(STORE_DETECTED_FIELD) { + let store = match store { + Value::Bool(store) => *store, + Value::Null => false, + _ => return Err(fail()), + }; + let explicit = Explicit::from_document(&native_json(&document)?); + let model = project_model::detect(root, options, &Environment::current()); + let page = crate::library_settings::Page { + zh: false, + root, + model: &model, + explicit: &explicit, + described: None, + }; + let (libraries, source_paths) = crate::library_settings::stored_entries(&page, store); + if let Some(libraries) = libraries { + document = edit_json(&document, LIBRARY_KEY, &libraries)?; + } + if let Some(source_paths) = source_paths { + document = edit_json( + &document, + SOURCE_PATHS_KEY, + &source_paths.unwrap_or(Value::Null), + )?; + } + } + Ok(document) +} +/// Sets or (with null) removes the string list `key`; a rich +/// `referencedLibraries` object keeps its excludes and sources and only +/// its `include` changes. +fn edit_json(bytes: &[u8], key: &str, 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)); + let rich = (key == LIBRARY_KEY) + .then(|| object.get(LIBRARY_KEY).and_then(|prop| prop.object_value())) + .flatten(); + let (target, key) = rich.map(|rich| (rich, "include")).unwrap_or((object, key)); if libraries.is_null() { if let Some(prop) = target.get(key) { prop.remove(); @@ -693,7 +847,7 @@ mod tests { "sources": {"old.jar": "old-sources.jar"} }, "privateToken": "untouched" }"#; - let updated = edit_json(source, &json!(["new.jar"])).unwrap(); + let updated = edit_json(source, LIBRARY_KEY, &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"])); @@ -701,7 +855,7 @@ mod tests { assert!(String::from_utf8(updated.clone()) .unwrap() .contains("private comment")); - let reset = native_json(&edit_json(&updated, &Value::Null).unwrap()).unwrap(); + let reset = native_json(&edit_json(&updated, LIBRARY_KEY, &Value::Null).unwrap()).unwrap(); assert!(reset[LIBRARY_KEY].get("include").is_none()); assert_eq!( reset[LIBRARY_KEY]["exclude"], @@ -733,7 +887,12 @@ mod tests { #[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(); + let updated = edit_json( + source, + LIBRARY_KEY, + &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!( @@ -741,7 +900,7 @@ mod tests { json!(["C:\\Program Files\\Java\\external.jar"]) ); assert_eq!(value["privateToken"], "private-value"); - let reset = edit_json(&updated, &Value::Null).unwrap(); + let reset = edit_json(&updated, LIBRARY_KEY, &Value::Null).unwrap(); assert!(native_json(&reset).unwrap().get(LIBRARY_KEY).is_none()); } #[test] @@ -777,8 +936,12 @@ mod tests { ) .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(); + let updated = crate::settings_session::with_native_settings( + original.clone(), + root, + &ModelOptions::default(), + ) + .unwrap(); assert_eq!( updated["java"]["configuration"], original["java"]["configuration"] diff --git a/backend/src/settings_session.rs b/backend/src/settings_session.rs index 6ed89d7..e4f1cb0 100644 --- a/backend/src/settings_session.rs +++ b/backend/src/settings_session.rs @@ -281,6 +281,9 @@ struct WorkspaceState { /// same default runtime the host runs. java_runtimes: Vec, native_root: Option, + /// The project model settings of the last launch; every push detects + /// the model with them, so a push never undoes what the launch configured. + model_options: crate::project_model::ModelOptions, /// Project updates waiting for a running server. pending_projects: Vec, /// Set from the moment the server is running until its collection is @@ -298,6 +301,7 @@ impl WorkspaceState { contributions: Contributions::default(), java_runtimes: Vec::new(), native_root: None, + model_options: crate::project_model::ModelOptions::default(), pending_projects: Vec::new(), collecting: None, } @@ -514,16 +518,26 @@ 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, + settings: Value, root: &std::path::Path, + options: &crate::project_model::ModelOptions, ) -> Result { - let native = crate::project_settings::native_settings(root)?; + Ok(with_native_model(settings, root, options)?.0) +} + +/// [`with_native_settings`], also returning the project model it detected. +pub fn with_native_model( + mut settings: Value, + root: &std::path::Path, + options: &crate::project_model::ModelOptions, +) -> Result<(Value, crate::project_model::ProjectModel), FunctionError> { + let (native, model) = crate::project_settings::native_settings(root, options)?; 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) + Ok((settings, model)) } /// Locks `mutex` even when a panic poisoned it: the guarded data stays @@ -747,7 +761,7 @@ impl SettingsSession { /// documentation. fn flush(&self, key: &str, report: &dyn Fn(&str, u64)) { let _delivery = lock(&self.gate); - let (workspace, params, projects, native_root) = { + let (workspace, params, projects, native_root, options) = { let mut states = self.lock_states(); let Some(state) = states.get_mut(key) else { return; @@ -760,10 +774,11 @@ impl SettingsSession { configuration_params(&state.contributions.fragments(), &state.java_runtimes), std::mem::take(&mut state.pending_projects), state.native_root.clone(), + state.model_options.clone(), ) }; let params = match native_root { - Some(root) => match with_native_settings(params["settings"].clone(), &root) { + Some(root) => match with_native_settings(params["settings"].clone(), &root, &options) { Ok(settings) => json!({"settings":settings}), Err(_) => { report(SESSION_PUSH_FAILED, 1); @@ -799,7 +814,7 @@ impl SettingsSession { root: &std::path::Path, ) -> Result<(), FunctionError> { let _delivery = lock(&self.gate); - let settings = { + let (settings, options) = { let states = self.lock_states(); let state = states.get(workspace.context_id()).ok_or_else(|| { PluginError::new( @@ -807,9 +822,12 @@ impl SettingsSession { "The Java language server is unavailable.", ) })?; - java_configuration(&state.contributions.fragments(), &state.java_runtimes) + ( + java_configuration(&state.contributions.fragments(), &state.java_runtimes), + state.model_options.clone(), + ) }; - let settings = with_native_settings(settings, root)?; + let settings = with_native_settings(settings, root, &options)?; self.host .push_configuration(workspace, json!({"settings":settings})) .map_err(|_| { @@ -844,6 +862,29 @@ impl SettingsSession { state.java_runtimes = runtimes; } + /// Records the project model settings a launch received, so pushes and + /// the settings page detect with the same ones. + pub fn set_model_options( + &self, + workspace: &WorkspaceContext, + options: crate::project_model::ModelOptions, + ) { + let mut states = self.lock_states(); + let state = states + .entry(workspace.context_id().to_string()) + .or_insert_with(|| WorkspaceState::new(workspace.clone())); + state.model_options = options; + } + + /// The project model settings of the last launch of `context_id`; the + /// manifest defaults for a workspace the session has not seen. + pub fn model_options(&self, context_id: &str) -> crate::project_model::ModelOptions { + self.lock_states() + .get(context_id) + .map(|state| state.model_options.clone()) + .unwrap_or_default() + } + /// The JDKs the last launch of the workspace `context_id` configured; /// empty for a workspace the session has not seen. pub fn java_runtimes(&self, context_id: &str) -> Vec { diff --git a/docs/assets/project-models/eclipse-wtp-en-dark.png b/docs/assets/project-models/eclipse-wtp-en-dark.png new file mode 100644 index 0000000..abfbe92 Binary files /dev/null and b/docs/assets/project-models/eclipse-wtp-en-dark.png differ diff --git a/docs/assets/project-models/eclipse-wtp-zh-light.png b/docs/assets/project-models/eclipse-wtp-zh-light.png new file mode 100644 index 0000000..7ae2a54 Binary files /dev/null and b/docs/assets/project-models/eclipse-wtp-zh-light.png differ diff --git a/docs/assets/project-models/idea-en-dark.png b/docs/assets/project-models/idea-en-dark.png new file mode 100644 index 0000000..addadb2 Binary files /dev/null and b/docs/assets/project-models/idea-en-dark.png differ diff --git a/docs/assets/project-models/idea-zh-light.png b/docs/assets/project-models/idea-zh-light.png new file mode 100644 index 0000000..17d0855 Binary files /dev/null and b/docs/assets/project-models/idea-zh-light.png differ diff --git a/docs/assets/project-models/java-settings-zh-light.png b/docs/assets/project-models/java-settings-zh-light.png new file mode 100644 index 0000000..dfdfecb Binary files /dev/null and b/docs/assets/project-models/java-settings-zh-light.png differ diff --git a/docs/assets/project-models/legacy-web-en-light.png b/docs/assets/project-models/legacy-web-en-light.png new file mode 100644 index 0000000..6c7c21a Binary files /dev/null and b/docs/assets/project-models/legacy-web-en-light.png differ diff --git a/docs/assets/project-models/legacy-web-zh-dark.png b/docs/assets/project-models/legacy-web-zh-dark.png new file mode 100644 index 0000000..d531d93 Binary files /dev/null and b/docs/assets/project-models/legacy-web-zh-dark.png differ diff --git a/docs/feature-matrix.md b/docs/feature-matrix.md index d305437..9695600 100644 --- a/docs/feature-matrix.md +++ b/docs/feature-matrix.md @@ -27,3 +27,16 @@ | 原生 JAR 引用与编译运行 | implemented / pending | implemented / pending | `scripts/compiler/` 编译外部 JAR 并运行引用它的程序;配置与包的只读边界见 native-settings.md | 2026-11-15:本地 macOS 自动化已通过,不将脚本通过等同于所有交互场景验收。Windows 的实机结果另随 PR 补充。 + +## 旧式与跨 IDE 工程模型(3.0.1) + +| 能力 | macOS | Windows | Linux | 证据 | +| --- | --- | --- | --- | --- | +| Eclipse WTP/MyEclipse 容器(Web App Libraries、EAR Libraries、Server Runtime、Java EE 库)与 `TOMCAT_HOME`/`CATALINA_HOME` 变量 | implemented / verified | implemented / pending | implemented / pending | `jdtls-extension/project-model`;macOS arm64 本机用固定的 JDT LS 1.61.0 跑 `scripts/compiler/test-project-models.mjs` 的 `eclipse-wtp` 场景 | +| 传统 Web(`WEB-INF/lib`)、EAR 库目录与 `MANIFEST.MF` Class-Path | implemented / verified | implemented / pending | implemented / pending | `backend/src/project_model/web.rs` 单元测试;`legacy-web` 场景 | +| IntelliJ IDEA 模块源码根、模块库、项目库(只读导入) | implemented / verified | implemented / pending | implemented / pending | `backend/src/project_model/idea.rs` 单元测试;`idea` 场景 | +| Servlet 容器:设置、环境变量、常见位置自动查找 | implemented / verified | implemented / pending | implemented / pending | `backend/src/project_model/servlet.rs` 单元测试,含 Windows 安装位置 | +| “Java 库”页的工程模型只读分组、源码文件夹与“保存识别结果” | implemented / verified | implemented / pending | implemented / pending | 后端投影与保存经 `test-project-models.mjs` 真实验证;`scripts/compiler/visual.mjs` 用宿主 Viva 无头窗口渲染三类工程的真实投影(中英、明暗),截图见 `docs/assets/project-models/` | + +2026-11-17:macOS arm64 本机自动化通过(三类工程编译成功,关闭识别后均失败;插件包、JDT LS 安装与项目文件不变)。Windows、Linux 结果由 CI 与后续实机验证补充。 + diff --git a/docs/native-settings.md b/docs/native-settings.md index 495fc5b..e5bcc32 100644 --- a/docs/native-settings.md +++ b/docs/native-settings.md @@ -6,6 +6,8 @@ 本地 JAR 入口在插件的语言/构建工具设置页,点击“读取本地 JAR 依赖”,选择目标模块并浏览文件后保存。每行一个路径,空格属于路径内容。JDT 的公开项目设置提供模块与实际值。JSONC、XML 和 properties 编辑器保留无关字段及注释;已有 JAR 排除和源码附件不被覆盖。Maven/Gradle 管理的项目使用各自插件的编译设置。 +没有 Maven/Gradle 的旧式 Web、Eclipse WTP 和 IntelliJ IDEA 项目,插件会只读识别其工程模型并在内存中补全类路径,“Java 库”页的“工程模型”分组列出识别结果,详见 [project-models.md](project-models.md)。 + 运行时状态和暂存放在宿主提供的用户状态/临时目录;插件安装包始终只读。暂存文件由一次保存拥有,完成或取消时删除,不跨工作树共享。新后端与翻译由各平台构建入口打入同一版本包并校验。 ## Compatibility diff --git a/docs/project-models.md b/docs/project-models.md new file mode 100644 index 0000000..27452be --- /dev/null +++ b/docs/project-models.md @@ -0,0 +1,92 @@ +# 旧式与跨 IDE 工程模型(3.0.1) + +没有 Maven/Gradle 构建文件的 Java 项目,常常带着其他 IDE 留下的工程结构:Eclipse WTP 的类路径容器、 +MyEclipse 的 J2EE 库、IntelliJ IDEA 的 `.idea` 与 `.iml`,或者只有 `WEB-INF/lib` 的传统 Web 目录。 +JDT LS 只认识 Maven、Gradle 和 Eclipse 的 `.project`,其余目录按“普通文件夹”导入,这些库和源码根会丢失, +`javax.servlet` 等也解析不到([1lck/Lithe-IDEA#2063](https://github.com/1lck/Lithe-IDEA/issues/2063))。 +插件在不修改项目文件的前提下补上这部分。 + +## 由谁决定类路径 + +按以下顺序,第一个命中的接管,后面的不再参与: + +1. Maven(`pom.xml`)或 Gradle(`build.gradle[.kts]`、`settings.gradle[.kts]`):完全由构建工具导入,插件不叠加任何东西。 +2. Eclipse `.project`:JDT 读取 `.classpath`。其中 JDT 自身不认识的容器由插件的 JDT LS 扩展包解析(见下文)。 +3. IntelliJ IDEA:`.idea/modules.xml`,或基于文件的 `.ipr`。 +4. 传统 Web 目录:含 `WEB-INF` 的 Web 根,或含 `META-INF/application.xml`/`EarContent` 的 EAR。 +5. 普通文件夹:JDT 上游默认行为(`lib/**` 下的 JAR,源码根由 package 声明推断)。 + +识别只读项目文件:一次有界扫描(深度 6、最多 20,000 个条目、跳过隐藏目录和 `target`/`build`/`bin`/`out`/`node_modules` 等), +每个描述文件最多读取 2 MiB。设置“Java → 工程模型 → 自动识别工程模型”可以整体关闭;关闭后行为与 3.0.0 相同。 + +## 各模型补充的内容 + +| 来源 | 插件补充 | 写入位置 | +| --- | --- | --- | +| Eclipse WTP `org.eclipse.jst.j2ee.internal.web.container`(Web App Libraries) | `WEB-INF/lib` 下的 JAR,以及组件文件中部署到 `/WEB-INF/lib` 的工具模块 | JDT 内存中的类路径容器 | +| Eclipse WTP `org.eclipse.jst.j2ee.internal.module.container`(EAR Libraries) | 引用本模块的 EAR 的库目录(`application.xml` 的 `library-directory`,默认 `lib`)和 `MANIFEST.MF` 的 `Class-Path` | 同上 | +| Eclipse `org.eclipse.jst.server.core.container`(Server Runtime)、MyEclipse J2EE 1.3/1.4、Java EE 5/6/7 库 | Servlet 容器的 `lib` 下的 JAR | 同上 | +| Eclipse 类路径变量 `TOMCAT_HOME`、`CATALINA_HOME` | Servlet 容器的安装目录 | JDT 内存中的类路径变量 | +| IntelliJ IDEA 模块 | 生产与测试源码文件夹(`java.project.sourcePaths`)、模块库、项目库(`.idea/libraries`)、`jarDirectory` | 推给 JDT 的设置,仅内存 | +| IDEA 应用服务器库、Web facet | Servlet 容器的 JAR | 同上 | +| 传统 Web / EAR | `WEB-INF/lib/*.jar`、EAR 库目录、`MANIFEST.MF` 的 `Class-Path` | 同上 | + +`.vscode/settings.json` 中已有的 `java.project.referencedLibraries`、`java.project.sourcePaths`、`java.project.outputPath` +始终优先:插件只在它们之后追加识别结果,保留其中的 `exclude` 和 `sources`;没有显式值时保留上游默认的 `lib/**`。 + +无法自动补全的条目会在“Java 库”设置页的“工程模型 → 未能解析”中逐项列出原因:IDEA 的全局库或应用库、 +只有 IDEA 知道的路径变量、类文件夹(JDT 只接受 JAR)、工作区之外的源码文件夹、Eclipse 用户库(定义在 Eclipse 工作区里)、 +不存在的文件。启动时同样以降级诊断计数记录:`launch.servlet_container_missing`、`launch.project_model_unresolved`、 +`launch.project_model_truncated`。 + +## Servlet 容器 + +需要 Servlet API 的项目(Web 根、Server Runtime 容器、IDEA Web facet 或应用服务器库)按以下顺序选择容器: + +1. 设置“Servlet 容器文件夹”。目录中没有 Servlet API 库(`lib/servlet-api.jar`,Tomcat 5.5 为 `common/lib`)时直接提示错误,不再回退。 +2. 环境变量 `CATALINA_HOME`,然后 `TOMCAT_HOME`。 +3. 常见安装位置:Homebrew(`opt/tomcat*/libexec`)、`/usr/local`、`/opt`、`/Library`、`/usr/share`、 + Windows 的 `Program Files\Apache Software Foundation` 和 `C:\`、用户主目录。优先选择项目点名的大版本 + (例如 `Apache Tomcat v9.0`),再按 `web.xml` 的 `javax`/`jakarta` 命名空间匹配,最后取最新版本。 + +容器路径属于本机,不会写入任何共享文件。 + +## 设置页与保存 + +“Java 库”设置页新增“工程模型”分组,只读显示:识别到的模型、自动识别的库(来源、所属模块、JAR 数)、IDEA 源码文件夹、 +Servlet 容器及其来源、Eclipse 每个项目的容器与变量解析结果,以及未能解析的条目。只读行绑定到模型自己的描述文件 +(`.idea/modules.xml`、`.project`、`WEB-INF/web.xml` 等),宿主的修订校验照常生效。 + +普通文件夹的 `.vscode/settings.json` 来源新增: + +- “源码文件夹”:`java.project.sourcePaths`,留空时继承 IDEA 模块的源码文件夹。 +- “将识别结果保存到此文件”:勾选并保存后,把识别出的库(不含本机 Servlet 容器路径)和 IDEA 源码文件夹写进 + `.vscode/settings.json`,供 VS Code 等其他编辑器和团队成员使用;取消勾选并保存则移除这些条目。 + +只有点击“保存”才会写文件;读取、启动和推送设置都不写项目文件。 + +## JDT LS 扩展包 + +Eclipse 容器和类路径变量只能在 JDT LS 进程内解析,插件为此自带一个扩展包 +`jdtls-extensions/project-model/io.github.lithe_idea.java.projectmodel_<版本>.jar`,源码在 `jdtls-extension/project-model/`。 + +- 构建:`scripts/package/project-model-bundle.mjs` 在打包时以 `--release 17` 对照 `scripts/prepare-jdtls.sh` 准备的 JDT LS 编译, + 需要 JDK 21 或更高的 `javac`(`JAVA_HOME`,或用 `LITHE_JAVAC`/`LITHE_JAR` 指定)。条目按固定日期打包,同一源码与 JDK 产出相同字节。 + macOS(`scripts/assemble-package.sh`)、Linux(`scripts/package/build-linux.mjs`)、Windows(`scripts/package/build-windows.mjs`)三个入口都会构建, + `scripts/verify-package.sh` 与 `backend/tests/repository_pins.rs` 校验它在包内。 +- 加载:后端在启动参数的 `initializationOptions.bundles` 中列出它,与 Java Debug、Java Test 扩展相同。 +- 运行时:只读取 JDT 设置 `java.lithe.projectModel`(后端推送的开关与 Servlet 容器)和项目文件;容器内容只存在于 JDT 的内存中, + 不写 `.classpath`、插件包或 JDT LS 安装目录。项目文件变化(JAR、组件文件、`.mymetadata`、`application.xml`、`MANIFEST.MF`)后自动重新计算。 +- 命令 `lithe.java.projectModel.describe` 返回各 Eclipse 项目的容器、变量和缺失库的解析状态,供设置页展示。 +- 生命周期:随插件版本发布,属于插件包的一部分,运行时只读;不下载、不缓存,也没有需要跨工作树复用的产物。 + +## 验证 + +- `cargo test --workspace`:识别、合并规则、设置页投影与保存的单元测试。 +- `node scripts/compiler/test-project-models.mjs <插件包> [eclipse-wtp,legacy-web,idea]`:用打好的包和真实 JDT LS 编译三类工程 + (Eclipse WTP + Server Runtime + `TOMCAT_HOME`、只有 `WEB-INF/lib` 的传统 Web、非标准源码根和模块/项目库的 IDEA 项目), + 核对设置页内容、项目文件(JDT 自己在 `.project` 中添加的资源过滤除外)、插件包和 JDT LS 安装目录均未被修改; + 传统 Web 场景还会通过设置页保存识别结果,再从文件重新编译。关闭识别后三类工程都会编译失败,可作反向对照。 + 测试同时把各场景的设置页投影写到 `.artifacts/compiler/visual-libraries-<场景>-<语言>.json`。 +- `node scripts/compiler/visual.mjs `:在宿主的 Viva 无头窗口中渲染编译器页、Java 设置页和三个场景的“Java 库”页(中英、明暗), + 截图写到 `.artifacts/compiler/visual/`;`docs/assets/project-models/` 保存了其中几张。 diff --git a/docs/releases/v3.0.1.md b/docs/releases/v3.0.1.md new file mode 100644 index 0000000..e784ed9 --- /dev/null +++ b/docs/releases/v3.0.1.md @@ -0,0 +1,39 @@ +# Java 3.0.1 + +## 中文 + +没有 Maven 或 Gradle 的老项目和从其他 IDE 迁来的项目,现在打开就能编译:插件只读识别项目里已有的工程结构,在内存中补全类路径,不修改任何项目文件([1lck/Lithe-IDEA#2063](https://github.com/1lck/Lithe-IDEA/issues/2063))。 + +### 新功能 + +- **Eclipse WTP 与 MyEclipse**:`.classpath` 中的 Web App Libraries(`WEB-INF/lib` 及部署进去的工具模块)、EAR Libraries(EAR 的库目录和 `MANIFEST.MF` 的 `Class-Path`)、Server Runtime 和 MyEclipse 的 J2EE/Java EE 库容器,以及 `TOMCAT_HOME`、`CATALINA_HOME` 类路径变量,由插件自带的 JDT LS 扩展包解析,不再出现 “Unbound classpath container” 导致整个项目无法构建。 +- **IntelliJ IDEA**:读取 `.idea/modules.xml`(或 `.ipr`)和各模块的 `.iml`,导入非标准的源码文件夹、模块库、`.idea/libraries` 中的项目库和 `jarDirectory`。 +- **传统 Web 项目**:只有 `WebContent`/`WebRoot` 下 `WEB-INF/lib` 的目录,以及 EAR 的库目录和 `MANIFEST.MF` 的 `Class-Path`。 +- **Servlet 容器**:Web 项目需要的 `javax.servlet` 等 API 自动来自本机的 Tomcat 或 Jetty:先用新设置“Servlet 容器文件夹”,再用 `CATALINA_HOME`/`TOMCAT_HOME`,最后在常见安装位置查找,并优先选择项目点名的版本。 +- **“Java 库”设置页**新增只读的“工程模型”分组,列出识别到的模型、自动加入的库、Servlet 容器、Eclipse 容器的解析结果和无法解析的条目及原因;普通文件夹新增“源码文件夹”和“将识别结果保存到此文件”,可以把识别结果写进 `.vscode/settings.json` 与其他编辑器共享。 + +Maven 和 Gradle 项目不受影响,`.vscode/settings.json` 中的显式配置始终优先。新设置“Java → 工程模型 → 自动识别工程模型”可以整体关闭。详见 `docs/project-models.md`。 + +### 兼容性 + +宿主要求与 3.0.0 相同。扩展包随插件一起加载到你安装的 JDT LS 中,已在 JDT LS 1.61.0 上验证。 + +--- + +## English + +Legacy projects without Maven or Gradle, and projects coming from other IDEs, now compile when opened: the plugin reads the project layout already on disk and completes the classpath in memory, without changing any project file ([1lck/Lithe-IDEA#2063](https://github.com/1lck/Lithe-IDEA/issues/2063)). + +### New + +- **Eclipse WTP and MyEclipse**: the Web App Libraries (`WEB-INF/lib` and utility modules deployed into it), EAR Libraries (the EAR library folder and `MANIFEST.MF` `Class-Path`), Server Runtime and MyEclipse J2EE/Java EE library containers in `.classpath`, and the `TOMCAT_HOME` and `CATALINA_HOME` classpath variables, are resolved by the plugin's own JDT LS extension bundle. "Unbound classpath container" no longer blocks the whole project. +- **IntelliJ IDEA**: `.idea/modules.xml` (or a `.ipr`) and each module's `.iml` provide non-standard source folders, module libraries, project libraries from `.idea/libraries`, and `jarDirectory` entries. +- **Legacy web projects**: folders with only `WEB-INF/lib` under `WebContent`/`WebRoot`, EAR library folders and `MANIFEST.MF` `Class-Path`. +- **Servlet container**: `javax.servlet` and the other server APIs come from a local Tomcat or Jetty: the new **Servlet container folder** setting, then `CATALINA_HOME`/`TOMCAT_HOME`, then standard installation folders, preferring the version the project names. +- The **Java Libraries** settings page gains a read-only **Project model** group listing the detected model, added libraries, the servlet container, how Eclipse containers resolved, and entries that cannot be resolved with the reason. Plain folders gain **Source folders** and **Save detected entries to this file**, which writes the detected entries to `.vscode/settings.json` for other editors. + +Maven and Gradle projects are unchanged, and explicit values in `.vscode/settings.json` always come first. Turn detection off with **Java → Project model → Detect project models**. See `docs/project-models.md`. + +### Compatibility + +Host requirements are the same as 3.0.0. The extension bundle is loaded into your own JDT LS with the plugin and is verified on JDT LS 1.61.0. diff --git a/e2e/host/desktop/internal/settingswindow/plugin_native_source_test.go b/e2e/host/desktop/internal/settingswindow/plugin_native_source_test.go index a8b3fab..03f60f5 100644 --- a/e2e/host/desktop/internal/settingswindow/plugin_native_source_test.go +++ b/e2e/host/desktop/internal/settingswindow/plugin_native_source_test.go @@ -6,8 +6,11 @@ import ( "context" "encoding/json" "errors" + "fmt" "os" "path/filepath" + "sort" + "strings" "testing" "time" @@ -27,6 +30,7 @@ type pluginNativeVisualSource struct { manifest json.RawMessage packageRoot, workspace string sources pluginsettings.SourceEditor + actionID string } func (s *pluginNativeVisualSource) Load(ctx context.Context, _ string, language i18n.Language) (pluginservice.SettingsEditor, error) { @@ -37,7 +41,7 @@ func (s *pluginNativeVisualSource) Save(context.Context, pluginservice.SettingsE 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 + return pluginservice.SettingsActionResult{Plan: core.PluginSettingsActionPlan{Kind: "invoke", ActionID: s.actionID, 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") @@ -56,7 +60,7 @@ func TestPluginNativeSourceVisual(t *testing.T) { ID, DisplayName, Version string SettingActions []struct { ID string - Page struct{ CompilerID string } + Page struct{ CompilerID, LanguageID string } } } if err = json.Unmarshal(manifest, &metadata); err != nil { @@ -67,68 +71,97 @@ func TestPluginNativeSourceVisual(t *testing.T) { if _, err = core.NewClient().ValidatePluginManifest(admission, manifest, pluginhost.Declared()); err != nil { t.Fatal(err) } - compilerID := "" + compilerID, languageID := "", "" for _, action := range metadata.SettingActions { - if action.ID == "compiler" { + switch action.ID { + case "compiler": compilerID = action.Page.CompilerID + case "libraries": + languageID = action.Page.LanguageID } } - if compilerID == "" { - t.Fatal("compiler action missing") + if compilerID == "" || languageID == "" { + t.Fatal("compiler or libraries action missing") + } + // One view per captured projection: the compiler page, and the libraries + // page of every project model scenario test-project-models.mjs captured. + type view struct { + name, actionID, key, snapshot string + page pageID + height int + } + views := []view{{name: "compiler", actionID: "compiler", key: "compiler:" + compilerID, snapshot: "visual-%s.json", page: pageBuild, height: 900}} + scenarios, _ := filepath.Glob(filepath.Join(input, "visual-libraries-*-zh.json")) + sort.Strings(scenarios) + for _, path := range scenarios { + scenario := strings.TrimSuffix(strings.TrimPrefix(filepath.Base(path), "visual-libraries-"), "-zh.json") + views = append(views, view{name: "libraries-" + scenario, actionID: "libraries", key: "language:" + languageID, snapshot: "visual-libraries-" + scenario + "-%s.json", page: pageLanguages, height: 1600}) } 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 + for _, item := range views { + for _, language := range []i18n.Language{i18n.Chinese, i18n.English} { + for _, theme := range []string{"dark", "light"} { + t.Run(item.name+"-"+language.Code()+"-"+theme, func(t *testing.T) { + code := "en" + if language == i18n.Chinese { + code = "zh" + } + raw, err := os.ReadFile(filepath.Join(input, fmt.Sprintf(item.snapshot, code))) + 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}, actionID: item.actionID} + 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, item.height + 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("plugin contribution", func() bool { return len(w.dynamic.pages) > 0 }) + w.selectSettingsPage(item.page, item.key) + d.until("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 == item.actionID { + title = action.Title + } + } + if title == "" { + t.Fatalf("action %s is not on page %s", item.actionID, item.key) + } + if item.actionID == "libraries" && item.name == views[1].name { + // The language page itself, with the plugin's own settings. + d.pump() + if err = session.Screenshot(filepath.Join(out, "java-settings-"+language.Code()+"-"+theme+".png")); err != nil { + t.Fatal(err) + } + } + d.click(title) + d.until("native source form", func() bool { return w.pluginSettings.sources != nil }) + d.pump() + if err = session.Screenshot(filepath.Join(out, item.name+"-"+language.Code()+"-"+theme+".png")); err != nil { + t.Fatal(err) } - } - 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 index eb99e08..31f6e3a 100644 --- a/io.github.lithe-idea.java-support/l10n/zh-Hans.json +++ b/io.github.lithe-idea.java-support/l10n/zh-Hans.json @@ -18,10 +18,20 @@ "WARNING": "警告", "SEVERE": "仅错误" } + }, + "projectModelDetection": { + "title": "自动识别工程模型", + "description": "对没有 Maven 或 Gradle 的文件夹,读取其他 IDE 留下的工程结构:Eclipse WTP 容器(Web App Libraries、EAR Libraries、Server Runtime)、IntelliJ IDEA 的模块和库,以及传统 Web 项目的 WEB-INF/lib。Lithe 在内存中把它们声明的库加入类路径,不修改项目文件。修改在 Java 语言服务器重启后生效。" + }, + "servletContainerHome": { + "title": "Servlet 容器文件夹", + "description": "为 Web 项目提供 javax.servlet 等服务器 API 的 Tomcat 或 Jetty 安装文件夹,对应 Eclipse 的 Server Runtime 和 IDEA 的应用服务器库。留空时依次使用 CATALINA_HOME、TOMCAT_HOME 和常见位置安装的 Tomcat,并优先选择项目指定的版本。", + "placeholder": "自动查找" } }, "sections": { - "Language server": "语言服务器" + "Language server": "语言服务器", + "Project model": "工程模型" }, "settingActions": { "compiler": { diff --git a/io.github.lithe-idea.java-support/plugin.json b/io.github.lithe-idea.java-support/plugin.json index 9871f81..6415594 100644 --- a/io.github.lithe-idea.java-support/plugin.json +++ b/io.github.lithe-idea.java-support/plugin.json @@ -2,7 +2,7 @@ "schemaVersion": 0, "id": "io.github.lithe-idea.java-support", "displayName": "Java Support", - "version": "3.0.0", + "version": "3.0.1", "pluginAPIVersion": 0, "requires": {"backend": 0, "debugAdapters": 0, "languages": 0, "languageServers": 0, "pluginFunctions": 0, "settings": 0, "projectGenerators": 0, "toolDefinitions": 0, "sourceSettings": 0}, "requiresTools": ["java", "jdtls-runtime"], @@ -567,6 +567,25 @@ ], "page": {"languageID": "java"}, "section": "Language server" + }, + { + "id": "projectModelDetection", + "type": "boolean", + "title": "Detect project models", + "description": "For folders without Maven or Gradle, read the project layout other IDEs leave behind: Eclipse WTP containers (Web App Libraries, EAR Libraries, Server Runtime), IntelliJ IDEA modules and libraries, and WEB-INF/lib of legacy web projects. Lithe adds what they declare to the classpath in memory and never changes the project files. Changes apply when the Java language server restarts.", + "default": true, + "page": {"languageID": "java"}, + "section": "Project model" + }, + { + "id": "servletContainerHome", + "type": "directory", + "title": "Servlet container folder", + "description": "Tomcat or Jetty installation that provides javax.servlet and the other server APIs to web projects, as Eclipse's Server Runtime and IDEA's application server libraries do. Leave empty to use CATALINA_HOME or TOMCAT_HOME, then a Tomcat installed in a standard folder, preferring the version the project names.", + "default": "", + "placeholder": "Automatic", + "page": {"languageID": "java"}, + "section": "Project model" } ], "languageServers": [ diff --git a/jdtls-extension/project-model/META-INF/MANIFEST.MF b/jdtls-extension/project-model/META-INF/MANIFEST.MF new file mode 100644 index 0000000..a95603f --- /dev/null +++ b/jdtls-extension/project-model/META-INF/MANIFEST.MF @@ -0,0 +1,13 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: Lithe Java Project Model +Bundle-SymbolicName: io.github.lithe_idea.java.projectmodel;singleton:=true +Bundle-Version: 1.0.0 +Bundle-Vendor: Lithe Community +Bundle-RequiredExecutionEnvironment: JavaSE-17 +Bundle-Activator: io.github.lithe_idea.java.projectmodel.Activator +Require-Bundle: org.eclipse.core.runtime, + org.eclipse.core.resources, + org.eclipse.jdt.core, + org.eclipse.jdt.ls.core +Automatic-Module-Name: io.github.lithe_idea.java.projectmodel diff --git a/jdtls-extension/project-model/plugin.xml b/jdtls-extension/project-model/plugin.xml new file mode 100644 index 0000000..8daa0bf --- /dev/null +++ b/jdtls-extension/project-model/plugin.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/jdtls-extension/project-model/src/io/github/lithe_idea/java/projectmodel/Activator.java b/jdtls-extension/project-model/src/io/github/lithe_idea/java/projectmodel/Activator.java new file mode 100644 index 0000000..73009b4 --- /dev/null +++ b/jdtls-extension/project-model/src/io/github/lithe_idea/java/projectmodel/Activator.java @@ -0,0 +1,37 @@ +package io.github.lithe_idea.java.projectmodel; + +import org.eclipse.core.resources.IResourceChangeEvent; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin; +import org.eclipse.jdt.ls.core.internal.preferences.PreferenceManager; +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; + +/** Owns the listeners of the bundle; both are removed when JDT LS stops it. */ +public final class Activator implements BundleActivator { + private ContainerRefresher refresher; + + @Override + public void start(BundleContext context) { + refresher = new ContainerRefresher(); + PreferenceManager preferences = JavaLanguageServerPlugin.getPreferencesManager(); + if (preferences != null) { + preferences.addPreferencesChangeListener(refresher); + } + ResourcesPlugin.getWorkspace().addResourceChangeListener(refresher, IResourceChangeEvent.POST_CHANGE); + } + + @Override + public void stop(BundleContext context) { + if (refresher == null) { + return; + } + PreferenceManager preferences = JavaLanguageServerPlugin.getPreferencesManager(); + if (preferences != null) { + preferences.removePreferencesChangeListener(refresher); + } + ResourcesPlugin.getWorkspace().removeResourceChangeListener(refresher); + refresher.cancel(); + refresher = null; + } +} diff --git a/jdtls-extension/project-model/src/io/github/lithe_idea/java/projectmodel/ContainerKind.java b/jdtls-extension/project-model/src/io/github/lithe_idea/java/projectmodel/ContainerKind.java new file mode 100644 index 0000000..fdc13d0 --- /dev/null +++ b/jdtls-extension/project-model/src/io/github/lithe_idea/java/projectmodel/ContainerKind.java @@ -0,0 +1,51 @@ +package io.github.lithe_idea.java.projectmodel; + +import java.util.Map; + +import org.eclipse.core.runtime.IPath; + +/** + * The classpath containers this bundle resolves, keyed by the first segment of + * the container path the way JDT selects an initializer. Must match plugin.xml. + */ +enum ContainerKind { + /** WTP "Web App Libraries": the module's WEB-INF/lib and utility modules. */ + WEB_APP("webApp"), + /** WTP "EAR Libraries": the lib directory of every EAR that bundles the module. */ + EAR("ear"), + /** WTP "Server Runtime": the servlet container's own libraries. */ + SERVER_RUNTIME("serverRuntime"), + /** MyEclipse Java EE API libraries; served by the servlet container too. */ + JAVA_EE("javaEE"); + + private static final Map BY_ID = Map.of( + "org.eclipse.jst.j2ee.internal.web.container", WEB_APP, + "org.eclipse.jst.j2ee.internal.module.container", EAR, + "org.eclipse.jst.server.core.container", SERVER_RUNTIME, + "com.genuitec.eclipse.j2eedt.core.J2EE13_CONTAINER", JAVA_EE, + "com.genuitec.eclipse.j2eedt.core.J2EE14_CONTAINER", JAVA_EE, + "melibrary.com.genuitec.eclipse.j2eedt.core.MYECLIPSE_JAVAEE_5_CONTAINER", JAVA_EE, + "melibrary.com.genuitec.eclipse.j2eedt.core.MYECLIPSE_JAVAEE_6_CONTAINER", JAVA_EE, + "melibrary.com.genuitec.eclipse.j2eedt.core.MYECLIPSE_JAVAEE_7_CONTAINER", JAVA_EE, + "com.genuitec.runtime.library", JAVA_EE); + + /** Stable identifier reported to the plugin backend. */ + final String wireName; + + ContainerKind(String wireName) { + this.wireName = wireName; + } + + /** The kind of {@code containerPath}, or null when another initializer owns it. */ + static ContainerKind of(IPath containerPath) { + if (containerPath == null || containerPath.segmentCount() == 0) { + return null; + } + return BY_ID.get(containerPath.segment(0)); + } + + /** Whether the container needs the servlet container the backend configures. */ + boolean usesServerRuntime() { + return this == SERVER_RUNTIME || this == JAVA_EE; + } +} diff --git a/jdtls-extension/project-model/src/io/github/lithe_idea/java/projectmodel/ContainerRefresher.java b/jdtls-extension/project-model/src/io/github/lithe_idea/java/projectmodel/ContainerRefresher.java new file mode 100644 index 0000000..eff3809 --- /dev/null +++ b/jdtls-extension/project-model/src/io/github/lithe_idea/java/projectmodel/ContainerRefresher.java @@ -0,0 +1,108 @@ +package io.github.lithe_idea.java.projectmodel; + +import java.util.List; +import java.util.Map; + +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IResourceChangeEvent; +import org.eclipse.core.resources.IResourceChangeListener; +import org.eclipse.core.resources.IResourceDelta; +import org.eclipse.core.resources.IResourceDeltaVisitor; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; +import org.eclipse.core.runtime.jobs.Job; +import org.eclipse.jdt.core.IClasspathContainer; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jdt.ls.core.internal.preferences.IPreferencesChangeListener; +import org.eclipse.jdt.ls.core.internal.preferences.Preferences; + +/** + * Recomputes every container this bundle owns when its configuration changes + * or a file it reads changes (a JAR dropped into WEB-INF/lib, an edited + * component or manifest). One job coalesces bursts of events. + */ +final class ContainerRefresher extends Job implements IPreferencesChangeListener, IResourceChangeListener { + /** Coalesces a burst of file events, such as copying many JARs, into one refresh. */ + static final long DELAY_MILLISECONDS = 500; + + ContainerRefresher() { + super("Refresh Lithe project model containers"); + setSystem(true); + } + + @Override + public void preferencesChange(Preferences oldPreferences, Preferences newPreferences) { + ProjectModelSettings before = ProjectModelSettings.from(oldPreferences); + ProjectModelSettings after = ProjectModelSettings.from(newPreferences); + if (!before.equals(after)) { + ServletHomeVariableInitializer.apply(after, ServletHomeVariableInitializer.VARIABLES); + schedule(0); + } + } + + @Override + public void resourceChanged(IResourceChangeEvent event) { + IResourceDelta delta = event.getDelta(); + if (delta == null) { + return; + } + boolean[] relevant = { false }; + try { + delta.accept((IResourceDeltaVisitor) child -> { + if (relevant[0]) { + return false; + } + IResource resource = child.getResource(); + if (resource.getType() == IResource.FILE && isModelInput(resource.getProjectRelativePath())) { + relevant[0] = true; + } + return true; + }); + } catch (CoreException e) { + ProjectModelLog.error("Cannot inspect a resource change", e); + } + if (relevant[0] && !ContainerResolver.ownedContainers().isEmpty()) { + schedule(DELAY_MILLISECONDS); + } + } + + /** Whether a project file feeds a container: a library or a module descriptor. */ + static boolean isModelInput(IPath path) { + String name = path.lastSegment(); + if (name == null) { + return false; + } + String lower = name.toLowerCase(java.util.Locale.ROOT); + if (lower.endsWith(".jar") || lower.endsWith(".zip")) { + return true; + } + return name.equals("org.eclipse.wst.common.component") || name.equals(WebModules.MYECLIPSE_METADATA) + || name.equals("application.xml") || name.equals("MANIFEST.MF"); + } + + @Override + protected IStatus run(IProgressMonitor monitor) { + ProjectModelSettings settings = ProjectModelSettings.current(); + for (Map.Entry> owned : ContainerResolver.ownedContainers().entrySet()) { + if (monitor.isCanceled()) { + return Status.CANCEL_STATUS; + } + List projects = owned.getValue(); + IClasspathContainer[] containers = new IClasspathContainer[projects.size()]; + for (int index = 0; index < containers.length; index++) { + // A null container unbinds it, which is what disabling means. + containers[index] = settings.enabled ? ContainerResolver.resolve(owned.getKey(), projects.get(index), settings) : null; + } + try { + JavaCore.setClasspathContainer(owned.getKey(), projects.toArray(IJavaProject[]::new), containers, monitor); + } catch (CoreException e) { + ProjectModelLog.error("Cannot refresh " + owned.getKey(), e); + } + } + return Status.OK_STATUS; + } +} diff --git a/jdtls-extension/project-model/src/io/github/lithe_idea/java/projectmodel/ContainerResolver.java b/jdtls-extension/project-model/src/io/github/lithe_idea/java/projectmodel/ContainerResolver.java new file mode 100644 index 0000000..1aec4eb --- /dev/null +++ b/jdtls-extension/project-model/src/io/github/lithe_idea/java/projectmodel/ContainerResolver.java @@ -0,0 +1,199 @@ +package io.github.lithe_idea.java.projectmodel; + +import java.io.File; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.Path; +import org.eclipse.jdt.core.IClasspathEntry; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.JavaCore; + +/** + * Computes the value of one container for one project from project files and + * the configured servlet container. Pure apart from bounded file reads, so the + * initializer, the refresh job and the describe command share one answer. + */ +final class ContainerResolver { + private ContainerResolver() { + } + + /** The container of {@code path} for {@code project}, never null for a known kind. */ + static LitheContainer resolve(IPath path, IJavaProject project, ProjectModelSettings settings) { + ContainerKind kind = ContainerKind.of(path); + File directory = location(project.getProject()); + Map entries = new LinkedHashMap<>(); + if (kind != null && directory != null) { + switch (kind) { + case WEB_APP -> webAppEntries(project.getProject(), directory, entries); + case EAR -> earEntries(project.getProject(), directory, entries); + case SERVER_RUNTIME, JAVA_EE -> { + for (String library : settings.serverRuntimeLibraries) { + addLibrary(new File(library), entries); + } + } + } + } + return new LitheContainer(path, description(path, kind, settings), entries.values().toArray(IClasspathEntry[]::new)); + } + + static String description(IPath path, ContainerKind kind, ProjectModelSettings settings) { + if (kind == null) { + return path.toString(); + } + return switch (kind) { + case WEB_APP -> "Web App Libraries"; + case EAR -> "EAR Libraries"; + case SERVER_RUNTIME -> "Server Runtime [" + (path.segmentCount() > 2 ? path.segment(2) : path.lastSegment()) + "]"; + case JAVA_EE -> "Java EE Libraries [" + path.lastSegment() + "]"; + }; + } + + /** WEB-INF/lib of the web root, then the utility modules deployed there. */ + private static void webAppEntries(IProject project, File directory, Map entries) { + File webRoot = WebModules.webRoot(directory); + if (webRoot != null) { + for (File library : WebModules.libraries(new File(webRoot, "WEB-INF/lib"))) { + addLibrary(library, entries); + } + } + WebModules.Component component = WebModules.readComponent(directory); + if (component == null) { + return; + } + for (WebModules.DependentModule module : component.dependents()) { + if (module.deployedTo("/WEB-INF/lib")) { + addDependent(project, module, entries); + } + } + } + + /** + * The library directory of every EAR in the workspace that bundles this + * module, the modules those EARs deploy there, and the module's manifest + * Class-Path resolved against the EAR's content. + */ + private static void earEntries(IProject project, File directory, Map entries) { + List classPath = WebModules.manifestClassPath(WebModules.moduleRoot(directory)); + for (IProject candidate : ResourcesPlugin.getWorkspace().getRoot().getProjects()) { + File earDirectory = location(candidate); + if (candidate.equals(project) || earDirectory == null) { + continue; + } + WebModules.Component ear = WebModules.readComponent(earDirectory); + if (ear == null || ear.dependents().stream().noneMatch(module -> project.getName().equals(module.projectName()))) { + continue; + } + File earRoot = WebModules.earRoot(earDirectory, ear); + String libraryDirectory = WebModules.earLibraryDirectory(earRoot); + for (File library : WebModules.libraries(new File(earRoot, libraryDirectory))) { + addLibrary(library, entries); + } + for (WebModules.DependentModule module : ear.dependents()) { + if (module.deployedTo(libraryDirectory) && !project.getName().equals(module.projectName())) { + addDependent(candidate, module, entries); + } + } + for (String entry : classPath) { + File library = new File(earRoot, entry); + if (library.isFile()) { + addLibrary(library, entries); + continue; + } + String archive = new Path(entry).lastSegment(); + for (WebModules.DependentModule module : ear.dependents()) { + if (archive != null && archive.equals(module.archiveName()) && !project.getName().equals(module.projectName())) { + addDependent(candidate, module, entries); + } + } + } + } + } + + /** A dependent module: a workspace project, a library path or a variable path. */ + private static void addDependent(IProject owner, WebModules.DependentModule module, Map entries) { + String projectName = module.projectName(); + if (projectName != null) { + IProject referenced = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName); + if (referenced.isAccessible() && !referenced.equals(owner)) { + IPath path = referenced.getFullPath(); + entries.putIfAbsent("project:" + path, JavaCore.newProjectEntry(path, false)); + } + return; + } + String library = module.libraryPath(); + if (library != null) { + addLibrary(libraryFile(library), entries); + return; + } + String[] variable = module.variablePath(); + if (variable != null) { + IPath root = JavaCore.getClasspathVariable(variable[0]); + if (root != null) { + addLibrary(root.append(variable[1]).toFile(), entries); + } + } + } + + /** A WTP library path: {@code /Project/rest} inside the workspace, else a file path. */ + private static File libraryFile(String value) { + IPath path = new Path(value); + if (!path.isEmpty() && path.getDevice() == null && path.segmentCount() > 1) { + IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(path.segment(0)); + File directory = location(project); + if (directory != null) { + return new File(directory, path.removeFirstSegments(1).toOSString()); + } + } + return path.toFile(); + } + + private static void addLibrary(File library, Map entries) { + if (library == null || !library.isFile()) { + return; + } + File absolute = library.getAbsoluteFile(); + String key = "library:" + absolute.getPath(); + if (entries.containsKey(key)) { + return; + } + File source = WebModules.sourceAttachment(absolute); + entries.put(key, JavaCore.newLibraryEntry(new Path(absolute.getPath()), source == null ? null : new Path(source.getPath()), null)); + } + + static File location(IProject project) { + if (project == null || !project.isAccessible() || project.getLocation() == null) { + return null; + } + return project.getLocation().toFile(); + } + + /** Every raw container entry of a kind this bundle resolves, per project. */ + static Map> ownedContainers() { + Map> owned = new LinkedHashMap<>(); + for (IProject project : ResourcesPlugin.getWorkspace().getRoot().getProjects()) { + if (!project.isAccessible()) { + continue; + } + IJavaProject javaProject = JavaCore.create(project); + try { + if (!javaProject.exists()) { + continue; + } + for (IClasspathEntry entry : javaProject.getRawClasspath()) { + if (entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER && ContainerKind.of(entry.getPath()) != null) { + owned.computeIfAbsent(entry.getPath(), key -> new ArrayList<>()).add(javaProject); + } + } + } catch (Exception e) { + // A project whose classpath cannot be read keeps its containers. + } + } + return owned; + } +} diff --git a/jdtls-extension/project-model/src/io/github/lithe_idea/java/projectmodel/DescribeCommandHandler.java b/jdtls-extension/project-model/src/io/github/lithe_idea/java/projectmodel/DescribeCommandHandler.java new file mode 100644 index 0000000..20ea876 --- /dev/null +++ b/jdtls-extension/project-model/src/io/github/lithe_idea/java/projectmodel/DescribeCommandHandler.java @@ -0,0 +1,144 @@ +package io.github.lithe_idea.java.projectmodel; + +import java.io.File; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.jdt.core.IClasspathContainer; +import org.eclipse.jdt.core.IClasspathEntry; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jdt.ls.core.internal.IDelegateCommandHandler; + +/** + * {@code lithe.java.projectModel.describe}: what JDT actually made of each + * project's container, variable and library entries, for the plugin's + * settings page. Read-only; asking resolves a container JDT has not resolved + * yet, as any classpath query would. + * + *

Result: {@code {version: 1, enabled, serverRuntimeName, projects: [{name, + * location, entries: [{kind, path, containerKind?, description?, status, + * libraries, projects}]}]}}. {@code status} is {@code resolved}, {@code empty}, + * {@code unbound}, {@code missing} or {@code disabled}. Library entries are + * listed only when their file is missing. + */ +public final class DescribeCommandHandler implements IDelegateCommandHandler { + static final String COMMAND = "lithe.java.projectModel.describe"; + /** Bounds the answer; the settings page shows at most this many rows per project. */ + static final int MAX_ENTRIES_PER_PROJECT = 128; + static final int MAX_PROJECTS = 1024; + + @Override + public Object executeCommand(String commandId, List arguments, IProgressMonitor monitor) throws Exception { + if (!COMMAND.equals(commandId)) { + throw new UnsupportedOperationException(commandId); + } + ProjectModelSettings settings = ProjectModelSettings.current(); + List projects = new ArrayList<>(); + for (IProject project : ResourcesPlugin.getWorkspace().getRoot().getProjects()) { + if (projects.size() >= MAX_PROJECTS || (monitor != null && monitor.isCanceled())) { + break; + } + File location = ContainerResolver.location(project); + IJavaProject javaProject = JavaCore.create(project); + if (location == null || !javaProject.exists()) { + continue; + } + List entries = new ArrayList<>(); + for (IClasspathEntry entry : javaProject.getRawClasspath()) { + if (entries.size() >= MAX_ENTRIES_PER_PROJECT) { + break; + } + Map described = describe(entry, javaProject, settings); + if (described != null) { + entries.add(described); + } + } + Map item = new LinkedHashMap<>(); + item.put("name", project.getName()); + item.put("location", location.getPath()); + item.put("entries", entries); + projects.add(item); + } + Map result = new LinkedHashMap<>(); + result.put("version", 1); + result.put("enabled", settings.enabled); + result.put("serverRuntimeName", settings.serverRuntimeName); + result.put("projects", projects); + return result; + } + + private static Map describe(IClasspathEntry entry, IJavaProject project, ProjectModelSettings settings) { + Map item = new LinkedHashMap<>(); + item.put("path", entry.getPath().toString()); + switch (entry.getEntryKind()) { + case IClasspathEntry.CPE_CONTAINER -> { + ContainerKind kind = ContainerKind.of(entry.getPath()); + item.put("kind", "container"); + item.put("containerKind", kind == null ? "other" : kind.wireName); + IClasspathContainer container = null; + try { + container = JavaCore.getClasspathContainer(entry.getPath(), project); + } catch (Exception e) { + // Reported as unbound below; the cause is in JDT's own log. + } + if (kind != null && !settings.enabled) { + item.put("status", "disabled"); + } else if (container == null) { + item.put("status", "unbound"); + } else { + int libraries = 0; + int projects = 0; + for (IClasspathEntry child : container.getClasspathEntries()) { + if (child.getEntryKind() == IClasspathEntry.CPE_PROJECT) { + projects++; + } else { + libraries++; + } + } + item.put("status", libraries + projects == 0 ? "empty" : "resolved"); + item.put("libraries", libraries); + item.put("projects", projects); + } + item.put("description", container != null ? container.getDescription() + : kind != null ? ContainerResolver.description(entry.getPath(), kind, settings) : entry.getPath().toString()); + return item; + } + case IClasspathEntry.CPE_VARIABLE -> { + item.put("kind", "variable"); + IClasspathEntry resolved = JavaCore.getResolvedClasspathEntry(entry); + item.put("status", resolved == null ? "unbound" : resolved.getPath().toFile().exists() ? "resolved" : "missing"); + if (resolved != null) { + item.put("resolvedPath", resolved.getPath().toOSString()); + } + return item; + } + case IClasspathEntry.CPE_LIBRARY -> { + IClasspathEntry resolved = JavaCore.getResolvedClasspathEntry(entry); + if (resolved != null && libraryExists(resolved)) { + return null; + } + item.put("kind", "library"); + item.put("status", "missing"); + return item; + } + default -> { + return null; + } + } + } + + /** A workspace-relative library is checked through its resource, others on disk. */ + private static boolean libraryExists(IClasspathEntry entry) { + if (entry.getPath().toFile().exists()) { + return true; + } + var resource = ResourcesPlugin.getWorkspace().getRoot().findMember(entry.getPath()); + return resource != null && resource.exists(); + } +} diff --git a/jdtls-extension/project-model/src/io/github/lithe_idea/java/projectmodel/LitheContainer.java b/jdtls-extension/project-model/src/io/github/lithe_idea/java/projectmodel/LitheContainer.java new file mode 100644 index 0000000..ddcbc67 --- /dev/null +++ b/jdtls-extension/project-model/src/io/github/lithe_idea/java/projectmodel/LitheContainer.java @@ -0,0 +1,28 @@ +package io.github.lithe_idea.java.projectmodel; + +import org.eclipse.core.runtime.IPath; +import org.eclipse.jdt.core.IClasspathContainer; +import org.eclipse.jdt.core.IClasspathEntry; + +/** An immutable container value computed by {@link ContainerResolver}. */ +record LitheContainer(IPath path, String description, IClasspathEntry[] entries) implements IClasspathContainer { + @Override + public IClasspathEntry[] getClasspathEntries() { + return entries.clone(); + } + + @Override + public String getDescription() { + return description; + } + + @Override + public int getKind() { + return K_APPLICATION; + } + + @Override + public IPath getPath() { + return path; + } +} diff --git a/jdtls-extension/project-model/src/io/github/lithe_idea/java/projectmodel/LitheContainerInitializer.java b/jdtls-extension/project-model/src/io/github/lithe_idea/java/projectmodel/LitheContainerInitializer.java new file mode 100644 index 0000000..1491165 --- /dev/null +++ b/jdtls-extension/project-model/src/io/github/lithe_idea/java/projectmodel/LitheContainerInitializer.java @@ -0,0 +1,37 @@ +package io.github.lithe_idea.java.projectmodel; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IPath; +import org.eclipse.jdt.core.ClasspathContainerInitializer; +import org.eclipse.jdt.core.IClasspathContainer; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.JavaCore; + +/** + * JDT's entry point for the containers in plugin.xml. When the backend turned + * project model detection off, the container is left unbound, exactly as JDT + * LS behaves without this bundle. + */ +public final class LitheContainerInitializer extends ClasspathContainerInitializer { + @Override + public void initialize(IPath containerPath, IJavaProject project) throws CoreException { + ProjectModelSettings settings = ProjectModelSettings.current(); + if (!settings.enabled || ContainerKind.of(containerPath) == null) { + return; + } + IClasspathContainer container = ContainerResolver.resolve(containerPath, project, settings); + JavaCore.setClasspathContainer(containerPath, new IJavaProject[] { project }, new IClasspathContainer[] { container }, null); + } + + @Override + public String getDescription(IPath containerPath, IJavaProject project) { + return ContainerResolver.description(containerPath, ContainerKind.of(containerPath), ProjectModelSettings.current()); + } + + @Override + public boolean canUpdateClasspathContainer(IPath containerPath, IJavaProject project) { + // The value is derived from project files; editing it in place would + // create a second source of truth. + return false; + } +} diff --git a/jdtls-extension/project-model/src/io/github/lithe_idea/java/projectmodel/ProjectModelLog.java b/jdtls-extension/project-model/src/io/github/lithe_idea/java/projectmodel/ProjectModelLog.java new file mode 100644 index 0000000..12673f5 --- /dev/null +++ b/jdtls-extension/project-model/src/io/github/lithe_idea/java/projectmodel/ProjectModelLog.java @@ -0,0 +1,13 @@ +package io.github.lithe_idea.java.projectmodel; + +import org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin; + +/** Routes failures into the JDT LS log, which the plugin configures and bounds. */ +final class ProjectModelLog { + private ProjectModelLog() { + } + + static void error(String message, Throwable error) { + JavaLanguageServerPlugin.logException("[Lithe project model] " + message, error); + } +} diff --git a/jdtls-extension/project-model/src/io/github/lithe_idea/java/projectmodel/ProjectModelSettings.java b/jdtls-extension/project-model/src/io/github/lithe_idea/java/projectmodel/ProjectModelSettings.java new file mode 100644 index 0000000..8e4f545 --- /dev/null +++ b/jdtls-extension/project-model/src/io/github/lithe_idea/java/projectmodel/ProjectModelSettings.java @@ -0,0 +1,102 @@ +package io.github.lithe_idea.java.projectmodel; + +import java.io.File; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin; +import org.eclipse.jdt.ls.core.internal.preferences.PreferenceManager; +import org.eclipse.jdt.ls.core.internal.preferences.Preferences; + +/** + * The part of the workspace configuration the plugin backend writes for this + * bundle: {@code java.lithe.projectModel = {enabled, serverRuntimeHome, + * serverRuntimeLibraries, serverRuntimeName}}. The backend owns detection of the servlet container; the + * bundle only consumes the absolute library paths it was given. + */ +final class ProjectModelSettings { + /** Bounds a malformed or hostile configuration; a real container has far fewer. */ + static final int MAX_LIBRARIES = 1024; + + final boolean enabled; + /** Absolute servlet container folder, or empty when none was found. */ + final String serverRuntimeHome; + final List serverRuntimeLibraries; + final String serverRuntimeName; + + private ProjectModelSettings(boolean enabled, String serverRuntimeHome, List serverRuntimeLibraries, String serverRuntimeName) { + this.enabled = enabled; + this.serverRuntimeHome = serverRuntimeHome; + this.serverRuntimeLibraries = serverRuntimeLibraries; + this.serverRuntimeName = serverRuntimeName; + } + + /** The settings of the current JDT LS preferences; defaults when absent. */ + static ProjectModelSettings current() { + PreferenceManager manager = JavaLanguageServerPlugin.getPreferencesManager(); + return manager == null ? from(null) : from(manager.getPreferences()); + } + + static ProjectModelSettings from(Preferences preferences) { + Object raw = preferences == null ? null : lookup(preferences.asMap(), "java", "lithe", "projectModel"); + if (!(raw instanceof Map map)) { + // Without a configuration from the backend (an older backend, or a + // JDT LS started by another client) the containers still resolve + // from project files; only the servlet container stays empty. + return new ProjectModelSettings(true, "", List.of(), ""); + } + boolean enabled = !Boolean.FALSE.equals(map.get("enabled")); + List libraries = new ArrayList<>(); + if (map.get("serverRuntimeLibraries") instanceof List list) { + for (Object item : list) { + if (libraries.size() >= MAX_LIBRARIES) { + break; + } + if (item instanceof String path && new File(path).isAbsolute()) { + libraries.add(path); + } + } + } + String name = map.get("serverRuntimeName") instanceof String text ? text : ""; + String home = map.get("serverRuntimeHome") instanceof String text && new File(text).isAbsolute() ? text : ""; + return new ProjectModelSettings(enabled, home, Collections.unmodifiableList(libraries), name); + } + + /** + * Reads {@code java.lithe.projectModel} whether the client sent it nested + * or with dotted keys, the two shapes JDT LS itself accepts. + */ + private static Object lookup(Map configuration, String... keys) { + if (configuration == null) { + return null; + } + Object dotted = configuration.get(String.join(".", keys)); + if (dotted != null) { + return dotted; + } + Object current = configuration; + for (String key : keys) { + if (!(current instanceof Map map)) { + return null; + } + current = map.get(key); + } + return current; + } + + @Override + public boolean equals(Object other) { + return other instanceof ProjectModelSettings that && enabled == that.enabled + && serverRuntimeHome.equals(that.serverRuntimeHome) + && serverRuntimeLibraries.equals(that.serverRuntimeLibraries) + && serverRuntimeName.equals(that.serverRuntimeName); + } + + @Override + public int hashCode() { + return Objects.hash(enabled, serverRuntimeHome, serverRuntimeLibraries, serverRuntimeName); + } +} diff --git a/jdtls-extension/project-model/src/io/github/lithe_idea/java/projectmodel/ServletHomeVariableInitializer.java b/jdtls-extension/project-model/src/io/github/lithe_idea/java/projectmodel/ServletHomeVariableInitializer.java new file mode 100644 index 0000000..db08fe6 --- /dev/null +++ b/jdtls-extension/project-model/src/io/github/lithe_idea/java/projectmodel/ServletHomeVariableInitializer.java @@ -0,0 +1,38 @@ +package io.github.lithe_idea.java.projectmodel; + +import java.util.List; + +import org.eclipse.core.runtime.Path; +import org.eclipse.jdt.core.ClasspathVariableInitializer; +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jdt.core.JavaModelException; + +/** + * Binds the classpath variables legacy Eclipse projects use for the servlet + * container ({@code TOMCAT_HOME/lib/servlet-api.jar}) to the folder the backend + * configured. Without one the variables stay unbound, as without this bundle. + */ +public final class ServletHomeVariableInitializer extends ClasspathVariableInitializer { + static final List VARIABLES = List.of("TOMCAT_HOME", "CATALINA_HOME"); + + @Override + public void initialize(String variable) { + apply(ProjectModelSettings.current(), List.of(variable)); + } + + /** Sets {@code variables} from {@code settings}, or removes them. */ + static void apply(ProjectModelSettings settings, List variables) { + boolean bound = settings.enabled && !settings.serverRuntimeHome.isEmpty(); + try { + for (String variable : variables) { + if (bound) { + JavaCore.setClasspathVariable(variable, new Path(settings.serverRuntimeHome), null); + } else if (JavaCore.getClasspathVariable(variable) != null) { + JavaCore.removeClasspathVariable(variable, null); + } + } + } catch (JavaModelException e) { + ProjectModelLog.error("Cannot update the servlet container classpath variables", e); + } + } +} diff --git a/jdtls-extension/project-model/src/io/github/lithe_idea/java/projectmodel/WebModules.java b/jdtls-extension/project-model/src/io/github/lithe_idea/java/projectmodel/WebModules.java new file mode 100644 index 0000000..fa7689b --- /dev/null +++ b/jdtls-extension/project-model/src/io/github/lithe_idea/java/projectmodel/WebModules.java @@ -0,0 +1,290 @@ +package io.github.lithe_idea.java.projectmodel; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.jar.Manifest; + +import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; + +/** + * Static reading of the module layout Eclipse WTP and MyEclipse keep in project + * files. Only fixed paths are read, every read is bounded, and a file that is + * missing or malformed contributes nothing: the container then resolves to + * fewer libraries instead of failing the project. + */ +final class WebModules { + /** Upper bound of libraries one directory contributes. */ + static final int MAX_LIBRARIES_PER_DIRECTORY = 4096; + /** Descriptor files larger than this are not module descriptors. */ + static final long MAX_DESCRIPTOR_BYTES = 1024 * 1024; + static final String COMPONENT = ".settings/org.eclipse.wst.common.component"; + static final String MYECLIPSE_METADATA = ".mymetadata"; + /** Web roots of common tools, tried in order when no descriptor names one. */ + static final List DEFAULT_WEB_ROOTS = List.of("WebContent", "WebRoot", "src/main/webapp", "web", "webapp", "WebApp"); + /** Content roots of EJB, connector and utility modules without a descriptor. */ + static final List DEFAULT_MODULE_ROOTS = List.of("ejbModule", "connectorModule", "appClientModule", "src"); + static final String DEFAULT_EAR_ROOT = "EarContent"; + + private WebModules() { + } + + /** A {@code } of a WTP component. */ + record DependentModule(String handle, String deployPath, String archiveName) { + /** The project of a {@code module:/resource//} handle, or null. */ + String projectName() { + String prefix = "module:/resource/"; + if (handle == null || !handle.startsWith(prefix)) { + return null; + } + String rest = handle.substring(prefix.length()); + int slash = rest.indexOf('/'); + return slash > 0 ? rest.substring(0, slash) : null; + } + + /** The path of a {@code module:/classpath/lib/} handle, or null. */ + String libraryPath() { + String prefix = "module:/classpath/lib/"; + return handle != null && handle.startsWith(prefix) ? handle.substring(prefix.length()) : null; + } + + /** {@code [variable, rest]} of a {@code module:/classpath/var//} handle, or null. */ + String[] variablePath() { + String prefix = "module:/classpath/var/"; + if (handle == null || !handle.startsWith(prefix)) { + return null; + } + String rest = handle.substring(prefix.length()); + int slash = rest.indexOf('/'); + return slash > 0 ? new String[] { rest.substring(0, slash), rest.substring(slash + 1) } : null; + } + + /** Whether the module is deployed into {@code directory} ("/WEB-INF/lib", "/lib"). */ + boolean deployedTo(String directory) { + return deployPath != null && trimSlashes(deployPath).equals(trimSlashes(directory)); + } + } + + /** The parts of a WTP component file this bundle uses. */ + record Component(List rootSources, List dependents) { + } + + /** The WTP component of the project at {@code projectDirectory}, or null. */ + static Component readComponent(File projectDirectory) { + Element root = parse(new File(projectDirectory, COMPONENT)); + if (root == null) { + return null; + } + List sources = new ArrayList<>(); + List dependents = new ArrayList<>(); + NodeList modules = root.getElementsByTagName("wb-module"); + for (int index = 0; index < modules.getLength(); index++) { + Element module = (Element) modules.item(index); + NodeList resources = module.getElementsByTagName("wb-resource"); + for (int item = 0; item < resources.getLength(); item++) { + Element resource = (Element) resources.item(item); + if ("/".equals(resource.getAttribute("deploy-path"))) { + String source = trimSlashes(resource.getAttribute("source-path")); + if (!source.isEmpty()) { + sources.add(source); + } + } + } + NodeList children = module.getElementsByTagName("dependent-module"); + for (int item = 0; item < children.getLength(); item++) { + Element child = (Element) children.item(item); + dependents.add(new DependentModule(child.getAttribute("handle"), child.getAttribute("deploy-path"), child.getAttribute("archiveName"))); + } + } + return new Component(List.copyOf(sources), List.copyOf(dependents)); + } + + /** + * The directory deployed as the web application root: the WTP component's + * root resource that holds WEB-INF, else MyEclipse's {@code webrootdir}, + * else the first of {@link #DEFAULT_WEB_ROOTS} that holds WEB-INF. + */ + static File webRoot(File projectDirectory) { + List candidates = new ArrayList<>(); + Component component = readComponent(projectDirectory); + if (component != null) { + candidates.addAll(component.rootSources()); + } + Element metadata = parse(new File(projectDirectory, MYECLIPSE_METADATA)); + if (metadata != null) { + NodeList modules = metadata.getElementsByTagName("project-module"); + for (int index = 0; index < modules.getLength(); index++) { + String root = trimSlashes(((Element) modules.item(index)).getAttribute("webrootdir")); + if (!root.isEmpty()) { + candidates.add(root); + } + } + } + candidates.addAll(DEFAULT_WEB_ROOTS); + for (String candidate : candidates) { + File directory = new File(projectDirectory, candidate); + if (new File(directory, "WEB-INF").isDirectory()) { + return directory; + } + } + return null; + } + + /** The directory whose META-INF/MANIFEST.MF describes the module, or null. */ + static File moduleRoot(File projectDirectory) { + List candidates = new ArrayList<>(); + Component component = readComponent(projectDirectory); + if (component != null) { + candidates.addAll(component.rootSources()); + } + File web = webRoot(projectDirectory); + if (web != null) { + candidates.add(0, projectDirectory.toPath().relativize(web.toPath()).toString()); + } + candidates.addAll(DEFAULT_MODULE_ROOTS); + for (String candidate : candidates) { + File directory = new File(projectDirectory, candidate); + if (new File(directory, "META-INF/MANIFEST.MF").isFile()) { + return directory; + } + } + return null; + } + + /** The EAR content root of an EAR project with {@code component}. */ + static File earRoot(File projectDirectory, Component component) { + for (String source : component.rootSources()) { + File directory = new File(projectDirectory, source); + if (directory.isDirectory()) { + return directory; + } + } + return new File(projectDirectory, DEFAULT_EAR_ROOT); + } + + /** + * The library directory of the EAR at {@code earRoot}: application.xml's + * {@code }, else the Java EE 5 default "lib". + */ + static String earLibraryDirectory(File earRoot) { + Element application = parse(new File(earRoot, "META-INF/application.xml")); + if (application != null) { + NodeList directories = application.getElementsByTagNameNS("*", "library-directory"); + if (directories.getLength() == 0) { + directories = application.getElementsByTagName("library-directory"); + } + if (directories.getLength() > 0) { + String directory = trimSlashes(directories.item(0).getTextContent().trim()); + if (!directory.isEmpty() && !directory.contains("..")) { + return directory; + } + } + } + return "lib"; + } + + /** The relative entries of the manifest Class-Path of the module at {@code moduleRoot}. */ + static List manifestClassPath(File moduleRoot) { + if (moduleRoot == null) { + return List.of(); + } + File file = new File(moduleRoot, "META-INF/MANIFEST.MF"); + if (!file.isFile() || file.length() > MAX_DESCRIPTOR_BYTES) { + return List.of(); + } + try (InputStream input = new FileInputStream(file)) { + String value = new Manifest(input).getMainAttributes().getValue("Class-Path"); + if (value == null) { + return List.of(); + } + List entries = new ArrayList<>(); + for (String entry : value.trim().split("\\s+")) { + if (!entry.isEmpty() && !entry.contains("..") && !entry.contains(":")) { + entries.add(entry); + } + } + return entries; + } catch (IOException | RuntimeException e) { + // A malformed manifest only means no Class-Path entries. + return List.of(); + } + } + + /** The JAR and ZIP files directly inside {@code directory}, in name order. */ + static List libraries(File directory) { + File[] files = directory == null ? null : directory.listFiles(); + if (files == null) { + return List.of(); + } + Arrays.sort(files); + List libraries = new ArrayList<>(); + for (File file : files) { + String name = file.getName().toLowerCase(java.util.Locale.ROOT); + if (file.isFile() && (name.endsWith(".jar") || name.endsWith(".zip")) && !name.endsWith("-sources.jar")) { + libraries.add(file); + if (libraries.size() >= MAX_LIBRARIES_PER_DIRECTORY) { + break; + } + } + } + return libraries; + } + + /** {@code foo-sources.jar} next to {@code foo.jar}, when present. */ + static File sourceAttachment(File library) { + String name = library.getName(); + int dot = name.lastIndexOf('.'); + if (dot <= 0) { + return null; + } + File candidate = new File(library.getParentFile(), name.substring(0, dot) + "-sources.jar"); + return candidate.isFile() ? candidate : null; + } + + static String trimSlashes(String value) { + String trimmed = value == null ? "" : value.trim().replace('\\', '/'); + while (trimmed.startsWith("/")) { + trimmed = trimmed.substring(1); + } + while (trimmed.endsWith("/")) { + trimmed = trimmed.substring(0, trimmed.length() - 1); + } + return trimmed; + } + + /** The document element of {@code file}, with DTDs and external entities refused. */ + private static Element parse(File file) { + if (!file.isFile() || file.length() > MAX_DESCRIPTOR_BYTES) { + return null; + } + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setNamespaceAware(true); + factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", false); + factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); + factory.setFeature("http://xml.org/sax/features/external-general-entities", false); + factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); + factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); + factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); + factory.setExpandEntityReferences(false); + DocumentBuilder builder = factory.newDocumentBuilder(); + builder.setErrorHandler(null); + builder.setEntityResolver((publicId, systemId) -> new org.xml.sax.InputSource(new java.io.StringReader(""))); + Document document = builder.parse(file); + return document.getDocumentElement(); + } catch (Exception e) { + // Malformed descriptors are skipped; see the class comment. + return null; + } + } +} diff --git a/scripts/assemble-package.sh b/scripts/assemble-package.sh index 8bc198d..483d4b1 100755 --- a/scripts/assemble-package.sh +++ b/scripts/assemble-package.sh @@ -63,6 +63,9 @@ for entry in lombok java-debug java-test manifest.json; do } cp -R "$jdtls_root/$entry" "$extensions/$entry" done +# The plugin's own extension bundle (Eclipse WTP containers, servlet +# container variables) is compiled here against the prepared JDT LS release. +node "$ROOT_DIR/scripts/package/project-model-bundle.mjs" "$jdtls_root" "$extensions" >&2 # The plugin backend is one Mach-O binary: a single architecture is copied as # built, a universal package joins the two with lipo. Both targets must be @@ -102,7 +105,7 @@ for declared in \ exit 1 } done -for directory in jdtls-extensions/java-debug jdtls-extensions/java-test/extensions; do +for directory in jdtls-extensions/java-debug jdtls-extensions/java-test/extensions jdtls-extensions/project-model; do [[ -n "$(find "$OUTPUT_DIR/$directory" -maxdepth 1 -name '*.jar' -print -quit 2>/dev/null)" ]] || { print -u2 -- "extension bundle directory $directory holds no bundles" exit 1 diff --git a/scripts/compiler/test-project-models.mjs b/scripts/compiler/test-project-models.mjs new file mode 100644 index 0000000..7b7e0b9 --- /dev/null +++ b/scripts/compiler/test-project-models.mjs @@ -0,0 +1,188 @@ +// Project models JDT LS cannot import on its own (issue 1lck/Lithe-IDEA#2063), +// run through the packaged backend, its project model bundle and the user's +// JDT LS: an Eclipse WTP project with Web App Libraries, Server Runtime and a +// TOMCAT_HOME variable, a legacy web folder with only WEB-INF/lib, and an +// IntelliJ IDEA project with a non-standard source folder and module and +// project libraries. Each must compile with JDT without any project file +// being written, the package and the JDT LS installation must stay unchanged, +// and the libraries page must show the model. The legacy web scenario also +// saves the detected entries through the page and builds again from the file. +// A fake servlet container outside the workspace stands for Tomcat 9. +// Usage: node scripts/compiler/test-project-models.mjs [scenario,...] +import assert from 'node:assert/strict'; +import {createHash} from 'node:crypto'; +import {existsSync,lstatSync,mkdirSync,mkdtempSync,readFileSync,readdirSync,realpathSync,renameSync,rmSync,writeFileSync} from 'node:fs'; +import {tmpdir} from 'node:os'; +import {dirname,join,resolve} from 'node:path'; +import {setTimeout as delay} from 'node:timers/promises'; +import {fileURLToPath,pathToFileURL} from 'node:url'; +import {Client} from '../package/lsp-client.mjs'; +import {answeredExecutable,serverInputs} from '../package/jdtls-test-inputs.mjs'; +import {createReport} from '../report.mjs'; +import {capture} from './capture.mjs'; +import {runTool} from './process.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 SCENARIOS=['eclipse-wtp','legacy-web','idea']; +const selected=(process.argv[3]??SCENARIOS.join(',')).split(','); +for(const name of selected)assert.ok(SCENARIOS.includes(name),`Unknown scenario ${name}`); +const inputs=serverInputs(); +const javac=process.env.LITHE_TEST_JAVAC??'javac',jarTool=process.env.LITHE_TEST_JAR??'jar'; +const write=(path,content)=>{mkdirSync(dirname(path),{recursive:true});writeFileSync(path,content);}; +// Files below `directory`, with content digests; build output folders are left out. +const OUTPUT=new Set(['bin','build','out','classes']); +const snapshot=(directory,skip=OUTPUT)=>{const items=[];const visit=(path,label)=>{const stat=lstatSync(path);assert.equal(stat.isSymbolicLink(),false);items.push([label,stat.isFile()?createHash('sha256').update(readFileSync(path)).digest('hex'):null]);if(stat.isDirectory())for(const name of readdirSync(path).sort())if(!skip.has(name))visit(join(path,name),`${label}/${name}`);};visit(directory,'');return items;}; +const samePath=(left,right)=>process.platform==='win32'?resolve(left).toLowerCase()===resolve(right).toLowerCase():resolve(left)===resolve(right); +async function until(get,accept,label,timeout=90000){const end=Date.now()+timeout;let last;while(Date.now()join(directory,path))],{timeout:60000}); + mkdirSync(dirname(output),{recursive:true}); + await runTool(jarTool,['--create','--file',output,'-C',directory,'.'],{timeout:60000}); +} +const HELLO='package demo;\npublic class Hello extends javax.servlet.http.HttpServlet {\n public static void main(String[] args) { System.out.print(com.acme.Util.value()); }\n}\n'; +const ECLIPSE_PROJECT=name=>`${name}org.eclipse.jdt.core.javabuilderorg.eclipse.jdt.core.javanatureorg.eclipse.wst.common.project.facet.core.nature`; + +// Each scenario writes its fixture and returns the source file, the classes +// JDT must see, and the descriptor the model rows are bound to. +const fixtures={ + async 'eclipse-wtp'(root,stage){ + const project=join(root,'WebApp'); + write(join(project,'.project'),ECLIPSE_PROJECT('WebApp')); + write(join(project,'.classpath'),''); + write(join(project,'.settings/org.eclipse.wst.common.component'),''); + await jar(stage,'util',{'com/acme/Util.java':'package com.acme; public class Util { public static String value() { return "web-ok"; } }'},join(project,'WebContent/WEB-INF/lib/util.jar')); + write(join(project,'src/demo/Hello.java'),HELLO); + return {source:join(project,'src/demo/Hello.java'),project,descriptor:'WebApp/.project',model:'Eclipse'}; + }, + async 'legacy-web'(root,stage){ + await jar(stage,'util',{'com/acme/Util.java':'package com.acme; public class Util { public static String value() { return "web-ok"; } }'},join(root,'WebRoot/WEB-INF/lib/util.jar')); + write(join(root,'WebRoot/WEB-INF/web.xml'),''); + write(join(root,'src/demo/Hello.java'),HELLO); + return {source:join(root,'src/demo/Hello.java'),project:root,descriptor:'WebRoot/WEB-INF/web.xml',model:'传统 Web',library:'WebRoot/WEB-INF/lib/*.jar'}; + }, + async idea(root,stage){ + write(join(root,'.idea/modules.xml'),''); + write(join(root,'app.iml'),''); + write(join(root,'.idea/libraries/servlet.xml'),''); + await jar(stage,'util',{'com/acme/Util.java':'package com.acme; public class Util { public static String value() { return "idea-ok"; } }'},join(root,'third-party/util.jar')); + await jar(stage,'servlet-copy',{'javax/servlet/http/HttpServlet.java':'package javax.servlet.http; public abstract class HttpServlet { }'},join(root,'vendor/servlet-api.jar')); + write(join(root,'java/demo/Hello.java'),HELLO); + return {source:join(root,'java/demo/Hello.java'),project:root,descriptor:'.idea/modules.xml',model:'IntelliJ IDEA',library:'third-party/util.jar',sourcePath:'java',projectServlet:true}; + }, +}; + +async function scenario(name,report){ + const step=(label,body)=>report.step(`${name}: ${label}`,body); + const stage=realpathSync.native(mkdtempSync(join(tmpdir(),`lithe-java-model-${name}-`))); + const root=join(stage,'workspace');mkdirSync(root); + let backend,server,configuration={}; + try{ + const tomcat=join(stage,'servers/apache-tomcat-9.0.98'); + await jar(stage,'servlet',{'javax/servlet/http/HttpServlet.java':'package javax.servlet.http; public abstract class HttpServlet { }'},join(tomcat,'lib/servlet-api.jar')); + await jar(stage,'jsp',{'javax/servlet/jsp/JspPage.java':'package javax.servlet.jsp; public interface JspPage { }'},join(tomcat,'lib/jsp-api.jar')); + const fixture=await fixtures[name](root,stage); + // JDT LS itself adds its resource filter (filteredResources) to an Eclipse + // .project on import; every other file must stay as the fixture wrote it. + const projectFiles=()=>snapshot(root,new Set([...OUTPUT,...(name==='eclipse-wtp'?['.project']:[])])); + const projectBaseline=projectFiles(); + const context={contextID:`ctx-${name}`,generation:1};let op=0; + const folders=[{rootID:'root',name:'workspace',path:root,uri:pathToFileURL(root).href}]; + const hostRequests={ + 'lithe/host/workspace/getContext':()=>({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:{darwin:'macos',win32:'windows'}[process.platform]??process.platform,arch:process.env.LITHE_TEST_ARCH??(process.arch==='arm64'?'arm64':'x86_64')},settings:{logLevel:'WARNING',languageServerHome:inputs.home,projectModelDetection:true,servletContainerHome:tomcat},tools:inputs.tools}; + for(const[key,directory]of Object.entries({stateDirectory:'state',workspaceStateDirectory:'workspace-state',logDirectory:'logs',temporaryDirectory:'tmp'})){params[key]=join(stage,directory);mkdirSync(params[key]);} + const invoke=(functionID,args,timeout=90000)=>backend.request('lithe/function/invoke',{functionID,operationID:`model-${++op}`,params:args,context},timeout); + const launch=await invoke('java.resolveLaunch',params);configuration=launch.workspaceConfiguration; + await step('the launch loads the bundle and configures the servlet container',async()=>{ + assert.ok(launch.initializationOptions.bundles.some(bundle=>/io\.github\.lithe_idea\.java\.projectmodel_.*\.jar$/.test(bundle)),JSON.stringify(launch.initializationOptions.bundles)); + const model=configuration.java.lithe?.projectModel; + // The IDEA fixture takes the servlet API from a project library, so it + // needs no servlet container. + if(fixture.projectServlet)assert.equal(model,undefined); + else assert.ok(model&&samePath(model.serverRuntimeHome,tomcat),JSON.stringify(configuration.java.lithe)); + if(fixture.library)assert.ok(JSON.stringify(configuration.java.project.referencedLibraries).includes(fixture.library),JSON.stringify(configuration.java.project)); + if(fixture.sourcePath)assert.deepEqual(configuration.java.project.sourcePaths,[fixture.sourcePath]); + }); + server=new Client(answeredExecutable(launch,inputs),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},180000);server.notify('initialized',{}); + backend.notify('lithe/host/languageServer/didChangeState',{context,serverID:'java',state:'running',generation:1}); + const execute=(command,args=[],timeout=60000)=>server.request('workspace/executeCommand',{command,arguments:args},timeout); + const projectUri=pathToFileURL(fixture.project).href; + const imported=()=>until(()=>execute('java.project.getAll'),projects=>projects.some(uri=>samePath(fileURLToPath(uri),fixture.project)),'JDT project import'); + const compiles=async()=>{ + assert.equal(await server.request('java/buildWorkspace',true,180000),1,'JDT reports build errors'); + const paths=await execute('vscode.java.resolveClasspath',['demo.Hello','']); + const classes=paths.flat().find(path=>typeof path==='string'&&existsSync(join(path,'demo/Hello.class'))); + assert.ok(classes,`demo/Hello.class was not compiled: ${JSON.stringify(paths)}`); + }; + await step('JDT imports the project and compiles it against the detected classpath',async()=>{ + await imported(); + if(fixture.library)await until(()=>execute('java.project.getSettings',[projectUri,['org.eclipse.jdt.ls.core.referencedLibraries']]),value=>(value['org.eclipse.jdt.ls.core.referencedLibraries']??[]).some(path=>path.endsWith('servlet-api.jar')),'JDT referenced libraries'); + if(fixture.sourcePath)await until(()=>execute('java.project.getSettings',[projectUri,['org.eclipse.jdt.ls.core.sourcePaths']]),value=>(value['org.eclipse.jdt.ls.core.sourcePaths']??[]).some(path=>samePath(path,join(root,fixture.sourcePath))),'JDT source paths'); + await compiles(); + }); + if(name==='eclipse-wtp')await step('the bundle resolves the WTP containers and the TOMCAT_HOME variable',async()=>{ + const described=await execute('lithe.java.projectModel.describe'); + const project=described.projects.find(item=>item.name==='WebApp');assert.ok(project,JSON.stringify(described)); + const entry=prefix=>project.entries.find(item=>item.path.startsWith(prefix)); + assert.equal(entry('org.eclipse.jst.j2ee.internal.web.container').status,'resolved'); + assert.equal(entry('org.eclipse.jst.j2ee.internal.web.container').libraries,1); + assert.equal(entry('org.eclipse.jst.server.core.container').status,'resolved'); + assert.ok(samePath(entry('TOMCAT_HOME').resolvedPath,join(tomcat,'lib/jsp-api.jar')),JSON.stringify(entry('TOMCAT_HOME'))); + }); + await step('the libraries page shows the model read-only',async()=>{ + const page=await invoke('libraries.settings',{context:{language:'zh-CN',builds:[]}}); + const model=page.sources.find(source=>source.group==='model'&&source.path===fixture.descriptor); + assert.ok(model,JSON.stringify(page.sources.map(source=>[source.group,source.path]))); + assert.equal(model.writable,false); + const value=id=>model.fields.find(field=>field.id===id)?.value; + assert.match(value('model'),new RegExp(fixture.model)); + if(fixture.projectServlet)assert.equal(value('servlet'),undefined); + else assert.match(value('servlet'),/Apache Tomcat 9\.0\.98/); + if(fixture.sourcePath)assert.deepEqual(value('source-folders'),[fixture.sourcePath]); + if(fixture.library)assert.ok(value('detected').some(line=>line.startsWith(fixture.library)),JSON.stringify(value('detected'))); + if(name==='eclipse-wtp')assert.ok(value('containers')?.some(line=>line.startsWith('Web App Libraries')),JSON.stringify(model.fields)); + assert.deepEqual(projectFiles(),projectBaseline,'Detection and the libraries page must not write project files'); + // The public projection, rendered by the native host in scripts/compiler/visual.mjs. + capture(`libraries-${name}-zh`,page); + capture(`libraries-${name}-en`,await invoke('libraries.settings',{context:{language:'en',builds:[]}})); + }); + if(name==='legacy-web')await step('saving the detected entries writes them and JDT builds from the file',async()=>{ + const page=await invoke('libraries.settings',{context:{language:'en',builds:[]}}); + const source=page.sources.find(item=>item.path==='.vscode/settings.json');assert.ok(source,JSON.stringify(page.sources)); + assert.equal(source.fields.find(field=>field.id==='store-detected')?.value,false); + const stageFile=join(stage,'settings-stage.json');writeFileSync(stageFile,''); + const edit=await invoke('compiler.prepareSettings',{operation:'editSource',sourceID:source.id,revision:source.revision,values:{'store-detected':true},outputFile:stageFile}); + assert.equal(edit.changed,true); + const saved=JSON.parse(readFileSync(stageFile,'utf8')); + assert.deepEqual(saved['java.project.referencedLibraries'],['lib/**',fixture.library],'Only portable entries are saved, never the machine\'s servlet container'); + mkdirSync(join(root,'.vscode'));renameSync(stageFile,join(root,source.path)); + const after=await invoke('libraries.settings',{operation:'readAfterSave',context:{language:'en',builds:[]}}); + assert.equal(after.sources.find(item=>item.path==='.vscode/settings.json').fields.find(field=>field.id==='store-detected').value,true); + await compiles(); + }); + await server.request('shutdown',null,30000);server.notify('exit',null); + }finally{ + try{if(server)await server.close();}finally{try{if(backend)await backend.close();}finally{rmSync(stage,{recursive:true,force:true});}} + } +} + +const report=createReport('project-models'); +const packageBaseline=snapshot(pkg,new Set()),serverBaseline=snapshot(inputs.home,new Set()); +try{ + for(const name of selected)await scenario(name,report); + await report.step('the package and the JDT LS installation stay unchanged',async()=>{ + assert.deepEqual(snapshot(pkg,new Set()),packageBaseline,'Project models must never write into the installed package'); + assert.deepEqual(snapshot(inputs.home,new Set()),serverBaseline,'Project models must never write into the user\'s JDT LS installation'); + }); +}finally{report.write();} diff --git a/scripts/package/build-linux.mjs b/scripts/package/build-linux.mjs index 51b9cce..edf874e 100644 --- a/scripts/package/build-linux.mjs +++ b/scripts/package/build-linux.mjs @@ -7,6 +7,7 @@ import {chmodSync,cpSync,mkdirSync,readFileSync,rmSync,mkdtempSync,readdirSync,l import {join,resolve} from 'node:path'; import {architectures,root,digest,verifyELF,verifyBinary} from './linux-runtime.mjs'; import {collectNotices,verifyNotices} from './collect-notices.mjs'; +import {BUNDLE_DIRECTORY,buildProjectModelBundle} from './project-model-bundle.mjs'; const arch=process.argv[2];const target=architectures[arch]; if(!target)throw Error('Usage: node scripts/package/build-linux.mjs arm64|x64 [native-backend]'); const run=(exe,args,options={})=>execFileSync(exe,args,{cwd:root,timeout:600000,stdio:['ignore','pipe','inherit'],...options}); @@ -23,12 +24,14 @@ const manifest=JSON.parse(readFileSync(join(root,id,'plugin.json'))); const staging=mkdtempSync(join(root,'.artifacts',`linux-${arch}-`)); const pkg=join(staging,id); const extensions=['lombok','java-debug','java-test','manifest.json']; +// The plugin's own bundle, compiled against the prepared JDT LS release. +const packaged=[...extensions,BUNDLE_DIRECTORY]; function verify(directory){ const actual=JSON.parse(readFileSync(join(directory,'plugin.json'))); if(JSON.stringify(actual)!==JSON.stringify(manifest))throw Error('Packaged manifest changed'); for(const name of ['LICENSE','NOTICE'])if(!readFileSync(join(directory,name)).equals(readFileSync(join(root,name))))throw Error(`Missing or modified ${name}`); verifyBinary(join(directory,manifest.backend.launch.path),arch,{executable:true}); - if(readdirSync(join(directory,'jdtls-extensions')).sort().join()!==[...extensions].sort().join())throw Error('Unexpected JDT LS extension entries'); + if(readdirSync(join(directory,'jdtls-extensions')).sort().join()!==[...packaged].sort().join())throw Error('Unexpected JDT LS extension entries'); const walk=path=>{for(const name of readdirSync(path)){const file=join(path,name);const s=lstatSync(file);if(s.isSymbolicLink())throw Error(`Package link: ${file}`); // JDT LS and the JDK are the user's; finding either means a build copied it in. if((s.isFile()&&/^org\.eclipse\.equinox\.launcher_.*\.jar$|^java$|^libjvm\.so$/.test(name))||(s.isDirectory()&&/^config_/.test(name)))throw Error(`Package must not contain JDT LS or a JDK: ${file}`); @@ -41,6 +44,7 @@ try{ for(const name of ['icons','templates','l10n'])cpSync(join(root,id,name),join(pkg,name),{recursive:true}); const destination=join(pkg,'jdtls-extensions');mkdirSync(destination); for(const name of extensions)cpSync(join(jdt,name),join(destination,name),{recursive:true}); + buildProjectModelBundle(jdt,destination); mkdirSync(join(pkg,'bin'));cpSync(backend,join(pkg,manifest.backend.launch.path));chmodSync(join(pkg,manifest.backend.launch.path),0o755); collectNotices(pkg);verify(pkg); const dist=join(root,'dist');mkdirSync(dist,{recursive:true}); diff --git a/scripts/package/build-windows.mjs b/scripts/package/build-windows.mjs index f43e5af..6234ba5 100644 --- a/scripts/package/build-windows.mjs +++ b/scripts/package/build-windows.mjs @@ -11,6 +11,7 @@ import { dirname, join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { execFileSync } from 'node:child_process'; import { collectNotices, verifyNotices } from './collect-notices.mjs'; +import { buildProjectModelBundle } from './project-model-bundle.mjs'; const root = resolve(dirname(fileURLToPath(import.meta.url)), '../..'); if (process.platform !== 'darwin') throw new Error('Assemble this development package on macOS.'); @@ -47,6 +48,8 @@ try { for (const name of ['lombok', 'java-debug', 'java-test', 'manifest.json']) { await cp(join(jdt, name), join(extensions, name), { recursive: true }); } + // The plugin's own bundle, compiled against the prepared JDT LS release. + buildProjectModelBundle(jdt, extensions); const manifest = JSON.parse(await readFile(join(root, id, 'plugin.json'), 'utf8')); manifest.backend.launch.path = 'bin/lithe-java-backend.exe'; await writeFile(join(packageRoot, 'plugin.json'), `${JSON.stringify(manifest, null, 2)}\n`); diff --git a/scripts/package/project-model-bundle.mjs b/scripts/package/project-model-bundle.mjs new file mode 100644 index 0000000..72a425b --- /dev/null +++ b/scripts/package/project-model-bundle.mjs @@ -0,0 +1,93 @@ +#!/usr/bin/env node +// Builds the plugin's own JDT LS extension bundle (jdtls-extension/project-model) +// into /project-model/. It is compiled against the JDT LS release +// prepared by scripts/prepare-jdtls.sh, the release the tests run; the bundle +// only uses APIs JDT has kept since its 3.x releases, so a user's newer JDT LS +// loads it too. The jar is reproducible: entries are sorted and dated +// BUNDLE_DATE, so the same sources and JDK give the same bytes. +// Usage: node scripts/package/project-model-bundle.mjs +import { execFileSync } from 'node:child_process'; +import { cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join, relative, resolve, sep } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +const root = resolve(dirname(fileURLToPath(import.meta.url)), '../..'); +export const BUNDLE_SOURCE = join(root, 'jdtls-extension/project-model'); +export const BUNDLE_DIRECTORY = 'project-model'; +export const BUNDLE_DATE = '2026-01-01T00:00:00Z'; +// The oldest Java a supported JDT LS runs on is 21; 17 keeps the class files +// loadable by every JDK the user may still point JDT LS at. +const RELEASE = '17'; + +/** The bundle's jar name, from its manifest's symbolic name and version. */ +export function bundleFileName() { + const manifest = readFileSync(join(BUNDLE_SOURCE, 'META-INF/MANIFEST.MF'), 'utf8'); + const name = /^Bundle-SymbolicName:\s*([^;\s]+)/m.exec(manifest)?.[1]; + const version = /^Bundle-Version:\s*(\S+)/m.exec(manifest)?.[1]; + if (!name || !version) throw new Error('The project model bundle manifest names no symbolic name or version'); + return `${name}_${version}.jar`; +} + +function tool(name) { + const override = process.env[`LITHE_${name.toUpperCase()}`]; + if (override) return override; + const home = process.env.JAVA_HOME; + const candidate = home && join(home, 'bin', process.platform === 'win32' ? `${name}.exe` : name); + return candidate && existsSync(candidate) ? candidate : name; +} + +// JDT LS 1.61 is compiled for Java 21; an older javac cannot read its classes. +const MINIMUM_JAVAC = 21; + +function checkedJavac() { + const javac = tool('javac'); + const output = execFileSync(javac, ['-version'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 30_000 }); + const major = Number(/javac (?:1\.)?(\d+)/.exec(output)?.[1]); + if (!(major >= MINIMUM_JAVAC)) { + throw new Error(`${javac} reports "${output.trim()}"; the project model bundle needs javac ${MINIMUM_JAVAC} or later to read the JDT LS classes. Set JAVA_HOME or LITHE_JAVAC to a JDK ${MINIMUM_JAVAC}+.`); + } + return javac; +} + +function sources(directory) { + const found = []; + for (const name of readdirSync(directory).sort()) { + const path = join(directory, name); + if (statSync(path).isDirectory()) found.push(...sources(path)); + else if (name.endsWith('.java')) found.push(path); + } + return found; +} + +/** Compiles and packs the bundle; returns the jar's path. */ +export function buildProjectModelBundle(jdtlsHome, extensionsDirectory) { + const plugins = join(jdtlsHome, 'plugins'); + if (!existsSync(plugins)) throw new Error(`No JDT LS plugins folder at ${plugins}`); + const work = mkdtempSync(join(tmpdir(), 'lithe-project-model-')); + try { + const classes = join(work, 'classes'); + mkdirSync(classes); + const classpath = readdirSync(plugins).filter(name => name.endsWith('.jar')).sort().map(name => join(plugins, name)).join(process.platform === 'win32' ? ';' : ':'); + execFileSync(checkedJavac(), ['--release', RELEASE, '-encoding', 'UTF-8', '-proc:none', '-Xlint:all,-options,-serial', '-Werror', '-classpath', classpath, '-d', classes, ...sources(join(BUNDLE_SOURCE, 'src'))], { stdio: ['ignore', 'inherit', 'inherit'], timeout: 180_000 }); + cpSync(join(BUNDLE_SOURCE, 'plugin.xml'), join(classes, 'plugin.xml')); + const output = join(extensionsDirectory, BUNDLE_DIRECTORY); + mkdirSync(output, { recursive: true }); + const jar = join(output, bundleFileName()); + rmSync(jar, { force: true }); + execFileSync(tool('jar'), ['--create', '--file', jar, '--manifest', join(BUNDLE_SOURCE, 'META-INF/MANIFEST.MF'), `--date=${BUNDLE_DATE}`, '-C', classes, '.'], { stdio: ['ignore', 'inherit', 'inherit'], timeout: 60_000 }); + return jar; + } finally { + rmSync(work, { recursive: true, force: true }); + } +} + +if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) { + const [jdtlsHome, destination] = process.argv.slice(2); + if (!jdtlsHome || !destination) { + process.stderr.write('Usage: node scripts/package/project-model-bundle.mjs \n'); + process.exit(2); + } + const jar = buildProjectModelBundle(resolve(jdtlsHome), resolve(destination)); + process.stdout.write(`${relative(process.cwd(), jar).split(sep).join('/')}\n`); +} diff --git a/scripts/verify-package.sh b/scripts/verify-package.sh index a6689a8..985433e 100755 --- a/scripts/verify-package.sh +++ b/scripts/verify-package.sh @@ -89,7 +89,7 @@ for declared in \ jdtls-extensions/java-test/runner/com.microsoft.java.test.runner-jar-with-dependencies.jar; do [[ -f "$PACKAGE/$declared" ]] || fail "the backend expects $declared, which the package does not contain" done -for directory in jdtls-extensions/java-debug jdtls-extensions/java-test/extensions; do +for directory in jdtls-extensions/java-debug jdtls-extensions/java-test/extensions jdtls-extensions/project-model; do [[ -n "$(find "$PACKAGE/$directory" -maxdepth 1 -name '*.jar' -print -quit 2>/dev/null)" ]] || fail "extension bundle directory $directory holds no bundles" done