diff --git a/crates/ide-build/Cargo.toml b/crates/ide-build/Cargo.toml index f0194fe83..2e2275746 100644 --- a/crates/ide-build/Cargo.toml +++ b/crates/ide-build/Cargo.toml @@ -17,6 +17,4 @@ serde_json.workspace = true specta.workspace = true tracing.workspace = true dirs.workspace = true - -[dev-dependencies] tempfile.workspace = true diff --git a/crates/ide-build/src/maven/sources.rs b/crates/ide-build/src/maven/sources.rs index f72a924c1..1b5a2b985 100644 --- a/crates/ide-build/src/maven/sources.rs +++ b/crates/ide-build/src/maven/sources.rs @@ -3,7 +3,13 @@ use super::MavenProject; use crate::process; use ide_core::{CancellationToken, IdeError, IdeResult}; +use std::collections::HashSet; +use std::fs::{self, File}; use std::path::{Component, Path, PathBuf}; +use std::time::SystemTime; + +const DEPENDENCY_PLUGIN: &str = "org.apache.maven.plugins:maven-dependency-plugin:3.8.1"; +const SOURCE_REFRESH_WORKERS: usize = 4; #[derive(Debug, PartialEq, Eq)] pub struct Artifact { @@ -11,6 +17,29 @@ pub struct Artifact { pub name: String, pub version: String, pub sources: PathBuf, + binary: PathBuf, +} + +fn valid_part(part: &str) -> bool { + !part.is_empty() + && part != "." + && part != ".." + && part.chars().all(|c| c.is_ascii_alphanumeric() || "_.-".contains(c)) +} + +fn modified_file(path: &Path) -> Option { + let metadata = fs::metadata(path).ok()?; + if metadata.is_file() { metadata.modified().ok() } else { None } +} + +impl Artifact { + fn stale_binary(&self) -> Option { + if !self.version.ends_with("-SNAPSHOT") { + return None; + } + let binary = modified_file(&self.binary)?; + (modified_file(&self.sources)? < binary).then_some(binary) + } } /// Resolve only jars inside the selected local repository, including custom repositories. @@ -28,16 +57,14 @@ pub fn artifact(jar: &Path, repository: &Path) -> Option { } let n = parts.len(); let (name, version, file) = (parts[n - 3], parts[n - 2], parts[n - 1]); - let valid = |s: &str| { - !s.is_empty() && s != "." && s != ".." && s.chars().all(|c| c.is_ascii_alphanumeric() || "_.-".contains(c)) - }; - if !parts[..n - 1].iter().all(|s| valid(s)) || file != format!("{name}-{version}.jar") { + if !parts[..n - 1].iter().all(|s| valid_part(s)) || file != format!("{name}-{version}.jar") { return None; } Some(Artifact { group: parts[..n - 3].join("."), name: name.into(), version: version.into(), + binary: jar.to_owned(), sources: jar.with_file_name(format!("{name}-{version}-sources.jar")), }) } @@ -48,26 +75,58 @@ pub fn download( artifact: &Artifact, repository: &Path, cancel: &CancellationToken, +) -> IdeResult> { + resolve(root, project, artifact, repository, &[], artifact.stale_binary(), cancel) +} + +fn resolve( + root: &Path, + project: &MavenProject, + artifact: &Artifact, + repository: &Path, + profile_args: &[String], + stale: Option, + cancel: &CancellationToken, ) -> IdeResult> { if cancel.is_cancelled() { return Err(IdeError::cancelled()); } - if artifact.sources.is_file() { + if stale.is_none() && artifact.sources.is_file() { return Ok(Some(artifact.sources.clone())); } let mut args = vec!["-B".into(), "-N".into(), "-Dstyle.color=never".into()]; - args.extend(project.options.clone()); - args.extend([ - format!("-Dmaven.repo.local={}", repository.display()), - "org.apache.maven.plugins:maven-dependency-plugin:3.8.1:get".into(), - format!("-Dartifact={}:{}:{}:jar:sources", artifact.group, artifact.name, artifact.version), - "-Dtransitive=false".into(), - ]); + args.extend(project.options.iter().cloned()); + args.extend(profile_args.iter().cloned()); + args.push(format!("-Dmaven.repo.local={}", repository.display())); + let coordinate = format!("-Dartifact={}:{}:{}:jar:sources", artifact.group, artifact.name, artifact.version); + let stage = if let Some(binary) = stale { + // Keep the existing attachment readable while Maven resolves the timestamped snapshot. + // Disable Resolver's in-place copy to the base -SNAPSHOT filename. + let stage = + tempfile::Builder::new().prefix(".openidea-sources-").tempdir_in(artifact.sources.parent().unwrap())?; + args.extend([ + "-U".into(), + "-Daether.artifactResolver.snapshotNormalization=false".into(), + format!("{DEPENDENCY_PLUGIN}:copy"), + coordinate, + "-Dmdep.useBaseVersion=true".into(), + format!("-DoutputDirectory={}", stage.path().display()), + ]); + Some((stage, binary)) + } else { + args.extend([format!("{DEPENDENCY_PLUGIN}:get"), coordinate, "-Dtransitive=false".into()]); + None + }; let output = process::run(&project.command, &args, &root.join(&project.dir), &project.env, cancel, |_, _| {})?; if cancel.is_cancelled() { return Err(IdeError::cancelled()); } - if artifact.sources.is_file() { + if let Some((stage, binary)) = stage { + let resolved = stage.path().join(artifact.sources.file_name().unwrap()); + if output.success && resolved.is_file() { + return replace_stale_sources(artifact, &resolved, binary, cancel); + } + } else if artifact.sources.is_file() { return Ok(Some(artifact.sources.clone())); } let coordinate = format!("{}:{}:jar:sources:{}", artifact.group, artifact.name, artifact.version); @@ -83,6 +142,115 @@ pub fn download( )) } +fn replace_stale_sources( + artifact: &Artifact, + resolved: &Path, + binary: SystemTime, + cancel: &CancellationToken, +) -> IdeResult> { + // Maven can fall back to a locally installed snapshot. Keep its timestamp if it returned + // the same bytes so a later reload can retry when newer sources are available. + let hash = |path| -> std::io::Result<_> { Ok(blake3::Hasher::new().update_reader(File::open(path)?)?.finalize()) }; + if hash(resolved)? == hash(&artifact.sources)? { + return Ok(None); + } + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + match artifact.stale_binary() { + Some(current) if current == binary => { + File::options().write(true).open(resolved)?.set_modified(SystemTime::now().max(binary))?; + fs::rename(resolved, &artifact.sources)?; + Ok(Some(artifact.sources.clone())) + } + None if artifact.sources.is_file() => Ok(Some(artifact.sources.clone())), + _ => Ok(None), + } +} + +/// Resolved Maven dependencies with an existing attachment. Binaries may still be +/// updating during import, so freshness is checked when the refresh runs. +pub fn cached_snapshots<'a>( + repository: &Path, + projects: impl Iterator, +) -> Vec<(usize, Artifact)> { + let mut seen = HashSet::new(); + let mut candidates = Vec::new(); + for (owner, project) in projects { + let mut dependencies: Vec<_> = project.dependencies.iter().collect(); + while let Some(dep) = dependencies.pop() { + if !dep.resolved() { + continue; + } + dependencies.extend(&dep.children); + let Some(version) = dep.version.as_deref().filter(|v| v.ends_with("-SNAPSHOT") && valid_part(v)) else { + continue; + }; + if dep.scope == "system" + || dep.classifier.is_some() + || !matches!(dep.kind.as_str(), "jar" | "bundle" | "maven-plugin" | "ejb") + || !valid_part(&dep.artifact_id) + || !dep.group_id.split('.').all(valid_part) + { + continue; + } + let name = &dep.artifact_id; + let jar = repository + .join(dep.group_id.replace('.', "/")) + .join(name) + .join(version) + .join(format!("{name}-{version}.jar")); + if let Some(artifact) = artifact(&jar, repository) + && artifact.sources.is_file() + && seen.insert(jar) + { + candidates.push((owner, artifact)); + } + } + } + candidates +} + +/// Refresh only previously attached snapshots. Maven subprocesses are bounded +/// and share the build reload's cancellation token. +pub fn refresh_snapshots( + root: &Path, + projects: &[MavenProject], + repository: &Path, + candidates: &[(usize, Artifact)], + profiles: &[String], + cancel: &CancellationToken, +) -> Vec { + let profile_args = if profiles.is_empty() { vec![] } else { vec![format!("-P{}", profiles.join(","))] }; + let profile_args = &profile_args; + let stale: Vec<_> = candidates.iter().filter(|(_, artifact)| artifact.stale_binary().is_some()).collect(); + let batch_size = stale.len().div_ceil(SOURCE_REFRESH_WORKERS).max(1); + std::thread::scope(|scope| { + let workers: Vec<_> = stale + .chunks(batch_size) + .map(|batch| { + scope.spawn(move || { + let mut refreshed = Vec::new(); + for (owner, artifact) in batch.iter().copied() { + if cancel.is_cancelled() { + break; + } + let Some(binary) = artifact.stale_binary() else { continue }; + match resolve(root, &projects[*owner], artifact, repository, profile_args, Some(binary), cancel) + { + Ok(Some(_)) => refreshed.push(artifact.binary.clone()), + Ok(None) => {} + Err(e) => tracing::debug!(path = %artifact.sources.display(), "Maven sources refresh: {e}"), + } + } + refreshed + }) + }) + .collect(); + workers.into_iter().flat_map(|worker| worker.join().expect("Maven sources worker")).collect() + }) +} + #[cfg(test)] mod tests { use super::*; @@ -121,4 +289,86 @@ mod tests { assert_eq!(artifact(Path::new(path), repository), None, "{path}"); } } + + #[test] + fn selects_existing_snapshot_attachments_from_the_resolved_tree() { + use crate::maven::{MavenDependency, Omission}; + + let repo = tempfile::tempdir().unwrap(); + let dependency = |name: &str, version: &str, cached: bool| { + if cached { + let dir = repo.path().join("example").join(name).join(version); + fs::create_dir_all(&dir).unwrap(); + fs::write(dir.join(format!("{name}-{version}-sources.jar")), b"cached").unwrap(); + } + MavenDependency { + group_id: "example".into(), + artifact_id: name.into(), + version: Some(version.into()), + kind: "jar".into(), + ..Default::default() + } + }; + let transitive = dependency("transitive", "1-SNAPSHOT", true); + let direct = MavenDependency { children: vec![transitive.clone()], ..dependency("direct", "1-SNAPSHOT", true) }; + let omitted = + MavenDependency { omitted: Some(Omission::Conflict), ..dependency("omitted", "1-SNAPSHOT", true) }; + let projects = [ + MavenProject { + dependencies: vec![ + direct, + omitted, + dependency("missing", "1-SNAPSHOT", false), + dependency("release", "1", true), + ], + ..Default::default() + }, + MavenProject { dependencies: vec![transitive], ..Default::default() }, + ]; + let mut found: Vec<_> = cached_snapshots(repo.path(), projects.iter().enumerate()) + .into_iter() + .map(|(owner, artifact)| (owner, artifact.name)) + .collect(); + found.sort(); + assert_eq!(found, [(0, "direct".into()), (0, "transitive".into())]); + } + + #[cfg(unix)] + #[test] + fn downloads_sources_again_when_the_snapshot_binary_is_newer() { + use std::fs::FileTimes; + use std::os::unix::fs::PermissionsExt; + use std::time::Duration; + + let dir = tempfile::tempdir().unwrap(); + let repository = dir.path().join("repository"); + let jar = repository.join("example/lib/1-SNAPSHOT/lib-1-SNAPSHOT.jar"); + fs::create_dir_all(jar.parent().unwrap()).unwrap(); + fs::write(&jar, b"new binary").unwrap(); + let artifact = artifact(&jar, &repository).unwrap(); + fs::write(&artifact.sources, b"old sources").unwrap(); + File::open(&artifact.sources) + .unwrap() + .set_times(FileTimes::new().set_modified(SystemTime::now() - Duration::from_secs(60))) + .unwrap(); + let launcher = dir.path().join("mvn"); + fs::write( + &launcher, + "#!/bin/sh\nfor arg do\n case \"$arg\" in\n -DoutputDirectory=*) out=\"${arg#*=}\" ;;\n esac\ndone\nprintf 'new sources' > \"$out/lib-1-SNAPSHOT-sources.jar\"\n", + ) + .unwrap(); + fs::set_permissions(&launcher, fs::Permissions::from_mode(0o755)).unwrap(); + let cancel = CancellationToken::new(); + cancel.cancel(); + assert!(download(dir.path(), &MavenProject::default(), &artifact, &repository, &cancel).is_err()); + assert_eq!(fs::read(&artifact.sources).unwrap(), b"old sources"); + let project = MavenProject { command: launcher.to_string_lossy().into_owned(), ..Default::default() }; + let cancel = CancellationToken::new(); + let path = download(dir.path(), &project, &artifact, &repository, &cancel).unwrap().unwrap(); + assert_eq!(fs::read(&path).unwrap(), b"new sources"); + assert_eq!( + download(dir.path(), &MavenProject::default(), &artifact, &repository, &CancellationToken::new()).unwrap(), + Some(path) + ); + } } diff --git a/crates/ide-host/src/ops/build.rs b/crates/ide-host/src/ops/build.rs index 8894d4ba1..a5a317991 100644 --- a/crates/ide-host/src/ops/build.rs +++ b/crates/ide-host/src/ops/build.rs @@ -9,13 +9,16 @@ use ide_command::command; use ide_build::compile::{self, BuildEvent, BuildKind, BuildResult}; use ide_build::maven::completion::{PomCompletion, PomCompletionOption}; +use ide_build::maven::sources; use ide_build::maven::{PomGoto, PomManagedDeclaration, PomNavigationOptions}; use ide_build::pom_edit::{ArtifactKey, Exclusion}; use ide_build::{BuildModel, BuildTool, SyncOptions, SyncProgress}; use ide_core::settings::Settings; -use ide_core::{DocId, FileEdit, IdeError, IdeEvent, IdeResult, Location, Pos, Range, RequestId, WorkspaceEdit}; -use std::collections::HashMap; -use std::path::Path; +use ide_core::{ + CancellationToken, DocId, FileEdit, IdeError, IdeEvent, IdeResult, Location, Pos, Range, RequestId, WorkspaceEdit, +}; +use std::collections::{HashMap, HashSet}; +use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex, OnceLock}; use std::time::{Duration, Instant}; @@ -281,6 +284,35 @@ pub async fn gradle_unlink_projects(host: &Host, window: &str, paths: Vec, +} + +fn cached_maven_sources( + model: &BuildModel, + scopes: Vec, + window_root: &Path, + build_dir: Option<&str>, +) -> Vec { + let Some(maven) = &model.maven else { return Vec::new() }; + scopes + .into_iter() + .filter(|scope| workspace::selected(scope, window_root, BuildTool::Maven, build_dir)) + .filter_map(|scope| { + let repository = ide_sdk::apply::maven_local_repository(&scope.root, &scope.settings) + .or_else(ide_build::maven::default_local_repo)?; + let projects = maven.projects.iter().enumerate().filter(|(_, project)| { + Path::new(project.project_root.as_deref().unwrap_or_default()) == scope.root + || (project.project_root.is_none() && scope.root == window_root) + }); + let candidates = sources::cached_snapshots(&repository, projects); + (!candidates.is_empty()).then_some(MavenSourceRefresh { root: scope.root, repository, candidates }) + }) + .collect() +} + /// Runs Maven (`help:effective-pom dependency:tree`) or Gradle (`tasks --all`) in the /// background, reporting progress on `on_progress`; cancellable with `cancel_request(request)`. /// Returns the refreshed model; a failed build is reported in its `syncError`. @@ -377,72 +409,122 @@ pub async fn build_sync( let scopes = workspace::scopes(&p, &config)?; let model = workspace::load_scopes(&p.root, &scopes); let updates = workspace::update_files(&p.root, &scopes, &model, tool); - Ok::<_, IdeError>((model, profiles_changed, offline_changed, updates)) + let snapshots = if tool == BuildTool::Maven && !offline { + cached_maven_sources(&model, scopes, &p.root, build_dir.as_deref()) + } else { + Vec::new() + }; + Ok::<_, IdeError>((model, profiles_changed || offline_changed, updates, snapshots)) }) .await .map_err(join_err); - host.end_request(request); - let (model, profiles_changed, offline_changed, updates) = result??; - if completion_token.is_cancelled() { - return Err(IdeError::cancelled()); - } - // Gradle may report project folders outside the project (`includeFlat`), and a Maven - // reactor may have gained or dropped modules beside it: index and list them. - project.refresh_index_scope(); - let p = project.clone(); - tokio::task::spawn_blocking(move || p.refresh_repositories()); - // New source folders and dependency versions: the Project view and External Libraries reload. - project.sink.emit(ide_core::IdeEvent::ProjectRootsChanged { root: project.root.clone().into() }); - if tool == BuildTool::Maven - && model.maven.is_some() - && let Some(bridge) = &project.kotlin_bridge - { - bridge.configure_maven(offline, bridge_profiles); - } - // jdtls re-imports on pom changes but misses artifacts added to ~/.m2 - // meanwhile ("missing artifact" stays until Invalidate Caches); asking it - // to update the project configurations re-resolves them (#436). The same - // holds for Gradle: it reuses its cached classpath on restart, so a - // dependency added to `build.gradle` stays unresolved until told to sync. - let lsp = project.lsp.clone(); - let documents = project.documents.clone(); - tokio::spawn(async move { - if profiles_changed || offline_changed { - // jdtls takes the profiles and offline mode from its Maven settings (see `ide_sdk::maven_profiles`). - lsp.reconfigure().await; + let result = async { + let (mut model, reconfigure, updates, snapshots) = result??; + if completion_token.is_cancelled() { + return Err(IdeError::cancelled()); } - let first = updates.first().cloned(); - for file in updates { - let uri = ide_lsp::path_to_uri_string(&file); - if let Err(e) = lsp.java_update_project_configs(&file, vec![uri]).await { - tracing::debug!("java/projectConfigurationsUpdate: {e}"); - } - } - let changed = { - let lsp = lsp.clone(); - tokio::task::spawn_blocking(move || lsp.changed_library_archives()).await.unwrap_or_default() - }; - if let Some(file) = first - && let Err(e) = lsp.java_refresh_archives(&file, &changed).await + // A reactor or Gradle build may have changed its external project folders. + project.refresh_index_scope(); + let p = project.clone(); + tokio::task::spawn_blocking(move || p.refresh_repositories()); + project.sink.emit(IdeEvent::ProjectRootsChanged { root: project.root.clone().into() }); + if tool == BuildTool::Maven + && model.maven.is_some() + && let Some(bridge) = &project.kotlin_bridge { - tracing::debug!("openidea.java.refreshArchives: {e}"); + bridge.configure_maven(offline, bridge_profiles.clone()); } - refresh_library_classes(&lsp, &documents).await; - }); - Ok(model) + let lsp = project.lsp.clone(); + let documents = project.documents.clone(); + if snapshots.is_empty() { + tokio::spawn(async move { + update_java_projects(&lsp, &updates, reconfigure, None).await; + refresh_library_archives(&lsp, &documents, &updates, Vec::new()).await; + }); + } else { + // JDT LS resolves the binary jars while importing Maven projects. + update_java_projects(&lsp, &updates, reconfigure, Some(&completion_token)).await; + let cancel = completion_token.clone(); + let (updated, refreshed) = tokio::task::spawn_blocking(move || { + let mut refreshed = Vec::new(); + if let Some(maven) = &model.maven { + for batch in snapshots { + if cancel.is_cancelled() { + break; + } + refreshed.extend(sources::refresh_snapshots( + &batch.root, + &maven.projects, + &batch.repository, + &batch.candidates, + &bridge_profiles, + &cancel, + )); + } + } + (model, refreshed) + }) + .await + .map_err(join_err)?; + model = updated; + tokio::spawn(async move { + refresh_library_archives(&lsp, &documents, &updates, refreshed).await; + }); + } + if completion_token.is_cancelled() { + return Err(IdeError::cancelled()); + } + Ok(model) + } + .await; + host.end_request(request); + result } -/// Open library classes whose jar was replaced in place (a SNAPSHOT installed -/// again keeps its path) show the new contents, like a reopened one. -async fn refresh_library_classes(lsp: &Arc, documents: &Arc) { +async fn update_java_projects( + lsp: &ide_lsp::LspManager, + updates: &[PathBuf], + reconfigure: bool, + wait: Option<&CancellationToken>, +) { + if reconfigure { + // jdtls takes the profiles and offline mode from its Maven settings. + lsp.reconfigure().await; + } + // JDT LS caches its classpath and re-imports on build-file changes. Ask it to + // re-resolve dependencies even when the build files stayed the same (#436). + if let Err(e) = lsp.java_update_project_configs(updates, wait).await { + tracing::debug!("Updating Java project configurations: {e}"); + } +} + +/// Re-read open library classes whose binary or attached sources changed in place. +async fn refresh_library_archives( + lsp: &Arc, + documents: &Arc, + updates: &[PathBuf], + refreshed: Vec, +) { + let changed = { + let lsp = lsp.clone(); + tokio::task::spawn_blocking(move || lsp.changed_library_archives()).await.unwrap_or_default() + }; + let archives: HashSet<_> = changed.into_iter().chain(refreshed).collect(); + if let Err(e) = lsp.java_refresh_archives(updates, &archives).await { + tracing::debug!("openidea.java.refreshArchives: {e}"); + } let changed = { let (lsp, documents) = (lsp.clone(), documents.clone()); tokio::task::spawn_blocking(move || { + lsp.invalidate_library_archives(&archives); documents .open_documents() .into_iter() .filter_map(|doc| Some((doc, documents.virtual_uri(doc).ok().flatten()?))) - .filter(|(_, uri)| lsp.library_class_changed(uri)) + .filter(|(_, uri)| { + lsp.library_class_changed(uri) + || ide_lsp::LspManager::library_archive(uri).is_some_and(|archive| archives.contains(&archive)) + }) .collect::>() }) .await diff --git a/crates/ide-lsp/src/jdtls.rs b/crates/ide-lsp/src/jdtls.rs index 57998c7a7..b79966604 100644 --- a/crates/ide-lsp/src/jdtls.rs +++ b/crates/ide-lsp/src/jdtls.rs @@ -13,6 +13,7 @@ use ide_core::{CancellationToken, IdeError, IdeResult, LanguageId}; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use specta::Type; +use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; use std::sync::Arc; use std::time::{Duration, Instant}; @@ -851,37 +852,65 @@ impl LspManager { } } - /// Tells jdtls the build files of `uris` changed (`java/projectConfigurationsUpdate`), - /// so it re-imports their projects (e.g. after `~/.m2` gained an artifact it could - /// not resolve). Best-effort: skipped while jdtls is not already running. - pub async fn java_update_project_configs(&self, path: &Path, uris: Vec) -> IdeResult<()> { - if uris.is_empty() { - return Ok(()); - } + fn running_java_projects<'a>(&self, files: &'a [PathBuf]) -> Vec<(Running, Vec<&'a Path>)> { let java = LanguageId::new("java"); - let Some(server) = self.servers_for(&java, path).into_iter().find(|s| s.name == SERVER) else { - return Ok(()); - }; - let Some(run) = server.running() else { return Ok(()) }; - let identifiers: Vec = uris.iter().map(|u| json!({ "uri": u })).collect(); - run.peer - .notify("java/projectConfigurationsUpdate", json!({ "identifiers": identifiers })) - .map_err(|e| crate::rpc_err(&server.name, "java/projectConfigurationsUpdate", e)) + let mut targets = HashMap::new(); + for file in files { + if let Some(server) = self.servers_for(&java, file).into_iter().find(|s| s.name == SERVER) + && let Some(run) = server.running() + { + let (_, paths) = targets.entry(server.id).or_insert_with(|| (run, Vec::new())); + paths.push(file.as_path()); + } + } + targets.into_values().collect() } - /// Asks jdtls to re-read library archives replaced in place (`openidea.java.refreshArchives`): - /// a SNAPSHOT installed again keeps its path, and JDT would keep showing the classes it read - /// from the old archive. Best-effort: skipped while jdtls is not already running. - pub async fn java_refresh_archives(&self, path: &Path, archives: &[PathBuf]) -> IdeResult<()> { - let java = LanguageId::new("java"); - let Some(server) = self.servers_for(&java, path).into_iter().find(|s| s.name == SERVER) else { - return Ok(()); - }; - if server.running().is_none() { - return Ok(()); + /// Re-imports projects even when their build files did not change. Wait for + /// the Maven configuration job when a source refresh depends on its binaries. + pub async fn java_update_project_configs( + &self, + files: &[PathBuf], + wait: Option<&CancellationToken>, + ) -> IdeResult<()> { + const UPDATE: &str = "openidea.java.updateProjectConfigurations"; + let mut result = Ok(()); + for (run, paths) in self.running_java_projects(files) { + let uris: Vec<_> = paths.iter().map(|path| crate::path_to_uri_string(path)).collect(); + let supports_wait = run.caps.read().commands().iter().any(|command| command == UPDATE); + let updated = match wait.filter(|_| supports_wait) { + Some(cancel) => self + .jdtls_request( + paths[0], + "workspace/executeCommand", + json!({ "command": UPDATE, "arguments": uris }), + BUILD_TIMEOUT, + cancel, + ) + .await + .map(|_| ()), + None => { + let identifiers: Vec<_> = uris.into_iter().map(|uri| json!({ "uri": uri })).collect(); + run.peer + .notify("java/projectConfigurationsUpdate", json!({ "identifiers": identifiers })) + .map_err(|e| crate::rpc_err(SERVER, "java/projectConfigurationsUpdate", e)) + } + }; + result = result.and(updated); } - let archives = archives.iter().map(|a| Value::String(a.to_string_lossy().into_owned())).collect(); - self.jdtls_command(path, "openidea.java.refreshArchives", archives).await.map(|_| ()) + result + } + + /// Asks jdtls to re-read library archives replaced in place. + pub async fn java_refresh_archives(&self, files: &[PathBuf], archives: &HashSet) -> IdeResult<()> { + let mut archives: Vec<_> = archives.iter().map(|a| Value::String(a.to_string_lossy().into_owned())).collect(); + archives.sort_by(|a, b| a.as_str().cmp(&b.as_str())); + let mut result = Ok(()); + for (_, paths) in self.running_java_projects(files) { + let refreshed = self.jdtls_command(paths[0], "openidea.java.refreshArchives", archives.clone()).await; + result = result.and(refreshed.map(|_| ())); + } + result } /// Pause autobuild before resolving the launch classpath. That query takes the diff --git a/crates/ide-lsp/src/lib.rs b/crates/ide-lsp/src/lib.rs index 6aace2f1a..ffda68a9e 100644 --- a/crates/ide-lsp/src/lib.rs +++ b/crates/ide-lsp/src/lib.rs @@ -280,7 +280,7 @@ pub struct LspManager { virtual_docs: Mutex>, /// Modification time of the archive behind a cached library class, so a jar /// replaced in place (a SNAPSHOT installed again) is read again. - virtual_stamps: Mutex>, + virtual_stamps: Mutex>, injections: injections::State, /// Open notebooks by path. Locked before `docs` when both are. notebooks: Mutex>, @@ -3631,6 +3631,16 @@ impl LspManager { archives } + /// Drop cached text after JDT LS reopens the archives. A request could have + /// read the old attachment while the binary already had its new timestamp. + pub fn invalidate_library_archives(&self, archives: &std::collections::HashSet) { + if !archives.is_empty() { + self.virtual_docs + .lock() + .retain(|uri, _| !virtual_doc::archive(uri).is_some_and(|archive| archives.contains(&archive))); + } + } + /// Contents of a virtual document, from the server that owns `uri`: /// `workspace/textDocumentContent` (LSP 3.18) when the server serves the /// scheme, jdtls' `java/classFileContents` for `jdt:` URIs. A `jar:` entry diff --git a/crates/ide-lsp/src/virtual_doc.rs b/crates/ide-lsp/src/virtual_doc.rs index 3576266e4..7ade597c5 100644 --- a/crates/ide-lsp/src/virtual_doc.rs +++ b/crates/ide-lsp/src/virtual_doc.rs @@ -192,9 +192,22 @@ pub(crate) fn archive(uri: &str) -> Option { } } -/// Modification time of the archive a `jar:` or `jdt:` library class comes from. -pub(crate) fn archive_modified(uri: &str) -> Option { - std::fs::metadata(archive(uri)?).and_then(|m| m.modified()).ok() +/// Timestamps for a library document's archive and its replaceable SNAPSHOT attachment. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct ArchiveStamp { + archive: std::time::SystemTime, + sources: Option, +} + +pub(crate) fn archive_modified(uri: &str) -> Option { + let modified = |path: &std::path::Path| std::fs::metadata(path).and_then(|m| m.modified()).ok(); + let archive = archive(uri)?; + let sources = archive + .file_name() + .and_then(|name| name.to_str()) + .and_then(|name| name.strip_suffix("-SNAPSHOT.jar")) + .and_then(|name| modified(&archive.with_file_name(format!("{name}-SNAPSHOT-sources.jar")))); + Some(ArchiveStamp { archive: modified(&archive)?, sources }) } /// Whether `uri` is jdtls' class `package.name`, in any archive. @@ -433,9 +446,14 @@ mod tests { let uri = format!("jar:file://{}!/p/C.class", jar.display()); assert_eq!(archive(&uri), Some(jar.clone())); let before = archive_modified(&uri).unwrap(); + std::fs::write(dir.path().join("lib-1.0-SNAPSHOT-sources.jar"), b"PK").unwrap(); + let with_sources = archive_modified(&uri).unwrap(); + assert_eq!(before.archive, with_sources.archive); + assert_ne!(with_sources, before); + let file = std::fs::File::options().write(true).open(&jar).unwrap(); - file.set_modified(before + std::time::Duration::from_secs(5)).unwrap(); - assert_ne!(archive_modified(&uri), Some(before)); + file.set_modified(before.archive + std::time::Duration::from_secs(5)).unwrap(); + assert_ne!(archive_modified(&uri), Some(with_sources)); std::fs::remove_file(&jar).unwrap(); assert_eq!(archive_modified(&uri), None); } diff --git a/crates/ide-sdk/src/java.rs b/crates/ide-sdk/src/java.rs index 26392675f..f9df8d5fa 100644 --- a/crates/ide-sdk/src/java.rs +++ b/crates/ide-sdk/src/java.rs @@ -1629,7 +1629,7 @@ pub fn usages_bundle(data_dir: &Path) -> Option { install_bundle( data_dir, "java-usages", - "1.17.0", + "1.18.0", include_bytes!("../../../java/java-usages/openidea-java-usages.jar"), ) } diff --git a/java/java-usages/MANIFEST.MF b/java/java-usages/MANIFEST.MF index ca787adaf..432e6faa8 100644 --- a/java/java-usages/MANIFEST.MF +++ b/java/java-usages/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: OpenIDEA Java usages Bundle-SymbolicName: ai.openidea.usages;singleton:=true -Bundle-Version: 1.17.0 +Bundle-Version: 1.18.0 Bundle-RequiredExecutionEnvironment: JavaSE-21 Require-Bundle: org.eclipse.jdt.ls.core,org.eclipse.jdt.core, org.eclipse.jdt.core.manipulation,org.eclipse.core.runtime, diff --git a/java/java-usages/README.md b/java/java-usages/README.md index 5506ce55e..ac1f868a5 100644 --- a/java/java-usages/README.md +++ b/java/java-usages/README.md @@ -88,7 +88,7 @@ is not a claim of full IntelliJ feature parity. ## Rebuild and delivery The checked-in jar is embedded by ide-sdk `include_bytes!`, installed as -`java-usages-1.17.0.jar`, and added alongside existing initialization bundles. +`java-usages-1.18.0.jar`, and added alongside existing initialization bundles. Users need no compiler, Maven or Python. Manifest/install version must change when replacing the bundle because OSGi caches bundles. diff --git a/java/java-usages/openidea-java-usages.jar b/java/java-usages/openidea-java-usages.jar index 053d57c1a..13e77472c 100644 Binary files a/java/java-usages/openidea-java-usages.jar and b/java/java-usages/openidea-java-usages.jar differ diff --git a/java/java-usages/plugin.xml b/java/java-usages/plugin.xml index fbab8c136..98cab62c7 100644 --- a/java/java-usages/plugin.xml +++ b/java/java-usages/plugin.xml @@ -19,6 +19,7 @@ + diff --git a/java/java-usages/src/ai/openidea/archives/RefreshArchivesCommand.java b/java/java-usages/src/ai/openidea/archives/RefreshArchivesCommand.java index 496f9c99c..1c3137e23 100644 --- a/java/java-usages/src/ai/openidea/archives/RefreshArchivesCommand.java +++ b/java/java-usages/src/ai/openidea/archives/RefreshArchivesCommand.java @@ -1,10 +1,12 @@ package ai.openidea.archives; import java.lang.reflect.Field; +import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; +import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; @@ -16,6 +18,8 @@ import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.ls.core.internal.IDelegateCommandHandler; import org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin; +import org.eclipse.jdt.ls.core.internal.ProjectUtils; +import org.eclipse.lsp4j.TextDocumentIdentifier; /** * Re-reads library archives replaced in place (a SNAPSHOT installed again keeps its path). The @@ -26,6 +30,17 @@ import org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin; public final class RefreshArchivesCommand implements IDelegateCommandHandler { @Override public Object executeCommand(String command, List arguments, IProgressMonitor monitor) throws Exception { + if ("openidea.java.updateProjectConfigurations".equals(command)) { + List files = arguments.stream() + .filter(String.class::isInstance) + .map(uri -> new TextDocumentIdentifier((String) uri)) + .toList(); + Collection projects = ProjectUtils.getProjectsFromDocumentIdentifiers(files); + if (!projects.isEmpty()) { + JavaLanguageServerPlugin.getProjectsManager().updateProjects(projects, true).join(0, monitor); + } + return null; + } IJavaModel model = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()); model.refreshExternalArchives(null, monitor); Set archives = new HashSet<>();