diff --git a/Cargo.lock b/Cargo.lock index 001a3b328..755e40ba5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4846,6 +4846,7 @@ dependencies = [ name = "ide-sdk" version = "0.1.50" dependencies = [ + "dirs 6.0.0", "dunce", "flate2", "ide-core", diff --git a/crates/ide-host/src/project.rs b/crates/ide-host/src/project.rs index 8a2a43778..5e85af3f8 100644 --- a/crates/ide-host/src/project.rs +++ b/crates/ide-host/src/project.rs @@ -286,6 +286,10 @@ impl Host { lombok.jar(), ); ide_sdk::apply::configure_gradle_runtime(cfg, root, server_root, &effective); + let gradle_dirs: Vec<_> = std::iter::once(data_dir.join("gradle")) + .chain(dirs::cache_dir().map(|dir| dir.join("openidea").join("gradle"))) + .collect(); + ide_sdk::apply::configure_gradle_classpath(cfg, &gradle_dirs); ide_sdk::apply::configure_maven_sources(cfg, &effective); ide_sdk::jdtls::launch_directly(cfg); } diff --git a/crates/ide-sdk/Cargo.toml b/crates/ide-sdk/Cargo.toml index 6ccbc17d4..745db57d3 100644 --- a/crates/ide-sdk/Cargo.toml +++ b/crates/ide-sdk/Cargo.toml @@ -6,6 +6,7 @@ edition.workspace = true license.workspace = true [dependencies] +dirs.workspace = true dunce.workspace = true ignore.workspace = true ide-core.workspace = true diff --git a/crates/ide-sdk/src/apply.rs b/crates/ide-sdk/src/apply.rs index dee7bacb1..ecb6d1b13 100644 --- a/crates/ide-sdk/src/apply.rs +++ b/crates/ide-sdk/src/apply.rs @@ -537,6 +537,42 @@ pub fn configure_gradle_runtime(cfg: &mut LanguageServerConfig, root: &Path, bui merge(cfg.settings.get_or_insert_with(|| json!({})), json!({"java": {"import": {"gradle": gradle}}})); } +/// Gradle's Eclipse model, which jdtls imports the build through, leaves out project dependencies +/// a source set only compiles against (`compileOnly(project(":a"))`) and marks some as test-only, +/// so their classes don't resolve in the editor although Gradle compiles. jdtls's Gradle import +/// runs an init script that adds them, written to the first of `dirs` whose path has no +/// whitespace: Buildship stores the import's arguments joined by spaces and splits them again, +/// so `Application Support` would break the path. The name carries the script's hash, so +/// releases running side by side never overwrite each other's script. +pub fn configure_gradle_classpath(cfg: &mut LanguageServerConfig, dirs: &[PathBuf]) { + const SCRIPT: &str = include_str!("gradle-classpath.init.gradle"); + if cfg.name != "jdtls" { + return; + } + let mut hash = 0xcbf29ce484222325u64; + for byte in SCRIPT.bytes() { + hash = (hash ^ u64::from(byte)).wrapping_mul(0x100000001b3); + } + let name = format!("openidea-classpath-{hash:016x}.init.gradle"); + let Some(script) = dirs + .iter() + .map(|dir| dir.join(&name)) + .filter(|script| !script.to_string_lossy().contains(char::is_whitespace)) + .find(|script| { + std::fs::read(script).ok().as_deref() == Some(SCRIPT.as_bytes()) + || script.parent().is_some_and(|dir| std::fs::create_dir_all(dir).is_ok()) + && std::fs::write(script, SCRIPT).is_ok() + }) + else { + tracing::warn!("no directory without spaces for the Gradle classpath init script: {dirs:?}"); + return; + }; + merge( + cfg.settings.get_or_insert_with(|| json!({})), + json!({"java": {"import": {"gradle": {"arguments": ["--init-script", script.to_string_lossy()]}}}}), + ); +} + /// Settings › Build Tools › Maven › Automatically download sources and Always update /// snapshots → jdtls `java.maven.downloadSources` / `java.maven.updateSnapshots`. pub fn configure_maven_sources(cfg: &mut LanguageServerConfig, s: &Settings) { @@ -2529,6 +2565,33 @@ mod maven_linkage_tests { assert_eq!(gradle["user"]["home"], resolved("/caches/gradle")); } + #[test] + fn gradle_import_adds_the_projects_a_source_set_compiles_against() { + let temp = tempfile::tempdir().unwrap(); + let spaced = temp.path().join("Application Support").join("gradle"); + let plain = temp.path().join("cache").join("gradle"); + let mut cfg = custom_server("jdtls", &LanguageServerSettings::default()); + cfg.settings = Some(json!({"java": {"import": {"gradle": {"enabled": true}}}})); + configure_gradle_classpath(&mut cfg, &[spaced.clone(), plain.clone()]); + let gradle = &cfg.settings.as_ref().unwrap()["java"]["import"]["gradle"]; + assert_eq!(gradle["enabled"], json!(true), "merged, not replaced"); + let args = gradle["arguments"].as_array().unwrap(); + assert_eq!(args[0], json!("--init-script")); + let script = PathBuf::from(args[1].as_str().unwrap()); + assert_eq!(script.parent(), Some(plain.as_path()), "Buildship splits arguments at spaces"); + assert!(!spaced.exists()); + let text = std::fs::read_to_string(&script).unwrap(); + assert!(text.contains("compileClasspath") && text.contains("whenMerged")); + + let mut other = custom_server("pyright", &LanguageServerSettings::default()); + configure_gradle_classpath(&mut other, &[plain]); + assert!(other.settings.is_none(), "only jdtls imports Gradle builds"); + + let mut nowhere = custom_server("jdtls", &LanguageServerSettings::default()); + configure_gradle_classpath(&mut nowhere, &[spaced]); + assert!(nowhere.settings.is_none(), "no usable directory: the import runs without it"); + } + #[test] fn gradle_import_of_a_gradle_build_runs_on_the_project_jdk_like_the_ides_builds() { let temp = tempfile::tempdir().unwrap(); diff --git a/crates/ide-sdk/src/gradle-classpath.init.gradle b/crates/ide-sdk/src/gradle-classpath.init.gradle new file mode 100644 index 000000000..68c89d4a3 --- /dev/null +++ b/crates/ide-sdk/src/gradle-classpath.init.gradle @@ -0,0 +1,37 @@ +// Gradle's Eclipse model leaves out project dependencies a source set only compiles against +// (compileOnly, compileOnlyApi), and marks some as test-only. Add each project the main or test +// compile classpath names, so Java code sees the classes it compiles against. +allprojects { + plugins.withId('java') { + apply plugin: 'eclipse' + eclipse.classpath.file.whenMerged { classpath -> + def projectOf = { dep -> + def path + try { path = dep.path } catch (MissingPropertyException ignored) { path = dep.dependencyProject.path } + rootProject.findProject(path) + } + def wanted = [:] + ['testCompileClasspath', 'compileClasspath'].each { name -> + def configuration = configurations.findByName(name) + if (configuration == null) return + configuration.allDependencies.withType(ProjectDependency).each { dep -> + def target = projectOf(dep) + if (target == null || target == project) return + def eclipseName = target.extensions.findByName('eclipse')?.project?.name ?: target.name + wanted['/' + eclipseName] = name == 'compileClasspath' + } + } + def existing = classpath.entries.findAll { it instanceof org.gradle.plugins.ide.eclipse.model.ProjectDependency } + wanted.each { path, main -> + def entry = existing.find { it.path == path } + if (entry == null) { + entry = new org.gradle.plugins.ide.eclipse.model.ProjectDependency(path) + entry.entryAttributes['without_test_code'] = 'true' + classpath.entries.add(entry) + } + if (main) entry.entryAttributes.remove('test') + else if (!entry.entryAttributes.containsKey('test')) entry.entryAttributes['test'] = 'true' + } + } + } +} diff --git a/crates/ide-sdk/src/jdtls.rs b/crates/ide-sdk/src/jdtls.rs index a8426aa03..021fcde81 100644 --- a/crates/ide-sdk/src/jdtls.rs +++ b/crates/ide-sdk/src/jdtls.rs @@ -287,8 +287,8 @@ pub fn launch_directly(cfg: &mut LanguageServerConfig) { return; } let Some(script) = script_for(cfg) else { return }; - let Some(install) = - jdtls_home(&script).and_then(|h| find_install(&h, std::env::consts::OS, std::env::consts::ARCH)) + let home = jdtls_home(&script); + let Some(install) = home.as_deref().and_then(|h| find_install(h, std::env::consts::OS, std::env::consts::ARCH)) else { return; }; @@ -307,14 +307,60 @@ pub fn launch_directly(cfg: &mut LanguageServerConfig) { cfg.launch_error = Some(error); return; } + let area = home.as_deref().and_then(|home| configuration_area(home, &cfg.args, dirs::cache_dir())); cfg.args = java_args(&install, jdk.major, &cfg.args); + if let Some(area) = area + && let Some(jar) = cfg.args.iter().position(|a| a == "-jar") + { + cfg.args.insert(jar, format!("-Dosgi.configuration.area={}", area.to_string_lossy())); + } cfg.command = java.to_string_lossy().into_owned(); } +/// Equinox extracts bundle files, jdtls's Gradle init scripts among them, into its writable +/// configuration area, `/configuration` unless the launch names one. jdtls passes those +/// scripts to every Gradle import as `--init-script` arguments, and Buildship stores a build's +/// arguments joined by spaces and splits them again. Under a home with spaces (macOS's +/// `Application Support`) each import that sets a Gradle JDK, user home or argument then fails +/// with "The specified initialization script '…/Application' does not exist". Such a home +/// gets an area without spaces in the user's cache directory, one per install. +fn configuration_area(home: &Path, args: &[String], cache: Option) -> Option { + let parsed = split_script_args(args); + let named = parsed.jvm.iter().any(|a| a.starts_with("-Dosgi.configuration.area=")) + || parsed.rest.iter().any(|a| a == "-configuration"); + if named || !home.join("configuration").to_string_lossy().contains(char::is_whitespace) { + return None; + } + let mut hash = 0xcbf29ce484222325u64; + for byte in home.to_string_lossy().bytes() { + hash = (hash ^ u64::from(byte)).wrapping_mul(0x100000001b3); + } + Some(cache?.join("openidea").join("jdtls-configuration").join(format!("{hash:016x}"))) + .filter(|area| !area.to_string_lossy().contains(char::is_whitespace)) +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn a_home_with_spaces_gets_a_configuration_area_without_them() { + let cache = Some(PathBuf::from("/cache")); + let spaced = Path::new("/Users/me/Library/Application Support/openidea/tools/jdtls"); + let area = configuration_area(spaced, &[], cache.clone()).unwrap(); + assert!(area.starts_with("/cache/openidea/jdtls-configuration")); + assert_eq!(configuration_area(spaced, &[], cache.clone()), Some(area), "one per install"); + assert_ne!( + configuration_area(Path::new("/opt/My Tools/jdtls"), &[], cache.clone()), + configuration_area(spaced, &[], cache.clone()) + ); + assert_eq!(configuration_area(Path::new("/opt/jdtls"), &[], cache.clone()), None, "the default is fine"); + let own = strings(&["--jvm-arg=-Dosgi.configuration.area=/mine"]); + assert_eq!(configuration_area(spaced, &own, cache.clone()), None, "the user's area stays"); + assert_eq!(configuration_area(spaced, &strings(&["-configuration", "/mine"]), cache), None); + assert_eq!(configuration_area(spaced, &[], Some(PathBuf::from("/My Cache"))), None); + } + fn strings(args: &[&str]) -> Vec { args.iter().map(|s| s.to_string()).collect() }