diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1555e44..d361f4e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -87,6 +87,7 @@ jobs: 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" + node scripts/compiler/test-module-structure.mjs "$package" - name: Upload native compiler projections uses: actions/upload-artifact@v4 with: @@ -146,6 +147,7 @@ jobs: 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" + node scripts/compiler/test-module-structure.mjs "$package/io.github.lithe-idea.java-support" rm -rf "$package" - uses: actions/upload-artifact@v4 with: diff --git a/README.md b/README.md index 2151e64..8004e3a 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,7 @@ # Java Support for Lithe +> **4.0.0 项目结构**:对标 IDEA“项目结构 → 模块”,在设置里逐个模块配置 Eclipse 工程的源文件夹、输出文件夹、JRE 和依赖(JAR、类文件夹、库、其他模块,可标导出与仅测试),保存时写回 `.classpath` 并保留其余内容;Maven/Gradle 模块只读显示解析出的类路径。需要支持 `sourceSettings` 1 的 Lithe 宿主,详见 [docs/module-structure.md](docs/module-structure.md)。 +> > **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)。 diff --git a/backend/src/lib.rs b/backend/src/lib.rs index 0be709b..e54912d 100644 --- a/backend/src/lib.rs +++ b/backend/src/lib.rs @@ -52,6 +52,7 @@ pub mod class_content; pub mod jdtls; pub mod launch; pub mod library_settings; +pub mod module_structure; pub mod plugin_functions; pub mod project_model; pub mod project_settings; diff --git a/backend/src/library_settings.rs b/backend/src/library_settings.rs index 8c10d10..d7973d6 100644 --- a/backend/src/library_settings.rs +++ b/backend/src/library_settings.rs @@ -23,8 +23,6 @@ pub const SOURCE_PATHS_FACT: &str = "org.eclipse.jdt.ls.core.sourcePaths"; 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; @@ -147,22 +145,6 @@ impl Page<'_> { 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)> { @@ -256,7 +238,7 @@ impl Page<'_> { continue; } let path = location.join(".project"); - let lines = self.container_lines(&location, false); + let lines = self.container_lines(&location); if lines.is_empty() || taken.contains(&path) || sources.iter().any(|(_, known, _)| known == &path) @@ -290,8 +272,8 @@ impl Page<'_> { } /// 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 { + /// at `location`. + fn container_lines(&self, location: &Path) -> Vec { let zh = self.zh; let Some(project) = self.described_projects().into_iter().find(|project| { project["location"].as_str().is_some_and(|value| { @@ -305,10 +287,6 @@ impl Page<'_> { 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; } @@ -359,28 +337,7 @@ impl Page<'_> { } _ => text(zh, "cannot be resolved", "无法解析"), }; - lines.push( - format!( - "{name}{}{state}", - if brief { - if zh { - "(" - } else { - " (" - } - } else { - " — " - } - ) + if brief { - if zh { - ")" - } else { - ")" - } - } else { - "" - }, - ); + lines.push(format!("{name} — {state}")); if lines.len() >= MAX_LINES { break; } @@ -813,10 +770,6 @@ mod tests { 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")); diff --git a/backend/src/module_structure.rs b/backend/src/module_structure.rs new file mode 100644 index 0000000..60c128f --- /dev/null +++ b/backend/src/module_structure.rs @@ -0,0 +1,893 @@ +//! Eclipse projects as modules of the Java project structure page, after +//! IntelliJ IDEA's Project Structure → Modules: each project's source folders, +//! output folder, JRE and dependencies, read from and written back to its +//! `.classpath`. Maven and Gradle modules show what JDT resolved, read-only, +//! because their build files own them. +//! +//! An edit rewrites only the entries the page manages. Entries are matched by +//! kind and path, so an unchanged entry keeps its other attributes (source +//! attachments, Javadoc locations, access rules); nodes the page does not show +//! stay where they are. + +use lithe_plugin_sdk::{FunctionError, PluginError, Value}; +use serde_json::{json, Map}; +use std::path::Path; +use xmltree::{Element, XMLNode}; + +pub const ROOTS_FIELD: &str = "roots"; +pub const OUTPUT_FIELD: &str = "output"; +pub const JRE_FIELD: &str = "jre"; +pub const DEPENDENCIES_FIELD: &str = "dependencies"; + +const JRE_CONTAINER: &str = "org.eclipse.jdt.launching.JRE_CONTAINER"; +const STANDARD_VM: &str = "org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType"; +const EXECUTION_ENVIRONMENTS: &[&str] = &[ + "JavaSE-1.8", + "JavaSE-11", + "JavaSE-17", + "JavaSE-21", + "JavaSE-25", +]; +/// Containers offered to every module besides those the workspace uses. +const KNOWN_CONTAINERS: &[&str] = &[ + "org.eclipse.jdt.junit.JUNIT_CONTAINER/4", + "org.eclipse.jdt.junit.JUNIT_CONTAINER/5", + "org.eclipse.jst.j2ee.internal.web.container", + "org.eclipse.jst.j2ee.internal.module.container", +]; +/// The contract's bounds on one entry list and its values. +const MAX_ENTRIES: usize = 256; +const MAX_CHOICES: usize = 1024; +const MAX_VALUE: usize = 4096; + +const FOLDER: &str = "folder"; +const ARCHIVE: &str = "archive"; +const CLASSES: &str = "classes"; +const LIBRARY: &str = "library"; +const MODULE: &str = "module"; +const VARIABLE: &str = "variable"; +const TEST: &str = "test"; +const EXPORTED: &str = "exported"; + +fn fail() -> FunctionError { + PluginError::new( + "java.moduleSettings.failed", + "Reload Java project settings and check that the module's .classpath is readable.", + ) + .into() +} + +fn outside() -> FunctionError { + PluginError::new( + "java.moduleSettings.sourceOutsideModule", + "Choose a source folder inside the module's folder.", + ) + .into() +} + +fn local(zh: bool, en: &str, cn: &str) -> String { + if zh { cn } else { en }.to_owned() +} + +/// What a `.classpath` entry is on the page. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Role { + Root, + Jre, + Dependency(&'static str), + Output, + Other, +} + +fn role(element: &Element) -> Role { + if element.name != "classpathentry" { + return Role::Other; + } + let path = attribute(element, "path"); + match attribute(element, "kind") { + "src" if path.starts_with('/') => Role::Dependency(MODULE), + "src" => Role::Root, + "con" if path == JRE_CONTAINER || path.starts_with(&format!("{JRE_CONTAINER}/")) => { + Role::Jre + } + "con" => Role::Dependency(LIBRARY), + "lib" if archive(path) => Role::Dependency(ARCHIVE), + "lib" => Role::Dependency(CLASSES), + "var" => Role::Dependency(VARIABLE), + "output" => Role::Output, + _ => Role::Other, + } +} + +fn attribute<'a>(element: &'a Element, name: &str) -> &'a str { + element + .attributes + .get(name) + .map(String::as_str) + .unwrap_or("") +} + +fn archive(path: &str) -> bool { + let lower = path.to_ascii_lowercase(); + lower.ends_with(".jar") || lower.ends_with(".zip") +} + +/// The `.classpath` kind an entry kind of the page is written as. +fn native_kind(kind: &str) -> Option<&'static str> { + Some(match kind { + FOLDER | MODULE => "src", + ARCHIVE | CLASSES => "lib", + LIBRARY => "con", + VARIABLE => "var", + _ => return None, + }) +} + +/// The value of a nested ``. +fn nested(element: &Element, name: &str) -> Option { + element + .get_child("attributes")? + .children + .iter() + .filter_map(XMLNode::as_element) + .find(|child| child.name == "attribute" && attribute(child, "name") == name) + .map(|child| attribute(child, "value").to_owned()) +} + +fn set_nested(element: &mut Element, name: &str, value: Option<&str>) { + if element.get_child("attributes").is_none() { + if value.is_none() { + return; + } + element + .children + .push(XMLNode::Element(Element::new("attributes"))); + } + let Some(attributes) = element.get_mut_child("attributes") else { + return; + }; + let existing = attributes.children.iter().position(|node| { + node.as_element() + .is_some_and(|child| child.name == "attribute" && attribute(child, "name") == name) + }); + match (existing, value) { + (Some(index), Some(value)) => { + if let Some(XMLNode::Element(child)) = attributes.children.get_mut(index) { + child.attributes.insert("value".into(), value.into()); + } + } + (Some(index), None) => { + attributes.children.remove(index); + } + (None, Some(value)) => { + let mut child = Element::new("attribute"); + child.attributes.insert("name".into(), name.into()); + child.attributes.insert("value".into(), value.into()); + attributes.children.push(XMLNode::Element(child)); + } + (None, None) => {} + } + let empty = element.get_child("attributes").is_some_and(|attributes| { + !attributes + .children + .iter() + .any(|node| node.as_element().is_some()) + }); + if empty { + element.take_child("attributes"); + } +} + +fn truncate(text: &str, bytes: usize) -> String { + let mut end = text.len().min(bytes); + while !text.is_char_boundary(end) { + end -= 1; + } + text[..end].to_owned() +} + +/// The last segment of a slash or backslash separated path, and what precedes it. +fn split_path(path: &str) -> (&str, &str) { + let trimmed = path.trim_end_matches(['/', '\\']); + match trimmed.rfind(['/', '\\']) { + Some(index) => (&trimmed[index + 1..], &trimmed[..index]), + None => (trimmed, ""), + } +} + +/// The name a container path is known by in Eclipse's Java Build Path page. +fn container_title(zh: bool, path: &str) -> String { + let (id, rest) = path.split_once('/').unwrap_or((path, "")); + let last = split_path(path).0; + match id { + "org.eclipse.jdt.junit.JUNIT_CONTAINER" => format!("JUnit {rest}"), + "org.eclipse.jdt.USER_LIBRARY" if !rest.is_empty() => rest.to_owned(), + "org.eclipse.jst.j2ee.internal.web.container" => { + local(zh, "Web App Libraries", "Web 应用库") + } + "org.eclipse.jst.j2ee.internal.module.container" => local(zh, "EAR Libraries", "EAR 库"), + "org.eclipse.jst.server.core.container" => { + format!("{}{last}", local(zh, "Server Runtime: ", "服务器运行时:")) + } + _ if !last.is_empty() => last.to_owned(), + _ => path.to_owned(), + } +} + +fn entry(zh: bool, kind: &str, element: &Element) -> Value { + let path = attribute(element, "path"); + let (title, detail) = match kind { + LIBRARY => (container_title(zh, path), path.to_owned()), + MODULE => (path.trim_start_matches('/').to_owned(), String::new()), + _ => { + let (name, parent) = split_path(path); + (name.to_owned(), parent.to_owned()) + } + }; + let mut value = json!({"kind":kind,"value":path,"title":truncate(&title,256)}); + if !detail.is_empty() && detail != title { + value["detail"] = json!(truncate(&detail, 1024)); + } + let mut attributes = Map::new(); + if nested(element, TEST).as_deref() == Some("true") { + attributes.insert(TEST.into(), json!(true)); + } + if kind != FOLDER && attribute(element, EXPORTED) == "true" { + attributes.insert(EXPORTED.into(), json!(true)); + } + if !attributes.is_empty() { + value["attributes"] = Value::Object(attributes); + } + value +} + +/// What one `.classpath` declares, in the terms of the page. +#[derive(Debug, Default)] +pub struct Classpath { + pub roots: Vec, + pub output: Option, + pub jre: Option, + pub dependencies: Vec, + /// Containers of every `con` entry but the JRE, offered to other modules. + pub containers: Vec, + /// False when an entry the contract cannot carry (a blank or overlong + /// path, too many entries) would be lost by a rewrite: the module is + /// then shown read-only. + pub editable: bool, +} + +fn parse(bytes: &[u8]) -> Result { + let document = Element::parse(bytes).map_err(|_| fail())?; + if document.name != "classpath" { + return Err(fail()); + } + Ok(document) +} + +pub fn read(zh: bool, bytes: &[u8]) -> Result { + let document = parse(bytes)?; + let mut classpath = Classpath { + editable: true, + ..Classpath::default() + }; + for element in document.children.iter().filter_map(XMLNode::as_element) { + let role = role(element); + let path = attribute(element, "path"); + if matches!(role, Role::Root | Role::Dependency(_)) + && (path.trim().is_empty() || path.len() > MAX_VALUE) + { + classpath.editable = false; + continue; + } + match role { + Role::Root => classpath.roots.push(entry(zh, FOLDER, element)), + Role::Jre => classpath.jre = Some(path.to_owned()), + Role::Output => classpath.output = Some(path.to_owned()), + Role::Dependency(kind) => { + if kind == LIBRARY && !classpath.containers.iter().any(|known| known == path) { + classpath.containers.push(path.to_owned()); + } + classpath.dependencies.push(entry(zh, kind, element)); + } + Role::Other => {} + } + } + for list in [&mut classpath.roots, &mut classpath.dependencies] { + if list.len() > MAX_ENTRIES { + list.truncate(MAX_ENTRIES); + classpath.editable = false; + } + } + Ok(classpath) +} + +/// Everything a module of the workspace may add besides files and folders. +pub struct Choices<'a> { + /// Container paths used anywhere in the workspace. + pub containers: &'a [String], + /// Eclipse project names of the workspace's modules. + pub modules: &'a [String], +} + +/// The fields of a writable Eclipse module, in Sources, Paths and +/// Dependencies sections. +pub fn fields( + zh: bool, + classpath: &Classpath, + name: &str, + choices: &Choices<'_>, + origin: &str, +) -> Vec { + let sources = local(zh, "Sources", "源"); + let paths = local(zh, "Paths", "路径"); + let dependencies = local(zh, "Dependencies", "依赖"); + let test = local(zh, "Test", "测试"); + let roots = json!(classpath.roots); + let mut jre_options = vec![ + json!({"value":JRE_CONTAINER,"title":local(zh,"Workspace default JRE","工作区默认 JRE")}), + ]; + for environment in EXECUTION_ENVIRONMENTS { + jre_options.push(json!({"value":format!("{JRE_CONTAINER}/{STANDARD_VM}/{environment}"),"title":environment})); + } + if let Some(jre) = &classpath.jre { + if !jre_options + .iter() + .any(|option| option["value"] == jre.as_str()) + { + jre_options.push(json!({"value":jre,"title":split_path(jre).0})); + } + } + let mut library_choices: Vec = Vec::new(); + for path in KNOWN_CONTAINERS + .iter() + .copied() + .chain(choices.containers.iter().map(String::as_str)) + { + if library_choices.len() < MAX_CHOICES + && path.len() <= MAX_VALUE + && !library_choices.iter().any(|choice| choice["value"] == path) + { + library_choices.push(json!({"value":path,"title":truncate(&container_title(zh,path),256),"detail":truncate(path,1024)})); + } + } + let module_choices: Vec = choices + .modules + .iter() + .filter(|module| module.as_str() != name) + .take(MAX_CHOICES) + .map(|module| json!({"value":format!("/{module}"),"title":truncate(module,256)})) + .collect(); + let mut kinds = vec![ + json!({"id":ARCHIVE,"title":local(zh,"JARs or ZIPs","JAR 或 ZIP"),"input":"file","extensions":["jar","zip"]}), + json!({"id":CLASSES,"title":local(zh,"Class folder","类文件夹"),"input":"directory"}), + json!({"id":LIBRARY,"title":local(zh,"Library","库"),"input":"choice","choices":library_choices}), + json!({"id":MODULE,"title":local(zh,"Module dependency","模块依赖"),"input":"choice","choices":module_choices}), + ]; + // Classpath variables are kept and reordered, but only Eclipse defines them. + if classpath + .dependencies + .iter() + .any(|entry| entry["kind"] == VARIABLE) + { + kinds.push(json!({"id":VARIABLE,"title":local(zh,"Classpath variable","类路径变量"),"input":"choice","choices":[]})); + } + let dependency_list = json!(classpath.dependencies); + vec![ + json!({"id":ROOTS_FIELD,"title":local(zh,"Source folders","源文件夹"),"section":sources,"kind":"entryList", + "description":local(zh,"Folders JDT compiles, in .classpath order. Mark a folder as Test to keep it out of the main classpath.","JDT 编译的文件夹,按 .classpath 顺序。标为“测试”的文件夹不进入主类路径。"), + "value":roots,"effectiveValue":roots,"effectiveSource":origin, + "entryKinds":[{"id":FOLDER,"title":local(zh,"Source folder","源文件夹"),"input":"directory"}], + "attributes":[{"id":TEST,"title":test,"kind":"boolean"}]}), + json!({"id":OUTPUT_FIELD,"title":local(zh,"Output folder","输出文件夹"),"section":paths,"kind":"text", + "description":local(zh,"Where JDT writes compiled classes, relative to the module. Empty uses bin.","JDT 写出编译结果的位置,相对于模块。留空使用 bin。"), + "value":classpath.output,"effectiveValue":classpath.output.clone().unwrap_or_else(||"bin".into()),"effectiveSource":origin}), + json!({"id":JRE_FIELD,"title":"JRE","section":dependencies.clone(),"kind":"enum", + "description":local(zh,"An execution environment compiles against the matching JDK of Toolchains.","执行环境对应“工具链”中匹配的 JDK。"), + "value":classpath.jre,"effectiveValue":classpath.jre,"effectiveSource":origin,"options":jre_options}), + json!({"id":DEPENDENCIES_FIELD,"title":dependencies,"section":local(zh,"Dependencies","依赖"),"kind":"entryList", + "description":local(zh,"Archives, class folders, libraries and other modules this module compiles against, in classpath order. Export makes an entry visible to modules that depend on this one.","此模块编译所依赖的归档、类文件夹、库和其他模块,按类路径顺序。“导出”让依赖本模块的模块也能看到该项。"), + "value":dependency_list,"effectiveValue":dependency_list,"effectiveSource":origin, + "entryKinds":kinds, + "attributes":[{"id":EXPORTED,"title":local(zh,"Export","导出"),"kind":"boolean"},{"id":TEST,"title":local(zh,"Test only","仅测试"),"kind":"boolean"}]}), + ] +} + +/// The dependencies of a Maven or Gradle module as JDT resolved them. A path +/// inside the workspace is shown relative to it: a class folder by its whole +/// relative path, since its last segment (`classes`) says little. +pub fn resolved_fields(zh: bool, root: &Path, paths: &[String], origin: &str) -> Vec { + let entries: Vec = paths + .iter() + .filter(|path| !path.trim().is_empty() && path.len() <= MAX_VALUE) + .take(MAX_ENTRIES) + .map(|path| { + let shown = crate::project_model::relative_inside(root, Path::new(path)) + .unwrap_or_else(|| path.clone()); + let kind = if archive(path) { ARCHIVE } else { CLASSES }; + let (title, detail) = if kind == ARCHIVE { + let (name, parent) = split_path(&shown); + (name.to_owned(), parent.to_owned()) + } else { + (shown.clone(), String::new()) + }; + let mut value = json!({"kind":kind,"value":path,"title":truncate(&title,256)}); + if !detail.is_empty() { + value["detail"] = json!(truncate(&detail, 1024)); + } + value + }) + .collect(); + let entries = json!(entries); + vec![ + json!({"id":DEPENDENCIES_FIELD,"title":local(zh,"Dependencies","依赖"),"kind":"entryList", + "description":local(zh,"Resolved by the build tool, including test dependencies. Change them in the build file.","由构建工具解析,包含测试依赖。请在构建文件中修改。"), + "value":entries,"effectiveValue":entries,"effectiveSource":origin, + "entryKinds":[{"id":ARCHIVE,"title":local(zh,"JARs or ZIPs","JAR 或 ZIP"),"input":"file"},{"id":CLASSES,"title":local(zh,"Class folder","类文件夹"),"input":"directory"}]}), + ] +} + +/// How a picked path is stored: relative to the module inside it, otherwise +/// absolute with forward slashes as Eclipse writes it. A value that is not an +/// absolute path is already in the file's terms. +fn stored_path(module: &Path, value: &str, inside_only: bool) -> Result { + let path = Path::new(value); + if !path.is_absolute() { + return Ok(value.to_owned()); + } + let resolved = dunce::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()); + let canonical = dunce::canonicalize(module).unwrap_or_else(|_| module.to_path_buf()); + // Compare as given and as resolved: a picked path that does not exist + // yet cannot be resolved, and a module may sit behind a link. + let relative = path + .strip_prefix(module) + .ok() + .or_else(|| resolved.strip_prefix(&canonical).ok()); + if let Some(relative) = relative { + let parts: Vec = relative + .components() + .map(|part| part.as_os_str().to_string_lossy().into_owned()) + .collect(); + if parts.is_empty() { + return Err(outside()); + } + return Ok(parts.join("/")); + } + if inside_only { + return Err(outside()); + } + Ok(resolved.to_string_lossy().replace('\\', "/")) +} + +fn flag(entry: &Value, id: &str) -> Result { + match entry + .get("attributes") + .and_then(|attributes| attributes.get(id)) + { + None | Some(Value::Null) => Ok(false), + Some(Value::Bool(on)) => Ok(*on), + Some(_) => Err(fail()), + } +} + +/// Takes the unused existing entry of `kind` at `path`, or makes a new one. +fn take(pool: &mut Vec, kind: &str, path: &str) -> Element { + if let Some(index) = pool.iter().position(|element| { + attribute(element, "kind") == kind && attribute(element, "path") == path + }) { + return pool.remove(index); + } + let mut element = Element::new("classpathentry"); + element.attributes.insert("kind".into(), kind.into()); + element.attributes.insert("path".into(), path.into()); + element +} + +fn list(values: &Map, id: &str) -> Result>, FunctionError> { + match values.get(id) { + None | Some(Value::Null) => Ok(None), + Some(Value::Array(entries)) if entries.len() <= MAX_ENTRIES => Ok(Some(entries.clone())), + Some(_) => Err(fail()), + } +} + +/// Applies the confirmed fields of a module to its `.classpath`. +pub fn edit( + bytes: &[u8], + module: &Path, + values: &Map, +) -> Result, FunctionError> { + let mut document = parse(bytes)?; + for id in values.keys() { + if ![ROOTS_FIELD, OUTPUT_FIELD, JRE_FIELD, DEPENDENCIES_FIELD].contains(&id.as_str()) { + return Err(fail()); + } + } + let managed = + |element: &Element| matches!(role(element), Role::Root | Role::Jre | Role::Dependency(_)); + let current: Vec = document + .children + .iter() + .filter_map(XMLNode::as_element) + .filter(|element| managed(element)) + .cloned() + .collect(); + let mut pool = current.clone(); + let mut next = Vec::new(); + + match list(values, ROOTS_FIELD)? { + Some(entries) => { + for entry in entries { + if entry["kind"] != FOLDER { + return Err(fail()); + } + let value = entry["value"].as_str().ok_or_else(fail)?; + let path = if pool + .iter() + .any(|e| role(e) == Role::Root && attribute(e, "path") == value) + { + value.to_owned() + } else { + stored_path(module, value, true)? + }; + let mut element = take(&mut pool, "src", &path); + set_nested(&mut element, TEST, flag(&entry, TEST)?.then_some("true")); + next.push(element); + } + } + None => next.extend(current.iter().filter(|e| role(e) == Role::Root).cloned()), + } + match values.get(JRE_FIELD) { + Some(Value::String(path)) + if path == JRE_CONTAINER || path.starts_with(&format!("{JRE_CONTAINER}/")) => + { + let mut element = match pool.iter().position(|e| role(e) == Role::Jre) { + Some(index) => pool.remove(index), + None => take(&mut pool, "con", path), + }; + element.attributes.insert("path".into(), path.clone()); + next.push(element); + } + Some(Value::Null) => {} + Some(_) => return Err(fail()), + None => next.extend(current.iter().filter(|e| role(e) == Role::Jre).cloned()), + } + match list(values, DEPENDENCIES_FIELD)? { + Some(entries) => { + for entry in entries { + let kind = entry["kind"].as_str().ok_or_else(fail)?; + let native = native_kind(kind) + .filter(|_| kind != FOLDER) + .ok_or_else(fail)?; + let value = entry["value"].as_str().ok_or_else(fail)?; + let known = pool + .iter() + .any(|e| attribute(e, "kind") == native && attribute(e, "path") == value); + let path = match kind { + ARCHIVE | CLASSES if !known => stored_path(module, value, false)?, + MODULE if !value.starts_with('/') || value.len() < 2 => return Err(fail()), + LIBRARY + if value == JRE_CONTAINER + || value.starts_with(&format!("{JRE_CONTAINER}/")) => + { + return Err(fail()) + } + VARIABLE if !known => return Err(fail()), + _ => value.to_owned(), + }; + let created = !pool + .iter() + .any(|e| attribute(e, "kind") == native && attribute(e, "path") == path); + let mut element = take(&mut pool, native, &path); + if created && kind == MODULE { + element + .attributes + .insert("combineaccessrules".into(), "false".into()); + } + if flag(&entry, EXPORTED)? { + element.attributes.insert(EXPORTED.into(), "true".into()); + } else { + element.attributes.remove(EXPORTED); + } + set_nested(&mut element, TEST, flag(&entry, TEST)?.then_some("true")); + next.push(element); + } + } + None => next.extend( + current + .iter() + .filter(|e| matches!(role(e), Role::Dependency(_))) + .cloned(), + ), + } + + // The new entries take the old ones' places in order, so comments + // between entries stay near them; extra entries follow the last place. + let mut next = next.into_iter(); + let last = document + .children + .iter() + .rposition(|node| node.as_element().is_some_and(&managed)); + let mut children = Vec::with_capacity(document.children.len()); + for (index, node) in std::mem::take(&mut document.children) + .into_iter() + .enumerate() + { + let slot = node.as_element().is_some_and(&managed); + let output = node.as_element().is_some_and(|e| role(e) == Role::Output); + if output && last.is_none() { + children.extend(next.by_ref().map(XMLNode::Element)); + } + if slot { + if let Some(element) = next.next() { + children.push(XMLNode::Element(element)); + } + } else { + children.push(node); + } + if Some(index) == last { + children.extend(next.by_ref().map(XMLNode::Element)); + } + } + children.extend(next.map(XMLNode::Element)); + document.children = children; + + match values.get(OUTPUT_FIELD) { + None => {} + Some(Value::String(path)) if !path.trim().is_empty() => { + let path = stored_path(module, path.trim(), true)?; + match document + .children + .iter_mut() + .filter_map(XMLNode::as_mut_element) + .find(|e| role(e) == Role::Output) + { + Some(element) => { + element.attributes.insert("path".into(), path); + } + None => { + let mut element = Element::new("classpathentry"); + element.attributes.insert("kind".into(), "output".into()); + element.attributes.insert("path".into(), path); + document.children.push(XMLNode::Element(element)); + } + } + } + Some(Value::String(_)) | Some(Value::Null) => document + .children + .retain(|node| !node.as_element().is_some_and(|e| role(e) == Role::Output)), + Some(_) => return Err(fail()), + } + crate::project_settings::write_classpath(bytes, &document) +} + +/// The Eclipse project name of a module: `.project`'s name, else its folder. +pub fn project_name(module: &Path) -> String { + let folder = module + .file_name() + .and_then(|name| name.to_str()) + .unwrap_or("Java") + .to_owned(); + let Some(bytes) = crate::project_model::read_bounded(&module.join(".project")) else { + return folder; + }; + Element::parse(bytes.as_slice()) + .ok() + .and_then(|document| { + document + .get_child("name") + .and_then(|name| name.get_text()) + .map(|name| name.trim().to_owned()) + }) + .filter(|name| !name.is_empty() && name.len() < MAX_VALUE) + .unwrap_or(folder) +} + +#[cfg(test)] +mod tests { + use super::*; + + const CLASSPATH: &str = r#" + + + + + + + + + + + + +"#; + + fn values(value: Value) -> Map { + value.as_object().unwrap().clone() + } + + #[test] + fn a_classpath_reads_as_source_folders_output_jre_and_dependencies() { + let classpath = read(false, CLASSPATH.as_bytes()).unwrap(); + assert!(classpath.editable); + assert_eq!( + json!(classpath.roots), + json!([{"kind":"folder","value":"src","title":"src"},{"kind":"folder","value":"test","title":"test","attributes":{"test":true}}]) + ); + assert_eq!(classpath.output.as_deref(), Some("bin")); + assert!(classpath.jre.as_deref().unwrap().ends_with("JavaSE-17")); + let kinds: Vec<_> = classpath + .dependencies + .iter() + .map(|entry| { + format!( + "{}:{}", + entry["kind"].as_str().unwrap(), + entry["title"].as_str().unwrap() + ) + }) + .collect(); + assert_eq!( + kinds, + [ + "archive:core.jar", + "library:Shared Libs", + "module:common", + "variable:tools.jar" + ] + ); + assert_eq!( + classpath.dependencies[1]["attributes"], + json!({"exported":true}) + ); + assert_eq!( + classpath.containers, + ["org.eclipse.jdt.USER_LIBRARY/Shared Libs"] + ); + let fields = fields( + false, + &classpath, + "app", + &Choices { + containers: &classpath.containers, + modules: &["app".into(), "common".into(), "web".into()], + }, + "app/.classpath", + ); + let dependencies = &fields[3]; + let modules = &dependencies["entryKinds"][3]["choices"]; + assert_eq!( + modules, + &json!([{"value":"/common","title":"common"},{"value":"/web","title":"web"}]) + ); + assert_eq!(dependencies["entryKinds"][4]["id"], VARIABLE); + } + + #[test] + fn an_edit_reorders_flags_and_adds_entries_keeping_what_the_page_does_not_show() { + let module = std::env::temp_dir(); + let picked = module.join("vendor").join("extra.jar"); + let edited = edit( + CLASSPATH.as_bytes(), + &module, + &values(json!({ + "roots":[{"kind":"folder","value":"test","attributes":{"test":true}},{"kind":"folder","value":"src","attributes":{"test":true}}], + "jre":"org.eclipse.jdt.launching.JRE_CONTAINER", + "dependencies":[ + {"kind":"module","value":"/common","attributes":{"exported":true}}, + {"kind":"archive","value":"lib/core.jar","attributes":{"test":true}}, + {"kind":"variable","value":"TOOLS_HOME/lib/tools.jar"}, + {"kind":"archive","value":picked.to_str().unwrap()}, + {"kind":"library","value":"org.eclipse.jdt.junit.JUNIT_CONTAINER/5"}, + {"kind":"module","value":"/web"} + ], + "output":"build/classes" + })), + ) + .unwrap(); + let text = String::from_utf8(edited.clone()).unwrap(); + for kept in [ + "", + "", + "core-sources.jar", + "javadoc_location", + "output=\"bin-test\"", + ] { + assert!(text.contains(kept), "{kept}: {text}"); + } + assert!(!text.contains("Shared Libs"), "{text}"); + let classpath = read(false, &edited).unwrap(); + let roots: Vec<_> = classpath + .roots + .iter() + .map(|e| (e["value"].as_str().unwrap(), flag(e, TEST).unwrap())) + .collect(); + assert_eq!(roots, [("test", true), ("src", true)]); + assert_eq!(classpath.jre.as_deref(), Some(JRE_CONTAINER)); + assert_eq!(classpath.output.as_deref(), Some("build/classes")); + let dependencies: Vec<_> = classpath + .dependencies + .iter() + .map(|e| { + ( + e["value"].as_str().unwrap().to_owned(), + flag(e, EXPORTED).unwrap(), + flag(e, TEST).unwrap(), + ) + }) + .collect(); + let extra = stored_path(&module, picked.to_str().unwrap(), false).unwrap(); + assert_eq!(extra, "vendor/extra.jar"); + assert_eq!( + dependencies, + [ + ("/common".to_owned(), true, false), + ("lib/core.jar".to_owned(), false, true), + ("TOOLS_HOME/lib/tools.jar".to_owned(), false, false), + (extra, false, false), + ( + "org.eclipse.jdt.junit.JUNIT_CONTAINER/5".to_owned(), + false, + false + ), + ("/web".to_owned(), false, false), + ] + ); + assert!( + text.contains(r#"combineaccessrules="false" kind="src" path="/web""#) + || text.contains("path=\"/web\""), + "{text}" + ); + // Fields the edit does not name stay as they are. + let unchanged = edit(&edited, &module, &values(json!({"output":null}))).unwrap(); + let after = read(false, &unchanged).unwrap(); + assert_eq!(after.output, None); + assert_eq!(json!(after.dependencies), json!(classpath.dependencies)); + assert_eq!(json!(after.roots), json!(classpath.roots)); + } + + #[test] + fn an_edit_refuses_what_the_page_never_offers() { + let module = std::env::temp_dir().join("module"); + let outside = std::env::temp_dir().join("elsewhere"); + for bad in [ + json!({"roots":[{"kind":"folder","value":outside.to_str().unwrap()}]}), + json!({"dependencies":[{"kind":"variable","value":"NEW_VAR/x.jar"}]}), + json!({"dependencies":[{"kind":"library","value":JRE_CONTAINER}]}), + json!({"dependencies":[{"kind":"folder","value":"src"}]}), + json!({"jre":"org.example.OTHER"}), + json!({"unknown":true}), + ] { + assert!( + edit(CLASSPATH.as_bytes(), &module, &values(bad.clone())).is_err(), + "{bad}" + ); + } + } + + #[test] + fn an_entry_the_contract_cannot_carry_makes_the_module_read_only() { + let classpath = read(false, br#""#).unwrap(); + assert!(!classpath.editable); + assert_eq!(classpath.dependencies.len(), 1); + } + + #[test] + fn resolved_dependencies_are_archives_and_class_folders() { + let root = std::env::temp_dir().join("workspace"); + let classes = root.join("core").join("target").join("classes"); + let fields = resolved_fields( + true, + &root, + &[ + "/repo/a/1/a-1.jar".into(), + classes.to_string_lossy().into_owned(), + String::new(), + ], + "pom.xml", + ); + assert_eq!( + fields[0]["value"], + json!([{"kind":"archive","value":"/repo/a/1/a-1.jar","title":"a-1.jar","detail":"/repo/a/1"},{"kind":"classes","value":classes.to_string_lossy(),"title":"core/target/classes"}]) + ); + } +} diff --git a/backend/src/project_settings.rs b/backend/src/project_settings.rs index 38042d4..a8bd0dd 100644 --- a/backend/src/project_settings.rs +++ b/backend/src/project_settings.rs @@ -212,6 +212,8 @@ impl ProjectSettings { crate::library_settings::SOURCE_PATHS_FACT ]); let mut facts = Vec::new(); + // Maven and Gradle projects: shown read-only on the structure page. + let mut managed_projects = Vec::new(); for entry in projects.as_array().ok_or_else(fail)? { context.check_cancelled()?; let value = entry.as_str().ok_or_else(fail)?; @@ -232,9 +234,11 @@ impl ProjectSettings { }); if !managed { facts.push((path, settings)); + } else if libraries { + managed_projects.push((path, value.to_owned())); } } - if facts.len() > 1023 { + if facts.len() + managed_projects.len() > 1023 { return Err(fail()); } // Global defaults come from the native global preference file, or @@ -309,13 +313,14 @@ impl ProjectSettings { paths.insert(path); sources.push(json!({"id":id,"group":"project","title":local(zh,"Project defaults","项目默认设置"),"path":PREFS,"revision":revision,"writable":true,"fields":compiler_fields(zh,&raw,&effective,false)})); } + let mut modules = Vec::new(); for (path, fact) in facts { + if libraries && read(&path.join(".classpath"))?.1 != "missing" { + modules.push(path); + continue; + } let source_path = if libraries { - if read(&path.join(".classpath"))?.1 != "missing" { - path.join(".classpath") - } else { - root.join(SETTINGS) - } + root.join(SETTINGS) } else { path.join(PREFS) }; @@ -331,14 +336,7 @@ impl ProjectSettings { let id = format!("source{:x}", Sha256::digest(rel.as_bytes())); let (bytes, revision) = read(&source_path)?; 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 { - page.settings_fields(&fact, library_input(&native_json(&bytes)?)) - } + page.settings_fields(&fact, library_input(&native_json(&bytes)?)) } else { compiler_fields(zh, &properties(&bytes)?, &fact, true) }; @@ -355,16 +353,39 @@ 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 module_sources = if libraries { + self.module_sources( + context, + zh, + &root, + &modules, + &managed_projects, + &mut bindings, + &mut paths, + )? + } else { + Vec::new() + }; let mut groups = if libraries { - vec![ - json!({"id":"libraries","title":local(zh,"Referenced libraries","引用的库"),"layout":"form"}), - ] + let mut groups = Vec::new(); + if !module_sources.is_empty() { + groups.push( + json!({"id":"modules","title":local(zh,"Modules","模块"),"layout":"sidebar"}), + ); + } + if module_sources.is_empty() + || sources.iter().any(|source| source["group"] == "libraries") + { + groups.push(json!({"id":"libraries","title":local(zh,"Referenced libraries","引用的库"),"layout":"form"})); + } + groups } 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"}), ] }; + sources.splice(0..0, module_sources); if let Some(page) = &page { let taken: Vec = paths.iter().cloned().collect(); let mut model_sources: Vec<(PathBuf, Value)> = Vec::new(); @@ -410,9 +431,131 @@ impl ProjectSettings { } 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":groups,"sources":sources}), + json!({"format":"litheSettingsSources","version":0,"title":if libraries{local(zh,"Java Project Structure","Java 项目结构")}else{local(zh,"Java Compiler","Java 编译器")},"groups":groups,"sources":sources}), ) } + /// The modules of the structure page, parents before children: Eclipse + /// projects edit their `.classpath`; Maven and Gradle projects show the + /// classpath JDT resolved, read-only. + #[allow(clippy::too_many_arguments)] + fn module_sources( + &self, + context: &Context, + zh: bool, + root: &Path, + eclipse: &[PathBuf], + managed: &[(PathBuf, String)], + bindings: &mut BTreeMap, + paths: &mut BTreeSet, + ) -> Result, FunctionError> { + use crate::module_structure as modules; + let mut classpaths = Vec::new(); + let mut containers = Vec::new(); + let mut names = Vec::new(); + for project in eclipse { + let file = project.join(".classpath"); + let (bytes, revision) = read(&file)?; + let classpath = modules::read(zh, &bytes)?; + for container in &classpath.containers { + if !containers.contains(container) { + containers.push(container.clone()); + } + } + let name = modules::project_name(project); + names.push(name.clone()); + classpaths.push((project.clone(), file, revision, classpath, name)); + } + // (folder, source file, source) in folder order, so that an + // enclosing module comes before the modules inside it. + let mut rows: Vec<(PathBuf, PathBuf, Value)> = Vec::new(); + for (project, file, revision, classpath, name) in classpaths { + let rel = project_model::relative_inside(root, &file).ok_or_else(fail)?; + let choices = modules::Choices { + containers: &containers, + modules: &names, + }; + let fields = modules::fields(zh, &classpath, &name, &choices, &rel); + let id = format!("source{:x}", Sha256::digest(rel.as_bytes())); + if classpath.editable { + bindings.insert(id.clone(), file.clone()); + } + rows.push((project, file, json!({"id":id,"group":"modules","title":name,"path":rel,"revision":revision,"writable":classpath.editable,"fields":fields}))); + } + let mut unavailable = 0; + for (project, uri) in managed { + context.check_cancelled()?; + let Some(file) = ["pom.xml", "build.gradle.kts", "build.gradle"] + .iter() + .map(|name| project.join(name)) + .find(|file| file.is_file()) + else { + continue; + }; + // JDT reads the options from a JSON string, as vscode-java sends them. + let resolved = command( + context, + "java.project.getClasspaths", + json!([uri, r#"{"scope":"test"}"#]), + ); + let Some(resolved) = resolved.ok().and_then(|value| { + value["classpaths"].as_array().map(|items| { + items + .iter() + .filter_map(Value::as_str) + .map(str::to_owned) + .collect::>() + }) + }) else { + unavailable += 1; + continue; + }; + let rel = project_model::relative_inside(root, &file).ok_or_else(fail)?; + let (_, revision) = read(&file)?; + let title = project + .file_name() + .and_then(|n| n.to_str()) + .unwrap_or("Java") + .to_owned(); + let id = format!("managed{:x}", Sha256::digest(rel.as_bytes())); + rows.push((project.clone(), file, json!({"id":id,"group":"modules","title":title,"path":rel,"revision":revision,"writable":false,"fields":modules::resolved_fields(zh,root,&resolved,&rel)}))); + } + if unavailable > 0 { + // A module JDT could not resolve is left out; the page still shows the others. + let _ = context.diagnostics().degraded( + context.function_id(), + "java.moduleSettings.classpathUnavailable", + Some(unavailable), + ); + } + rows.sort_by(|a, b| a.0.cmp(&b.0)); + let mut depths: Vec<(PathBuf, String, usize)> = Vec::new(); + let mut sources = Vec::new(); + for (project, file, mut source) in rows { + if !paths.insert(file) { + continue; + } + // The nearest enclosing module is the parent, within the + // contract's eight levels. + if let Some((_, parent, depth)) = depths + .iter() + .filter(|(folder, _, depth)| { + project != *folder && project.starts_with(folder) && *depth < 7 + }) + .max_by_key(|(folder, _, _)| folder.components().count()) + { + source["parent"] = json!(parent); + depths.push(( + project, + source["id"].as_str().unwrap_or("").to_owned(), + depth + 1, + )); + } else { + depths.push((project, source["id"].as_str().unwrap_or("").to_owned(), 0)); + } + sources.push(source); + } + Ok(sources) + } /// Prepares only the confirmed native source; publication belongs to the host. pub fn edit( &self, @@ -447,10 +590,7 @@ impl ProjectSettings { } let values = params["values"].as_object().ok_or_else(fail)?; let replacement = if path.ends_with(".classpath") { - match values.get("libraries") { - Some(libraries) => edit_classpath(&bytes, libraries)?, - None => bytes.clone(), - } + crate::module_structure::edit(&bytes, parent, values)? } else if path.ends_with(SETTINGS) { let workspace = context.workspace_context().ok_or_else(fail)?; let options = session.model_options(workspace.context_id()); @@ -615,55 +755,13 @@ fn edit_json(bytes: &[u8], key: &str, libraries: &Value) -> Result, Func } Ok(root.to_string().into_bytes()) } -fn classpath_libraries(bytes: &[u8]) -> Result, FunctionError> { - let doc = xmltree::Element::parse(bytes).map_err(|_| fail())?; - if doc.name != "classpath" { - return Err(fail()); - } - Ok(doc - .children - .iter() - .filter_map(xmltree::XMLNode::as_element) - .filter(|e| { - e.name == "classpathentry" && e.attributes.get("kind").is_some_and(|v| v == "lib") - }) - .filter_map(|e| e.attributes.get("path").cloned()) - .collect()) -} -fn edit_classpath(bytes: &[u8], libraries: &Value) -> Result, FunctionError> { - let mut doc = xmltree::Element::parse(bytes).map_err(|_| fail())?; - if doc.name != "classpath" { - return Err(fail()); - } - let paths = libraries - .as_array() - .map(|v| { - v.iter() - .map(|p| p.as_str().map(str::to_owned).ok_or_else(fail)) - .collect::, _>>() - }) - .transpose()? - .unwrap_or_default(); - let mut retained = BTreeSet::new(); - doc.children.retain(|node| match node.as_element() { - Some(e) - if e.name == "classpathentry" - && e.attributes.get("kind").is_some_and(|v| v == "lib") => - { - e.attributes - .get("path") - .is_some_and(|path| paths.contains(path) && retained.insert(path.clone())) - } - _ => true, - }); - for path in paths.difference(&retained) { - let mut entry = xmltree::Element::new("classpathentry"); - entry.attributes.insert("kind".into(), "lib".into()); - entry.attributes.insert("path".into(), path.clone()); - doc.children.push(xmltree::XMLNode::Element(entry)); - } - // Preserve nodes outside the root too, including comments and processing - // instructions. xmltree validates each node before this serialization. +/// Serializes an edited `.classpath` root in place of the original one, +/// keeping the nodes outside the root, including comments and processing +/// instructions. xmltree validates each node before this serialization. +pub(crate) fn write_classpath( + bytes: &[u8], + doc: &xmltree::Element, +) -> Result, FunctionError> { let nodes = xmltree::Element::parse_all(bytes).map_err(|_| fail())?; let mut out = b"\n".to_vec(); for node in nodes { @@ -904,28 +1002,6 @@ mod tests { assert!(native_json(&reset).unwrap().get(LIBRARY_KEY).is_none()); } #[test] - fn eclipse_classpath_edits_preserve_containers_source_roots_attachments_and_comments() { - let source=br#""#; - let updated = edit_classpath(source, &json!(["keep.jar", "External Library.jar"])).unwrap(); - let text = String::from_utf8_lossy(&updated); - for item in [ - "", - "", - "", - "keep-sources.jar", - "javadoc_location", - "JRE_CONTAINER", - "kind=\"src\"", - "kind=\"output\"", - ] { - assert!(text.contains(item), "{item}: {text}"); - } - assert_eq!( - classpath_libraries(&updated).unwrap(), - vec!["keep.jar", "External Library.jar"] - ); - } - #[test] fn complete_configuration_keeps_runtime_and_imports_when_native_keys_are_added() { let directory = TestDirectory::new(); let root = &directory.0; diff --git a/compiler-host.json b/compiler-host.json index 0d5167c..07e9e3d 100644 --- a/compiler-host.json +++ b/compiler-host.json @@ -1,6 +1,6 @@ { "repository": "https://github.com/1lck/Lithe-IDEA", - "revision": "3be45fbb7cecedc68c48446f9d0065f98c576f44", - "coreRevision": "10fd6f8ae847868a7d5255195bf1a5b9ef84844f", + "revision": "81d01a25bbecc24292aaa3ef0454c19d7ea53e36", + "coreRevision": "788e61eb62177dff4cb0bfe11a48eed0a1083fb3", "package": "io.github.lithe-idea.java-support" } diff --git a/docs/assets/module-structure/modules-dependencies-en-dark.png b/docs/assets/module-structure/modules-dependencies-en-dark.png new file mode 100644 index 0000000..1b7c1a5 Binary files /dev/null and b/docs/assets/module-structure/modules-dependencies-en-dark.png differ diff --git a/docs/assets/module-structure/modules-dependencies-zh-Hans-light.png b/docs/assets/module-structure/modules-dependencies-zh-Hans-light.png new file mode 100644 index 0000000..ab26673 Binary files /dev/null and b/docs/assets/module-structure/modules-dependencies-zh-Hans-light.png differ diff --git a/docs/assets/module-structure/modules-maven-zh-Hans-dark.png b/docs/assets/module-structure/modules-maven-zh-Hans-dark.png new file mode 100644 index 0000000..291534a Binary files /dev/null and b/docs/assets/module-structure/modules-maven-zh-Hans-dark.png differ diff --git a/docs/assets/module-structure/modules-zh-Hans-light.png b/docs/assets/module-structure/modules-zh-Hans-light.png new file mode 100644 index 0000000..ce19491 Binary files /dev/null and b/docs/assets/module-structure/modules-zh-Hans-light.png differ diff --git a/docs/feature-matrix.md b/docs/feature-matrix.md index 9695600..ffc47e9 100644 --- a/docs/feature-matrix.md +++ b/docs/feature-matrix.md @@ -40,3 +40,14 @@ 2026-11-17:macOS arm64 本机自动化通过(三类工程编译成功,关闭识别后均失败;插件包、JDT LS 安装与项目文件不变)。Windows、Linux 结果由 CI 与后续实机验证补充。 + +## 项目结构:模块、标签页与依赖(4.0.0) + +| 能力 | macOS | Windows | Linux | 证据 | +| --- | --- | --- | --- | --- | +| 模块侧栏:Eclipse 工程可编辑,Maven/Gradle 模块只读(JDT 解析的类路径),按文件夹嵌套 | implemented / verified | implemented / pending | implemented / pending | `backend/src/module_structure.rs`、`backend/src/project_settings.rs`;`scripts/compiler/test-module-structure.mjs` | +| 源文件夹(测试标记)、输出文件夹、JRE 执行环境写回 `.classpath` | implemented / verified | implemented / pending | implemented / pending | 单元测试 `module_structure::tests`;`test-module-structure.mjs` 保存后 JDT 编译到新输出文件夹 | +| 依赖:JAR/ZIP、类文件夹、库容器、模块依赖,导出与仅测试,保留源码附件、注释和未显示条目 | implemented / verified | implemented / pending | implemented / pending | 同上;`test-live.mjs` 的 Eclipse 模式经依赖列表添加外部 JAR 并编译运行 | +| 项目结构页无头截图 | implemented / verified | — | — | `scripts/compiler/visual.mjs` 渲染真实投影(中英、明暗),截图见 `docs/assets/module-structure/` | + +2026-11-17:macOS arm64 本机用 JDT LS 1.61.0 自动化通过。需要宿主声明 `sourceSettings` 1([1lck/Lithe-IDEA#2087](https://github.com/1lck/Lithe-IDEA/pull/2087));原生文件选择器、Windows 与 Linux 结果由实机验收和 CI 补充。 diff --git a/docs/module-structure.md b/docs/module-structure.md new file mode 100644 index 0000000..2529f34 --- /dev/null +++ b/docs/module-structure.md @@ -0,0 +1,44 @@ +# Java 项目结构(4.0.0) + +对标 IntelliJ IDEA 的“项目结构 → 模块”:在“语言与框架 → Java”页点击“读取项目结构”,左侧列出工作区里的每个模块,右侧按“源 / 路径 / 依赖”三个标签页逐个配置([1lck/Lithe-IDEA#2086](https://github.com/1lck/Lithe-IDEA/issues/2086))。 + +| 源文件夹 | 依赖 | +| --- | --- | +| ![源文件夹](assets/module-structure/modules-zh-Hans-light.png) | ![依赖](assets/module-structure/modules-dependencies-zh-Hans-light.png) | +| Dependencies (English, dark) | Maven 模块(只读) | +| ![Dependencies](assets/module-structure/modules-dependencies-en-dark.png) | ![Maven 模块](assets/module-structure/modules-maven-zh-Hans-dark.png) | + +## 哪些模块可以编辑 + +| 模块 | 来源 | 能改什么 | +| --- | --- | --- | +| Eclipse 工程(有 `.classpath`) | 模块自己的 `.classpath` | 源文件夹(可标“测试”)、输出文件夹、JRE、依赖(JAR/ZIP、类文件夹、库容器、其他模块),每项可标“导出”“仅测试” | +| Maven、Gradle 模块 | `pom.xml` / `build.gradle(.kts)` | 只读,显示 JDT 解析出的完整类路径(含测试依赖),请在构建文件里修改 | +| 没有 `.classpath` 的普通文件夹 | `.vscode/settings.json` | 仍在“引用的库”分组里编辑引用的 JAR 和源码文件夹 | + +IntelliJ IDEA 工程、Eclipse 容器的解析结果仍在只读的“工程模型”分组里,见 [project-models.md](project-models.md)。 + +## 依赖怎么添加 + +“+”菜单按种类添加: + +- **JAR 或 ZIP**、**类文件夹**:打开系统文件选择器。选中的路径在模块文件夹内时写成相对路径,否则写成正斜杠的绝对路径(Eclipse 的写法)。 +- **库**:从 JUnit 4/5、Web App Libraries、EAR Libraries,以及工作区其他模块已经用到的容器(用户库、Server Runtime 等)中选择。 +- **模块依赖**:从工作区的其他 Eclipse 模块中选择,写成 `/项目名`,新加的项带 `combineaccessrules="false"`,与 Eclipse 一致。 +- **类路径变量**:只保留和排序文件里已有的变量项;变量本身由 Eclipse 定义,这里不新增。 + +JRE 下拉框可选“工作区默认 JRE”或 JavaSE-1.8/11/17/21/25 执行环境,执行环境对应“工具链”里匹配的 JDK。 + +## 保存时保留什么 + +只有点击“保存”才写文件,外部修改会要求重新读取。保存只改页面管理的条目,按种类和路径匹配已有条目,所以: + +- 源码附件(`sourcepath`)、Javadoc 位置、访问规则等页面不显示的属性原样保留; +- 注释和页面不显示的条目留在原位置,新条目按页面顺序依次占用原来的位置; +- 输出文件夹留空表示删除 `output` 条目,JDT 使用默认的 `bin`。 + +条目路径为空、超过 4096 字节或单个列表超过 256 项的 `.classpath` 无法完整显示,这类模块只读,避免保存时丢项。 + +## 验证 + +`scripts/compiler/test-module-structure.mjs` 用真实 JDT LS 打开两个 Eclipse 工程和一个 Maven 模块:检查读取页面不写任何项目文件、Maven 模块只读并带解析出的类路径;再通过页面添加模块依赖(导出)、工作区外的 JAR、新的源文件夹并修改输出文件夹,确认写回的 `.classpath` 保留注释和源码附件,JDT 随后编译成功,class 落在新的输出文件夹;插件包和 JDT LS 安装不变。`scripts/compiler/visual.mjs` 用宿主 Viva 无头窗口渲染同一份真实投影(中英、明暗)。 diff --git a/docs/native-settings.md b/docs/native-settings.md index e5bcc32..f4633f4 100644 --- a/docs/native-settings.md +++ b/docs/native-settings.md @@ -4,7 +4,7 @@ 管理 JDK:在“构建、执行、部署”的工具链区使用“全局默认”,选择自动识别结果,或从磁盘添加多个 JDK,核对版本后保存;无需先打开项目。个别项目可切换到“当前项目”单独覆盖。已启动的进程需重启后采用新版本。JDK 是运行编译器的程序;目标字节码决定生成的 class 版本,两者分别设置。构建工具自己的显式 Java 环境或工具链配置仍按该工具的规则生效。 -本地 JAR 入口在插件的语言/构建工具设置页,点击“读取本地 JAR 依赖”,选择目标模块并浏览文件后保存。每行一个路径,空格属于路径内容。JDT 的公开项目设置提供模块与实际值。JSONC、XML 和 properties 编辑器保留无关字段及注释;已有 JAR 排除和源码附件不被覆盖。Maven/Gradle 管理的项目使用各自插件的编译设置。 +项目结构入口在插件的语言设置页,点击“读取项目结构”:Eclipse 工程按模块编辑源文件夹、输出文件夹、JRE 和依赖并写回 `.classpath`,Maven/Gradle 模块只读,详见 [module-structure.md](module-structure.md);没有 `.classpath` 的普通文件夹在“引用的库”分组中选择文件并保存。每行一个路径,空格属于路径内容。JDT 的公开项目设置提供模块与实际值。JSONC、XML 和 properties 编辑器保留无关字段及注释;已有 JAR 排除和源码附件不被覆盖。Maven/Gradle 管理的项目使用各自插件的编译设置。 没有 Maven/Gradle 的旧式 Web、Eclipse WTP 和 IntelliJ IDEA 项目,插件会只读识别其工程模型并在内存中补全类路径,“Java 库”页的“工程模型”分组列出识别结果,详见 [project-models.md](project-models.md)。 @@ -12,6 +12,6 @@ ## Compatibility -This version requires a desktop host advertising `sourceSettings: 0`. Older hosts retain their previous compatible plugin version. Read compiler settings under Build, Execution, Deployment; read local JAR dependencies on the language/build-system page. Save changes only the listed native sources and rejects a changed baseline. JDK selection and target bytecode are separate settings. +This version requires a desktop host advertising `sourceSettings: 1`. Older hosts retain their previous compatible plugin version. Read compiler settings under Build, Execution, Deployment; read the project structure on the language page. Save changes only the listed native sources and rejects a changed baseline. JDK selection and target bytecode are separate settings. Tests in `scripts/compiler/` execute the real upstream engine, inspect class-file major versions and run code using an external JAR. HTML and JUnit timing reports are written to `.artifacts/test-stability/`; tests own and clean their temporary workspaces and processes. diff --git a/docs/releases/v4.0.0.md b/docs/releases/v4.0.0.md new file mode 100644 index 0000000..69add61 --- /dev/null +++ b/docs/releases/v4.0.0.md @@ -0,0 +1,39 @@ +# Java 4.0.0 + +## 中文 + +“Java 库”页升级为“Java 项目结构”,对标 IntelliJ IDEA 的“项目结构 → 模块”:左侧是模块列表,右侧按“源 / 路径 / 依赖”标签页逐个配置([1lck/Lithe-IDEA#2086](https://github.com/1lck/Lithe-IDEA/issues/2086))。 + +### 新功能 + +- **Eclipse 工程按模块编辑**:源文件夹(可标为测试)、输出文件夹、JRE(工作区默认或 JavaSE 执行环境)和依赖列表,保存时写回模块的 `.classpath`。 +- **依赖列表**:可添加 JAR/ZIP、类文件夹、库容器(JUnit 4/5、Web App Libraries、EAR Libraries 及工作区已用到的用户库和 Server Runtime)和其他模块;可调整顺序,每项可标“导出”“仅测试”。 +- **保留原文件内容**:源码附件、Javadoc 位置、访问规则、注释和页面不显示的条目都保持不变。 +- **Maven、Gradle 模块只读显示** JDT 解析出的完整类路径(含测试依赖),提示在构建文件里修改。 +- 设置动作“读取本地 JAR 依赖”改名为“读取项目结构”;没有 `.classpath` 的普通文件夹仍在“引用的库”分组里编辑。 + +详见 `docs/module-structure.md`。 + +### 兼容性 + +**需要声明 `sourceSettings` 1 的 Lithe 宿主**([1lck/Lithe-IDEA#2087](https://github.com/1lck/Lithe-IDEA/pull/2087)),因此是主版本升级。宿主不支持时继续使用 3.0.1。本版本在支持它的宿主稳定版发布前作为预发布版提供。已在 JDT LS 1.61.0 上验证。 + +--- + +## English + +The **Java Libraries** page becomes **Java Project Structure**, after IntelliJ IDEA's Project Structure → Modules: a module list on the left and Sources / Paths / Dependencies tabs for the selected module ([1lck/Lithe-IDEA#2086](https://github.com/1lck/Lithe-IDEA/issues/2086)). + +### New + +- **Eclipse projects are edited module by module**: source folders (optionally marked as test), output folder, JRE (workspace default or a JavaSE execution environment) and dependencies, saved to the module's `.classpath`. +- **Dependency list**: add JARs/ZIPs, class folders, library containers (JUnit 4/5, Web App Libraries, EAR Libraries, and the user libraries and Server Runtimes the workspace already uses) and other modules; reorder them, and mark each as Export or Test only. +- **The rest of the file is kept**: source attachments, Javadoc locations, access rules, comments and entries the page does not show stay as they are. +- **Maven and Gradle modules are shown read-only** with the classpath JDT resolved, test dependencies included; change them in the build file. +- The **Read local JAR dependencies** action is now **Read project structure**; plain folders without `.classpath` are still edited in the **Referenced libraries** group. + +See `docs/module-structure.md`. + +### Compatibility + +**Requires a Lithe host advertising `sourceSettings` 1** ([1lck/Lithe-IDEA#2087](https://github.com/1lck/Lithe-IDEA/pull/2087)), hence the major version. Hosts without it keep 3.0.1. This version ships as a prerelease until a stable host supports it. 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 03f60f5..18de821 100644 --- a/e2e/host/desktop/internal/settingswindow/plugin_native_source_test.go +++ b/e2e/host/desktop/internal/settingswindow/plugin_native_source_test.go @@ -156,9 +156,24 @@ func TestPluginNativeSourceVisual(t *testing.T) { } 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) + shot := func(name string) { + d.pump() + if err = session.Screenshot(filepath.Join(out, name+"-"+language.Code()+"-"+theme+".png")); err != nil { + t.Fatal(err) + } + } + shot(item.name) + if item.name == "libraries-modules" { + // The Eclipse module's dependencies tab, then the Maven + // module JDT resolved, read-only. + dependencies := "Dependencies" + if language == i18n.Chinese { + dependencies = "依赖" + } + d.click(dependencies) + shot(item.name + "-dependencies") + d.click("service") + shot(item.name + "-maven") } }) } 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 31f6e3a..25f057b 100644 --- a/io.github.lithe-idea.java-support/l10n/zh-Hans.json +++ b/io.github.lithe-idea.java-support/l10n/zh-Hans.json @@ -39,8 +39,8 @@ "description": "读取工具的实际配置;保存时写入页面列出的原生配置文件。" }, "libraries": { - "title": "读取本地 JAR 依赖", - "description": "读取项目实际引用的 JAR;保存时更新页面列出的原生配置文件。" + "title": "读取项目结构", + "description": "读取每个模块的源文件夹、输出文件夹、JRE 和依赖。保存时写入 Eclipse 的 .classpath 和页面列出的库配置文件;Maven、Gradle 模块只读。" } } } diff --git a/io.github.lithe-idea.java-support/plugin.json b/io.github.lithe-idea.java-support/plugin.json index 6415594..a9e0633 100644 --- a/io.github.lithe-idea.java-support/plugin.json +++ b/io.github.lithe-idea.java-support/plugin.json @@ -2,9 +2,9 @@ "schemaVersion": 0, "id": "io.github.lithe-idea.java-support", "displayName": "Java Support", - "version": "3.0.1", + "version": "4.0.0", "pluginAPIVersion": 0, - "requires": {"backend": 0, "debugAdapters": 0, "languages": 0, "languageServers": 0, "pluginFunctions": 0, "settings": 0, "projectGenerators": 0, "toolDefinitions": 0, "sourceSettings": 0}, + "requires": {"backend": 0, "debugAdapters": 0, "languages": 0, "languageServers": 0, "pluginFunctions": 0, "settings": 0, "projectGenerators": 0, "toolDefinitions": 0, "sourceSettings": 1}, "requiresTools": ["java", "jdtls-runtime"], "vendor": { "id": "io.github.lithe-idea", @@ -853,5 +853,5 @@ ] } ], - "settingActions": [{"id": "compiler", "title": "Read compiler settings", "description": "Read actual Eclipse JDT project settings. Save writes the displayed native preferences or library configuration files.", "function": "compiler.settings", "sourceEditor": {"editFunction": "compiler.prepareSettings", "languageID": "java"}, "page": {"compilerID": "java"}}, {"id": "libraries", "title": "Read local JAR dependencies", "description": "Read actual Eclipse JDT project settings. Save writes the displayed native preferences or library configuration files.", "function": "libraries.settings", "sourceEditor": {"editFunction": "compiler.prepareSettings", "languageID": "java"}, "page": {"languageID": "java"}}] + "settingActions": [{"id": "compiler", "title": "Read compiler settings", "description": "Read actual Eclipse JDT project settings. Save writes the displayed native preferences or library configuration files.", "function": "compiler.settings", "sourceEditor": {"editFunction": "compiler.prepareSettings", "languageID": "java"}, "page": {"compilerID": "java"}}, {"id": "libraries", "title": "Read project structure", "description": "Read each module's source folders, output folder, JRE and dependencies. Save writes Eclipse .classpath files and the library configuration files shown; Maven and Gradle modules are read-only.", "function": "libraries.settings", "sourceEditor": {"editFunction": "compiler.prepareSettings", "languageID": "java"}, "page": {"languageID": "java"}}] } diff --git a/scripts/compiler/test-live.mjs b/scripts/compiler/test-live.mjs index 5f91f15..750356e 100644 --- a/scripts/compiler/test-live.mjs +++ b/scripts/compiler/test-live.mjs @@ -55,7 +55,7 @@ try{ const invoke=(functionID,params)=>backend.request('lithe/function/invoke',{functionID,operationID:`native-${++op}`,params,context},90000); let sources; await step('Discover the project from the real JDT server',async()=>{await until(()=>execute('java.project.getAll'),projects=>projects.some(uri=>(process.platform==='win32'?fileURLToPath(uri).replace(/[\\/]$/,'').toLowerCase()===root.toLowerCase():fileURLToPath(uri).replace(/\/$/,'')===root)),'JDT project import');sources=await invoke('libraries.settings',{context:{language:'zh-CN',builds:[]}});assert.equal(sources.sources[0].path,eclipse?'.classpath':'.vscode/settings.json');}); - await step('Save a referenced JAR and confirm JDT resolves the actual classpath',async()=>{const source=sources.sources[0],stageFile=join(stage,'libraries-stage.json');writeFileSync(stageFile,'');await invoke('compiler.prepareSettings',{operation:'editSource',sourceID:source.id,revision:source.revision,values:{libraries:[jar]},outputFile:stageFile});mkdirSync(join(root,'.vscode'),{recursive:true});renameSync(stageFile,join(root,source.path));await invoke('libraries.settings',{operation:'readAfterSave',context:{language:'zh-CN',builds:[]}});if(!eclipse)await until(()=>execute('java.project.getSettings',[pathToFileURL(root).href,['org.eclipse.jdt.ls.core.referencedLibraries']]),value=>value['org.eclipse.jdt.ls.core.referencedLibraries']?.some(path=>samePath(path,jar)),'JDT classpath refresh');}); + await step('Save a referenced JAR and confirm JDT resolves the actual classpath',async()=>{const source=sources.sources[0],stageFile=join(stage,'libraries-stage.json');writeFileSync(stageFile,'');await invoke('compiler.prepareSettings',{operation:'editSource',sourceID:source.id,revision:source.revision,values:eclipse?{dependencies:[{kind:'archive',value:jar}]}:{libraries:[jar]},outputFile:stageFile});mkdirSync(join(root,'.vscode'),{recursive:true});renameSync(stageFile,join(root,source.path));await invoke('libraries.settings',{operation:'readAfterSave',context:{language:'zh-CN',builds:[]}});if(!eclipse)await until(()=>execute('java.project.getSettings',[pathToFileURL(root).href,['org.eclipse.jdt.ls.core.referencedLibraries']]),value=>value['org.eclipse.jdt.ls.core.referencedLibraries']?.some(path=>samePath(path,jar)),'JDT classpath refresh');}); await step('Save native compiler target and verify real JDT effective settings',async()=>{sources=await invoke('compiler.settings',{context:{language:'zh-CN',builds:[]}});const source=sources.sources.find(s=>s.id==='defaults'),stageFile=join(stage,'compiler-stage.prefs');writeFileSync(stageFile,'');await invoke('compiler.prepareSettings',{operation:'editSource',sourceID:source.id,revision:source.revision,values:{target:'8'},outputFile:stageFile});mkdirSync(join(root,'.settings'),{recursive:true});renameSync(stageFile,join(root,source.path));await invoke('compiler.settings',{operation:'readAfterSave',context:{language:'zh-CN',builds:[]}});await until(()=>execute('java.project.getSettings',[pathToFileURL(root).href,['org.eclipse.jdt.core.compiler.codegen.targetPlatform']]),value=>value['org.eclipse.jdt.core.compiler.codegen.targetPlatform']==='1.8','JDT compiler refresh');}); await step('Compile with JDT, inspect Java 8 bytecode and run with the external JAR',async()=>{ const result=await execute('vscode.java.buildWorkspace',[JSON.stringify({mainClass:'Main',filePath:sourceFile,isFullBuild:true})]);assert.equal(result,1); diff --git a/scripts/compiler/test-module-structure.mjs b/scripts/compiler/test-module-structure.mjs new file mode 100644 index 0000000..a4414b3 --- /dev/null +++ b/scripts/compiler/test-module-structure.mjs @@ -0,0 +1,158 @@ +// The project structure page (1lck/Lithe-IDEA#2086) run through the packaged +// backend and the user's JDT LS: two Eclipse projects and a Maven module. +// The page must list them as modules, show the Maven module read-only with +// the classpath JDT resolved, and save an edit of the Eclipse module's source +// folders, output folder and dependencies (another module, exported, and a +// JAR outside the workspace) to its .classpath, keeping what the page does +// not show. JDT must then compile the module against the new classpath. +// Reading the page writes nothing, and the package and the JDT LS +// installation stay unchanged. +// Usage: node scripts/compiler/test-module-structure.mjs +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 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);}; +const OUTPUT=new Set(['bin','build','target','classes']); +// Files below `directory`, with content digests; build output, JDT's own +// metadata and the named files are left out. +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); +const slashes=path=>path.replaceAll('\\','/'); +async function until(get,accept,label,timeout=120000){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 PROJECT=name=>`${name}org.eclipse.jdt.core.javabuilderorg.eclipse.jdt.core.javanature`; +const JRE='org.eclipse.jdt.launching.JRE_CONTAINER'; + +const report=createReport('module-structure'); +const packageBaseline=snapshot(pkg,new Set()),serverBaseline=snapshot(inputs.home,new Set()); +const stage=realpathSync.native(mkdtempSync(join(tmpdir(),'lithe-java-modules-'))); +let backend,server; +try{ + const root=join(stage,'workspace');mkdirSync(root); + const vendor=join(stage,'vendor/acme-util.jar'); + await jar(stage,'acme',{'com/acme/Util.java':'package com.acme; public class Util { public static String value() { return "acme"; } }'},vendor); + const common=join(root,'common'),app=join(root,'app'),service=join(root,'service'); + write(join(common,'.project'),PROJECT('common')); + write(join(common,'.classpath'),``); + write(join(common,'src/com/common/Greeter.java'),'package com.common; public class Greeter { public static String greet() { return "hi"; } }'); + await jar(stage,'old',{'com/old/Old.java':'package com.old; public class Old { }'},join(app,'lib/old.jar')); + write(join(app,'.project'),PROJECT('app')); + const original=`\n\n\t\n\t\n\t\n\t\n\t\n\n`; + write(join(app,'.classpath'),original); + write(join(app,'src/demo/App.java'),'package demo; public class App { public static void main(String[] args) { System.out.print(com.common.Greeter.greet() + com.acme.Util.value() + demo.extra.Extra.NAME); } }'); + write(join(app,'extra/demo/extra/Extra.java'),'package demo.extra; public class Extra { public static final String NAME = "extra"; }'); + write(join(service,'pom.xml'),'4.0.0test.litheservice11717'); + write(join(service,'src/main/java/demo/Service.java'),'package demo; public class Service { }'); + + const context={contextID:'ctx-modules',generation:1};let op=0,configuration={}; + 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},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=120000)=>backend.request('lithe/function/invoke',{functionID,operationID:`modules-${++op}`,params:args,context},timeout); + const launch=await invoke('java.resolveLaunch',params);configuration=launch.workspaceConfiguration; + const problems=new Map(); + server=new Client(answeredExecutable(launch,inputs),launch.arguments,{notifications:(method,p)=>{if(method==='textDocument/publishDiagnostics')problems.set(p.uri,p.diagnostics.filter(item=>item.severity===1).map(item=>item.message));},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 page=language=>invoke('libraries.settings',{context:{language,builds:[]}}); + const module=(snapshot,title)=>snapshot.sources.find(source=>source.group==='modules'&&source.title===title); + const field=(source,id)=>source.fields.find(item=>item.id===id); + + await report.step('JDT imports the two Eclipse projects and the Maven module',async()=>{ + await until(()=>execute('java.project.getAll'),projects=>[common,app,service].every(project=>projects.some(uri=>samePath(fileURLToPath(uri),project))),'JDT project import',240000); + }); + // JDT LS adds its resource filter to an Eclipse .project on import. + const projectFiles=()=>snapshot(root,new Set([...OUTPUT,'.project','.settings'])); + let before; + await report.step('the structure page lists the modules and writes nothing',async()=>{ + const baseline=projectFiles(); + before=await page('zh-CN'); + assert.deepEqual(before.groups[0],{id:'modules',title:'模块',layout:'sidebar'},JSON.stringify(before.groups)); + const appModule=module(before,'app');assert.ok(appModule,JSON.stringify(before.sources.map(source=>[source.group,source.title]))); + assert.equal(appModule.writable,true); + assert.equal(appModule.path,'app/.classpath'); + assert.deepEqual(field(appModule,'roots').value.map(entry=>entry.value),['src']); + assert.equal(field(appModule,'jre').value,JRE); + assert.deepEqual(field(appModule,'dependencies').value.map(entry=>`${entry.kind}:${entry.value}`),['archive:lib/old.jar']); + const moduleChoices=field(appModule,'dependencies').entryKinds.find(kind=>kind.id==='module').choices.map(choice=>choice.value); + assert.deepEqual(moduleChoices,['/common']); + assert.equal(module(before,'common').writable,true); + const serviceModule=module(before,'service'); + assert.ok(serviceModule,JSON.stringify(before.sources.map(source=>source.title))); + assert.equal(serviceModule.writable,false); + assert.equal(serviceModule.path,'service/pom.xml'); + const resolved=field(serviceModule,'dependencies').value; + assert.ok(resolved.some(entry=>entry.kind==='classes'&&slashes(entry.value).endsWith('target/classes')),JSON.stringify(resolved)); + assert.deepEqual(projectFiles(),baseline,'Reading the structure page must not write project files'); + // The public projection, rendered by the native host in scripts/compiler/visual.mjs. + capture('libraries-modules-zh',before); + capture('libraries-modules-en',await page('en')); + }); + await report.step('saving the module writes its .classpath and keeps what the page does not show',async()=>{ + const appModule=module(before,'app'); + const stageFile=join(stage,'classpath-stage.xml');writeFileSync(stageFile,''); + const edit=await invoke('compiler.prepareSettings',{operation:'editSource',sourceID:appModule.id,revision:appModule.revision,outputFile:stageFile,values:{ + roots:[{kind:'folder',value:'src'},{kind:'folder',value:join(app,'extra')}], + output:'build/classes', + dependencies:[{kind:'module',value:'/common',attributes:{exported:true}},{kind:'archive',value:'lib/old.jar'},{kind:'archive',value:vendor}], + }}); + assert.equal(edit.changed,true); + const text=readFileSync(stageFile,'utf8'); + for(const kept of['','sourcepath="lib/old-sources.jar"','path="extra"','path="build/classes"','exported="true"','combineaccessrules="false"',`path="${slashes(realpathSync.native(vendor))}"`])assert.ok(text.includes(kept),`${kept}\n${text}`); + assert.equal(snapshot(root).find(([label])=>label==='/app/.classpath')[1],createHash('sha256').update(original).digest('hex'),'Preparing an edit must not touch the file'); + renameSync(stageFile,join(app,'.classpath')); + const after=await invoke('libraries.settings',{operation:'readAfterSave',context:{language:'en',builds:[]}}); + const saved=module(after,'app'); + assert.deepEqual(field(saved,'roots').value.map(entry=>entry.value),['src','extra']); + assert.equal(field(saved,'output').value,'build/classes'); + assert.deepEqual(field(saved,'dependencies').value.map(entry=>[entry.kind,entry.title,entry.attributes?.exported??false]),[['module','common',true],['archive','old.jar',false],['archive','acme-util.jar',false]]); + }); + await report.step('JDT compiles the module against the saved classpath',async()=>{ + const errors=()=>JSON.stringify([...problems].filter(([,messages])=>messages.length)); + // A full build cleans every project first and may build the module before + // the module it now depends on; the incremental builds that follow, as + // JDT LS's own auto-build would run them, settle it. + let full=true; + const build=()=>{const request=server.request('java/buildWorkspace',full,180000);full=false;return request;}; + await until(build,status=>status===1,'JDT build after the .classpath edit',60000).catch(error=>{throw Error(`${error.message}: ${errors()}`);}); + assert.ok(existsSync(join(app,'build/classes/demo/App.class')),'demo/App.class is not in the saved output folder'); + assert.ok(existsSync(join(app,'build/classes/demo/extra/Extra.class')),'the added source folder was not compiled'); + }); + await server.request('shutdown',null,30000);server.notify('exit',null); + await report.step('the package and the JDT LS installation stay unchanged',async()=>{ + assert.deepEqual(snapshot(pkg,new Set()),packageBaseline,'The structure page must never write into the installed package'); + assert.deepEqual(snapshot(inputs.home,new Set()),serverBaseline,'The structure page must never write into the user\'s JDT LS installation'); + }); +}finally{ + try{if(server)await server.close();}finally{try{if(backend)await backend.close();}finally{rmSync(stage,{recursive:true,force:true});report.write();}} +} diff --git a/scripts/package/lsp-client.mjs b/scripts/package/lsp-client.mjs index 07a2b00..85303fa 100644 --- a/scripts/package/lsp-client.mjs +++ b/scripts/package/lsp-client.mjs @@ -3,7 +3,7 @@ import {spawn,execFileSync} from 'node:child_process'; export class Client { constructor(executable,args=[],options={}){ - this.hostRequests=options.hostRequests??{};const {hostRequests,...spawnOptions}=options; + this.hostRequests=options.hostRequests??{};this.notifications=options.notifications??(()=>{});const {hostRequests,notifications,...spawnOptions}=options; this.next=1;this.pending=new Map();this.buffer=Buffer.alloc(0);this.stderr=''; this.child=spawn(executable,args,{...spawnOptions,detached:true,stdio:['pipe','pipe','pipe']}); this.exited=new Promise(resolve=>{this.child.once('exit',(code,signal)=>{this.fail(Error(`Process exited: ${code}/${signal}: ${this.stderr}`));resolve();});this.child.once('error',error=>{this.fail(error);resolve();});}); @@ -22,7 +22,8 @@ export class Client { const handler=this.hostRequests[message.method]; if(handler){Promise.resolve().then(()=>handler(message.params)).then(result=>this.send({id:message.id,result}),error=>this.send({id:message.id,error:{code:-32603,message:error.message}}));} else{const result=message.method==='workspace/configuration'?(message.params?.items??[]).map(()=>({})):null;this.send({id:message.id,result});} - }else if(message.id!==undefined){const item=this.pending.get(message.id);if(item){this.pending.delete(message.id);clearTimeout(item.timer);message.error?item.reject(Error(JSON.stringify(message.error))):item.resolve(message.result);}} + }else if(message.method){this.notifications(message.method,message.params);} + else if(message.id!==undefined){const item=this.pending.get(message.id);if(item){this.pending.delete(message.id);clearTimeout(item.timer);message.error?item.reject(Error(JSON.stringify(message.error))):item.resolve(message.result);}} } }catch(error){this.fail(error);} });