diff --git a/backend/src/library_settings.rs b/backend/src/library_settings.rs index d7973d6..992617c 100644 --- a/backend/src/library_settings.rs +++ b/backend/src/library_settings.rs @@ -11,20 +11,26 @@ use crate::project_model::{ Explicit, ModelKind, Origin, ProjectModel, UnresolvedKind, UPSTREAM_DEFAULT_LIBRARIES, }; use serde_json::{json, Value}; +use std::collections::BTreeSet; 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 CLASS_FOLDERS_FIELD: &str = "class-folders"; 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"; +pub const OUTPUT_PATH_FACT: &str = "org.eclipse.jdt.ls.core.outputPath"; /// 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 one list item. const MAX_ITEM_BYTES: usize = 4096; +pub(crate) const JAR_DIRECTORY: &str = "jar-directory"; +pub(crate) const CLASS_FOLDER: &str = "classes"; +pub(crate) const ARCHIVE: &str = "archive"; fn text(zh: bool, en: &str, cn: &str) -> String { if zh { cn } else { en }.to_owned() @@ -79,7 +85,11 @@ impl Page<'_> { 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 { + let library_source = if self.model.kind == ModelKind::Idea + && !fact[crate::project_settings::LIBRARIES_FACT].is_array() + { + text(zh, "JDT classpath not confirmed", "JDT 类路径未确认") + } else if detected > 0 { if zh { format!("JDT 实际生效,含自动识别的 {detected} 项") } else { @@ -128,6 +138,32 @@ impl Page<'_> { "inheritedValue": if inherited.is_empty() { Value::Null } else { json!(inherited) }, "effectiveSource": effective_source, })); + if !self.model.kind.managed() { + let class_folders_value = self + .explicit + .class_folders + .as_ref() + .and_then(Value::as_array) + .map(|items| { + json!(items + .iter() + .filter_map(Value::as_str) + .filter(|path| valid_path(path)) + .take(MAX_LINES) + .collect::>()) + }); + fields.push(json!({ + "id": CLASS_FOLDERS_FIELD, + "title":text(zh,"Additional class folders","补充类目录"), + "description":text(zh, + "Folders containing compiled classes. Add an absolute path or a workspace-relative path, one per line. Saved under java.lithe.classFolders in .vscode/settings.json.", + "包含已编译类的目录。每行填写一个绝对路径或相对于工作区的路径,保存到 .vscode/settings.json 的 java.lithe.classFolders。"), + "kind":"stringList", + "value":class_folders_value, + "effectiveValue":Value::Null, + "effectiveSource":".vscode/settings.json", + })); + } if !self.storable().is_empty() || !self.storable_source_paths().is_empty() { let stored = self.stored(); fields.push(json!({ @@ -145,6 +181,249 @@ impl Page<'_> { fields } + pub fn workspace_fields( + &self, + fact: &Value, + classpaths: Option<&[String]>, + ) -> (Vec, bool) { + use crate::module_structure::{ + classpath_key, DEPENDENCIES_FIELD, OUTPUT_FIELD, ROOTS_FIELD, + }; + + let zh = self.zh; + let dependencies = text(zh, "Dependencies", "依赖"); + let origin = ".vscode/settings.json"; + let mut fields = self.settings_fields(fact, Value::Null); + fields.retain(|field| field["id"] == STORE_DETECTED_FIELD); + let configured_roots = self.explicit.source_paths.as_ref().filter(|value| { + value.as_array().is_some_and(|paths| !paths.is_empty()) + || (value.is_array() && !self.explicit.source_roles.is_empty()) + }); + let has_roles = !self.explicit.source_roles.is_empty(); + let has_declared_roots = configured_roots.is_some() || has_roles; + let jdt_roots = relative_list(self.root, &fact[SOURCE_PATHS_FACT]); + let kinds = [ + ("folder", text(zh, "Source folder", "源码文件夹")), + ("test", text(zh, "Test source", "测试源码")), + ("resource", text(zh, "Resources", "资源")), + ("test-resource", text(zh, "Test resources", "测试资源")), + ("excluded", text(zh, "Excluded folder", "排除目录")), + ]; + let entry_kinds: Vec<_> = kinds + .iter() + .map(|(id, title)| json!({"id":id,"title":title,"input":"directory"})) + .collect(); + let entries = |value: Option<&Value>| { + value.and_then(Value::as_array).map(|paths| { + let mut seen = BTreeSet::new(); + let rows = paths.iter().filter_map(Value::as_str).filter(|path| valid_path(path) && seen.insert(*path)) + .take(MAX_LINES).map(|path| json!({"kind":"folder","value":path,"title":truncate(path.to_owned(),256)})).collect::>(); + json!(rows) + }) + }; + let mut declared = entries(configured_roots).or_else(|| has_roles.then(|| json!([]))); + let mut roots_truncated = false; + if let Some(rows) = declared.as_mut().and_then(Value::as_array_mut) { + let mut seen_paths = BTreeSet::new(); + for row in rows.iter_mut() { + if let Some(path) = row["value"].as_str() { + seen_paths.insert(path.to_owned()); + } + if let Some((kind, label)) = kinds.iter().skip(1).take(3).find(|(kind, _)| { + self.explicit + .source_roles + .get(kind) + .is_some_and(|paths| paths.iter().any(|path| row["value"] == path.as_str())) + }) { + row["kind"] = json!(kind); + row["detail"] = json!(label); + } + } + for (kind, label) in kinds.iter().skip(1).take(3) { + if let Some(paths) = self.explicit.source_roles.get(kind) { + for path in paths { + if !valid_path(path) { + roots_truncated = true; + continue; + } + if seen_paths.insert(path.clone()) { + if rows.len() >= MAX_LINES { + roots_truncated = true; + } else { + rows.push(json!({"kind":kind,"value":path,"title":truncate(path.clone(),256),"detail":label})); + } + } + } + } + } + if let Some(paths) = self.explicit.source_roles.get("excluded") { + let mut seen_excluded = BTreeSet::new(); + for path in paths { + if !valid_path(path) { + roots_truncated = true; + continue; + } + if seen_excluded.insert(path.as_str()) { + if rows.len() >= MAX_LINES { + roots_truncated = true; + } else { + rows.push(json!({"kind":"excluded","value":path,"title":truncate(path.clone(),256),"detail":kinds[4].1})); + } + } + } + } + } + let configured_valid = configured_roots + .and_then(Value::as_array) + .is_none_or(|paths| { + let mut seen = BTreeSet::new(); + let mut unique = 0usize; + for path in paths { + let Some(path) = path.as_str().filter(|path| valid_path(path)) else { + return false; + }; + if seen.insert(path) { + unique += 1; + } + } + unique <= MAX_LINES + }); + let roles_valid = self + .explicit + .source_roles + .values() + .flatten() + .all(|path| valid_path(path)); + let roots_complete = configured_valid && roles_valid && !roots_truncated; + fields.insert(0, json!({"id":ROOTS_FIELD,"title":text(zh,"Source folders","源码文件夹"), + "section":text(zh,"Sources","源"),"kind":"entryList", + "value":declared,"effectiveValue":entries(Some(&jdt_roots)), + "inheritedValue":if !has_declared_roots { entries(Some(&jdt_roots)) } else { None }, + "effectiveSource":if has_declared_roots { origin.to_owned() } else { text(zh,"JDT inference","JDT 推断") }, + "description":text(zh, "Choose each folder's role. Exclusions apply within source roots. Resource folders copy non-Java files to the compiler output.", "可按用途添加目录。排除目录作用于其所在的源码根。资源目录中的非 Java 文件会复制到编译输出。"), + "entryKinds":entry_kinds})); + let output = self.explicit.output_path.as_ref().and_then(Value::as_str); + let effective_output = fact[OUTPUT_PATH_FACT] + .as_str() + .filter(|path| !path.is_empty()) + .map(|path| crate::project_model::relative_or_absolute(self.root, Path::new(path))); + fields.insert(1, json!({"id":OUTPUT_FIELD,"title":text(zh,"Output folder","输出文件夹"), + "section":text(zh,"Paths","路径"),"kind":"text","value":output,"effectiveValue":effective_output, + "inheritedValue":if output.is_none() { effective_output.as_deref() } else { None }, + "effectiveSource":if effective_output.is_some() || output.is_none() { "JDT" } else { origin }, + "description":text(zh,"Workspace-relative output folder. Leave empty to use JDT's default.","填写相对于工作区的输出文件夹。留空时使用 JDT 默认目录。")})); + for field in &mut fields[2..] { + field["section"] = json!(&dependencies); + } + + let actual = classpaths.map(|paths| { + paths + .iter() + .map(|path| classpath_key(Path::new(path))) + .collect::>() + }); + let include = if self.explicit.libraries.is_none() { + vec![UPSTREAM_DEFAULT_LIBRARIES.to_owned()] + } else { + self.explicit.include() + }; + let class_folders = self + .explicit + .class_folders + .as_ref() + .and_then(Value::as_array) + .into_iter() + .flatten(); + let mut seen = BTreeSet::new(); + let mut complete = true; + let mut rows = Vec::new(); + for (value, class_folder) in include + .iter() + .map(|v| (v.as_str(), false)) + .chain(class_folders.filter_map(Value::as_str).map(|v| (v, true))) + { + let normalized = value.replace('\\', "/"); + let directory = (!class_folder) + .then(|| jar_directory(&normalized)) + .flatten(); + let (kind, label, target) = if class_folder { + ( + CLASS_FOLDER, + text(zh, "Class folder", "类目录"), + normalized.as_str(), + ) + } else if let Some((base, _)) = directory { + (JAR_DIRECTORY, text(zh, "JAR directory", "JAR 库目录"), base) + } else { + ( + ARCHIVE, + text(zh, "JAR file or pattern", "JAR 文件或匹配规则"), + normalized.as_str(), + ) + }; + if !seen.insert((kind, value)) { + continue; + } + if rows.len() == MAX_LINES || !valid_path(value) { + complete = false; + continue; + } + let status = match &actual { + Some(actual) if !target.contains(['*', '?', '[', '{']) => { + let path = self.root.join(target); + let key = classpath_key(&dunce::canonicalize(&path).unwrap_or(path)); + if let Some((_, recursive)) = directory { + let prefix = format!("{}/", key.trim_end_matches('/')); + let count = actual + .iter() + .filter(|path| { + path.strip_prefix(&prefix).is_some_and(|tail| { + tail.to_ascii_lowercase().ends_with(".jar") + && (recursive || !tail.contains('/')) + }) + }) + .count(); + if zh { + format!("JDT 已加载 {count} 个 JAR") + } else { + format!("{count} JARs loaded by JDT") + } + } else if actual.contains(&key) { + text(zh, "Loaded by JDT", "JDT 已生效") + } else { + text(zh, "Not on JDT classpath", "未进入 JDT 类路径") + } + } + _ => text(zh, "JDT status unconfirmed", "JDT 状态未确认"), + }; + let title = target + .trim_end_matches('/') + .rsplit('/') + .next() + .filter(|name| !name.is_empty()) + .unwrap_or(target); + rows.push( + json!({"kind":kind,"value":value,"title":truncate(title.to_owned(),256), + "detail":truncate(format!("{label} · {status} · {value}"),1024)}), + ); + } + let description = if complete { + text(zh, "Workspace dependencies saved in .vscode/settings.json. Automatically detected entries are shown under Project model.", + "工作区依赖保存到 .vscode/settings.json。自动识别的依赖显示在「工程模型」。") + } else { + text(zh, "Some configured dependencies exceed this editor's limits. Edit .vscode/settings.json to change them.", + "部分依赖超出编辑器支持的范围。请在 .vscode/settings.json 中修改。") + }; + fields.insert(2, json!({"id":DEPENDENCIES_FIELD,"title":dependencies,"section":dependencies,"kind":"entryList", + "description":description,"value":rows,"effectiveValue":rows,"effectiveSource":origin, + "entryKinds":[ + {"id":ARCHIVE,"title":text(zh,"JAR file","JAR 文件"),"input":"file","extensions":["jar"]}, + {"id":JAR_DIRECTORY,"title":text(zh,"JAR directory","JAR 库目录"),"input":"directory"}, + {"id":CLASS_FOLDER,"title":text(zh,"Class folder","类目录"),"input":"directory"} + ]})); + (fields, complete && roots_complete) + } + /// 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)> { @@ -498,11 +777,6 @@ impl Page<'_> { "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", @@ -525,6 +799,20 @@ impl Page<'_> { } } +pub(crate) fn jar_directory(pattern: &str) -> Option<(&str, bool)> { + pattern + .strip_suffix("/**/*.jar") + .or_else(|| pattern.strip_suffix("/**")) + .map(|base| (base, true)) + .or_else(|| pattern.strip_suffix("/*.jar").map(|base| (base, false))) +} + +pub(crate) fn valid_path(value: &str) -> bool { + !value.trim().is_empty() + && value.len() <= MAX_ITEM_BYTES + && !value.chars().any(char::is_control) +} + /// `n` English things, singular for one. fn count(n: u64, thing: &str) -> String { if n == 1 { @@ -636,12 +924,100 @@ mod tests { use crate::project_model::servlet::{ServletResolution, ServletRuntime}; use crate::project_model::{Detected, Unresolved}; + #[test] + fn workspace_shows_jdt_source_and_output_without_creating_overrides() { + let model = model(ModelKind::Plain); + let explicit = Explicit::default(); + let root = Path::new("workspace"); + let (fields, _) = Page { + zh: false, + root, + model: &model, + explicit: &explicit, + described: None, + } + .workspace_fields( + &json!({ + (SOURCE_PATHS_FACT): [root.join("src")], + "org.eclipse.jdt.ls.core.outputPath": root.join("bin"), + }), + None, + ); + let field = |id| fields.iter().find(|field| field["id"] == id).unwrap(); + assert!(field("roots")["value"].is_null()); + assert_eq!(field("roots")["inheritedValue"][0]["value"], "src"); + assert!(field("output")["value"].is_null()); + assert_eq!(field("output")["inheritedValue"], "bin"); + assert_eq!(field("output")["effectiveValue"], "bin"); + } + + #[test] + fn settings_fields_sanitizes_invalid_class_folders() { + let model = model(ModelKind::Idea); + let mut items = vec![json!(42), json!(""), json!("bad\npath")]; + for index in 0..(MAX_LINES + 10) { + items.push(json!(format!("classes-{index}"))); + } + let explicit = Explicit::from_document(&json!({ + "java.lithe.classFolders": items, + })); + let fields = Page { + zh: false, + root: Path::new("workspace"), + model: &model, + explicit: &explicit, + described: None, + } + .settings_fields(&json!({}), Value::Null); + let class_folders = fields + .iter() + .find(|field| field["id"] == CLASS_FOLDERS_FIELD) + .unwrap()["value"] + .as_array() + .unwrap(); + assert_eq!(class_folders.len(), MAX_LINES); + assert_eq!(class_folders[0], "classes-0"); + assert!(class_folders + .iter() + .all(|item| item.as_str().is_some_and(valid_path))); + } + + #[test] + fn workspace_fields_shows_source_roles_without_explicit_source_paths() { + let model = model(ModelKind::Plain); + let explicit = Explicit::from_document(&json!({ + "java.lithe.excludedSourceFolders": ["src/generated"], + "java.lithe.testSourceFolders": ["test"], + })); + let root = Path::new("workspace"); + let (fields, complete) = Page { + zh: false, + root, + model: &model, + explicit: &explicit, + described: None, + } + .workspace_fields(&json!({ (SOURCE_PATHS_FACT): [root.join("src")] }), None); + assert!(complete); + let roots = fields.iter().find(|field| field["id"] == "roots").unwrap(); + assert_eq!(roots["effectiveSource"], ".vscode/settings.json"); + assert!(roots["inheritedValue"].is_null()); + assert_eq!( + roots["value"], + json!([ + {"kind":"test","value":"test","title":"test","detail":"Test source"}, + {"kind":"excluded","value":"src/generated","title":"src/generated","detail":"Excluded folder"} + ]) + ); + } + fn model(kind: ModelKind) -> ProjectModel { ProjectModel { kind, enabled: true, descriptor: Some(".idea/modules.xml".into()), idea_modules: 2, + idea_module_details: Vec::new(), eclipse_projects: 0, libraries: vec![Detected { pattern: "web/WEB-INF/lib/*.jar".into(), diff --git a/backend/src/module_structure.rs b/backend/src/module_structure.rs index 24685fd..5e2da5d 100644 --- a/backend/src/module_structure.rs +++ b/backend/src/module_structure.rs @@ -186,6 +186,11 @@ fn truncate(text: &str, bytes: usize) -> String { text[..end].to_owned() } +pub(crate) fn clean_text(text: &str, bytes: usize) -> String { + let cleaned: String = text.chars().filter(|ch| !ch.is_control()).collect(); + truncate(&cleaned, bytes) +} + /// 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(['/', '\\']); @@ -682,6 +687,296 @@ pub fn project_name(module: &Path) -> String { .unwrap_or(folder) } +/// IDEA modules are displayed as declared. JDT resolves their libraries in +/// one unmanaged workspace project, so effective paths are workspace facts. +pub(crate) fn idea_fields( + zh: bool, + root: &Path, + module: &crate::project_model::IdeaModule, + classpaths: Option<&[String]>, +) -> Vec { + use crate::project_model::Origin; + use std::collections::BTreeSet; + + let source_section = local(zh, "Sources", "源"); + let paths_section = local(zh, "Paths", "路径"); + let dependencies_section = local(zh, "Dependencies", "依赖"); + let declared = local(zh, "IDEA declaration", "IDEA 声明"); + let effective: Option> = classpaths.map(|paths| { + paths + .iter() + .map(|path| classpath_key(Path::new(path))) + .collect() + }); + let row = |kind: &str, value: &str, title: &str, detail: &str| { + json!({ + "kind": kind, + "value": clean_text(value, MAX_VALUE), + "title": clean_text(title, 256), + "detail": clean_text(detail, 1024), + }) + }; + let kinds = [ + (FOLDER, "Source folder", "源码文件夹", &module.sources), + ("test", "Test source", "测试源码", &module.test_sources), + ("resource", "Resource", "资源", &module.resources), + ( + "test-resource", + "Test resource", + "测试资源", + &module.test_resources, + ), + ("excluded", "Excluded", "排除", &module.excluded), + ]; + let mut seen_roots = BTreeSet::new(); + let mut roots = Vec::new(); + for (kind, en, cn, paths) in &kinds { + let detail = local(zh, en, cn); + for raw in *paths { + if roots.len() == MAX_ENTRIES { + break; + } + let value = clean_text(raw, MAX_VALUE); + if value.trim().is_empty() || !seen_roots.insert((*kind, value.clone())) { + continue; + } + roots.push(row(kind, &value, &value, &detail)); + } + } + let root_kinds: Vec<_> = kinds + .iter() + .map(|(kind, en, cn, _)| json!({"id":kind,"title":local(zh,en,cn),"input":"directory"})) + .collect(); + let content_roots: Vec<_> = module + .content_roots + .iter() + .filter_map(|path| { + let path = if path == "." { + root.to_path_buf() + } else { + root.join(path) + }; + let cleaned = clean_text(&path.display().to_string(), MAX_VALUE); + (!cleaned.trim().is_empty()).then_some(cleaned) + }) + .take(MAX_ENTRIES) + .collect(); + let mut seen_deps = BTreeSet::<(&str, String)>::new(); + let mut dependencies = Vec::new(); + for (entry, directory) in module + .libraries + .iter() + .map(|item| (item, false)) + .chain(module.class_folders.iter().map(|item| (item, true))) + { + if dependencies.len() == MAX_ENTRIES { + break; + } + let pattern = clean_text(entry.pattern.as_str(), MAX_VALUE); + if pattern.trim().is_empty() { + continue; + } + let glob = pattern + .strip_suffix("/**/*.jar") + .map(|base| (base, true)) + .or_else(|| pattern.strip_suffix("/*.jar").map(|base| (base, false))); + let (kind, type_name, title) = if let Some((base, _)) = glob { + ( + LIBRARY, + local(zh, "JAR directory", "JAR 库目录"), + split_path(base).0, + ) + } else if directory { + ( + CLASSES, + local(zh, "Class folder", "类目录"), + split_path(&pattern).0, + ) + } else { + ( + ARCHIVE, + local(zh, "Archive", "归档"), + split_path(&pattern).0, + ) + }; + if !seen_deps.insert((kind, pattern.clone())) { + continue; + } + let source = if entry.origin == Origin::IdeaProjectLibrary { + local(zh, "IDEA project library", "IDEA 项目库") + } else { + local(zh, "IDEA module library", "IDEA 模块库") + }; + let status = effective.as_ref().map_or_else( + || local(zh, "JDT status unconfirmed", "JDT 状态未确认"), + |paths| { + if let Some((base, recursive)) = glob { + let prefix = + format!("{}/", classpath_key(&root.join(base)).trim_end_matches('/')); + let matches = paths + .iter() + .filter(|path| { + path.strip_prefix(&prefix).is_some_and(|tail| { + tail.to_ascii_lowercase().ends_with(".jar") + && (recursive || !tail.contains('/')) + }) + }) + .count(); + if matches > 0 { + return if zh { + format!("JDT 已加载 {matches} 个 JAR") + } else { + format!("{matches} JARs loaded by JDT") + }; + } + } else if paths.contains(&classpath_key(&root.join(&pattern))) { + return local(zh, "Loaded by JDT", "JDT 已生效"); + } + local(zh, "Not on JDT classpath", "未进入 JDT 类路径") + }, + ); + let detail = format!( + "{type_name} · {source} ({}) · {status} · {pattern}", + entry.label + ); + dependencies.push(row(kind, &pattern, title, &detail)); + } + let module_detail = local( + zh, + "IDEA module dependency (declared)", + "IDEA 模块依赖(原工程声明)", + ); + for name in &module.module_dependencies { + if dependencies.len() == MAX_ENTRIES { + break; + } + let value = clean_text(name, MAX_VALUE); + if value.trim().is_empty() || !seen_deps.insert((MODULE, value.clone())) { + continue; + } + dependencies.push(row(MODULE, &value, &value, &module_detail)); + } + for item in &module.unresolved { + if dependencies.len() == MAX_ENTRIES { + break; + } + use crate::project_model::UnresolvedKind; + let reason = match item.kind { + UnresolvedKind::MissingFile => local(zh, "Missing path", "路径不存在"), + UnresolvedKind::MissingLibrary => local(zh, "Undefined library", "找不到项目库定义"), + UnresolvedKind::IdeLibrary => local( + zh, + "IDEA library outside the project", + "IDEA 全局库或应用库", + ), + UnresolvedKind::UnknownMacro => { + local(zh, "Unknown IDEA path variable", "IDEA 路径变量未解析") + } + UnresolvedKind::OutsideWorkspace => continue, + UnresolvedKind::UserLibrary => continue, + }; + let value = clean_text(&item.name, MAX_VALUE); + if value.trim().is_empty() || !seen_deps.insert((LIBRARY, value.clone())) { + continue; + } + dependencies.push(row(LIBRARY, &value, &value, &reason)); + } + let output_source = if module.inherits_output { + local(zh, "Inherited from IDEA project", "继承 IDEA 项目输出") + } else { + declared.clone() + }; + let output = module + .output + .as_deref() + .map(|path| clean_text(path, MAX_VALUE)) + .filter(|path| !path.trim().is_empty()); + let test_output = module + .test_output + .as_deref() + .map(|path| clean_text(path, MAX_VALUE)) + .filter(|path| !path.trim().is_empty()); + let sdk = clean_text( + module.sdk.as_deref().unwrap_or(&local( + zh, + "Inherited from IDEA project", + "继承 IDEA 项目 SDK", + )), + MAX_VALUE, + ); + let descriptor = clean_text(&module.descriptor, 1024); + let classpath_status = if effective.is_some() { + local( + zh, + "JDT returned the workspace classpath", + "JDT 已返回工作区类路径", + ) + } else { + local( + zh, + "JDT classpath unconfirmed. Reload after indexing finishes.", + "JDT 类路径未确认。索引结束后可点「重新加载」。", + ) + }; + vec![ + json!({"id":"content-roots","title":local(zh,"Content roots","内容根"),"section":source_section,"kind":"stringList", + "value":content_roots,"effectiveValue":content_roots,"effectiveSource":declared}), + json!({"id":ROOTS_FIELD,"title":local(zh,"Source folders","源码文件夹"),"section":source_section,"kind":"entryList", + "value":roots,"effectiveValue":roots,"effectiveSource":declared, + "entryKinds":root_kinds}), + json!({"id":OUTPUT_FIELD,"title":local(zh,"IDEA output","IDEA 输出目录"),"section":paths_section,"kind":"text", + "value":output,"effectiveValue":Value::Null,"effectiveSource":output_source}), + json!({"id":"test-output","title":local(zh,"IDEA test output","IDEA 测试输出目录"),"section":paths_section,"kind":"text", + "value":test_output,"effectiveValue":Value::Null,"effectiveSource":output_source}), + json!({"id":JRE_FIELD,"title":local(zh,"IDEA SDK","IDEA SDK"),"section":dependencies_section,"kind":"text", + "value":sdk,"effectiveValue":Value::Null,"effectiveSource":declared}), + json!({"id":"jdt-status","title":local(zh,"JDT classpath status","JDT 类路径状态"),"section":dependencies_section,"kind":"text", + "value":classpath_status,"effectiveValue":classpath_status,"effectiveSource":"JDT"}), + json!({"id":DEPENDENCIES_FIELD,"title":dependencies_section,"section":dependencies_section,"kind":"entryList", + "description":local(zh,"Read from the IDEA module. JDT status refers to the workspace compile classpath. Edit in IDEA or add workspace libraries in Referenced libraries (.vscode/settings.json).", + "读取 IDEA 模块声明。生效状态以 JDT 工作区类路径为准。可在 IDEA 修改原配置,或在「引用的库」补充工作区配置(.vscode/settings.json)。"), + "value":dependencies,"effectiveValue":dependencies,"effectiveSource":descriptor, + "entryKinds":[ + {"id":ARCHIVE,"title":local(zh,"Archive","归档"),"input":"file"}, + {"id":CLASSES,"title":local(zh,"Class folder","类目录"),"input":"directory"}, + {"id":LIBRARY,"title":local(zh,"Library","库"),"input":"choice","choices":[]}, + {"id":MODULE,"title":local(zh,"Module dependency","模块依赖"),"input":"choice","choices":[]} + ]}), + ] +} + +fn normalize_lexical(path: &Path) -> std::path::PathBuf { + use std::path::Component; + let mut parts = Vec::new(); + for component in path.components() { + match component { + Component::CurDir => {} + Component::ParentDir => { + if matches!(parts.last(), Some(Component::Normal(_))) { + parts.pop(); + } else if !matches!( + parts.last(), + Some(Component::RootDir | Component::Prefix(_)) + ) { + parts.push(component); + } + } + other => parts.push(other), + } + } + parts.into_iter().collect() +} + +pub(crate) fn classpath_key(path: &Path) -> String { + let resolved = dunce::canonicalize(path).unwrap_or_else(|_| normalize_lexical(path)); + let path = resolved.to_string_lossy().replace('\\', "/"); + if cfg!(windows) { + path.to_lowercase() + } else { + path + } +} + #[cfg(test)] mod tests { use super::*; @@ -890,4 +1185,68 @@ mod tests { 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"}]) ); } + + #[test] + fn idea_fields_deduplicates_entries_and_strips_invalid_values() { + use crate::project_model::{Detected, IdeaModule, Origin, Unresolved, UnresolvedKind}; + let module = IdeaModule { + descriptor: "app\n.iml".into(), + name: "app".into(), + sources: vec!["src".into(), "src".into(), "".into(), "\t".into()], + test_sources: vec!["test".into()], + content_roots: vec![".".into(), " ".into()], + resources: vec![], + test_resources: vec![], + excluded: vec![], + libraries: vec![Detected { + pattern: "lib/*.jar".into(), + origin: Origin::IdeaModuleLibrary, + label: "libs".into(), + count: 1, + }], + class_folders: vec![], + module_dependencies: vec!["core".into(), "core".into(), "".into()], + unresolved: vec![ + Unresolved { + kind: UnresolvedKind::MissingLibrary, + name: "lib/*.jar".into(), + }, + Unresolved { + kind: UnresolvedKind::MissingFile, + name: "missing.jar".into(), + }, + Unresolved { + kind: UnresolvedKind::MissingFile, + name: "missing.jar".into(), + }, + Unresolved { + kind: UnresolvedKind::MissingFile, + name: " ".into(), + }, + ], + output: Some("out\0".into()), + test_output: Some(" ".into()), + inherits_output: false, + sdk: None, + }; + let fields = idea_fields(false, Path::new("/workspace"), &module, None); + let field = |id| fields.iter().find(|item| item["id"] == id).unwrap(); + let roots = field(ROOTS_FIELD)["value"].as_array().unwrap(); + assert_eq!(roots.len(), 2); + let deps = field(DEPENDENCIES_FIELD)["value"].as_array().unwrap(); + let keys: std::collections::BTreeSet<_> = deps + .iter() + .map(|item| { + ( + item["kind"].as_str().unwrap().to_owned(), + item["value"].as_str().unwrap().to_owned(), + ) + }) + .collect(); + assert_eq!(deps.len(), 3); + assert_eq!(keys.len(), 3); + assert_eq!(field(OUTPUT_FIELD)["value"], "out"); + assert!(field("test-output")["value"].is_null()); + assert_eq!(field(DEPENDENCIES_FIELD)["effectiveSource"], "app.iml"); + } } diff --git a/backend/src/project_model/idea.rs b/backend/src/project_model/idea.rs index f53ad8f..30c02c8 100644 --- a/backend/src/project_model/idea.rs +++ b/backend/src/project_model/idea.rs @@ -9,7 +9,7 @@ use super::{ read_bounded, relative_inside, relative_or_absolute, xml, Detected, Origin, Unresolved, UnresolvedKind, }; -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::fs; use std::path::{Path, PathBuf}; use xmltree::Element; @@ -34,10 +34,21 @@ pub struct IdeaFacts { /// Workspace-relative path of the descriptor that was read. pub descriptor: String, pub modules: usize, + pub module_details: Vec, /// Workspace-relative production source folders, then test ones. pub source_paths: Vec, pub test_source_paths: Vec, + pub content_roots: Vec, + pub resources: Vec, + pub test_resources: Vec, + pub excluded: Vec, pub libraries: Vec, + pub class_folders: Vec, + pub module_dependencies: Vec, + pub output: Option, + pub test_output: Option, + pub inherits_output: bool, + pub sdk: Option, pub unresolved: Vec, /// Web roots declared by web facets. pub web_roots: Vec, @@ -47,10 +58,30 @@ pub struct IdeaFacts { pub truncated: bool, } +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct IdeaModule { + pub descriptor: String, + pub name: String, + pub sources: Vec, + pub test_sources: Vec, + pub content_roots: Vec, + pub resources: Vec, + pub test_resources: Vec, + pub excluded: Vec, + pub libraries: Vec, + pub class_folders: Vec, + pub module_dependencies: Vec, + pub unresolved: Vec, + pub output: Option, + pub test_output: Option, + pub inherits_output: bool, + pub sdk: Option, +} + /// 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) = + let (descriptor, modules_document, project_libraries) = if let Some(document) = read_bounded(&directory.join("modules.xml")).and_then(|bytes| xml::parse(&bytes)) { ( @@ -70,6 +101,13 @@ pub fn read(root: &Path, ipr_files: &[PathBuf], macros: &Macros) -> Option Option Option Option, + project_libraries: &BTreeMap, facts: &mut IdeaFacts, roots: &mut usize, ) { @@ -153,11 +232,35 @@ fn read_module( let Some(manager) = component(document, "NewModuleRootManager") else { return; }; + let output = |tag| { + xml::children(manager, tag) + .next() + .and_then(|entry| expand(xml::attribute(entry, "url")?, macros, module_dir)) + .map(|path| relative_or_absolute(root, &path)) + }; + facts.output = output("output"); + facts.test_output = output("output-test"); + facts.inherits_output = xml::attribute(manager, "inherit-compiler-output") == Some("true"); 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; + if let Some(path) = + xml::attribute(content, "url").and_then(|url| expand(url, macros, module_dir)) + { + let path = relative_or_absolute(root, &path); + if !facts.content_roots.contains(&path) { + facts.content_roots.push(path); } + } + for folder in xml::children(content, "excludeFolder") { + if let Some(path) = + xml::attribute(folder, "url").and_then(|url| expand(url, macros, module_dir)) + { + let path = relative_or_absolute(root, &path); + if !facts.excluded.contains(&path) { + facts.excluded.push(path); + } + } + } + for folder in xml::children(content, "sourceFolder") { let Some(path) = xml::attribute(folder, "url").and_then(|url| expand(url, macros, module_dir)) else { @@ -170,10 +273,15 @@ fn read_module( }); continue; }; - let target = if xml::attribute(folder, "isTestSource") == Some("true") { - &mut facts.test_source_paths - } else { - &mut facts.source_paths + let target = match xml::attribute(folder, "type") { + Some("java-resource") => &mut facts.resources, + Some("java-test-resource") => &mut facts.test_resources, + Some(kind) if kind.contains("resource") => continue, + Some("java-test-source") => &mut facts.test_source_paths, + _ if xml::attribute(folder, "isTestSource") == Some("true") => { + &mut facts.test_source_paths + } + _ => &mut facts.source_paths, }; if !target.contains(&relative) { target.push(relative); @@ -182,6 +290,12 @@ fn read_module( } for entry in xml::children(manager, "orderEntry") { match xml::attribute(entry, "type") { + Some("jdk") => facts.sdk = xml::attribute(entry, "jdkName").map(str::to_owned), + Some("module") => { + if let Some(name) = xml::attribute(entry, "module-name") { + facts.module_dependencies.push(name.to_owned()); + } + } Some("module-library") => { if let Some(library) = xml::children(entry, "library").next() { let name = xml::attribute(library, "name") @@ -204,11 +318,11 @@ fn read_module( .unwrap_or_default() .to_string(); match xml::attribute(entry, "level") { - Some("project") => match project_libraries.get(&name).cloned() { + Some("project") => match project_libraries.get(&name) { Some(library) => { add_library( root, - &library, + library, &name, Origin::IdeaProjectLibrary, macros, @@ -216,10 +330,7 @@ fn read_module( 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, @@ -257,6 +368,13 @@ fn add_library( facts: &mut IdeaFacts, roots: &mut usize, ) { + let jar_directories: Vec<_> = xml::children(library, "jarDirectory") + .filter(|entry| xml::attribute(entry, "type") != Some("SOURCES")) + .filter_map(|entry| { + let path = expand(xml::attribute(entry, "url")?, macros, base)?; + Some((path, xml::attribute(entry, "recursive") == Some("true"))) + }) + .collect(); for classes in xml::children(library, "CLASSES") { for entry in xml::children(classes, "root") { if *roots >= MAX_LIBRARY_ROOTS { @@ -273,10 +391,20 @@ fn add_library( continue; }; if path.is_dir() { - facts.unresolved.push(Unresolved { - kind: UnresolvedKind::ClassFolder, - name: relative_or_absolute(root, &path), - }); + if !jar_directories + .iter() + .any(|(directory, _)| directory == &path) + { + push( + &mut facts.class_folders, + Detected { + pattern: relative_or_absolute(root, &path), + origin, + label: name.to_string(), + count: 1, + }, + ); + } continue; } if !path.is_file() { @@ -286,44 +414,48 @@ fn add_library( }); continue; } - push(facts, relative_or_absolute(root, &path), origin, name, 1); + push( + &mut facts.libraries, + Detected { + pattern: relative_or_absolute(root, &path), + origin, + label: name.to_string(), + count: 1, + }, + ); } } - for directory in xml::children(library, "jarDirectory") { - let Some(path) = xml::attribute(directory, "url").and_then(|url| expand(url, macros, base)) - else { - continue; - }; + for (path, recursive) in jar_directories { let count = super::web::count_libraries(&path); - if count == 0 && xml::attribute(directory, "recursive") != Some("true") { + if count == 0 && !recursive { continue; } - let glob = if xml::attribute(directory, "recursive") == Some("true") { - "**/*.jar" - } else { - "*.jar" - }; + let glob = if recursive { "**/*.jar" } else { "*.jar" }; push( - facts, - format!("{}/{glob}", relative_or_absolute(root, &path)), - origin, - name, - count.max(1), + &mut facts.libraries, + Detected { + pattern: format!("{}/{glob}", relative_or_absolute(root, &path)), + origin, + label: name.to_string(), + count: 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, - }); +fn push(libraries: &mut Vec, library: Detected) { + if !libraries.iter().any(|item| item.pattern == library.pattern) { + libraries.push(library); } } +fn append_unique(target: &mut Vec, values: &[T]) { + for value in values { + if !target.contains(value) { + target.push(value.clone()); + } + } +} /// 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)) @@ -418,16 +550,20 @@ mod tests { #[test] fn modules_source_folders_and_libraries_are_imported_read_only() { let tree = Tree::new(&[ + ( + ".idea/misc.xml", + r#""#, + ), ( ".idea/modules.xml", r#" - + "#, ), ( - "app.iml", + ".idea/app.iml", r#" @@ -435,6 +571,8 @@ mod tests { + + @@ -475,6 +613,21 @@ mod tests { assert_eq!(facts.modules, 2); assert_eq!(facts.source_paths, vec!["src", "core/java"]); assert_eq!(facts.test_source_paths, vec!["test"]); + assert_eq!(facts.module_details[0].descriptor, ".idea/app.iml"); + let app = &facts.module_details[0]; + assert_eq!(app.content_roots, ["."]); + assert_eq!(app.resources, ["resources"]); + assert_eq!(app.test_resources, ["test-resources"]); + assert_eq!(app.excluded, ["generated"]); + assert_eq!(app.output.as_deref(), Some("out/production/app")); + assert_eq!(app.test_output.as_deref(), Some("out/test/app")); + assert!(app.inherits_output); + assert_eq!(facts.module_details[0].module_dependencies, vec!["core"]); + assert_eq!( + facts.module_details[0].class_folders[0].pattern, + "classes-folder" + ); + assert_eq!(facts.module_details[1].libraries[0].label, "shared"); let libraries: Vec<_> = facts .libraries .iter() @@ -514,7 +667,6 @@ mod tests { .unwrap() ), (UnresolvedKind::MissingFile, "lib/missing.jar"), - (UnresolvedKind::ClassFolder, "classes-folder"), (UnresolvedKind::UnknownMacro, "jar://$TOOLS_DIR$/x.jar!/"), (UnresolvedKind::IdeLibrary, "Global Utils"), (UnresolvedKind::MissingLibrary, "absent"), diff --git a/backend/src/project_model/mod.rs b/backend/src/project_model/mod.rs index a5f3ae5..a57191b 100644 --- a/backend/src/project_model/mod.rs +++ b/backend/src/project_model/mod.rs @@ -18,6 +18,7 @@ pub mod eclipse; mod idea; +pub(crate) use idea::IdeaModule; mod scan; pub mod servlet; mod web; @@ -25,6 +26,7 @@ mod xml; use serde_json::{json, Value}; use servlet::{ServletEnvironment, ServletResolution}; +use std::collections::BTreeMap; use std::fs; use std::io::Read; use std::path::{Path, PathBuf}; @@ -36,6 +38,7 @@ 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/**"; +pub const CLASS_FOLDERS_KEY: &str = "java.lithe.classFolders"; /// Largest descriptor file read. pub const MAX_DESCRIPTOR_BYTES: u64 = 2 * 1024 * 1024; @@ -126,8 +129,6 @@ pub enum UnresolvedKind { 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. @@ -150,6 +151,7 @@ pub struct ProjectModel { /// Workspace-relative descriptor that identifies the model, if any. pub descriptor: Option, pub idea_modules: usize, + pub(crate) idea_module_details: Vec, pub eclipse_projects: usize, /// Libraries for the invisible project; empty for managed kinds. pub libraries: Vec, @@ -201,6 +203,7 @@ pub fn detect(root: &Path, options: &ModelOptions, environment: &Environment) -> enabled: options.detection, descriptor: None, idea_modules: 0, + idea_module_details: Vec::new(), eclipse_projects: found.eclipse_projects.len(), libraries: Vec::new(), source_paths: Vec::new(), @@ -285,6 +288,7 @@ pub fn detect(root: &Path, options: &ModelOptions, environment: &Environment) -> .chain(idea.test_source_paths) .collect(); model.libraries = idea.libraries; + model.idea_module_details = idea.module_details; model.unresolved = idea.unresolved; model.needs_servlet = idea.needs_servlet; model.truncated |= idea.truncated; @@ -322,14 +326,31 @@ pub struct Explicit { pub libraries: Option, pub source_paths: Option, pub output_path: Option, + pub class_folders: Option, + pub source_roles: BTreeMap<&'static str, Vec>, } +pub(crate) const SOURCE_ROLE_KEYS: [(&str, &str); 4] = [ + ("test", "java.lithe.testSourceFolders"), + ("resource", "java.lithe.resourceFolders"), + ("test-resource", "java.lithe.testResourceFolders"), + ("excluded", "java.lithe.excludedSourceFolders"), +]; + 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(), + class_folders: document.get(CLASS_FOLDERS_KEY).cloned(), + source_roles: SOURCE_ROLE_KEYS + .into_iter() + .filter_map(|(kind, key)| { + let paths = strings(document.get(key)); + (!paths.is_empty()).then_some((kind, paths)) + }) + .collect(), } } @@ -405,7 +426,7 @@ pub fn effective_source_paths(model: &ProjectModel, explicit: &Explicit) -> Opti /// 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 { +pub fn overlay(root: &Path, model: &ProjectModel, explicit: &Explicit) -> Value { let mut project = json!({}); if let Some(libraries) = effective_libraries(model, explicit) { project["referencedLibraries"] = libraries; @@ -417,13 +438,71 @@ pub fn overlay(model: &ProjectModel, explicit: &Explicit) -> Value { project["outputPath"] = output.clone(); } let runtime = model.servlet.runtime.as_ref(); - if model.enabled && runtime.is_none() { + let mut seen = std::collections::BTreeSet::new(); + let class_folders: Vec<_> = if model.kind.managed() { + Vec::new() + } else { + strings(explicit.class_folders.as_ref()) + .into_iter() + .chain(model.idea_module_details.iter().flat_map(|module| { + module + .class_folders + .iter() + .map(|folder| folder.pattern.clone()) + })) + .filter(|path| !path.trim().is_empty() && path.len() <= 4096) + .map(|path| root.join(path)) + .filter(|path| seen.insert(path.clone())) + .take(1024) + .collect() + }; + let canonical_root = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf()); + let roles = if matches!(model.kind, ModelKind::Plain | ModelKind::LegacyWeb) { + let mut roles = BTreeMap::new(); + for (&kind, paths) in &explicit.source_roles { + let paths: Vec<_> = paths + .iter() + .take(256) + .filter(|path| crate::library_settings::valid_path(path)) + .filter_map(|path| dunce::canonicalize(canonical_root.join(path)).ok()) + .filter(|path| path.is_dir() && path.starts_with(&canonical_root)) + .collect(); + if !paths.is_empty() { + roles.insert(kind, paths); + } + } + roles + } else { + BTreeMap::new() + }; + let workspace_module = matches!(model.kind, ModelKind::Plain | ModelKind::LegacyWeb); + let workspace_source_paths = workspace_module + .then_some(explicit.source_paths.as_ref()) + .flatten() + .filter(|paths| { + paths + .as_array() + .is_some_and(|paths| !paths.is_empty() || roles.contains_key("excluded")) + }); + let manages_workspace_paths = + workspace_module && (workspace_source_paths.is_some() || explicit.output_path.is_some()); + if model.enabled + && runtime.is_none() + && class_folders.is_empty() + && roles.is_empty() + && !manages_workspace_paths + { return json!({"project": project}); } json!({ "project": project, "lithe": {"projectModel": { "enabled": model.enabled, + "classFolderWorkspace": root, + "classFolders": class_folders, + "sourceRoles": roles, + "workspaceSourcePaths": workspace_source_paths, + "workspaceOutputPath": workspace_module.then(|| explicit.output_path.as_ref().and_then(Value::as_str).unwrap_or("")), "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(), @@ -557,7 +636,7 @@ pub(crate) mod tests { model.descriptor.as_deref(), Some("project/WebContent/WEB-INF/web.xml") ); - let value = overlay(&model, &Explicit::default()); + let value = overlay(&tree.root, &model, &Explicit::default()); assert_eq!( value["project"]["referencedLibraries"], json!([ @@ -578,6 +657,24 @@ pub(crate) mod tests { ); } + #[test] + fn excluding_the_only_source_root_overrides_jdt_with_an_empty_source_list() { + let tree = Tree::new(&[("src/Main.java", "")]); + let root = dunce::canonicalize(&tree.root).unwrap(); + let model = detect(&root, &ModelOptions::default(), &environment(&tree)); + let explicit = Explicit::from_document(&json!({ + "java.project.sourcePaths": [], + "java.lithe.excludedSourceFolders": ["src"], + })); + let value = overlay(&root, &model, &explicit); + assert_eq!( + value["lithe"]["projectModel"]["workspaceSourcePaths"], + json!([]) + ); + let inherited = Explicit::from_document(&json!({"java.project.sourcePaths": []})); + assert!(overlay(&root, &model, &inherited).get("lithe").is_none()); + } + #[test] fn explicit_values_stay_first_and_keep_excludes_and_sources() { let tree = Tree::new(&[("WebRoot/WEB-INF/lib/a.jar", "")]); @@ -587,7 +684,7 @@ pub(crate) mod tests { "java.project.sourcePaths": ["src/java"], "java.project.outputPath": "out", })); - let value = overlay(&model, &explicit); + let value = overlay(&tree.root, &model, &explicit); assert_eq!( value["project"]["referencedLibraries"]["include"], json!(["vendor/x.jar", "WebRoot/WEB-INF/lib/*.jar"]) @@ -602,8 +699,10 @@ pub(crate) mod tests { ); 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()); + let bundle = &value["lithe"]["projectModel"]; + assert_eq!(bundle["workspaceSourcePaths"], json!(["src/java"])); + assert_eq!(bundle["workspaceOutputPath"], "out"); + assert_eq!(bundle["serverRuntimeLibraries"], json!([])); } #[test] @@ -620,7 +719,7 @@ pub(crate) mod tests { ]); let model = detect(&tree.root, &ModelOptions::default(), &environment(&tree)); assert_eq!(model.kind, ModelKind::Idea); - let value = overlay(&model, &Explicit::default()); + let value = overlay(&tree.root, &model, &Explicit::default()); assert_eq!(value["project"]["sourcePaths"], json!(["java", "tests"])); assert!(value["project"].get("referencedLibraries").is_none()); assert!(value.get("lithe").is_none()); @@ -630,7 +729,10 @@ pub(crate) mod tests { (model.kind, model.descriptor.as_deref()), (ModelKind::Gradle, Some("module/build.gradle")) ); - assert_eq!(overlay(&model, &Explicit::default())["project"], json!({})); + assert_eq!( + overlay(&tree.root, &model, &Explicit::default())["project"], + json!({}) + ); } #[test] @@ -656,7 +758,7 @@ pub(crate) mod tests { name: "Libs".into() }] ); - let value = overlay(&model, &Explicit::default()); + let value = overlay(&tree.root, &model, &Explicit::default()); assert_eq!(value["project"], json!({})); assert_eq!( value["lithe"]["projectModel"]["serverRuntimeHome"], @@ -674,7 +776,7 @@ pub(crate) mod tests { }; let model = detect(&tree.root, &options, &environment(&tree)); assert_eq!(model.kind, ModelKind::LegacyWeb); - let value = overlay(&model, &Explicit::default()); + let value = overlay(&tree.root, &model, &Explicit::default()); assert_eq!(value["project"], json!({})); assert_eq!(value["lithe"]["projectModel"]["enabled"], false); } diff --git a/backend/src/project_settings.rs b/backend/src/project_settings.rs index 25bf76b..aa18b41 100644 --- a/backend/src/project_settings.rs +++ b/backend/src/project_settings.rs @@ -14,7 +14,7 @@ use std::path::{Path, PathBuf}; use std::sync::Mutex; use url::Url; -use crate::project_model::{self, Environment, Explicit, ModelOptions, ProjectModel}; +use crate::project_model::{self, Environment, Explicit, ModelKind, ModelOptions, ProjectModel}; const LIMIT: u64 = 2 * 1024 * 1024; const TARGET: &str = "org.eclipse.jdt.core.compiler.codegen.targetPlatform"; @@ -27,6 +27,11 @@ 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"; +const OUTPUT_KEY: &str = "java.project.outputPath"; +const JDT_COMMAND_TIMEOUT_MS: u64 = 30_000; +const WORKSPACE_CLASSPATH_TIMEOUT_MS: u64 = 1_500; +const WORKSPACE_AFTER_SAVE_TIMEOUT_MS: u64 = 10_000; +const WORKSPACE_CLASSPATH_UNAVAILABLE: &str = "java.workspaceSettings.classpathUnavailable"; /// Bounded native read bindings; no configuration documents or tool models are cached. #[derive(Default)] @@ -77,9 +82,17 @@ fn root(context: &Context) -> Result { dunce::canonicalize(path).map_err(|_| fail()) } fn command(context: &Context, name: &str, args: Value) -> Result { + command_with_timeout(context, name, args, JDT_COMMAND_TIMEOUT_MS) +} +fn command_with_timeout( + context: &Context, + name: &str, + args: Value, + timeout_ms: u64, +) -> Result { context.check_cancelled()?; let workspace = context.workspace_context().ok_or_else(fail)?; - let answer=context.host().request(crate::settings_session::REQUEST_METHOD,json!({"context":workspace.to_value(),"serverID":"java","method":"workspace/executeCommand","params":{"command":name,"arguments":args},"timeoutMilliseconds":30000})).map_err(|_|fail())?; + let answer=context.host().request(crate::settings_session::REQUEST_METHOD,json!({"context":workspace.to_value(),"serverID":"java","method":"workspace/executeCommand","params":{"command":name,"arguments":args},"timeoutMilliseconds":timeout_ms})).map_err(|_|fail())?; Ok(answer.get("value").cloned().unwrap_or(Value::Null)) } fn local(zh: bool, en: &str, cn: &str) -> String { @@ -173,7 +186,7 @@ fn compiler_fields( } impl ProjectSettings { - /// Projects native settings only after the declared JDT server is ready. + /// Projects native settings and reports the JDT facts available for them. pub fn snapshot( &self, params: Value, @@ -191,7 +204,29 @@ impl ProjectSettings { .refresh_native_settings(context.workspace_context().ok_or_else(fail)?, &root) .map_err(|_| fail())?; } - let projects = command(context, "java.project.getAll", json!([]))?; + 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)?); + Some(( + project_model::detect(&root, &options, &Environment::current()), + explicit, + )) + } else { + None + }; + let workspace_module = model.as_ref().is_some_and(|(model, _)| { + matches!(model.kind, ModelKind::Plain | ModelKind::LegacyWeb) + }); + let workspace_uri = model + .as_ref() + .filter(|(model, _)| workspace_module || !model.idea_module_details.is_empty()) + .and_then(|_| Url::from_file_path(&root).ok()); + let projects = if let Some(uri) = &workspace_uri { + json!([uri.as_str()]) + } else { + command(context, "java.project.getAll", json!([]))? + }; if params["operation"] == "readAfterSave" { let identifiers: Vec<_> = projects .as_array() @@ -211,10 +246,63 @@ impl ProjectSettings { LIBRARIES_FACT, crate::library_settings::SOURCE_PATHS_FACT ]); + // The workspace configuration is available while JDT waits for indexing. + let workspace_timeout = if params["operation"] == "readAfterSave" { + WORKSPACE_AFTER_SAVE_TIMEOUT_MS + } else { + WORKSPACE_CLASSPATH_TIMEOUT_MS + }; + let mut workspace_degraded = false; + let workspace_classpaths = workspace_uri.as_ref().and_then(|uri| { + let resolved = resolved_classpaths(context, uri.as_str(), workspace_timeout); + if resolved.is_none() { + workspace_degraded = true; + } + resolved + }); let mut facts = Vec::new(); + if let Some(uri) = &workspace_uri { + let settings = if workspace_classpaths.is_some() { + match command_with_timeout( + context, + "java.project.getSettings", + json!([ + uri.as_str(), + [ + LIBRARIES_FACT, + crate::library_settings::SOURCE_PATHS_FACT, + crate::library_settings::OUTPUT_PATH_FACT + ] + ]), + workspace_timeout, + ) { + Ok(value) => value, + Err(_) => { + workspace_degraded = true; + Value::Null + } + } + } else { + Value::Null + }; + facts.push((root.clone(), settings)); + } + if workspace_degraded { + let _ = context.diagnostics().degraded( + context.function_id(), + WORKSPACE_CLASSPATH_UNAVAILABLE, + Some(1), + ); + } + context.check_cancelled()?; // 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)? { + for entry in projects + .as_array() + .ok_or_else(fail)? + .iter() + .filter(|_| workspace_uri.is_none()) + { context.check_cancelled()?; let value = entry.as_str().ok_or_else(fail)?; let path = Url::parse(value) @@ -275,31 +363,25 @@ impl ProjectSettings { // 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( + let described = if libraries && workspace_uri.is_none() { + command( context, crate::library_settings::DESCRIBE_COMMAND, json!([]), ) - .ok(); - Some((model, explicit, described)) + .ok() } 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 page = model + .as_ref() + .map(|(model, explicit)| 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(); @@ -335,8 +417,22 @@ impl ProjectSettings { .replace('\\', "/"); let id = format!("source{:x}", Sha256::digest(rel.as_bytes())); let (bytes, revision) = read(&source_path)?; + let mut writable = true; let mut fields = if let Some(page) = &page { - page.settings_fields(&fact, library_input(&native_json(&bytes)?)) + let settings = native_json(&bytes)?; + if workspace_module { + let explicit = Explicit::from_document(&settings); + let page = crate::library_settings::Page { + explicit: &explicit, + ..*page + }; + let (fields, complete) = + page.workspace_fields(&fact, workspace_classpaths.as_deref()); + writable = complete; + fields + } else { + page.settings_fields(&fact, library_input(&settings)) + } } else { compiler_fields(zh, &properties(&bytes)?, &fact, true) }; @@ -350,10 +446,21 @@ 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})); + if writable { + bindings.insert(id.clone(), source_path); + } + let title = crate::module_structure::clean_text( + &crate::module_structure::project_name(&path), + 256, + ); + let title = if title.trim().is_empty() { + "Java".to_owned() + } else { + title + }; + sources.push(json!({"id":id,"group":if libraries && !workspace_module{"libraries"}else{"modules"},"title":title,"path":rel,"revision":revision,"writable":writable,"fields":fields})); } - let module_sources = if libraries { + let mut module_sources = if libraries { self.module_sources( context, zh, @@ -366,10 +473,44 @@ impl ProjectSettings { } else { Vec::new() }; + if let Some(page) = &page { + if !page.model.idea_module_details.is_empty() { + for module in &page.model.idea_module_details { + let Ok(file) = dunce::canonicalize(root.join(&module.descriptor)) else { + continue; + }; + let Some(rel) = project_model::relative_inside(&root, &file) else { + continue; + }; + if rel == "." || rel.split('/').any(|part| part == "." || part == "..") { + continue; + } + if !paths.insert(file.clone()) { + continue; + } + let (_, revision) = read(&file)?; + let id = format!("idea{:x}", Sha256::digest(rel.as_bytes())); + let fields = crate::module_structure::idea_fields( + zh, + &root, + module, + workspace_classpaths.as_deref(), + ); + let title = crate::module_structure::clean_text(&module.name, 256); + let title = if title.trim().is_empty() { + "IDEA".to_owned() + } else { + title + }; + module_sources.push(json!({"id":id,"group":"modules","title":title,"path":rel,"revision":revision,"writable":false,"fields":fields})); + } + } + } let mut groups = if libraries { let mut groups = Vec::new(); if module_sources .iter() + .chain(&sources) .any(|source| source["group"] == "modules") { groups.push( @@ -382,9 +523,7 @@ impl ProjectSettings { { groups.push(json!({"id":"facets","title":local(zh,"Web Facets","Web Facet"),"layout":"sidebar"})); } - if module_sources.is_empty() - || sources.iter().any(|source| source["group"] == "libraries") - { + if sources.iter().any(|source| source["group"] == "libraries") { groups.push(json!({"id":"libraries","title":local(zh,"Referenced libraries","引用的库"),"layout":"form"})); } groups @@ -528,21 +667,7 @@ impl ProjectSettings { 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 { + let Some(resolved) = resolved_classpaths(context, uri, JDT_COMMAND_TIMEOUT_MS) else { unavailable += 1; continue; }; @@ -676,6 +801,25 @@ impl ProjectSettings { } } +fn resolved_classpaths(context: &Context, uri: &str, timeout_ms: u64) -> Option> { + // JDT reads the options from a JSON string, as vscode-java sends them. + let value = command_with_timeout( + context, + "java.project.getClasspaths", + json!([uri, r#"{"scope":"test"}"#]), + timeout_ms, + ) + .ok()?; + Some( + value["classpaths"] + .as_array()? + .iter() + .filter_map(Value::as_str) + .map(str::to_owned) + .collect(), + ) +} + /// 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. @@ -691,7 +835,7 @@ pub fn native_settings( let (bytes, _) = read(&root.join(SETTINGS))?; let explicit = Explicit::from_document(&native_json(&bytes)?); let model = project_model::detect(root, options, &Environment::current()); - let overlay = project_model::overlay(&model, &explicit); + let overlay = project_model::overlay(root, &model, &explicit); for section in ["project", "lithe"] { if overlay .get(section) @@ -731,7 +875,9 @@ fn edit_settings( values: &serde_json::Map, options: &ModelOptions, ) -> Result, FunctionError> { - use crate::library_settings::{LIBRARIES_FIELD, SOURCE_PATHS_FIELD, STORE_DETECTED_FIELD}; + use crate::library_settings::{ + CLASS_FOLDERS_FIELD, 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)?; @@ -739,6 +885,140 @@ fn edit_settings( if let Some(paths) = values.get(SOURCE_PATHS_FIELD) { document = edit_json(&document, SOURCE_PATHS_KEY, paths)?; } + if let Some(roots) = values.get(crate::module_structure::ROOTS_FIELD) { + let existing_explicit = Explicit::from_document(&native_json(&document)?); + let normalize_existing = |path: &str| -> String { + let normalized = path.replace('\\', "/"); + if normalized == "." { + normalized + } else { + normalized.trim_end_matches('/').to_owned() + } + }; + let existing_known: BTreeSet = existing_explicit + .source_paths + .as_ref() + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(Value::as_str) + .chain( + existing_explicit + .source_roles + .values() + .flat_map(|paths| paths.iter().map(String::as_str)), + ) + .map(normalize_existing) + .collect(); + let canonical_root = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf()); + let mut roles = BTreeMap::<&str, Vec>::new(); + let paths = match roots { + Value::Null => Value::Null, + Value::Array(entries) if entries.len() <= 256 => { + let mut folders: Vec<(&str, String)> = Vec::new(); + for entry in entries { + let kind = entry["kind"] + .as_str() + .filter(|kind| { + *kind == "folder" + || project_model::SOURCE_ROLE_KEYS + .iter() + .any(|(role, _)| role == kind) + }) + .ok_or_else(fail)?; + let raw_path = entry["value"] + .as_str() + .filter(|path| crate::library_settings::valid_path(path)) + .ok_or_else(fail)?; + let path = Path::new(raw_path); + let candidate = if path.is_absolute() { + path.to_path_buf() + } else { + canonical_root.join(path) + }; + let relative = match dunce::canonicalize(&candidate) { + Ok(resolved) => { + if !resolved.is_dir() { + return Err(fail()); + } + project_model::relative_inside(&canonical_root, &resolved) + .ok_or_else(fail)? + } + Err(_) => { + let normalized = normalize_existing(raw_path); + let safe_relative = !normalized.is_empty() + && !Path::new(&normalized).is_absolute() + && Path::new(&normalized).components().all(|part| { + matches!( + part, + std::path::Component::Normal(_) + | std::path::Component::CurDir + ) + }); + if !safe_relative || !existing_known.contains(&normalized) { + return Err(fail()); + } + normalized + } + }; + if relative.contains(['*', '?', '|']) || (kind == "excluded" && relative == ".") + { + return Err(fail()); + } + if let Some((mark, _)) = folders.iter_mut().find(|(_, path)| *path == relative) + { + *mark = kind; + } else { + folders.push((kind, relative)); + } + } + let mut paths = Vec::new(); + for (kind, relative) in folders { + if kind != "folder" { + roles.entry(kind).or_default().push(relative.clone()); + } + if kind != "excluded" { + paths.push(relative); + } + } + json!(paths) + } + _ => return Err(fail()), + }; + document = edit_json(&document, SOURCE_PATHS_KEY, &paths)?; + let current = native_json(&document)?; + for (kind, key) in project_model::SOURCE_ROLE_KEYS { + let value = roles.remove(kind).map_or(Value::Null, |paths| json!(paths)); + if current.get(key).unwrap_or(&Value::Null) != &value { + document = edit_json(&document, key, &value)?; + } + } + } + if let Some(paths) = values.get(CLASS_FOLDERS_FIELD) { + document = edit_json(&document, project_model::CLASS_FOLDERS_KEY, paths)?; + } + if let Some(entries) = values.get(crate::module_structure::DEPENDENCIES_FIELD) { + document = edit_workspace_dependencies(root, &document, entries)?; + } + if let Some(output) = values.get(crate::module_structure::OUTPUT_FIELD) { + let output = match output { + Value::Null => Value::Null, + Value::String(path) if path.trim().is_empty() => Value::Null, + Value::String(path) + if crate::library_settings::valid_path(path) + && Path::new(path).components().all(|part| { + matches!( + part, + std::path::Component::Normal(_) | std::path::Component::CurDir + ) + }) => + { + output.clone() + } + _ => return Err(fail()), + }; + document = edit_json(&document, OUTPUT_KEY, &output)?; + } if let Some(store) = values.get(STORE_DETECTED_FIELD) { let store = match store { Value::Bool(store) => *store, @@ -768,7 +1048,88 @@ fn edit_settings( } Ok(document) } -/// Sets or (with null) removes the string list `key`; a rich + +fn edit_workspace_dependencies( + root: &Path, + bytes: &[u8], + entries: &Value, +) -> Result, FunctionError> { + use crate::library_settings::{ + jar_directory, valid_path, ARCHIVE, CLASS_FOLDER, JAR_DIRECTORY, + }; + let settings = native_json(bytes)?; + let original = Explicit::from_document(&settings); + let mut include = Vec::new(); + let mut classes = Vec::new(); + if !entries.is_null() { + let entries = entries + .as_array() + .filter(|items| items.len() <= 256) + .ok_or_else(fail)?; + for entry in entries { + let path = entry["value"] + .as_str() + .filter(|path| valid_path(path)) + .ok_or_else(fail)?; + let (list, value) = match entry["kind"].as_str() { + Some(ARCHIVE) => (&mut include, path.to_owned()), + Some(CLASS_FOLDER) => (&mut classes, path.to_owned()), + Some(JAR_DIRECTORY) => { + let normalized = path.replace('\\', "/"); + let pattern = if jar_directory(&normalized).is_some() { + path.to_owned() + } else { + let canonical_root = + dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf()); + let input_path = Path::new(path); + let candidate = if input_path.is_absolute() { + dunce::canonicalize(input_path) + .unwrap_or_else(|_| input_path.to_path_buf()) + } else { + dunce::canonicalize(canonical_root.join(input_path)) + .unwrap_or_else(|_| input_path.to_path_buf()) + }; + let base = project_model::relative_inside(&canonical_root, &candidate) + .or_else(|| project_model::relative_inside(root, input_path)) + .unwrap_or(normalized); + format!("{}/*.jar", base.trim_end_matches('/')) + }; + if !valid_path(&pattern) { + return Err(fail()); + } + (&mut include, pattern) + } + _ => return Err(fail()), + }; + if !list.contains(&value) { + list.push(value); + } + } + } + let mut document = bytes.to_vec(); + let implicit = [project_model::UPSTREAM_DEFAULT_LIBRARIES]; + if entries.is_null() || !(original.libraries.is_none() && include == implicit) { + let libraries = if entries.is_null() { + Value::Null + } else { + json!(include) + }; + if library_input(&settings) != libraries { + document = edit_json(&document, LIBRARY_KEY, &libraries)?; + } + } + let classes = if classes.is_empty() { + Value::Null + } else { + json!(classes) + }; + if original.class_folders.unwrap_or(Value::Null) != classes { + document = edit_json(&document, project_model::CLASS_FOLDERS_KEY, &classes)?; + } + Ok(document) +} + +/// Sets or (with null) removes `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> { @@ -785,17 +1146,21 @@ fn edit_json(bytes: &[u8], key: &str, libraries: &Value) -> Result, Func prop.remove(); } } else { - let values = libraries - .as_array() - .ok_or_else(fail)? - .iter() - .map(|v| { - v.as_str() - .map(|s| CstInputValue::String(s.to_owned())) - .ok_or_else(fail) - }) - .collect::, _>>()?; - let input = CstInputValue::Array(values); + let input = if key == OUTPUT_KEY { + CstInputValue::String(libraries.as_str().ok_or_else(fail)?.to_owned()) + } else { + let values = libraries + .as_array() + .ok_or_else(fail)? + .iter() + .map(|v| { + v.as_str() + .map(|s| CstInputValue::String(s.to_owned())) + .ok_or_else(fail) + }) + .collect::, _>>()?; + CstInputValue::Array(values) + }; if let Some(prop) = target.get(key) { prop.set_value(input); } else { @@ -988,6 +1353,65 @@ mod tests { } } } + #[test] + fn selecting_another_role_for_a_source_folder_replaces_the_previous_role() { + let directory = TestDirectory::new(); + let root = dunce::canonicalize(&directory.0).unwrap(); + fs::create_dir(root.join("src")).unwrap(); + let values = json!({"roots":[{"kind":"folder","value":"src"},{"kind":"test","value":root.join("src")}]}); + let updated = edit_settings( + &root, + b"{}", + values.as_object().unwrap(), + &ModelOptions::default(), + ) + .unwrap(); + let document = native_json(&updated).unwrap(); + assert_eq!(document[SOURCE_PATHS_KEY], json!(["src"])); + assert_eq!(document["java.lithe.testSourceFolders"], json!(["src"])); + } + + #[test] + fn jar_directory_with_uncanonicalized_root_writes_relative_glob() { + let directory = TestDirectory::new(); + let lib_dir = directory.0.join("WebRoot/WEB-INF/lib"); + fs::create_dir_all(&lib_dir).unwrap(); + let canonical_root = dunce::canonicalize(&directory.0).unwrap(); + let entries = json!([{"kind":"jar-directory","value":lib_dir}]); + let updated = edit_workspace_dependencies(&canonical_root, b"{}", &entries).unwrap(); + let parsed = native_json(&updated).unwrap(); + assert_eq!(parsed[LIBRARY_KEY], json!(["WebRoot/WEB-INF/lib/*.jar"])); + } + + #[test] + fn editing_roots_preserves_existing_missing_folder_but_rejects_new_missing_folder() { + let directory = TestDirectory::new(); + let root = dunce::canonicalize(&directory.0).unwrap(); + fs::create_dir(root.join("test")).unwrap(); + let initial = br#"{"java.project.sourcePaths":["missing-src"]}"#; + let updated = edit_settings( + &root, + initial, + json!({"roots":[{"kind":"folder","value":"missing-src"},{"kind":"test","value":"test"}]}) + .as_object() + .unwrap(), + &ModelOptions::default(), + ) + .unwrap(); + let parsed = native_json(&updated).unwrap(); + assert_eq!(parsed[SOURCE_PATHS_KEY], json!(["missing-src", "test"])); + assert_eq!(parsed["java.lithe.testSourceFolders"], json!(["test"])); + assert!(edit_settings( + &root, + initial, + json!({"roots":[{"kind":"folder","value":"never-existed"}]}) + .as_object() + .unwrap(), + &ModelOptions::default(), + ) + .is_err()); + } + #[test] fn rich_library_configuration_keeps_excludes_sources_and_comments() { let source = br#"{ // private comment @@ -997,9 +1421,17 @@ mod tests { "sources": {"old.jar": "old-sources.jar"} }, "privateToken": "untouched" }"#; - let updated = edit_json(source, LIBRARY_KEY, &json!(["new.jar"])).unwrap(); + let updated = edit_workspace_dependencies( + Path::new("."), + source, + &json!([{"kind":"archive","value":"new.jar"},{"kind":"classes","value":"WebRoot/WEB-INF/classes"}]), + ).unwrap(); let parsed = native_json(&updated).unwrap(); assert_eq!(parsed[LIBRARY_KEY]["include"], json!(["new.jar"])); + assert_eq!( + parsed[project_model::CLASS_FOLDERS_KEY], + json!(["WebRoot/WEB-INF/classes"]) + ); assert_eq!(parsed[LIBRARY_KEY]["exclude"], json!(["secret/**/*.jar"])); assert_eq!(parsed[LIBRARY_KEY]["sources"]["old.jar"], "old-sources.jar"); assert!(String::from_utf8(updated.clone()) @@ -1014,6 +1446,33 @@ mod tests { assert_eq!(reset["privateToken"], "untouched"); } + #[test] + fn editing_class_folders_keeps_the_default_jar_rule_until_it_is_removed() { + let source = br#"{"editor.tabSize":4}"#; + let entries = json!([ + {"kind":"jar-directory","value":"lib/**"}, + {"kind":"classes","value":"WEB-INF/classes"} + ]); + let source = edit_workspace_dependencies(Path::new("."), source, &entries).unwrap(); + let parsed = native_json(&source).unwrap(); + assert!(parsed.get(LIBRARY_KEY).is_none()); + assert_eq!( + parsed[project_model::CLASS_FOLDERS_KEY], + json!(["WEB-INF/classes"]) + ); + let removed = edit_workspace_dependencies(Path::new("."), &source, &json!([])).unwrap(); + let parsed = native_json(&removed).unwrap(); + assert_eq!(parsed[LIBRARY_KEY], json!([])); + assert!(parsed.get(project_model::CLASS_FOLDERS_KEY).is_none()); + assert_eq!(parsed["editor.tabSize"], 4); + assert!(edit_workspace_dependencies( + Path::new("."), + &removed, + &json!([{"kind":"unsupported","value":"lib"}]) + ) + .is_err()); + } + #[test] fn properties_edits_preserve_comments_private_keys_and_escaped_continuations() { let source=b"# keep this comment\r\neclipse.preferences.version=1\r\nprivateKey=private-value\r\norg.eclipse.jdt.core.compiler.codegen.targetPlatform : 1.8\r\norg.eclipse.jdt.core.compiler.sou\\\r\n rce=1.8\r\n! trailing comment\r\n"; diff --git a/docs/assets/project-models/idea-en-dark.png b/docs/assets/project-models/idea-en-dark.png index addadb2..74fcbee 100644 Binary files a/docs/assets/project-models/idea-en-dark.png 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 index 17d0855..ec61429 100644 Binary files a/docs/assets/project-models/idea-zh-light.png and b/docs/assets/project-models/idea-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 index 6c7c21a..b9278c9 100644 Binary files a/docs/assets/project-models/legacy-web-en-light.png 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 index d531d93..ac69239 100644 Binary files a/docs/assets/project-models/legacy-web-zh-dark.png 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 24d6e42..8ac73b1 100644 --- a/docs/feature-matrix.md +++ b/docs/feature-matrix.md @@ -1,5 +1,13 @@ # 功能验证矩阵 +## 传统工程项目结构与目录标记 + +| 能力 | macOS | Windows | Linux | 证据 | +| --- | --- | --- | --- | --- | +| 普通 Java 与传统 Java EE 工作区按模块展示源码根、输出目录与依赖(统一维护 JAR、JAR 库目录与类目录并显示 JDT 类路径状态);支持源码/测试源码/资源/测试资源/排除目录标记及独立测试输出,确认保存后写回 `.vscode/settings.json` 并更新 JDT 类路径 | implemented / verified | implemented / pending | implemented / pending | `backend/src/library_settings.rs`、`backend/src/project_settings.rs`、`jdtls-extension/project-model/src/.../SourceFolderClasspath.java`、`ClassFolderClasspath.java`;单元测试及 macOS arm64 本机用 JDT LS 1.61.0 运行 `scripts/compiler/test-project-models.mjs`(`legacy-web` 场景)、`scripts/compiler/visual.mjs`(2026-11-19);原作者另称在 Windows 隔离工程用 JDT LS 1.61.0 验证过,本仓 Windows/Linux CI 与实机待补 | +| IDEA 模块只读展示内容根、目录标记、继承后生产/测试输出、SDK 与类路径状态,并将类目录注入 JDT 容器支持导航与补全 | implemented / verified | implemented / pending | implemented / pending | `backend/src/project_model/idea.rs`、`backend/src/module_structure.rs`、`jdtls-extension/project-model/src/.../ClassFolderClasspath.java`;单元测试及 macOS arm64 本机运行 `scripts/compiler/test-project-models.mjs`(`idea` 场景,含双类目录跳转/补全及 JDT 阻断降级)与 `scripts/compiler/visual.mjs`(2026-11-19) | +| 工作区与 IDEA 项目结构投影经宿主 Core `ReadSourceSettings` 校验与 Viva 无头截图渲染(中英文、明暗主题) | implemented / verified | — | — | `scripts/compiler/visual.mjs`,截图见 `docs/assets/project-models/`(2026-11-19 macOS arm64) | + ## 工具链分组与设置搜索关键词(本次改动) | 能力 | macOS | Windows | Linux | 证据 | diff --git a/docs/module-structure.md b/docs/module-structure.md index eeab309..0f11df1 100644 --- a/docs/module-structure.md +++ b/docs/module-structure.md @@ -14,9 +14,10 @@ | --- | --- | --- | | Eclipse 工程(有 `.classpath`) | 模块自己的 `.classpath` | 源文件夹(可标“测试”)、输出文件夹、JRE、依赖(JAR/ZIP、类文件夹、库容器、其他模块),每项可标“导出”“仅测试” | | Maven、Gradle 模块 | `pom.xml` / `build.gradle(.kts)` | 只读,显示 JDT 解析出的完整类路径(含测试依赖),请在构建文件里修改 | -| 没有 `.classpath` 的普通文件夹 | `.vscode/settings.json` | 仍在“引用的库”分组里编辑引用的 JAR 和源码文件夹 | +| IntelliJ IDEA 模块 | `.iml` 和项目的 `.idea/misc.xml` | 只读,显示内容根、目录标记、编译输出、SDK 和依赖。依赖行标明类型、来源和 JDT 是否加载 | +| 没有构建描述符的普通 Java、Java EE 文件夹 | `.vscode/settings.json` | 可标记源码、测试源码、资源、测试资源和排除目录,可修改输出路径,并添加 JAR、JAR 库目录和类目录 | -IntelliJ IDEA 工程、Eclipse 容器的解析结果仍在只读的“工程模型”分组里,见 [project-models.md](project-models.md)。 +IDEA 模块依赖的状态取自当前 JDT 工作区类路径。索引期间如果 JDT 未及时返回,页面仍显示 `.iml` 声明,并标记「JDT 类路径未确认」。索引结束后点「重新加载」可核对实际生效状态。展开式 JAR 和明确声明的 `WEB-INF/classes` 是类目录依赖;WAR/EAR 目录不会成为额外的源码模块。“引用的库”可在 `.vscode/settings.json` 补充 JAR、源码目录和类目录。Eclipse 容器的解析结果在“工程模型”中显示,见 [project-models.md](project-models.md)。 ## 依赖怎么添加 @@ -31,7 +32,7 @@ JRE 下拉框可选“工作区默认 JRE”或 JavaSE-1.8/11/17/21/25 执行环 ## 保存时保留什么 -只有点击“保存”才写文件,外部修改会要求重新读取。保存只改页面管理的条目,按种类和路径匹配已有条目,所以: +只有点击“保存”才写文件,外部修改会提示冲突并要求重新读取。保存只改页面管理的条目,按种类和路径匹配已有条目,所以: - 源码附件(`sourcepath`)、Javadoc 位置、访问规则等页面不显示的属性原样保留; - 注释和页面不显示的条目留在原位置,新条目按页面顺序依次占用原来的位置; diff --git a/docs/project-models.md b/docs/project-models.md index 27452be..009bb73 100644 --- a/docs/project-models.md +++ b/docs/project-models.md @@ -28,6 +28,7 @@ JDT LS 只认识 Maven、Gradle 和 Eclipse 的 `.project`,其余目录按“ | 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 的设置,仅内存 | +| IntelliJ IDEA 类目录 | 声明为编译库根的类目录,包括磁盘上实际为目录的展开式 JAR、`WEB-INF/classes` | 由插件扩展加入 JDT 内部工程的类路径容器 | | IDEA 应用服务器库、Web facet | Servlet 容器的 JAR | 同上 | | 传统 Web / EAR | `WEB-INF/lib/*.jar`、EAR 库目录、`MANIFEST.MF` 的 `Class-Path` | 同上 | @@ -35,7 +36,7 @@ JDT LS 只认识 Maven、Gradle 和 Eclipse 的 `.project`,其余目录按“ 始终优先:插件只在它们之后追加识别结果,保留其中的 `exclude` 和 `sources`;没有显式值时保留上游默认的 `lib/**`。 无法自动补全的条目会在“Java 库”设置页的“工程模型 → 未能解析”中逐项列出原因:IDEA 的全局库或应用库、 -只有 IDEA 知道的路径变量、类文件夹(JDT 只接受 JAR)、工作区之外的源码文件夹、Eclipse 用户库(定义在 Eclipse 工作区里)、 +只有 IDEA 知道的路径变量、工作区之外的源码文件夹、Eclipse 用户库(定义在 Eclipse 工作区里)、 不存在的文件。启动时同样以降级诊断计数记录:`launch.servlet_container_missing`、`launch.project_model_unresolved`、 `launch.project_model_truncated`。 @@ -60,6 +61,7 @@ Servlet 容器及其来源、Eclipse 每个项目的容器与变量解析结果 普通文件夹的 `.vscode/settings.json` 来源新增: - “源码文件夹”:`java.project.sourcePaths`,留空时继承 IDEA 模块的源码文件夹。 +- “补充类目录”:`java.lithe.classFolders`,每行一个工作区相对路径或绝对路径,加入 JDT 编译类路径。 - “将识别结果保存到此文件”:勾选并保存后,把识别出的库(不含本机 Servlet 容器路径)和 IDEA 源码文件夹写进 `.vscode/settings.json`,供 VS Code 等其他编辑器和团队成员使用;取消勾选并保存则移除这些条目。 diff --git a/io.github.lithe-idea.java-support/plugin.json b/io.github.lithe-idea.java-support/plugin.json index e412c80..a9ff8b1 100644 --- a/io.github.lithe-idea.java-support/plugin.json +++ b/io.github.lithe-idea.java-support/plugin.json @@ -806,8 +806,8 @@ "function": "java.resolveLaunch", "timeoutMilliseconds": 60000 }, - "requestMethods": ["java/classFileContents", "workspace/executeCommand"], - "commands": ["java.project.updateSettings", "vscode.java.buildWorkspace", "vscode.java.resolveClasspath", "vscode.java.resolveMainMethod", "vscode.java.test.findTestTypesAndMethods", "vscode.java.test.junit.argument"], + "requestMethods": ["java/classFileContents", "java/projectConfigurationsUpdate", "workspace/executeCommand"], + "commands": ["java.project.getAll", "java.project.getSettings", "java.project.getClasspaths", "lithe.java.projectModel.describe", "java.project.updateSettings", "vscode.java.buildWorkspace", "vscode.java.resolveClasspath", "vscode.java.resolveMainMethod", "vscode.java.test.findTestTypesAndMethods", "vscode.java.test.junit.argument"], "forwardNotifications": ["language/eventNotification", "language/progressReport", "language/status"], "state": { "scope": "workspace", diff --git a/jdtls-extension/project-model/plugin.xml b/jdtls-extension/project-model/plugin.xml index 8daa0bf..809089c 100644 --- a/jdtls-extension/project-model/plugin.xml +++ b/jdtls-extension/project-model/plugin.xml @@ -9,6 +9,7 @@ --> + diff --git a/jdtls-extension/project-model/src/io/github/lithe_idea/java/projectmodel/ClassFolderClasspath.java b/jdtls-extension/project-model/src/io/github/lithe_idea/java/projectmodel/ClassFolderClasspath.java new file mode 100644 index 0000000..ef88824 --- /dev/null +++ b/jdtls-extension/project-model/src/io/github/lithe_idea/java/projectmodel/ClassFolderClasspath.java @@ -0,0 +1,82 @@ +package io.github.lithe_idea.java.projectmodel; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.Path; +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.ProjectUtils; + +/** Adds IDEA class directories to JDT's own invisible project, whose metadata lives under the server workspace. */ +final class ClassFolderClasspath { + static final IPath ID = new Path("io.github.lithe_idea.java.projectmodel.IDEA_CLASS_FOLDERS"); + static final String DESCRIPTION = "IntelliJ IDEA class folders"; + + static void refresh(ProjectModelSettings settings, IProgressMonitor monitor) { + for (IJavaProject project : ProjectUtils.getJavaProjects()) { + if (monitor.isCanceled()) { + return; + } + if (!ProjectUtils.isUnmanagedFolder(project.getProject())) { + continue; + } + try { + List raw = new ArrayList<>(Arrays.asList(project.getRawClasspath())); + boolean present = raw.stream().anyMatch(ClassFolderClasspath::isOwned); + boolean active = applies(project, settings); + if (active) { + IClasspathEntry[] entries = entries(settings); + IClasspathContainer current = present ? JavaCore.getClasspathContainer(ID, project) : null; + if (current == null || !Arrays.equals(current.getClasspathEntries(), entries)) { + bind(project, entries, monitor); + } + if (!present) { + raw.add(JavaCore.newContainerEntry(ID)); + } + } else if (present) { + raw.removeIf(ClassFolderClasspath::isOwned); + } + if (present != active) { + project.setRawClasspath(raw.toArray(IClasspathEntry[]::new), monitor); + } + } catch (CoreException e) { + ProjectModelLog.error("Cannot update IDEA class folders for " + project.getElementName(), e); + } + } + } + + static void bind(IJavaProject project, ProjectModelSettings settings, IProgressMonitor monitor) throws CoreException { + bind(project, applies(project, settings) ? entries(settings) : new IClasspathEntry[0], monitor); + } + + private static IClasspathEntry[] entries(ProjectModelSettings settings) { + return settings.classFolders.stream() + .map(File::new) + .filter(File::isDirectory) + .map(folder -> JavaCore.newLibraryEntry(Path.fromOSString(folder.getPath()), null, null)) + .toArray(IClasspathEntry[]::new); + } + + private static void bind(IJavaProject project, IClasspathEntry[] entries, IProgressMonitor monitor) throws CoreException { + IClasspathContainer container = new LitheContainer(ID, DESCRIPTION, entries); + JavaCore.setClasspathContainer(ID, new IJavaProject[] { project }, new IClasspathContainer[] { container }, monitor); + } + + private static boolean applies(IJavaProject project, ProjectModelSettings settings) { + IPath folder = ProjectUtils.getProjectRealFolder(project.getProject()); + return !settings.classFolders.isEmpty() + && ProjectModelSettings.sameDirectory(folder, settings.classFolderWorkspace); + } + + private static boolean isOwned(IClasspathEntry entry) { + return entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER && ID.equals(entry.getPath()); + } +} 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 index eff3809..4d4af80 100644 --- 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 @@ -8,6 +8,7 @@ import org.eclipse.core.resources.IResourceChangeListener; import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.resources.IResourceDeltaVisitor; +import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; @@ -32,6 +33,7 @@ final class ContainerRefresher extends Job implements IPreferencesChangeListener ContainerRefresher() { super("Refresh Lithe project model containers"); setSystem(true); + setRule(ResourcesPlugin.getWorkspace().getRoot()); } @Override @@ -51,21 +53,32 @@ public void resourceChanged(IResourceChangeEvent event) { return; } boolean[] relevant = { false }; + boolean[] classpath = { false }; + ProjectModelSettings settings = ProjectModelSettings.current(); + boolean checkClasspath = !settings.classFolders.isEmpty() || !settings.sourceRoles.isEmpty() + || settings.workspaceSourcePaths.isPresent() || settings.workspaceOutputPath.isPresent(); try { delta.accept((IResourceDeltaVisitor) child -> { - if (relevant[0]) { + if (relevant[0] && (!checkClasspath || classpath[0])) { return false; } IResource resource = child.getResource(); if (resource.getType() == IResource.FILE && isModelInput(resource.getProjectRelativePath())) { relevant[0] = true; } + if (checkClasspath && ((resource.getType() == IResource.PROJECT + && (child.getKind() == IResourceDelta.ADDED + || (child.getFlags() & (IResourceDelta.OPEN | IResourceDelta.DESCRIPTION)) != 0)) + || (resource.getType() == IResource.FILE + && ".classpath".equals(resource.getProjectRelativePath().toString())))) { + classpath[0] = true; + } return true; }); } catch (CoreException e) { ProjectModelLog.error("Cannot inspect a resource change", e); } - if (relevant[0] && !ContainerResolver.ownedContainers().isEmpty()) { + if (classpath[0] || (relevant[0] && !ContainerResolver.ownedContainers().isEmpty())) { schedule(DELAY_MILLISECONDS); } } @@ -87,6 +100,8 @@ static boolean isModelInput(IPath path) { @Override protected IStatus run(IProgressMonitor monitor) { ProjectModelSettings settings = ProjectModelSettings.current(); + ClassFolderClasspath.refresh(settings, monitor); + SourceFolderClasspath.refresh(settings, monitor); for (Map.Entry> owned : ContainerResolver.ownedContainers().entrySet()) { if (monitor.isCanceled()) { return Status.CANCEL_STATUS; 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 index 1491165..fc05e42 100644 --- 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 @@ -16,6 +16,10 @@ public final class LitheContainerInitializer extends ClasspathContainerInitializ @Override public void initialize(IPath containerPath, IJavaProject project) throws CoreException { ProjectModelSettings settings = ProjectModelSettings.current(); + if (ClassFolderClasspath.ID.equals(containerPath)) { + ClassFolderClasspath.bind(project, settings, null); + return; + } if (!settings.enabled || ContainerKind.of(containerPath) == null) { return; } @@ -25,6 +29,9 @@ public void initialize(IPath containerPath, IJavaProject project) throws CoreExc @Override public String getDescription(IPath containerPath, IJavaProject project) { + if (ClassFolderClasspath.ID.equals(containerPath)) { + return ClassFolderClasspath.DESCRIPTION; + } return ContainerResolver.description(containerPath, ContainerKind.of(containerPath), ProjectModelSettings.current()); } 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 index 8e4f545..7f71c00 100644 --- 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 @@ -1,11 +1,15 @@ package io.github.lithe_idea.java.projectmodel; import java.io.File; +import java.io.IOException; +import java.nio.file.InvalidPathException; +import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Optional; import org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin; import org.eclipse.jdt.ls.core.internal.preferences.PreferenceManager; @@ -26,12 +30,24 @@ final class ProjectModelSettings { final String serverRuntimeHome; final List serverRuntimeLibraries; final String serverRuntimeName; + final String classFolderWorkspace; + final List classFolders; + final Map> sourceRoles; + final Optional> workspaceSourcePaths; + final Optional workspaceOutputPath; - private ProjectModelSettings(boolean enabled, String serverRuntimeHome, List serverRuntimeLibraries, String serverRuntimeName) { + private ProjectModelSettings(boolean enabled, String serverRuntimeHome, List serverRuntimeLibraries, String serverRuntimeName, + String classFolderWorkspace, List classFolders, Map> sourceRoles, + Optional> workspaceSourcePaths, Optional workspaceOutputPath) { this.enabled = enabled; this.serverRuntimeHome = serverRuntimeHome; this.serverRuntimeLibraries = serverRuntimeLibraries; this.serverRuntimeName = serverRuntimeName; + this.classFolderWorkspace = classFolderWorkspace; + this.classFolders = classFolders; + this.sourceRoles = sourceRoles; + this.workspaceSourcePaths = workspaceSourcePaths; + this.workspaceOutputPath = workspaceOutputPath; } /** The settings of the current JDT LS preferences; defaults when absent. */ @@ -46,11 +62,33 @@ static ProjectModelSettings from(Preferences preferences) { // 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(), ""); + return new ProjectModelSettings(true, "", List.of(), "", "", List.of(), Map.of(), Optional.empty(), Optional.empty()); } boolean enabled = !Boolean.FALSE.equals(map.get("enabled")); + String name = map.get("serverRuntimeName") instanceof String text ? text : ""; + String home = map.get("serverRuntimeHome") instanceof String text && new File(text).isAbsolute() ? text : ""; + String workspace = map.get("classFolderWorkspace") instanceof String text && new File(text).isAbsolute() ? text : ""; + Map> roles = new java.util.HashMap<>(); + if (map.get("sourceRoles") instanceof Map sourceRoles) { + for (String role : List.of("test", "resource", "test-resource", "excluded")) { + List paths = absolutePaths(sourceRoles.get(role)); + if (!paths.isEmpty()) { + roles.put(role, paths); + } + } + } + Optional> sources = map.get("workspaceSourcePaths") instanceof List paths + ? Optional.of(paths.stream().filter(String.class::isInstance).map(String.class::cast) + .limit(MAX_LIBRARIES).toList()) + : Optional.empty(); + Optional output = map.get("workspaceOutputPath") instanceof String path ? Optional.of(path) : Optional.empty(); + return new ProjectModelSettings(enabled, home, absolutePaths(map.get("serverRuntimeLibraries")), name, + workspace, absolutePaths(map.get("classFolders")), Map.copyOf(roles), sources, output); + } + + private static List absolutePaths(Object value) { List libraries = new ArrayList<>(); - if (map.get("serverRuntimeLibraries") instanceof List list) { + if (value instanceof List list) { for (Object item : list) { if (libraries.size() >= MAX_LIBRARIES) { break; @@ -60,9 +98,7 @@ static ProjectModelSettings from(Preferences preferences) { } } } - 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); + return Collections.unmodifiableList(libraries); } /** @@ -87,16 +123,46 @@ private static Object lookup(Map configuration, String... keys) return current; } + static Path realPath(Path path) { + try { + return path.toRealPath(); + } catch (IOException e) { + return path.toAbsolutePath().normalize(); + } + } + + static Path realPath(String path) { + try { + return realPath(Path.of(path)); + } catch (InvalidPathException e) { + return null; + } + } + + static boolean sameDirectory(org.eclipse.core.runtime.IPath folder, String other) { + if (folder == null || other == null || other.isEmpty()) { + return false; + } + Path otherPath = realPath(other); + return otherPath != null && realPath(folder.toFile().toPath()).equals(otherPath); + } + @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); + && serverRuntimeName.equals(that.serverRuntimeName) + && classFolderWorkspace.equals(that.classFolderWorkspace) + && classFolders.equals(that.classFolders) + && sourceRoles.equals(that.sourceRoles) + && workspaceSourcePaths.equals(that.workspaceSourcePaths) + && workspaceOutputPath.equals(that.workspaceOutputPath); } @Override public int hashCode() { - return Objects.hash(enabled, serverRuntimeHome, serverRuntimeLibraries, serverRuntimeName); + return Objects.hash(enabled, serverRuntimeHome, serverRuntimeLibraries, serverRuntimeName, + classFolderWorkspace, classFolders, sourceRoles, workspaceSourcePaths, workspaceOutputPath); } } diff --git a/jdtls-extension/project-model/src/io/github/lithe_idea/java/projectmodel/SourceFolderClasspath.java b/jdtls-extension/project-model/src/io/github/lithe_idea/java/projectmodel/SourceFolderClasspath.java new file mode 100644 index 0000000..d74a463 --- /dev/null +++ b/jdtls-extension/project-model/src/io/github/lithe_idea/java/projectmodel/SourceFolderClasspath.java @@ -0,0 +1,175 @@ +package io.github.lithe_idea.java.projectmodel; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IFolder; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.Path; +import org.eclipse.jdt.core.IClasspathAttribute; +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.ProjectUtils; +import org.eclipse.jdt.ls.core.internal.managers.InvisibleProjectImporter; + +/** Applies workspace folder roles to JDT's unmanaged project metadata. */ +final class SourceFolderClasspath { + private static final String TEST_OWNER = "lithe.testSource"; + private static final String TEST_OUTPUT_OWNER = "lithe.originalTestOutput"; + private static final String EXCLUSION_OWNER = "lithe.sourceExclusions"; + + static void refresh(ProjectModelSettings settings, IProgressMonitor monitor) { + for (IJavaProject project : ProjectUtils.getJavaProjects()) { + if (monitor.isCanceled()) { + return; + } + if (!ProjectUtils.isUnmanagedFolder(project.getProject())) { + continue; + } + IPath workspace = ProjectUtils.getProjectRealFolder(project.getProject()); + boolean matches = ProjectModelSettings.sameDirectory(workspace, settings.classFolderWorkspace); + Map> roles = matches ? settings.sourceRoles : Map.of(); + try { + IClasspathEntry[] before = project.getRawClasspath(); + IPath oldOutput = project.getOutputLocation(); + IPath output = matches && settings.workspaceOutputPath.isPresent() + ? InvisibleProjectImporter.getOutputPath(project, settings.workspaceOutputPath.get(), true) : oldOutput; + IClasspathEntry[] after = matches && (settings.workspaceSourcePaths.isPresent() || !output.equals(oldOutput)) + ? resolveSources(project, before, settings.workspaceSourcePaths.orElse(null), output, oldOutput) + : before.clone(); + IPath testOutput = project.getProject().getFullPath().append("lithe-test-bin"); + for (int index = 0; index < after.length; index++) { + IClasspathEntry entry = after[index]; + if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) { + IResource resource = entry.getPath().segmentCount() == 1 ? project.getProject() + : project.getProject().getWorkspace().getRoot().getFolder(entry.getPath()); + after[index] = apply(entry, resource.getLocation(), roles, output, testOutput); + } + } + if (!Arrays.equals(before, after) || !output.equals(oldOutput)) { + project.setRawClasspath(after, output, monitor); + } + } catch (CoreException e) { + ProjectModelLog.error("Cannot update Java source folder roles for " + project.getElementName(), e); + } + } + } + + private static IClasspathEntry[] resolveSources(IJavaProject project, IClasspathEntry[] before, List paths, + IPath output, IPath oldOutput) + throws CoreException { + IFolder link = project.getProject().getFolder(ProjectUtils.WORKSPACE_LINK); + if (!link.exists()) { + return before.clone(); + } + for (String path : paths == null ? List.of() : paths) { + IPath relative = Path.fromPortableString(path); + if (!relative.isEmpty() && relative.segmentCount() > 0 && !relative.isAbsolute() && relative.getDevice() == null + && !Arrays.asList(relative.segments()).contains("..")) { + IFolder folder = link.getFolder(relative); + if (!folder.exists()) { + folder.refreshLocal(IResource.DEPTH_INFINITE, null); + } + } + } + List existing = Arrays.stream(before).filter(entry -> entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) + .map(IClasspathEntry::getPath).toList(); + List desired = paths == null ? existing : InvisibleProjectImporter.getSourcePaths(paths, link); + if (output.equals(oldOutput) && new LinkedHashSet<>(existing).equals(new LinkedHashSet<>(desired))) { + return before.clone(); + } + Map sources = new LinkedHashMap<>(); + for (IPath path : desired) { + sources.put(path, null); + } + List excludes = InvisibleProjectImporter.getExcludingPath(project, output, link); + return ProjectUtils.resolveClassPathEntries(project, sources, excludes, output); + } + + private static IClasspathEntry apply(IClasspathEntry entry, IPath folder, Map> roles, + IPath defaultOutput, IPath testOutput) { + List attributes = new ArrayList<>(Arrays.asList(entry.getExtraAttributes())); + Set exclusions = new LinkedHashSet<>(Arrays.asList(entry.getExclusionPatterns())); + IPath output = entry.getOutputLocation(); + boolean ownedTest = attributes.removeIf(attribute -> TEST_OWNER.equals(attribute.getName())); + if (ownedTest) { + attributes.removeIf(attribute -> IClasspathAttribute.TEST.equals(attribute.getName())); + } + for (IClasspathAttribute attribute : List.copyOf(attributes)) { + if (EXCLUSION_OWNER.equals(attribute.getName())) { + for (String pattern : attribute.getValue().split("\\|")) { + exclusions.remove(Path.fromPortableString(pattern)); + } + attributes.remove(attribute); + } else if (TEST_OUTPUT_OWNER.equals(attribute.getName())) { + output = attribute.getValue().isEmpty() ? null : Path.fromPortableString(attribute.getValue()); + attributes.remove(attribute); + } + } + java.nio.file.Path folderPath = folder == null ? null : ProjectModelSettings.realPath(folder.toFile().toPath()); + if (folderPath != null && !roles.isEmpty()) { + boolean testResource = contains(roles, "test-resource", folderPath); + boolean test = testResource || contains(roles, "test", folderPath); + if (test + && attributes.stream().noneMatch(attribute -> IClasspathAttribute.TEST.equals(attribute.getName()))) { + attributes.add(JavaCore.newClasspathAttribute(IClasspathAttribute.TEST, "true")); + attributes.add(JavaCore.newClasspathAttribute(TEST_OWNER, "true")); + } + if (test && (output == null || output.equals(defaultOutput))) { + attributes.add(JavaCore.newClasspathAttribute(TEST_OUTPUT_OWNER, output == null ? "" : output.toPortableString())); + output = testOutput; + } + List added = new ArrayList<>(); + if (testResource || contains(roles, "resource", folderPath)) { + addExclusion(exclusions, added, "**/*.java"); + } + for (String path : roles.getOrDefault("excluded", List.of())) { + java.nio.file.Path excluded = ProjectModelSettings.realPath(path); + if (excluded != null && excluded.startsWith(folderPath) && !excluded.equals(folderPath)) { + java.nio.file.Path relative = folderPath.relativize(excluded); + StringBuilder portable = new StringBuilder(); + for (int i = 0; i < relative.getNameCount(); i++) { + if (i > 0) { + portable.append('/'); + } + portable.append(relative.getName(i).toString()); + } + if (portable.length() > 0) { + addExclusion(exclusions, added, portable.append('/').toString()); + } + } + } + if (!added.isEmpty()) { + attributes.add(JavaCore.newClasspathAttribute(EXCLUSION_OWNER, String.join("|", added))); + } + } + if (Arrays.equals(entry.getExtraAttributes(), attributes.toArray(IClasspathAttribute[]::new)) + && Arrays.equals(entry.getExclusionPatterns(), exclusions.toArray(IPath[]::new)) + && java.util.Objects.equals(entry.getOutputLocation(), output)) { + return entry; + } + return JavaCore.newSourceEntry(entry.getPath(), entry.getInclusionPatterns(), + exclusions.toArray(IPath[]::new), output, attributes.toArray(IClasspathAttribute[]::new)); + } + + private static boolean contains(Map> roles, String role, java.nio.file.Path folderPath) { + return roles.getOrDefault(role, List.of()).stream() + .map(ProjectModelSettings::realPath) + .anyMatch(folderPath::equals); + } + + private static void addExclusion(Set exclusions, List added, String pattern) { + if (exclusions.add(Path.fromPortableString(pattern))) { + added.add(pattern); + } + } +} diff --git a/scripts/compiler/test-module-structure.mjs b/scripts/compiler/test-module-structure.mjs index 5156d55..ee5ab16 100644 --- a/scripts/compiler/test-module-structure.mjs +++ b/scripts/compiler/test-module-structure.mjs @@ -27,6 +27,11 @@ 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 javaServer=manifest.languageServers.find(server=>server.languageID==='java'); +for(const command of ['java.project.getAll','java.project.getSettings','java.project.getClasspaths','lithe.java.projectModel.describe']){ + assert.ok(javaServer.commands.includes(command),`Undeclared language-server command: ${command}`); +} +assert.ok(javaServer.requestMethods.includes('java/projectConfigurationsUpdate'),'Undeclared project settings refresh notification'); 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);}; diff --git a/scripts/compiler/test-project-models.mjs b/scripts/compiler/test-project-models.mjs index 7b7e0b9..0dbc18f 100644 --- a/scripts/compiler/test-project-models.mjs +++ b/scripts/compiler/test-project-models.mjs @@ -65,12 +65,19 @@ const fixtures={ }, async idea(root,stage){ write(join(root,'.idea/modules.xml'),''); - write(join(root,'app.iml'),''); + 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}; + const classFolders=['businessobjects.jar','web.war/WEB-INF/classes'].map(path=>join(stage,'MAXIMO.ear',path)); + for(const [index,folder] of classFolders.entries()){ + const name=`Legacy${index}`, source=join(stage,`${name}.java`); + write(source,`package acme.legacy; public class ${name} { public static void touch() {} }`); + mkdirSync(folder,{recursive:true}); + await runTool(javac,['--release','8','-d',folder,source],{timeout:60000}); + } + write(join(root,'java/demo/Hello.java'),HELLO.replace('System.out.print','acme.legacy.Legacy0.touch(); acme.legacy.Legacy1.touch(); System.out.print')); + 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,classFolders}; }, }; @@ -90,11 +97,18 @@ async function scenario(name,report){ 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}]; + let blockedRequests; 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/request':async p=>{ + if(blockedRequests){ + blockedRequests.push([p.params.command,p.timeoutMilliseconds]); + throw Error('JDT indexing: request timed out'); + } + return {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}); @@ -108,7 +122,10 @@ async function scenario(name,report){ 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); + if(fixture.projectServlet){ + assert.deepEqual(model?.classFolders?.map(path=>resolve(path)),fixture.classFolders.map(path=>resolve(path))); + assert.equal(model.serverRuntimeHome,''); + } 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]); @@ -129,8 +146,24 @@ async function scenario(name,report){ 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'); + if(fixture.classFolders)await until(()=>execute('java.project.getClasspaths',[projectUri,'{"scope":"test"}']),value=>fixture.classFolders.every(folder=>value.classpaths.some(path=>samePath(path,folder))),'JDT class folders'); await compiles(); }); + if(fixture.classFolders)await step('JDT completes and navigates to classes in both directories',async()=>{ + const uri=pathToFileURL(fixture.source).href,text=readFileSync(fixture.source,'utf8'); + const textDocument={uri}; + server.notify('textDocument/didOpen',{textDocument:{uri,languageId:'java',version:1,text}}); + const line=text.split('\n').findIndex(value=>value.includes('Legacy0')); + const use=text.split('\n')[line]; + for(const index of [0,1]){ + const name=`Legacy${index}`, character=use.indexOf(name); + await until(()=>server.request('textDocument/definition',{textDocument,position:{line,character:character+2}},15000), + value=>[value].flat().some(location=>(location?.uri??location?.targetUri??'').includes(name)),'JDT definition '+name); + await until(()=>server.request('textDocument/completion',{textDocument,position:{line,character:character+name.length+1}},15000), + value=>(value?.items??value??[]).some(item=>item.label.startsWith('touch')),'JDT completion '+name); + } + server.notify('textDocument/didClose',{textDocument}); + }); 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)); @@ -140,8 +173,28 @@ async function scenario(name,report){ 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'))); }); + if(fixture.classFolders)await step('the IDEA structure opens while JDT cannot answer',async()=>{ + blockedRequests=[]; + try{ + const page=await invoke('libraries.settings',{context:{language:'zh-CN',builds:[]}}); + const module=page.sources.find(source=>source.group==='modules'&&source.path==='app.iml'); + assert.equal(module?.writable,false); + const dependencies=module.fields.find(field=>field.id==='dependencies').value; + assert.ok(dependencies.some(row=>row.kind==='classes'&&row.detail.includes('JDT 状态未确认'))); + assert.match(module.fields.find(field=>field.id==='jdt-status').value,/JDT 类路径未确认/); + assert.ok(page.sources.some(source=>source.path==='.vscode/settings.json'&&source.writable)); + assert.deepEqual(blockedRequests.map(([command])=>command),['java.project.getClasspaths']); + assert.ok(blockedRequests[0][1]<=1500); + }finally{blockedRequests=undefined;} + }); await step('the libraries page shows the model read-only',async()=>{ const page=await invoke('libraries.settings',{context:{language:'zh-CN',builds:[]}}); + for(const source of page.sources){ + for(const field of source.fields){ + assert.ok(Object.hasOwn(field,'value')&&Object.hasOwn(field,'effectiveValue')&&typeof field.effectiveSource==='string', + `Missing source-state field in ${source.path}: ${field.id}`); + } + } 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); @@ -151,27 +204,117 @@ async function scenario(name,report){ 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(fixture.classFolders){ + const modules=page.sources.filter(source=>source.group==='modules'); + assert.deepEqual(modules.map(source=>[source.title,source.path,source.writable]),[['app','app.iml',false]]); + const dependencies=modules[0].fields.find(field=>field.id==='dependencies').value; + assert.match(modules[0].fields.find(field=>field.id==='jdt-status').value,/JDT 已返回工作区类路径/); + for(const folder of fixture.classFolders){ + const entry=dependencies.find(item=>item.kind==='classes'&&samePath(item.value,folder)); + assert.match(entry?.detail??'',/JDT 已生效/); + } + const directory=dependencies.filter(item=>item.value==='third-party/*.jar'); + assert.equal(directory.length,1); + assert.match(directory[0].detail,/JDT 已加载 1 个 JAR/); + assert.ok(page.sources.some(source=>source.path==='.vscode/settings.json'&&source.writable)); + } 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==='eclipse-wtp')await step('saving an Eclipse module still writes its own .classpath',async()=>{ + const page=await invoke('libraries.settings',{context:{language:'en',builds:[]}}); + const module=page.sources.find(item=>item.group==='modules'&&item.path==='WebApp/.classpath'); + assert.equal(module?.writable,true); + const stageFile=join(stage,'classpath-stage.xml');writeFileSync(stageFile,''); + const edit=await invoke('compiler.prepareSettings',{operation:'editSource',sourceID:module.id,revision:module.revision,values:{output:'build/verified'},outputFile:stageFile}); + assert.equal(edit.changed,true); + const contents=readFileSync(stageFile,'utf8'); + assert.match(contents,/kind="output" path="build\/verified"/); + assert.match(contents,/org\.eclipse\.jst\.j2ee\.internal\.web\.container/); + renameSync(stageFile,join(root,module.path)); + const after=await invoke('libraries.settings',{operation:'readAfterSave',context:{language:'en',builds:[]}}); + assert.equal(after.sources.find(item=>item.id===module.id).fields.find(field=>field.id==='output').value,'build/verified'); + await compiles(); + assert.ok(existsSync(join(fixture.project,'build/verified/demo/Hello.class'))); + }); 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.group,'modules'); + assert.equal(source.title,root.split(/[\\/]/).at(-1)); + assert.deepEqual([...new Set(source.fields.map(field=>field.section))],['Sources','Paths','Dependencies']); + const initialOutput=source.fields.find(field=>field.id==='output'); + assert.equal(initialOutput.value,null); + assert.ok(initialOutput.effectiveValue, 'JDT reports the default output location'); + assert.equal(initialOutput.inheritedValue,initialOutput.effectiveValue); + assert.ok(source.fields.find(field=>field.id==='roots').inheritedValue.some(row=>row.value==='src')); + assert.deepEqual(source.fields.find(field=>field.id==='dependencies').entryKinds.map(kind=>[kind.id,kind.input]), + [['archive','file'],['jar-directory','directory'],['classes','directory']]); assert.equal(source.fields.find(field=>field.id==='store-detected')?.value,false); + await jar(stage,'manual',{'demo/manual/Extra.java':'package demo.manual; public class Extra {}'},join(stage,'manual.jar')); + const classFolder=join(stage,'jar-manual'); + const resolved=()=>execute('java.project.getClasspaths',[projectUri,'{"scope":"test"}']); + const hasClassFolder=value=>value.classpaths.some(path=>samePath(path,classFolder)); 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}); + const selectedLibrary=join(stage,'manual.jar'); + const selectedDirectory=join(root,'WebRoot/WEB-INF/lib'); + write(join(root,'test/demo/ExampleTest.java'),'package demo; public class ExampleTest {}'); + write(join(root,'src/demo/excluded/Invalid.java'),'intentionally invalid Java'); + write(join(root,'resources/verified.properties'),'verified=true'); + write(join(root,'test-resources/verified-test.properties'),'verified=true'); + write(join(root,'resources/NotJava.java'),'intentionally invalid Java'); + const edit=await invoke('compiler.prepareSettings',{operation:'editSource',sourceID:source.id,revision:source.revision,values:{ + 'store-detected':true,output:'build/verified', + roots:[{kind:'folder',value:join(root,'src')},{kind:'test',value:join(root,'test')}, + {kind:'excluded',value:join(root,'src/demo/excluded')},{kind:'resource',value:join(root,'resources')}, + {kind:'test-resource',value:join(root,'test-resources')}], + dependencies:[{kind:'jar-directory',value:selectedDirectory},{kind:'archive',value:selectedLibrary},{kind:'classes',value:classFolder}] + },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'); + assert.deepEqual(saved['java.project.referencedLibraries'],[fixture.library,selectedLibrary],'The library directory stores a JAR pattern and the server libraries stay implicit'); + assert.deepEqual(saved['java.lithe.classFolders'],[classFolder]); + assert.equal(saved['java.project.outputPath'],'build/verified'); + assert.deepEqual(saved['java.project.sourcePaths'],['src','test','resources','test-resources']); 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); + const savedSource=after.sources.find(item=>item.path==='.vscode/settings.json'); + assert.equal(savedSource.fields.find(field=>field.id==='store-detected').value,true); + assert.equal(savedSource.fields.find(field=>field.id==='output').value,'build/verified'); + await until(resolved,value=>hasClassFolder(value)&&value.classpaths.some(path=>samePath(path,selectedLibrary)), + 'JDT loads the saved JAR and class folder'); + const marked=await until(()=>execute('java.project.getSettings',[projectUri,['org.eclipse.jdt.ls.core.classpathEntries']]), + value=>JSON.stringify(value).includes('demo/excluded/')&&JSON.stringify(value).includes('**/*.java'), + 'JDT applied the test and excluded folder markers'); + assert.equal(await execute('java.project.isTestFile',[pathToFileURL(join(root,'test/demo/ExampleTest.java')).href]),true); + const current=await invoke('libraries.settings',{context:{language:'en',builds:[]}}); + const rows=current.sources.find(item=>item.id===source.id).fields.find(field=>field.id==='dependencies').value; + assert.equal(rows.filter(row=>row.kind==='jar-directory').length,1); + assert.match(rows.find(row=>row.kind==='jar-directory').detail,/1 JARs? loaded by JDT/); + assert.match(rows.find(row=>row.kind==='classes').detail,/Loaded by JDT/); + capture('workspace-dependencies-en',current); await compiles(); + const jdtOutput=(await execute('java.project.getSettings',[projectUri,['org.eclipse.jdt.ls.core.outputPath']]))['org.eclipse.jdt.ls.core.outputPath']; + assert.ok(samePath(jdtOutput,join(root,'build/verified')), 'JDT uses the configured production output'); + assert.ok(existsSync(join(jdtOutput,'verified.properties'))); + const testOutput=marked['org.eclipse.jdt.ls.core.classpathEntries'].find(entry=>samePath(entry.path,join(root,'test-resources'))).output; + assert.ok(testOutput&&!samePath(testOutput,jdtOutput)); + assert.ok(existsSync(join(testOutput,'verified-test.properties'))); + writeFileSync(stageFile,''); + await invoke('compiler.prepareSettings',{operation:'editSource',sourceID:savedSource.id,revision:savedSource.revision,values:{ + dependencies:[{kind:'jar-directory',value:fixture.library}] + },outputFile:stageFile}); + assert.deepEqual(JSON.parse(readFileSync(stageFile,'utf8'))['java.project.referencedLibraries'],[fixture.library]); + renameSync(stageFile,join(root,source.path)); + await invoke('libraries.settings',{operation:'readAfterSave',context:{language:'en',builds:[]}}); + await until(resolved,value=>!hasClassFolder(value)&&!value.classpaths.some(path=>samePath(path,selectedLibrary)), + 'JDT drops the removed JAR and class folder'); }); await server.request('shutdown',null,30000);server.notify('exit',null); + await Promise.race([server.exited,delay(2000,undefined,{ref:false})]); }finally{ try{if(server)await server.close();}finally{try{if(backend)await backend.close();}finally{rmSync(stage,{recursive:true,force:true});}} }