diff --git a/crates/ide-build/src/compile/mod.rs b/crates/ide-build/src/compile/mod.rs index 37732b1af..532beeff9 100644 --- a/crates/ide-build/src/compile/mod.rs +++ b/crates/ide-build/src/compile/mod.rs @@ -15,12 +15,12 @@ pub use fingerprint::{LaunchFingerprint, launch_fingerprint, menu_fingerprint}; pub use launch_resources::process_launch_resources; pub use modules::record_module_build; pub use single::{ - SingleFileTarget, compile_file_plan, find_javac, javac_step, module_classpath, module_classpaths, - single_file_classpath, single_file_target, + SingleFileTarget, compile_file_plan, compile_file_plan_cancellable, find_javac, gradle_compile_file_plan, + has_gradle_file_target, javac_step, module_classpath, module_classpaths, single_file_classpath, single_file_target, }; pub use structure::{ - StructureJdk, StructureRoots, artifact_file, artifact_output, language_release, structure_outputs, structure_plan, - structure_war_plan, structure_web_artifacts, + StructureJdk, StructureRoots, artifact_file, artifact_output, language_release, structure_compile_file_plan, + structure_outputs, structure_plan, structure_war_plan, structure_web_artifacts, }; pub use up_to_date::{menu_up_to_date, record_menu_build}; diff --git a/crates/ide-build/src/compile/parse.rs b/crates/ide-build/src/compile/parse.rs index d33e5d438..99d920732 100644 --- a/crates/ide-build/src/compile/parse.rs +++ b/crates/ide-build/src/compile/parse.rs @@ -200,19 +200,22 @@ fn kotlin_line(line: &str) -> Option { kotlin_location(rest, severity) } -/// javac: `A.java:12: error: msg` / `A.java:12: warning: [deprecation] msg`. +/// javac: `A.java:12: error: msg` / `A.java:12: warning: [deprecation] msg` +/// (and localized javac prefixes such as Chinese/Japanese `错误:` / `錯誤:` / `エラー:` / `警告:`). fn javac_header(line: &str) -> Option { let (path, ln, col, rest) = path_line_col(line)?; if !looks_like_source_path(path) { return None; } let rest = rest.trim_start_matches(':').trim_start(); - let (severity, msg) = if let Some(m) = rest.strip_prefix("error:") { - (Severity::Error, m) - } else { - let m = rest.strip_prefix("warning:")?; - (Severity::Warning, m) - }; + let (severity, msg) = ["error:", "错误:", "錯誤:", "エラー:"] + .into_iter() + .find_map(|prefix| rest.strip_prefix(prefix).map(|m| (Severity::Error, m))) + .or_else(|| { + ["warning:", "警告:"] + .into_iter() + .find_map(|prefix| rest.strip_prefix(prefix).map(|m| (Severity::Warning, m))) + })?; Some(RawMessage::new(severity, msg.trim(), ColUnit::Char).at(path, ln, col)) } @@ -555,6 +558,31 @@ mod tests { assert_eq!(out[1].text, "[removal] finalize() has been deprecated"); } + #[test] + fn localized_javac_errors_and_warnings() { + let out = parse( + Format::Gradle, + "/p/src/A.java:12: 错误: 找不到符号\n\ + \x20 Foo foo = new Foo();\n\ + \x20 ^\n\ + \x20 符号: 类 Foo\n\ + \x20 位置: 类 A\n\ + /p/src/B.java:5: 錯誤: 需要 ';'\n\ + \x20 int x = 1\n\ + \x20 ^\n\ + /p/src/C.java:8: 警告: [deprecation] old() 已过时\n\ + \x20 old();\n\ + \x20 ^\n", + ); + assert_eq!(out.len(), 3, "{out:?}"); + assert_eq!(pos(&out[0]), (Severity::Error, "/p/src/A.java", 12, Some(9))); + assert_eq!(out[0].text, "找不到符号\n符号: 类 Foo\n位置: 类 A"); + assert_eq!(pos(&out[1]), (Severity::Error, "/p/src/B.java", 5, Some(14))); + assert_eq!(out[1].text, "需要 ';'"); + assert_eq!(pos(&out[2]), (Severity::Warning, "/p/src/C.java", 8, Some(5))); + assert_eq!(out[2].text, "[deprecation] old() 已过时"); + } + #[test] fn gradle_kotlin() { let out = parse( diff --git a/crates/ide-build/src/compile/single.rs b/crates/ide-build/src/compile/single.rs index b87f5bee4..8bd7c5f63 100644 --- a/crates/ide-build/src/compile/single.rs +++ b/crates/ide-build/src/compile/single.rs @@ -1,4 +1,4 @@ -//! Single-file Java compilation with `javac` for the Compile File action (#2476). +//! Single-file Java compilation with `javac` for the Recompile action (#2476). //! //! A module build (`-pl … -am`) still walks every upstream module, and packaging //! walks the whole reactor; compiling one file only needs that file's module @@ -6,12 +6,93 @@ use super::*; use serde::{Deserialize, Serialize}; use std::fs; -use std::process::Command as ProcCommand; /// Output file of the `dependency:build-classpath` probe, relative to each module. const CP_FILE: &str = "target/ide-compile-cp.txt"; // Older records include undeclared reactor test outputs even in runtime classpaths. const CLASSPATH_CACHE_VERSION: u32 = 1; +const GRADLE_COMPILE_CP_INIT_SCRIPT: &str = include_str!("../gradle-compile-cp.init.gradle"); + +pub(super) fn is_java_file(file: &Path) -> IdeResult { + if file.extension().is_none_or(|ext| !ext.eq_ignore_ascii_case("java")) { + return Err(IdeError::invalid("only Java sources can be compiled as a single file")); + } + if !file.is_file() { + return Err(IdeError::not_found("no Java source found for single-file compilation")); + } + Ok(file.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default()) +} + +pub(super) fn is_test_source(rel: &str) -> bool { + let parts: Vec<&str> = rel.split(['/', '\\']).collect(); + parts.windows(2).any(|w| w == ["src", "test"]) +} + +pub(super) fn java_home_major(env: &BTreeMap) -> Option { + let home = env.get("JAVA_HOME").filter(|h| !h.trim().is_empty())?; + let release = fs::read_to_string(Path::new(home).join("release")).ok()?; + let value = release.lines().find_map(|l| l.trim().strip_prefix("JAVA_VERSION="))?; + let value = value.trim().trim_matches(['"', '\'']); + language_release(value) +} + +/// `--release N` from JDK 9 on; older compilers only know `-source` / `-target`. +pub(super) fn release_args(level: Option, jdk_major: Option) -> Vec { + let Some(level) = level else { return Vec::new() }; + if jdk_major.is_none_or(|m| m >= 9) { + vec!["--release".into(), level.to_string()] + } else { + vec!["-source".into(), format!("1.{level}"), "-target".into(), format!("1.{level}")] + } +} + +pub(super) fn join_classpath(entries: impl IntoIterator) -> String { + let separator = if cfg!(windows) { ";" } else { ":" }; + let mut seen = HashSet::new(); + let mut out = Vec::new(); + for entry in entries { + if !entry.is_empty() && seen.insert(entry.clone()) { + out.push(entry); + } + } + out.join(separator) +} + +#[allow(clippy::too_many_arguments)] +pub(super) fn build_javac_step( + javac: &str, + cwd: &Path, + out_dir: &Path, + classpath: &str, + sources: &[PathBuf], + release: Vec, + file: &Path, + env: BTreeMap, +) -> IdeResult { + fs::create_dir_all(out_dir) + .map_err(|e| IdeError::internal(format!("cannot create {} ({e})", out_dir.display())))?; + // Raw `javac` prints `path:line: error: …`, the same form Gradle forwards. + let mut step = BuildStep::new(javac, &[], cwd, Format::Gradle); + step.args.extend(["-encoding".into(), "UTF-8".into(), "-g".into()]); + step.args.extend(["-d".into(), out_dir.to_string_lossy().into_owned()]); + if !classpath.is_empty() { + step.args.extend(["-cp".into(), classpath.to_owned()]); + } + // Classes of the module that were never built (or are older than their source) are read + // from its sources; only `file` is written, so a test compile never puts main classes + // into test-classes. + if !sources.is_empty() { + let separator = if cfg!(windows) { ";" } else { ":" }; + step.args.push("-sourcepath".into()); + step.args.push(sources.iter().map(|p| p.to_string_lossy()).collect::>().join(separator)); + step.args.push("-implicit:none".into()); + } + step.args.extend(release); + step.args.push(file.to_string_lossy().into_owned()); + step.env = env; + step.mkdirs = vec![out_dir.to_path_buf()]; + Ok(step) +} /// The resolved dependency classpath for one module and scope, tied to the same /// inputs as its launch build so POM, JDK, settings and profile changes invalidate it. @@ -41,12 +122,7 @@ pub struct SingleFileTarget { /// Locates the linked Maven module owning a `.java` source file. pub fn single_file_target(root: &Path, model: &BuildModel, file: &Path) -> IdeResult { - if file.extension().is_none_or(|ext| ext != "java") { - return Err(IdeError::invalid("only Java sources can be compiled as a single file")); - } - if !file.is_file() { - return Err(IdeError::not_found("no Java source found for single-file compilation")); - } + is_java_file(file)?; let Some(m) = &model.maven else { return Err(IdeError::not_found("no linked Maven project found for module")); }; @@ -70,8 +146,7 @@ pub fn single_file_target(root: &Path, model: &BuildModel, file: &Path) -> IdeRe let top_dir = subdir(root, &top.dir); let pl = module.strip_prefix(&top_dir).map(|r| r.to_string_lossy().replace('\\', "/")).unwrap_or_default(); // Test sources see the test classpath and compile into test classes. - let parts: Vec<&str> = rel.split('/').collect(); - let test = parts.windows(2).any(|w| w == ["src", "test"]); + let test = is_test_source(&rel); let out_dir = module.join("target").join(if test { "test-classes" } else { "classes" }); Ok(SingleFileTarget { module, test, out_dir, top: top.clone(), pl, java_version: project.java_version }) } @@ -112,7 +187,17 @@ pub fn find_javac(env: &BTreeMap) -> String { /// `mvn dependency:build-classpath` (which resolves without compiling anything, /// so `-am` stays cheap). Entries are platform-separated (`;` on Windows). pub fn single_file_classpath(root: &Path, model: &BuildModel, target: &SingleFileTarget) -> IdeResult { - classpath(root, model, target, "test", false) + single_file_classpath_cancellable(root, model, target, &CancellationToken::new()) +} + +fn single_file_classpath_cancellable( + root: &Path, + model: &BuildModel, + target: &SingleFileTarget, + cancel: &CancellationToken, +) -> IdeResult { + let scope = if target.test { "test" } else { "compile" }; + classpath(root, model, target, scope, false, cancel) } /// Runtime (or test) dependency classpath for a launch module. @@ -172,10 +257,12 @@ pub fn module_classpaths( } let scope = if test { "test" } else { "runtime" }; let targets: Vec<&SingleFileTarget> = probes.iter().map(|p| &p.0).collect(); - let classpaths = match classpaths(root, model, &targets, scope, true) { + let classpaths = match classpaths(root, model, &targets, scope, true, cancel) { Ok(classpaths) => classpaths, // Another module's failure must not cost this launch its own probe. - Err(_) if targets.len() > 1 && !cancel.is_cancelled() => classpaths(root, model, &targets[..1], scope, true)?, + Err(_) if targets.len() > 1 && !cancel.is_cancelled() => { + classpaths(root, model, &targets[..1], scope, true, cancel)? + } Err(e) => return Err(e), }; if cancel.is_cancelled() { @@ -236,8 +323,9 @@ fn classpath( target: &SingleFileTarget, scope: &str, compile_first: bool, + cancel: &CancellationToken, ) -> IdeResult { - Ok(classpaths(root, model, &[target], scope, compile_first)?.pop().unwrap()) + Ok(classpaths(root, model, &[target], scope, compile_first, cancel)?.pop().unwrap()) } /// The classpath of each of `targets` (modules of one reactor) from one Maven probe. @@ -247,6 +335,7 @@ fn classpaths( targets: &[&SingleFileTarget], scope: &str, compile_first: bool, + cancel: &CancellationToken, ) -> IdeResult> { let top = &targets[0].top; let probe = CP_FILE; @@ -274,16 +363,17 @@ fn classpaths( } args.extend(["dependency:build-classpath", output_arg.as_str(), scope_arg.as_str(), "-q"]); let top_dir = subdir(root, &top.dir); - let mut command = ProcCommand::new(&top.command); - command.args(&args).envs(&top.env).current_dir(&top_dir); - let status = ide_core::process::prepare(&mut command) - .output() - .map_err(|e| IdeError::internal(format!("cannot resolve the compile classpath: {e}")))?; - if !status.status.success() { - let stdout = String::from_utf8_lossy(&status.stdout); - let stderr = String::from_utf8_lossy(&status.stderr); + let owned_args: Vec = args.into_iter().map(str::to_owned).collect(); + let out = process::run_bounded(&top.command, &owned_args, &top_dir, &top.env, cancel, |_, _| {}).map_err(|e| { + if e.kind == ide_core::error::ErrorKind::Cancelled { + e + } else { + IdeError::internal(format!("cannot resolve the compile classpath: {}", e.message)) + } + })?; + if !out.success { // Maven reports reactor/dependency failures on stdout, not only stderr. - let tail: Vec<&str> = stdout.lines().chain(stderr.lines()).filter(|l| !l.trim().is_empty()).collect(); + let tail: Vec<&str> = out.text.lines().filter(|l| !l.trim().is_empty()).collect(); let tail = tail.iter().rev().take(5).rev().cloned().collect::>().join("\n"); return Err(IdeError::internal(format!("cannot resolve the compile classpath:\n{tail}"))); } @@ -325,39 +415,14 @@ fn target_classpath(root: &Path, model: &BuildModel, target: &SingleFileTarget) })?; let separator = if cfg!(windows) { ';' } else { ':' }; entries.extend(content.split([separator, '\n', '\r']).map(str::trim).filter(|e| !e.is_empty()).map(str::to_owned)); - entries.dedup(); - Ok(entries.join(&separator.to_string())) + Ok(join_classpath(entries)) } /// The `javac` step compiling `file` into `target`'s output directory. pub fn javac_step(target: &SingleFileTarget, file: &Path, classpath: &str, javac: &str) -> IdeResult { - fs::create_dir_all(&target.out_dir) - .map_err(|e| IdeError::internal(format!("cannot create {} ({e})", target.out_dir.display())))?; - let mut step = BuildStep::new(javac, &[], &target.module, Format::Gradle); - // Raw `javac` prints `path:line: error: …`, the same form Gradle forwards. - step.args.push("-encoding".into()); - step.args.push("UTF-8".into()); - step.args.push("-d".into()); - step.args.push(target.out_dir.to_string_lossy().into_owned()); - step.args.push("-cp".into()); - step.args.push(classpath.to_owned()); - // Classes of the module that were never built (or are older than their source) are read - // from its sources; only `file` is written, so a test compile never puts main classes - // into test-classes. let sources = source_roots(target); - if !sources.is_empty() { - let separator = if cfg!(windows) { ";" } else { ":" }; - step.args.push("-sourcepath".into()); - step.args.push(sources.iter().map(|p| p.to_string_lossy()).collect::>().join(separator)); - step.args.push("-implicit:none".into()); - } - if let Some(version) = target.java_version { - step.args.push("--release".into()); - step.args.push(version.to_string()); - } - step.args.push(file.to_string_lossy().into_owned()); - step.env = target.top.env.clone(); - Ok(step) + let release = release_args(target.java_version, java_home_major(&target.top.env)); + build_javac_step(javac, &target.module, &target.out_dir, classpath, &sources, release, file, target.top.env.clone()) } /// The module's Java source folders that exist, generated ones included; test sources see @@ -383,8 +448,18 @@ fn source_roots(target: &SingleFileTarget) -> Vec { /// Resolves the classpath and plans the `javac` invocation for one Java source. pub fn compile_file_plan(root: &Path, model: &BuildModel, file: &Path) -> IdeResult { + compile_file_plan_cancellable(root, model, file, &CancellationToken::new()) +} + +/// Cancellable [`compile_file_plan`]. +pub fn compile_file_plan_cancellable( + root: &Path, + model: &BuildModel, + file: &Path, + cancel: &CancellationToken, +) -> IdeResult { let target = single_file_target(root, model, file)?; - let classpath = single_file_classpath(root, model, &target)?; + let classpath = single_file_classpath_cancellable(root, model, &target, cancel)?; let javac = find_javac(&target.top.env); let name = file.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); Ok(BuildPlan { @@ -394,6 +469,140 @@ pub fn compile_file_plan(root: &Path, model: &BuildModel, file: &Path) -> IdeRes }) } +fn gradle_for_file<'a>( + root: &Path, + model: &'a BuildModel, + file: &Path, +) -> Option<(&'a crate::GradleModel, &'a crate::GradleProject, PathBuf)> { + let file = normalize(file); + let file_ref = &file; + model + .gradle + .iter() + .flat_map(|g| { + let g_dir = normalize(&subdir(root, &g.dir)); + let g_depth = g_dir.components().count(); + g.projects.iter().filter_map(move |p| { + let p_dir = normalize(&subdir(root, &p.dir)); + file_ref.starts_with(&p_dir).then_some((g, p, p_dir, g_depth)) + }) + }) + .max_by_key(|(_, _, p_dir, g_depth)| (p_dir.components().count(), *g_depth)) + .map(|(g, p, p_dir, _)| (g, p, p_dir)) +} + +/// Whether `file` lies inside a linked Gradle project of `model`. +pub fn has_gradle_file_target(root: &Path, model: &BuildModel, file: &Path) -> bool { + gradle_for_file(root, model, file).is_some() +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct GradleCompileCp { + out_dir: Option, + #[serde(default)] + classpath: Vec, + #[serde(default)] + src_dirs: Vec, + release: Option, +} + +/// Resolves the compile classpath from Gradle and plans a single-file `javac` step. +pub fn gradle_compile_file_plan( + root: &Path, + model: &BuildModel, + file: &Path, + cache: &Path, + cancel: &CancellationToken, +) -> IdeResult { + let name = is_java_file(file)?; + let (gradle, project, module_dir) = gradle_for_file(root, model, file) + .ok_or_else(|| IdeError::not_found("no linked Gradle project found for file"))?; + let rel = rel_str(&module_dir, file); + let test = is_test_source(&rel); + let scope = if test { "test" } else { "main" }; + + fs::create_dir_all(cache)?; + let init_script = cache.join("gradle-compile-cp.init.gradle"); + fs::write(&init_script, GRADLE_COMPILE_CP_INIT_SCRIPT)?; + let args = vec![ + "--console=plain".into(), + "-q".into(), + "-Dorg.gradle.configuration-cache=false".into(), + "--init-script".into(), + init_script.to_string_lossy().into_owned(), + format!("-Popenidea.target={}", project.path), + format!("-Popenidea.scope={scope}"), + "help".into(), + ]; + let gradle_dir = subdir(root, &gradle.dir); + let mut reported: Option = None; + let out = process::run_bounded(&gradle.command, &args, &gradle_dir, &gradle.env, cancel, |_, line| { + if let Some(json) = line.strip_prefix("@openidea-compile-cp\t") { + reported = Some(json.to_owned()); + } + }) + .map_err(|e| { + if e.kind == ide_core::error::ErrorKind::Cancelled { + e + } else { + IdeError::internal(format!("cannot resolve the compile classpath: {}", e.message)) + } + })?; + if !out.success { + let tail: Vec<&str> = out.text.lines().filter(|l| !l.trim().is_empty()).collect(); + let tail = tail.iter().rev().take(5).rev().cloned().collect::>().join("\n"); + return Err(IdeError::internal(format!("cannot resolve the compile classpath:\n{tail}"))); + } + let json = reported.ok_or_else(|| { + IdeError::internal(format!( + "cannot resolve the compile classpath: Gradle did not report source set '{scope}' for {}", + project.path + )) + })?; + let cp: GradleCompileCp = serde_json::from_str(&json) + .map_err(|e| IdeError::internal(format!("cannot parse Gradle compile classpath: {e}")))?; + + let out_dir = cp + .out_dir + .filter(|d| !d.trim().is_empty()) + .map(PathBuf::from) + .unwrap_or_else(|| module_dir.join("build/classes/java").join(scope)); + let mut cp_entries: Vec = Vec::new(); + if out_dir.is_dir() { + cp_entries.push(out_dir.to_string_lossy().into_owned()); + } + if test { + let main_out = module_dir.join("build/classes/java/main"); + if main_out.is_dir() { + cp_entries.push(main_out.to_string_lossy().into_owned()); + } + } + for sibling in &gradle.projects { + let sibling_dir = subdir(root, &sibling.dir); + if sibling_dir == module_dir { + continue; + } + let classes = sibling_dir.join("build/classes/java/main"); + if classes.is_dir() { + cp_entries.push(classes.to_string_lossy().into_owned()); + } + } + cp_entries.extend(cp.classpath); + let classpath = join_classpath(cp_entries); + + let mut sources: Vec = cp.src_dirs.into_iter().map(PathBuf::from).filter(|p| p.is_dir()).collect(); + if sources.is_empty() { + let fallback: &[&str] = if test { &["src/test/java", "src/main/java"] } else { &["src/main/java"] }; + sources.extend(fallback.iter().map(|s| module_dir.join(s)).filter(|p| p.is_dir())); + } + let javac = find_javac(&gradle.env); + let release = release_args(cp.release.or(gradle.java_version), java_home_major(&gradle.env)); + let step = + build_javac_step(&javac, &module_dir, &out_dir, &classpath, &sources, release, file, gradle.env.clone())?; + Ok(BuildPlan { system: BuildSystem::Gradle, title: format!("Compile {name}"), steps: vec![step] }) +} + #[cfg(test)] mod tests { use super::*; @@ -439,7 +648,8 @@ mod tests { #[test] fn target_finds_the_owning_module_and_the_test_scope() { let dir = tempfile::tempdir().unwrap(); - let root = dir.path(); + let root_buf = dunce::canonicalize(dir.path()).unwrap(); + let root = root_buf.as_path(); let model = fixture(root); let main = single_file_target(root, &model, &root.join("app/src/main/java/demo/Main.java")).unwrap(); assert_eq!(main.module, root.join("app")); @@ -453,7 +663,8 @@ mod tests { #[test] fn target_rejects_non_java_missing_and_unlinked_files() { let dir = tempfile::tempdir().unwrap(); - let root = dir.path(); + let root_buf = dunce::canonicalize(dir.path()).unwrap(); + let root = root_buf.as_path(); let model = fixture(root); write(root, "app/pom.xml", ""); assert!(single_file_target(root, &model, &root.join("app/pom.xml")).is_err()); @@ -465,7 +676,8 @@ mod tests { #[test] fn javac_prefers_the_module_jdk_and_scopes_test_sources() { let dir = tempfile::tempdir().unwrap(); - let root = dir.path(); + let root_buf = dunce::canonicalize(dir.path()).unwrap(); + let root = root_buf.as_path(); let model = fixture(root); let file = root.join("app/src/test/java/demo/MainTest.java"); let target = single_file_target(root, &model, &file).unwrap(); @@ -501,7 +713,8 @@ mod tests { use std::os::unix::fs::PermissionsExt; let dir = tempfile::tempdir().unwrap(); - let root = dir.path(); + let root_buf = dunce::canonicalize(dir.path()).unwrap(); + let root = root_buf.as_path(); fixture(root); let script = root.join("mvnw"); fs::write( @@ -532,6 +745,7 @@ mod tests { assert!(cp.split(separator).count() >= 3, "{cp}"); let args = fs::read_to_string(root.join("args.txt")).unwrap(); assert!(!args.lines().any(|a| a == "compile" || a == "package"), "{args}"); + assert!(args.lines().any(|a| a == "-Dmdep.includeScope=compile"), "{args}"); fs::create_dir_all(root.join("app/target/test-classes")).unwrap(); let target = single_file_target(root, &model, &root.join("app/src/test/java/demo/MainTest.java")).unwrap(); let cp = single_file_classpath(root, &model, &target).unwrap(); @@ -539,6 +753,8 @@ mod tests { assert_eq!(paths[0], root.join("app/target/test-classes")); assert!(paths.contains(&root.join("app/target/classes")), "{cp}"); assert!(!paths.contains(&root.join("lib/target/test-classes")), "{cp}"); + let args = fs::read_to_string(root.join("args.txt")).unwrap(); + assert!(args.lines().any(|a| a == "-Dmdep.includeScope=test"), "{args}"); } /// Launches request Maven's matching scope without adding reactor test outputs. @@ -548,7 +764,8 @@ mod tests { use std::os::unix::fs::PermissionsExt; let dir = tempfile::tempdir().unwrap(); - let root = dir.path(); + let root_buf = dunce::canonicalize(dir.path()).unwrap(); + let root = root_buf.as_path(); fixture(root); let script = root.join("mvnw"); fs::write( @@ -605,7 +822,8 @@ mod tests { use std::os::unix::fs::PermissionsExt; let dir = tempfile::tempdir().unwrap(); - let root = dir.path(); + let root_buf = dunce::canonicalize(dir.path()).unwrap(); + let root = root_buf.as_path(); fixture(root); write(root, "lib/src/main/java/demo/Lib.java", "class Lib {}"); let script = root.join("mvnw"); @@ -646,7 +864,8 @@ mod tests { use std::os::unix::fs::PermissionsExt; let dir = tempfile::tempdir().unwrap(); - let root = dir.path(); + let root_buf = dunce::canonicalize(dir.path()).unwrap(); + let root = root_buf.as_path(); fixture(root); let script = root.join("mvnw"); // `dependency:build-classpath` reports reactor outputs as absolute paths. Keep @@ -712,4 +931,79 @@ mod tests { calls.push('x'); assert_eq!(fs::read_to_string(root.join("calls.txt")).unwrap(), calls); } + + #[test] + fn javac_step_omits_empty_classpath_and_uses_source_target_on_jdk_8() { + let dir = tempfile::tempdir().unwrap(); + let root_buf = dunce::canonicalize(dir.path()).unwrap(); + let root = root_buf.as_path(); + let mut model = fixture(root); + let file = root.join("app/src/main/java/demo/Main.java"); + let jdk8 = root.join("jdk8"); + fs::create_dir_all(jdk8.join("bin")).unwrap(); + fs::write(jdk8.join("release"), "JAVA_VERSION=\"1.8.0_372\"\n").unwrap(); + let project = model.maven.as_mut().unwrap().projects.iter_mut().find(|p| p.dir == "app").unwrap(); + project.java_version = Some(8); + let mut target = single_file_target(root, &model, &file).unwrap(); + target.top.env.insert("JAVA_HOME".into(), jdk8.to_string_lossy().into_owned()); + let step = javac_step(&target, &file, "", "javac").unwrap(); + assert!(!step.args.iter().any(|a| a == "-cp"), "{:?}", step.args); + assert!(step.args.iter().any(|a| a == "-g"), "{:?}", step.args); + assert!(step.args.windows(4).any(|w| w == ["-source", "1.8", "-target", "1.8"]), "{:?}", step.args); + assert!(!step.args.iter().any(|a| a == "--release"), "{:?}", step.args); + } + + #[cfg(unix)] + #[test] + fn gradle_single_file_compiles_with_source_set_classpath_and_siblings() { + use std::os::unix::fs::PermissionsExt; + + let dir = tempfile::tempdir().unwrap(); + let root_buf = dunce::canonicalize(dir.path()).unwrap(); + let root = root_buf.as_path(); + write(root, "settings.gradle", "include ':lib', ':app'"); + write(root, "lib/build.gradle", "plugins { id 'java' }"); + write(root, "app/build.gradle", "plugins { id 'java' }"); + write(root, "app/src/main/java/demo/App.java", "package demo; class App {}"); + write(root, "app/src/test/java/demo/AppTest.java", "package demo; class AppTest {}"); + fs::create_dir_all(root.join("lib/build/classes/java/main")).unwrap(); + fs::create_dir_all(root.join("app/build/classes/java/main")).unwrap(); + let wrapper = root.join("gradlew"); + fs::write( + &wrapper, + "#!/bin/sh\nprintf '%s\\n' \"$@\" > gradle_args.txt\nscope='main'\nfor a in \"$@\"; do\ncase \"$a\" in -Popenidea.scope=*) scope=\"${a#-Popenidea.scope=}\" ;; esac\ndone\nprintf '@openidea-compile-cp\\t{\"outDir\":\"%s/app/build/classes/java/%s\",\"classpath\":[\"%s/deps/guava.jar\"],\"srcDirs\":[\"%s/app/src/%s/java\"],\"release\":17}\\n' \"$PWD\" \"$scope\" \"$PWD\" \"$PWD\" \"$scope\"\n", + ) + .unwrap(); + fs::set_permissions(&wrapper, fs::Permissions::from_mode(0o755)).unwrap(); + + let model = crate::load(root, &root.join("cache"), None); + let cache = root.join("cache"); + let cancel = CancellationToken::new(); + + let main_file = root.join("app/src/main/java/demo/App.java"); + let main_plan = gradle_compile_file_plan(root, &model, &main_file, &cache, &cancel).unwrap(); + assert_eq!(main_plan.system, BuildSystem::Gradle); + assert_eq!(main_plan.title, "Compile App.java"); + let step = &main_plan.steps[0]; + let args = fs::read_to_string(root.join("gradle_args.txt")).unwrap(); + assert!(args.lines().any(|a| a == "-Popenidea.target=:app"), "{args}"); + assert!(args.lines().any(|a| a == "-Popenidea.scope=main"), "{args}"); + let cp = &step.args[step.args.iter().position(|a| a == "-cp").unwrap() + 1]; + let paths: Vec<_> = std::env::split_paths(cp).collect(); + assert!(paths.contains(&root.join("app/build/classes/java/main")), "{cp}"); + assert!(paths.contains(&root.join("lib/build/classes/java/main")), "{cp}"); + assert!(paths.contains(&root.join("deps/guava.jar")), "{cp}"); + assert!(step.args.windows(2).any(|w| w == ["--release", "17"]), "{:?}", step.args); + assert!(step.args.iter().any(|a| a == "-implicit:none"), "{:?}", step.args); + + let test_file = root.join("app/src/test/java/demo/AppTest.java"); + let test_plan = gradle_compile_file_plan(root, &model, &test_file, &cache, &cancel).unwrap(); + assert_eq!(test_plan.title, "Compile AppTest.java"); + let test_step = &test_plan.steps[0]; + let args = fs::read_to_string(root.join("gradle_args.txt")).unwrap(); + assert!(args.lines().any(|a| a == "-Popenidea.scope=test"), "{args}"); + assert!( + test_step.args.windows(2).any(|w| w == ["-d", &root.join("app/build/classes/java/test").to_string_lossy()]) + ); + } } diff --git a/crates/ide-build/src/compile/structure.rs b/crates/ide-build/src/compile/structure.rs index 1c90cd089..20df075d4 100644 --- a/crates/ide-build/src/compile/structure.rs +++ b/crates/ide-build/src/compile/structure.rs @@ -162,16 +162,6 @@ fn classpath(entries: &[String]) -> String { entries.join(if cfg!(windows) { ";" } else { ":" }) } -/// `--release N` from JDK 9 on; older compilers only know `-source` / `-target`. -fn release_args(level: Option, jdk: Option<&StructureJdk>) -> Vec { - let Some(level) = level else { return Vec::new() }; - if jdk.is_none_or(|j| j.major >= 9) { - vec!["--release".into(), level.to_string()] - } else { - vec!["-source".into(), format!("1.{level}"), "-target".into(), format!("1.{level}")] - } -} - /// `"17"`, `"1.8"`, `"JDK_17"` → the release number. pub fn language_release(level: &str) -> Option { let digits = level.trim().trim_start_matches("JDK_").trim_start_matches("jdk").replace('_', "."); @@ -179,6 +169,25 @@ pub fn language_release(level: &str) -> Option { digits.split(['.', ' ']).next()?.parse().ok().filter(|n| *n > 0) } +fn structure_compiler( + root: &Path, + ps: &ProjectStructureSettings, + jdk: Option<&StructureJdk>, + language_level: &str, +) -> (Option, BTreeMap, String) { + let module = root_module(root, ps); + let level = module + .map(|m| m.language_level.as_str()) + .filter(|l| !l.trim().is_empty()) + .or(Some(language_level)) + .and_then(language_release); + let env: BTreeMap = jdk + .map(|j| BTreeMap::from([("JAVA_HOME".to_owned(), j.home.to_string_lossy().into_owned())])) + .unwrap_or_default(); + let javac = find_javac(&env); + (level, env, javac) +} + /// The Build / Rebuild plan of a project without a build tool, or `None` when it has no /// Java sources under its source roots. `language_level`: the project's, unless the module /// overrides it. Writes the javac argument files below `cache`. @@ -203,16 +212,7 @@ pub fn structure_plan( return Ok(None); } let (main_out, test_out) = structure_outputs(root, ps); - let module = root_module(root, ps); - let level = module - .map(|m| m.language_level.as_str()) - .filter(|l| !l.trim().is_empty()) - .or(Some(language_level)) - .and_then(language_release); - let env: BTreeMap = jdk - .map(|j| BTreeMap::from([("JAVA_HOME".to_owned(), j.home.to_string_lossy().into_owned())])) - .unwrap_or_default(); - let javac = find_javac(&env); + let (level, env, javac) = structure_compiler(root, ps, jdk, language_level); let args_dir = cache.join("javac"); fs::create_dir_all(&args_dir) .map_err(|e| IdeError::internal(format!("cannot create {} ({e})", args_dir.display())))?; @@ -241,7 +241,7 @@ pub fn structure_plan( if !cp.is_empty() { step.args.extend(["-cp".into(), classpath(cp)]); } - step.args.extend(release_args(level, jdk)); + step.args.extend(single::release_args(level, jdk.map(|j| j.major))); step.args.push(format!("@{}", args_file.to_string_lossy())); step.env = env.clone(); step.mkdirs = vec![out.to_path_buf()]; @@ -281,6 +281,47 @@ pub fn structure_plan( Ok(Some(BuildPlan { system: BuildSystem::Javac, title: module_name(root), steps })) } +/// Single-file `javac` plan for a Java project without a build tool (Project Structure). +pub fn structure_compile_file_plan( + root: &Path, + ps: &ProjectStructureSettings, + roots: &StructureRoots, + jdk: Option<&StructureJdk>, + language_level: &str, + file: &Path, +) -> IdeResult { + let name = single::is_java_file(file)?; + let rel = rel_str(root, file); + let test = if roots.tests.is_empty() { + single::is_test_source(&rel) + } else { + let file_norm = normalize(file); + roots.tests.iter().any(|t| file_norm.starts_with(normalize(t))) + }; + let (main_out, test_out) = structure_outputs(root, ps); + let out_dir = if test { &test_out } else { &main_out }; + let mut cp: Vec = Vec::new(); + if test && test_out.is_dir() { + cp.push(test_out.to_string_lossy().into_owned()); + } + if main_out.is_dir() { + cp.push(main_out.to_string_lossy().into_owned()); + } + cp.extend(library_entries(root, ps, test)); + let cp = single::join_classpath(cp); + + let mut src_roots: Vec = Vec::new(); + if test { + src_roots.extend(roots.tests.iter().filter(|p| p.is_dir()).cloned()); + } + src_roots.extend(roots.sources.iter().filter(|p| p.is_dir()).cloned()); + + let (level, env, javac) = structure_compiler(root, ps, jdk, language_level); + let release = single::release_args(level, jdk.map(|j| j.major)); + let step = single::build_javac_step(&javac, root, out_dir, &cp, &src_roots, release, file, env)?; + Ok(BuildPlan { system: BuildSystem::Javac, title: format!("Compile {name}"), steps: vec![step] }) +} + /// Where an artifact goes: its output folder, else `out/artifacts/`. pub fn artifact_output(root: &Path, artifact: &ArtifactConfig) -> PathBuf { resolve_dir(root, &artifact.output_directory) @@ -1008,4 +1049,99 @@ mod tests { layout(&["a.jar"]).run(&CancellationToken::new()).unwrap(); assert!(project.join("c.jar").is_file()); } + + #[test] + fn plans_single_file_javac_for_main_test_and_jdk8() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path().join("shop"); + write(&root.join("src/com/a/Main.java"), "package com.a; class Main {}"); + write(&root.join("test/com/a/MainTest.java"), "package com.a; class MainTest {}"); + write(&root.join("out/production/shop/com/a/Helper.class"), ""); + let ps = ProjectStructureSettings { + libraries: vec![ + ProjectLibrary { name: "core".into(), classes: vec!["lib/core.jar".into()], ..Default::default() }, + ProjectLibrary { + name: "junit".into(), + classes: vec!["lib/junit.jar".into()], + scope: DependencyScope::Test, + ..Default::default() + }, + ], + ..Default::default() + }; + let roots = + StructureRoots { sources: vec![root.join("src")], tests: vec![root.join("test")], ..Default::default() }; + + let jdk21 = StructureJdk { home: PathBuf::from("/jdk21"), major: 21 }; + let main_plan = + structure_compile_file_plan(&root, &ps, &roots, Some(&jdk21), "17", &root.join("src/com/a/Main.java")) + .unwrap(); + assert_eq!(main_plan.system, BuildSystem::Javac); + assert_eq!(main_plan.title, "Compile Main.java"); + let main_step = &main_plan.steps[0]; + let cp = &main_step.args[main_step.args.iter().position(|a| a == "-cp").unwrap() + 1]; + assert!(cp.contains("core.jar") && !cp.contains("junit.jar"), "{cp}"); + assert!(main_step.args.windows(2).any(|w| w == ["--release", "17"])); + assert!(main_step.args.iter().any(|a| a == "-implicit:none")); + + let jdk8 = StructureJdk { home: PathBuf::from("/jdk8"), major: 8 }; + let test_plan = + structure_compile_file_plan(&root, &ps, &roots, Some(&jdk8), "8", &root.join("test/com/a/MainTest.java")) + .unwrap(); + let test_step = &test_plan.steps[0]; + let test_cp = &test_step.args[test_step.args.iter().position(|a| a == "-cp").unwrap() + 1]; + assert!(test_cp.contains("out/production/shop") || test_cp.contains("out\\production\\shop"), "{test_cp}"); + assert!(test_cp.contains("junit.jar"), "{test_cp}"); + assert!(test_step.args.windows(4).any(|w| w == ["-source", "1.8", "-target", "1.8"])); + assert!(test_step.args.windows(2).any(|w| w[0] == "-d" && Path::new(&w[1]).ends_with("out/test/shop"))); + } + + #[test] + fn compiles_only_the_target_java_file_and_reports_errors() { + let exe = if cfg!(windows) { "javac.exe" } else { "javac" }; + if !std::process::Command::new(exe).arg("-version").output().is_ok_and(|o| o.status.success()) { + return; + } + let tmp = tempfile::tempdir().unwrap(); + let root = dunce::canonicalize(tmp.path()).unwrap().join("demo"); + let good = root.join("src/p/Good.java"); + let broken_sibling = root.join("src/p/BrokenSibling.java"); + let bad_target = root.join("src/p/BadTarget.java"); + write(&good, "package p;\npublic class Good { public static int ok() { return 1; } }\n"); + write(&broken_sibling, "package p;\npublic class BrokenSibling { MissingType field; }\n"); + write(&bad_target, "package p;\npublic class BadTarget {\n UnknownSymbol field;\n}\n"); + + let ps = ProjectStructureSettings::default(); + let roots = StructureRoots { sources: vec![root.join("src")], ..Default::default() }; + let cancel = CancellationToken::new(); + + // 1. Valid file compiles cleanly without touching or failing on BrokenSibling.java. + let plan = structure_compile_file_plan(&root, &ps, &roots, None, "", &good).unwrap(); + let events = std::sync::Mutex::new(Vec::new()); + let result = run(&root, &plan, &cancel, &|e| events.lock().unwrap().push(e)).unwrap(); + assert!(result.success, "expected single-file compile to succeed: {:?}", result.messages); + assert_eq!(result.errors, 0); + assert!(root.join("out/production/demo/p/Good.class").is_file()); + assert!(!root.join("out/production/demo/p/BrokenSibling.class").exists()); + + // 2. Broken target fails, streams raw compiler output, and produces structured diagnostics. + let plan = structure_compile_file_plan(&root, &ps, &roots, None, "", &bad_target).unwrap(); + let bad_events = std::sync::Mutex::new(Vec::new()); + let bad_result = run(&root, &plan, &cancel, &|e| bad_events.lock().unwrap().push(e)).unwrap(); + assert!(!bad_result.success); + assert!(bad_result.errors >= 1, "{bad_result:?}"); + assert!( + bad_events.lock().unwrap().iter().any(|e| matches!(e, BuildEvent::Output { .. })), + "expected streamed output" + ); + assert!( + bad_result.messages.iter().any(|m| { + m.severity == Severity::Error + && m.path.as_ref().is_some_and(|p| >::as_ref(p) == bad_target) + && m.range.is_some_and(|r| r.start.line == 2) + }), + "messages={:?}", + bad_result.messages + ); + } } diff --git a/crates/ide-build/src/gradle-compile-cp.init.gradle b/crates/ide-build/src/gradle-compile-cp.init.gradle new file mode 100644 index 000000000..c26b37a5d --- /dev/null +++ b/crates/ide-build/src/gradle-compile-cp.init.gradle @@ -0,0 +1,58 @@ +// OpenIDEA single-file javac classpath probe for Gradle projects. +// Prints the target source set's output directory, compile classpath, source dirs and release version. +import groovy.json.JsonOutput + +def identity = { Project p -> try { p.identityPath.toString() } catch (ignored) { p.path } } + +gradle.projectsEvaluated { g -> + def wantedTarget = g.rootProject.findProperty('openidea.target')?.toString() ?: ':' + def scope = g.rootProject.findProperty('openidea.scope')?.toString() ?: 'main' + def project = g.rootProject.allprojects.find { identity(it) == wantedTarget } + if (project == null && g.parent == null) { + project = g.rootProject.allprojects.find { it.path == wantedTarget } + } + if (project == null) return + + def sets = project.extensions.findByName('sourceSets') ?: project.findProperty('sourceSets') + def ss = sets?.findByName(scope) + if (ss == null) return + + def outDir = null + try { outDir = ss.java.destinationDirectory.get().asFile.canonicalPath } catch (ignored) {} + if (outDir == null) { + try { outDir = ss.output.classesDirs.files.iterator().next().canonicalPath } catch (ignored) {} + } + + def cp = [] + if (scope == 'test') { + def mainSet = sets.findByName('main') + try { mainSet?.output?.classesDirs?.files?.each { cp << it.canonicalPath } } catch (ignored) {} + } + try { ss.compileClasspath.files.each { cp << it.canonicalPath } } catch (ignored) {} + cp = cp.unique() + + def srcDirs = [] + try { ss.java.srcDirs.each { srcDirs << it.canonicalPath } } catch (ignored) {} + if (scope == 'test') { + def mainSet = sets.findByName('main') + try { mainSet?.java?.srcDirs?.each { srcDirs << it.canonicalPath } } catch (ignored) {} + } + srcDirs = srcDirs.unique() + + def release = null + try { + def compileTask = project.tasks.findByName(ss.compileJavaTaskName) + release = compileTask?.options?.release?.getOrNull() + } catch (ignored) {} + if (release == null) { + try { + def java = project.extensions.findByName('java') + def lv = null + try { lv = java?.toolchain?.languageVersion?.getOrNull() } catch (ignored) {} + def target = java != null ? java.targetCompatibility : project.findProperty('targetCompatibility') + release = lv != null ? lv.asInt() : (target?.majorVersion as Integer) + } catch (ignored) {} + } + + println '@openidea-compile-cp\t' + JsonOutput.toJson([outDir: outDir, classpath: cp, srcDirs: srcDirs, release: release]) +} diff --git a/crates/ide-host/src/ops/build.rs b/crates/ide-host/src/ops/build.rs index 62648a59b..32378c4c2 100644 --- a/crates/ide-host/src/ops/build.rs +++ b/crates/ide-host/src/ops/build.rs @@ -1109,11 +1109,39 @@ pub async fn build_run( Ok(outcome) } -/// Build › Compile File: compiles one Java source of a linked Maven module with -/// `javac`, streaming the console and messages on `on_event`; cancellable with -/// `cancel_request(request)`. Diagnostics of `clear` (the files of the previous -/// build) are cleared first; the new messages are published as `build` -/// diagnostics. +fn plan_compile_file( + root: &Path, + cache: &Path, + settings: &Settings, + detected: &[ide_workspace::roots::SourceFolder], + file: &Path, + cancel: &CancellationToken, + on_progress: &dyn Fn(String), +) -> IdeResult { + if file.extension().is_none_or(|ext| !ext.eq_ignore_ascii_case("java")) { + return Err(IdeError::invalid("only Java sources can be compiled as a single file")); + } + if !file.is_file() { + return Err(IdeError::not_found("no Java source found for single-file compilation")); + } + let name = file.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + let model = with_profiles(load(root, cache, settings), cache); + if compile::single_file_target(root, &model, file).is_ok() { + on_progress(format!("Resolving classpath for {name}…")); + return compile::compile_file_plan_cancellable(root, &model, file, cancel); + } + if compile::has_gradle_file_target(root, &model, file) { + on_progress(format!("Resolving classpath for {name}…")); + return compile::gradle_compile_file_plan(root, &model, file, cache, cancel); + } + let (ps, roots, jdk) = structure_inputs(root, settings, detected); + compile::structure_compile_file_plan(root, &ps, &roots, jdk.as_ref(), &settings.languages.java.language_level, file) +} + +/// Build › Recompile: compiles one Java source file with `javac`, streaming the +/// console and messages on `on_event`; cancellable with `cancel_request(request)`. +/// Diagnostics of `clear` (the files of the previous build) are cleared first; +/// the new messages are published as `build` diagnostics. #[command(trust = trusted)] pub async fn build_compile_file( host: &Host, @@ -1125,8 +1153,19 @@ pub async fn build_compile_file( ) -> IdeResult { host.require_trust(window)?; let project = host.project(window)?; - let (root, cache, sink) = (project.root.clone(), project.build_cache_dir(), project.sink.clone()); - let settings = project.settings.effective(); + let file = ide_core::project_roots::resolve(&project.root, &file); + let scope = { + let (project, file) = (project.clone(), file.clone()); + blocking(move || workspace::scope_for(&project, &file)).await? + }; + let scope_root = scope.root.clone(); + let detected = if scope.root == project.root { + project.detected_roots.read().clone() + } else { + let root = scope.root.clone(); + blocking_value(move || ide_workspace::roots::detect(&root)).await? + }; + let sink = project.sink.clone(); let token = host.begin_project_request(window, request); let result = blocking(move || { for path in clear { @@ -1136,8 +1175,11 @@ pub async fn build_compile_file( items: Vec::new(), }); } - let plan = compile::compile_file_plan(&root, &with_profiles(load(&root, &cache, &settings), &cache), &file)?; - let result = compile::run(&root, &plan, &token, &|e| { + let plan = + plan_compile_file(&scope.root, &scope.cache, &scope.settings, &detected, &file, &token, &|message| { + let _ = on_event.send(BuildEvent::Progress { message, fraction: None }); + })?; + let result = compile::run(&scope.root, &plan, &token, &|e| { let _ = on_event.send(e); })?; for (path, items) in compile::diagnostics(&result.messages) { @@ -1149,7 +1191,7 @@ pub async fn build_compile_file( host.end_request(request); let outcome = result?; if outcome.system == ide_build::compile::BuildSystem::Maven { - project.lsp.sync_maven_generated_sources(&project.root).await; + project.lsp.sync_maven_generated_sources(&scope_root).await; } Ok(outcome) } @@ -1374,6 +1416,60 @@ mod build_tool_settings_tests { assert_eq!(model.env["JAVA_HOME"], root.join("jdk21").to_string_lossy()); assert_eq!(model.env["GRADLE_USER_HOME"], root.join("user-home").to_string_lossy()); } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn single_file_plan_falls_back_to_project_structure_and_resolves_workspace_scope() { + let tmp = tempfile::tempdir().unwrap(); + let base = dunce::canonicalize(tmp.path()).unwrap(); + let plain = base.join("plain"); + let java_file = plain.join("src/Main.java"); + std::fs::create_dir_all(java_file.parent().unwrap()).unwrap(); + std::fs::write(&java_file, "class Main {}").unwrap(); + let detected = ide_workspace::roots::detect(&plain); + let plan = plan_compile_file( + &plain, + &base.join("cache"), + &Settings::default(), + &detected, + &java_file, + &ide_core::CancellationToken::new(), + &|_| {}, + ) + .unwrap(); + assert_eq!(plan.system, compile::BuildSystem::Javac); + assert_eq!(plan.title, "Compile Main.java"); + + let txt = plain.join("notes.txt"); + std::fs::write(&txt, "hi").unwrap(); + assert!( + plan_compile_file( + &plain, + &base.join("cache"), + &Settings::default(), + &detected, + &txt, + &ide_core::CancellationToken::new(), + &|_| {}, + ) + .is_err() + ); + + let host = + Host::new(crate::HostConfig { local_data_dir: base.join("local"), ..crate::HostConfig::for_test(&base) }); + let member_a = base.join("member-a"); + let member_b = base.join("member-b"); + for m in [&member_a, &member_b] { + std::fs::create_dir_all(m.join("src")).unwrap(); + std::fs::write(m.join("src/App.java"), "class App {}").unwrap(); + } + let ws = base.join("ws"); + std::fs::create_dir_all(&ws).unwrap(); + ide_workspace::workspace::Workspace::save(&ws, "WS", vec![member_a.clone(), member_b.clone()], true).unwrap(); + let project = host.open_project("win", &ws).unwrap(); + let scope = workspace::scope_for(&project, &member_b.join("src/App.java")).unwrap(); + assert_eq!(scope.root, member_b); + host.close_project("win"); + } } #[cfg(test)] diff --git a/docs/en/guide/build-tools.mdx b/docs/en/guide/build-tools.mdx index 6a28e773c..4ad2cb060 100644 --- a/docs/en/guide/build-tools.mdx +++ b/docs/en/guide/build-tools.mdx @@ -9,12 +9,13 @@ OpenIDEA does not have its own build system. It reads your build files, runs the The **Build** menu works with every supported build system. OpenIDEA picks the build system of the project, or of the module that holds the current file. -| Action | macOS | Windows / Linux | -| --------------------------------------------------- | ------ | --------------- | -| **Build Project**: compile sources and tests | `⌘F9` | `Ctrl+F9` | -| **Build Module**: compile the current file's module | `⌘⇧F9` | `Ctrl+Shift+F9` | -| **Rebuild Project**: clean, then build | — | — | -| **Build Artifacts**: package the outputs | — | — | +| Action | macOS | Windows / Linux | +| ------------------------------------------------------------ | ------ | --------------- | +| **Build Project**: compile sources and tests | `⌘F9` | `Ctrl+F9` | +| **Build Module**: compile the current file's module | — | — | +| **Recompile '\.java'**: compile the current Java file | `⌘⇧F9` | `Ctrl+Shift+F9` | +| **Rebuild Project**: clean, then build | — | — | +| **Build Artifacts**: package the outputs | — | — | What each action runs: diff --git a/docs/zh/guide/build-tools.mdx b/docs/zh/guide/build-tools.mdx index 2f912dfb1..c0169ba65 100644 --- a/docs/zh/guide/build-tools.mdx +++ b/docs/zh/guide/build-tools.mdx @@ -9,12 +9,13 @@ OpenIDEA 没有自己的构建系统:它读取项目的构建文件,调用 **构建** 菜单适用于所有支持的构建系统。OpenIDEA 会根据项目(或当前文件所在模块)自动选择构建系统。 -| 操作 | macOS | Windows / Linux | -| ---------------------------------- | ------ | --------------- | -| **构建项目**:编译源码和测试 | `⌘F9` | `Ctrl+F9` | -| **构建模块**:编译当前文件所在模块 | `⌘⇧F9` | `Ctrl+Shift+F9` | -| **重新构建项目**:先清理再构建 | — | — | -| **构建工件**:打包产物 | — | — | +| 操作 | macOS | Windows / Linux | +| -------------------------------------------------- | ------ | --------------- | +| **构建项目**:编译源码和测试 | `⌘F9` | `Ctrl+F9` | +| **构建模块**:编译当前文件所在模块 | — | — | +| **重新编译 '\.java'**:仅编译当前 Java 文件 | `⌘⇧F9` | `Ctrl+Shift+F9` | +| **重新构建项目**:先清理再构建 | — | — | +| **构建工件**:打包产物 | — | — | 各操作实际执行的命令: diff --git a/src-tauri/src/menu.rs b/src-tauri/src/menu.rs index 993219070..1e7bf2845 100644 --- a/src-tauri/src/menu.rs +++ b/src-tauri/src/menu.rs @@ -617,6 +617,7 @@ pub fn spec(os: Os) -> Vec { vec![ act("build.buildProject", "Build Project"), act("build.buildModule", "Build Module"), + act("build.compileFile", "Recompile"), act("build.rebuildProject", "Rebuild Project"), SEP, act("build.buildArtifacts", "Build Artifacts"), @@ -2532,9 +2533,40 @@ mod tests { "toolwindow.hideActive", "editor.closeOtherTabs", "toolbar.customize", + "build.compileFile", ] { assert!(ids.contains(&required), "{required} missing on {os:?}"); } } } + + #[test] + fn build_menu_lists_recompile_and_patches_its_label() { + for os in ALL_OS { + let entries = spec(os); + let Entry::Submenu { children, .. } = + entries.iter().find(|e| matches!(e, Entry::Submenu { id: "build", .. })).unwrap() + else { + panic!("Build menu missing") + }; + assert_eq!( + action_ids(children), + [ + "build.buildProject", + "build.buildModule", + "build.compileFile", + "build.rebuildProject", + "build.buildArtifacts", + ], + "{os:?}" + ); + assert!(!fires_natively(&entries, "build.compileFile")); + } + let entries = spec(Os::Mac); + let mut base = MenuConfig::default(); + base.labels.insert("menu.build.compileFile".into(), "Recompile".into()); + let mut active = base.clone(); + active.labels.insert("menu.build.compileFile".into(), "Recompile 'Main.java'".into()); + assert_eq!(changed_menus(&render_bar(&entries, &base, &[]), &render_bar(&entries, &active, &[])), ["build"]); + } } diff --git a/src/bindings.ts b/src/bindings.ts index b9c329ede..091b3caa0 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -234,11 +234,10 @@ export const commands = { /** Applies a (previewed) workspace edit, e.g. after rename confirmation. */ applyWorkspaceEdit: (edit: WorkspaceEdit) => typedError(__TAURI_INVOKE("apply_workspace_edit", { edit })), /** - * Build › Compile File: compiles one Java source of a linked Maven module with - * `javac`, streaming the console and messages on `on_event`; cancellable with - * `cancel_request(request)`. Diagnostics of `clear` (the files of the previous - * build) are cleared first; the new messages are published as `build` - * diagnostics. + * Build › Recompile: compiles one Java source file with `javac`, streaming the + * console and messages on `on_event`; cancellable with `cancel_request(request)`. + * Diagnostics of `clear` (the files of the previous build) are cleared first; + * the new messages are published as `build` diagnostics. */ buildCompileFile: (file: string, request: RequestId, clear: string[], onEvent: Channel) => typedError(__TAURI_INVOKE("build_compile_file", { file, request, clear, onEvent })), /** Maven and Gradle projects of the window's project, from the build files plus the last sync. */ diff --git a/src/features/app/__tests__/menuBridge.test.ts b/src/features/app/__tests__/menuBridge.test.ts index 489e98abf..dfe20dab1 100644 --- a/src/features/app/__tests__/menuBridge.test.ts +++ b/src/features/app/__tests__/menuBridge.test.ts @@ -182,6 +182,48 @@ describe("menu state from the frontend", () => { setContext("testMenuEditor", false); offs.forEach((d) => d()); }); + + it("re-pushes menu config when switching Java files, and skips non-Java switches", async () => { + vi.useFakeTimers(); + vi.spyOn(ipc, "isTauri").mockReturnValue(true); + vi.spyOn(document, "hasFocus").mockReturnValue(true); + vi.spyOn(ipc.commands, "appBuildInfo").mockRejectedValue(new Error("No build info in tests")); + const configure = vi.spyOn(ipc.commands, "menuConfigure").mockResolvedValue(); + vi.spyOn(ipc.commands, "menuModel").mockResolvedValue([]); + vi.spyOn(ipc.commands, "menuSetDisabled").mockResolvedValue(); + const dispose = installMenuBridge(); + try { + await vi.advanceTimersByTimeAsync(120); + configure.mockClear(); + + setContext("editorPath", "/p/src/A.java"); + await vi.advanceTimersByTimeAsync(60); + expect(configure).toHaveBeenCalledTimes(1); + expect(configure.mock.calls.at(-1)![0].labels["menu.build.compileFile"]).toBe("Recompile 'A.java'"); + configure.mockClear(); + + setContext("editorPath", "/p/src/B.java"); + await vi.advanceTimersByTimeAsync(60); + expect(configure).toHaveBeenCalledTimes(1); + expect(configure.mock.calls.at(-1)![0].labels["menu.build.compileFile"]).toBe("Recompile 'B.java'"); + configure.mockClear(); + + setContext("editorPath", "/p/pom.xml"); + await vi.advanceTimersByTimeAsync(60); + expect(configure).toHaveBeenCalledTimes(1); + expect(configure.mock.calls.at(-1)![0].labels["menu.build.compileFile"]).toBe("Recompile"); + configure.mockClear(); + + setContext("editorPath", "/p/README.md"); + await vi.advanceTimersByTimeAsync(60); + expect(configure).not.toHaveBeenCalled(); + } finally { + dispose(); + clearContext("editorPath"); + vi.useRealTimers(); + vi.restoreAllMocks(); + } + }); }); afterEach(() => { @@ -223,6 +265,7 @@ describe("menu config", () => { const mac = buildMenuConfig("macos"); expect(mac.accelerators["file.save"]).toBe("Meta+S"); expect(mac.accelerators["navigate.gotoFile"]).toBe("Shift+Meta+O"); + expect(mac.accelerators["build.compileFile"]).toBe("Shift+Meta+F9"); expect(mac.accelerators["navigate.searchEverywhere"]).toBeUndefined(); }); @@ -289,6 +332,28 @@ describe("window-scoped menu labels", () => { expect(buildMenuConfig("macos").labels["menu.editor.toggleZen"]).toBe("Exit Distraction Free Mode"); resetDistractionFree(); }); + + it("formats Recompile with the active local Java filename across locales", async () => { + try { + expect(buildMenuConfig("macos").labels["menu.build.compileFile"]).toBe("Recompile"); + setContext("editorPath", "/p/src/Main.java"); + expect(buildMenuConfig("macos").labels["menu.build.compileFile"]).toBe("Recompile 'Main.java'"); + setContext("editorPath", "/p/pom.xml"); + expect(buildMenuConfig("macos").labels["menu.build.compileFile"]).toBe("Recompile"); + setContext("editorPath", "jdt://contents/rt.jar/java/lang/String.java"); + expect(buildMenuConfig("macos").labels["menu.build.compileFile"]).toBe("Recompile"); + setContext("editorPath", "untitled:Untitled-1.java"); + expect(buildMenuConfig("macos").labels["menu.build.compileFile"]).toBe("Recompile"); + + await setLocale("zh"); + setContext("editorPath", null); + expect(buildMenuConfig("macos").labels["menu.build.compileFile"]).toBe("重新编译"); + setContext("editorPath", "/p/src/Main.java"); + expect(buildMenuConfig("macos").labels["menu.build.compileFile"]).toBe("重新编译 'Main.java'"); + } finally { + clearContext("editorPath"); + } + }); }); describe("View › Appearance check marks", () => { diff --git a/src/features/app/menuBridge.ts b/src/features/app/menuBridge.ts index 41d70993e..10315b30c 100644 --- a/src/features/app/menuBridge.ts +++ b/src/features/app/menuBridge.ts @@ -21,7 +21,8 @@ import { } from "@/platform/keymap"; import { useProject } from "@/platform/project"; import { useContributions, useMenuSlotItems, useStandaloneEditor } from "@/workbench/contributions"; -import { isDistractionFree, useDistractionFree } from "@/workbench/distractionFree"; +import { useDistractionFree } from "@/workbench/distractionFree"; +import { javaFileNameOf, menuLabelParams } from "@/workbench/menuLabels"; import { orderStatusItems } from "@/workbench/StatusBar"; import { statusWidgetRows } from "@/workbench/statusBarWidgets"; import { useToolWindowLayouts } from "@/workbench/toolwindows/layouts"; @@ -101,11 +102,7 @@ export function menuAccelerator(binding: string): string | undefined { export function buildMenuConfig(os: HostOs): MenuConfig { const labels: Record = {}; // Per-window state some labels follow (View › Appearance › Enter / Exit Distraction Free Mode). - const params = { - os, - distractionFree: isDistractionFree() ? "on" : "off", - toolWindows: toolWindowsRestorable() ? "hidden" : "shown", - }; + const params = menuLabelParams(os); for (const key of keysWithPrefix("menu.")) labels[key] = t(key, params); labels["menu.layout.applyNamed"] = tx("Apply"); labels["menu.layout.restoreNamed"] = tx("Restore"); @@ -288,7 +285,10 @@ export function installMenuBridge(): () => void { }), useToolWindowLayouts.subscribe(push), useMenuSlotItems.subscribe(push), - useContextKeys.subscribe(() => pushEnablement()), + useContextKeys.subscribe((s, prev) => { + pushEnablement(); + if (javaFileNameOf(s.editorPath) !== javaFileNameOf(prev.editorPath)) push(); + }), useActions.subscribe(() => pushEnablement()), // Project membership and names also change the Open Recent list. useProject.subscribe((s, prev) => { diff --git a/src/features/build/build.test.tsx b/src/features/build/build.test.tsx index d7f278b03..65fffa077 100644 --- a/src/features/build/build.test.tsx +++ b/src/features/build/build.test.tsx @@ -1,8 +1,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { act, fireEvent, render, screen } from "@testing-library/react"; import { executeAction, getAction, isActionEnabled } from "@/platform/actions"; -import { getContext, setContext } from "@/platform/context"; -import { bindingsFor } from "@/platform/keymap"; +import { clearContext, getContext, setContext } from "@/platform/context"; +import { bindingsFor, installKeyboardDispatcher } from "@/platform/keymap"; import { IpcError, type BuildEvent, type BuildMessage, type BuildResult } from "@/platform/ipc"; import { useProject } from "@/platform/project"; import { @@ -179,6 +179,7 @@ describe("build feature", () => { useProject.setState({ project: null, settings: null }); setContext("projectOpen", false); setContext("run.cmakeBuild", null); + clearContext("editorPath"); }); it("shows the CMake hammer and builds the selected target through the shared action", async () => { @@ -205,8 +206,11 @@ describe("build feature", () => { expect(getAction(id), id).toBeDefined(); expect(isActionEnabled(getAction(id)!)).toBe(true); } + expect(getAction("build.compileFile")).toBeDefined(); + expect(isActionEnabled(getAction("build.compileFile")!)).toBe(false); expect(bindingsFor("build.buildProject")).toContain("Meta+F9"); - expect(bindingsFor("build.buildModule")).toContain("Meta+Shift+F9"); + expect(bindingsFor("build.compileFile")).toContain("Meta+Shift+F9"); + expect(bindingsFor("build.buildModule")).toEqual([]); const tw = useContributions.getState().toolWindows.get("build"); expect(tw).toMatchObject({ anchor: "bottom", stripe: "onUse", icon: "toolwindow-build" }); expect(menuGroupItems("projectView", { paths: ["/p/core"] })).toContainEqual({ @@ -569,4 +573,93 @@ describe("build feature", () => { fake.resolve(result([], true)); }); }); + + it("gates Recompile to local Java files and offers context menu labels", () => { + const compileFile = getAction("build.compileFile")!; + let currentPath: string | null = "/p/core/src/A.java"; + provideEditorService({ + openFile, + saveAll: () => Promise.resolve(), + activePath: () => currentPath, + } as unknown as EditorService); + expect(isActionEnabled(compileFile)).toBe(true); + + for (const nonTarget of [ + "/p/core/pom.xml", + "jdt://contents/rt.jar/java/lang/String.class", + "untitled:Untitled-1.java", + null, + ]) { + currentPath = nonTarget; + expect(isActionEnabled(compileFile), String(nonTarget)).toBe(false); + } + expect(isActionEnabled(compileFile, getContext(), "/p/core/src/Explicit.java")).toBe(true); + + for (const menu of ["editor", "editorTab", "projectView"] as const) { + expect(menuGroupItems(menu, { paths: ["/p/core/src/A.java"] })).toContainEqual({ + kind: "action", + action: "build.compileFile", + arg: "/p/core/src/A.java", + label: "Recompile 'A.java'", + }); + expect( + menuGroupItems(menu, { paths: ["jdt://contents/rt.jar/java/lang/String.java"] }).some( + (i) => i.kind === "action" && i.action === "build.compileFile", + ), + ).toBe(false); + } + }); + + it("dispatches Shift+Cmd+F9 to Recompile for the active Java file only", async () => { + let currentPath: string | null = "/p/core/src/OnlyThis.java"; + provideEditorService({ + openFile, + saveAll: () => Promise.resolve(), + activePath: () => currentPath, + } as unknown as EditorService); + const uninstall = installKeyboardDispatcher(window); + try { + fireEvent.keyDown(window, { code: "F9", key: "F9", metaKey: true, shiftKey: true }); + await act(async () => {}); + expect(fake.calls).toEqual([{ kind: "compileFile", file: "/p/core/src/OnlyThis.java", clear: [] }]); + expect(isActionEnabled(getAction("build.compileFile")!)).toBe(false); + await act(async () => { + fake.resolve(result([], true)); + }); + + currentPath = "/p/core/pom.xml"; + fireEvent.keyDown(window, { code: "F9", key: "F9", metaKey: true, shiftKey: true }); + await act(async () => {}); + expect(fake.calls).toHaveLength(1); + } finally { + uninstall(); + } + }); + + it("streams single-file compile errors to BuildView and opens the first error", async () => { + const run = startCompileFile("/p/core/src/Broken.java"); + await act(async () => {}); + const messages = [err("/p/core/src/Broken.java", 7, "cannot find symbol")]; + await act(async () => { + fake.emit!({ kind: "started", system: "javac", title: "Compile Broken.java" }); + fake.emit!({ kind: "step", command: "javac -encoding UTF-8 Broken.java", cwd: "/p/core" }); + fake.emit!({ kind: "output", text: "/p/core/src/Broken.java:8: error: cannot find symbol\n", stderr: true }); + fake.emit!({ kind: "message", message: messages[0]! }); + await new Promise((r) => setTimeout(r, 30)); + }); + render(); + expect(screen.getByText("Compile Broken.java")).toBeInTheDocument(); + await act(async () => { + fake.resolve({ ...result(messages, false), system: "javac", title: "Compile Broken.java" }); + await run; + }); + expect(useBuildRun.getState().status).toBe("failed"); + expect(useBuildRun.getState().selected).toBe(firstError(messages)!.key); + expect(show).toHaveBeenCalledWith("build", false); + expect(openFile).toHaveBeenCalledWith( + "/p/core/src/Broken.java", + expect.objectContaining({ focus: true, selection: { line: 7, col: 4 } }), + ); + expect(screen.getByRole("document", { name: "Build message" })).toHaveTextContent("cannot find symbol"); + }); }); diff --git a/src/features/build/index.ts b/src/features/build/index.ts index 0aba5c25d..131c918dc 100644 --- a/src/features/build/index.ts +++ b/src/features/build/index.ts @@ -1,11 +1,14 @@ /** - * Build menu (Build Project ⌘F9, Build Module ⇧⌘F9, Rebuild Project, Build - * Artifacts) and the Build tool window. The backend picks the build system of - * the project or module: Maven, Gradle, Cargo, Go, TypeScript or CMake. + * Build menu (Build Project ⌘F9, Recompile '.java' ⇧⌘F9, Build Module, + * Rebuild Project, Build Artifacts) and the Build tool window. The backend picks + * the build system of the project or module: Maven, Gradle, Cargo, Go, + * TypeScript, CMake or javac. */ -import { getContext } from "@/platform/context"; +import { getContext, type ContextKeys } from "@/platform/context"; import { registerActions } from "@/platform/actions"; -import { useProject } from "@/platform/project"; +import { tx } from "@/platform/i18n"; +import { basename, useProject } from "@/platform/project"; +import { isVirtualUri } from "@/platform/virtualDocs"; import { maybeEditorService, registerMenuGroup, @@ -25,6 +28,17 @@ function moduleTarget(arg: unknown): string | null { return maybeEditorService()?.activePath() ?? null; } +/** The local Java source file to compile: the invoker's path or the active editor's file. */ +function javaFileTarget(arg: unknown, ctx: ContextKeys = getContext()): string | null { + const path = + typeof arg === "string" && arg + ? arg + : typeof arg === "object" && arg !== null && "target" in arg && typeof arg.target === "string" + ? arg.target + : (maybeEditorService()?.activePath() ?? (typeof ctx.editorPath === "string" ? ctx.editorPath : null)); + return path && !isVirtualUri(path) && /\.java$/i.test(path) ? path : null; +} + function useErrorBadge(): number | null { return useBuildRun((s) => s.status === "failed" ? s.messages.filter((m) => m.severity === "error").length || null : null, @@ -88,15 +102,16 @@ export function activate(): () => void { }, { id: "build.compileFile", - title: "Compile File", + title: "Recompile", description: "Compiles the current Java file with javac, without building its module", category: "Build", when: WHEN, - keywords: ["javac", "single file", "recompile"], - run: ({ arg }) => { + enabled: ({ ctx, arg }) => javaFileTarget(arg, ctx) !== null, + keywords: ["compile file", "javac", "single file"], + run: ({ ctx, arg }) => { const options = typeof arg === "object" && arg !== null ? arg : {}; const activate = !("activate" in options && options.activate === false); - const file = moduleTarget(arg); + const file = javaFileTarget(arg, ctx); if (file) void startCompileFile(file, activate); }, }, @@ -153,8 +168,8 @@ export function activate(): () => void { order: 40, items: (_menu, { paths, dirs }) => { const path = paths.length === 1 && !dirs?.[0] ? paths[0]! : null; - if (!path || !/\.java$/i.test(path) || !useProject.getState().project) return []; - return [{ kind: "action", action: "build.compileFile", arg: path }]; + if (!path || isVirtualUri(path) || !/\.java$/i.test(path) || !useProject.getState().project) return []; + return [{ kind: "action", action: "build.compileFile", arg: path, label: tx`Recompile '${basename(path)}'` }]; }, }), useProject.subscribe((s, prev) => { diff --git a/src/platform/keymaps/ideaParity.test.ts b/src/platform/keymaps/ideaParity.test.ts index a35d81673..32b2ac8d4 100644 --- a/src/platform/keymaps/ideaParity.test.ts +++ b/src/platform/keymaps/ideaParity.test.ts @@ -87,6 +87,8 @@ describe("IDEA keymap parity", () => { ["navigate.back", ["Meta+[", "Meta+Alt+Left", "Button4", "SwipeRight"], ["Ctrl+Alt+Left", "Button4"]], ["navigate.forward", ["Meta+]", "Meta+Alt+Right", "Button5", "SwipeLeft"], ["Ctrl+Alt+Right", "Button5"]], ["file.projectStructure", ["Meta+;"], ["Ctrl+Alt+Shift+S"]], + ["build.compileFile", ["Meta+Shift+F9"], ["Ctrl+Shift+F9"]], + ["build.buildModule", [], []], ])("%s", (id, mac, win) => { expect(intellijMacos[id]).toEqual(mac); expect(intellijWindows[id]).toEqual(win); diff --git a/src/platform/keymaps/intellij-macos.ts b/src/platform/keymaps/intellij-macos.ts index b603225b1..bcd7bfbef 100644 --- a/src/platform/keymaps/intellij-macos.ts +++ b/src/platform/keymaps/intellij-macos.ts @@ -258,7 +258,8 @@ export const intellijMacos: Record = { // Build "build.buildProject": ["Meta+F9"], - "build.buildModule": ["Meta+Shift+F9"], + "build.buildModule": [], + "build.compileFile": ["Meta+Shift+F9"], "build.rebuildProject": [], "build.buildArtifacts": [], diff --git a/src/platform/keymaps/intellij-windows.ts b/src/platform/keymaps/intellij-windows.ts index 47bb182d8..a49ba3f8e 100644 --- a/src/platform/keymaps/intellij-windows.ts +++ b/src/platform/keymaps/intellij-windows.ts @@ -252,7 +252,8 @@ export const intellijWindows: Record = { // Build "build.buildProject": ["Ctrl+F9"], - "build.buildModule": ["Ctrl+Shift+F9"], + "build.buildModule": [], + "build.compileFile": ["Ctrl+Shift+F9"], "build.rebuildProject": [], "build.buildArtifacts": [], diff --git a/src/platform/keymaps/vscode-macos.ts b/src/platform/keymaps/vscode-macos.ts index ce3789862..cd33b6133 100644 --- a/src/platform/keymaps/vscode-macos.ts +++ b/src/platform/keymaps/vscode-macos.ts @@ -274,6 +274,7 @@ export const vscodeMacos: Record = { // Build (Terminal › Run Build Task) "build.buildProject": ["Meta+Shift+B"], "build.buildModule": [], + "build.compileFile": [], "build.rebuildProject": [], "build.buildArtifacts": [], diff --git a/src/platform/locales/en.json b/src/platform/locales/en.json index fddad66d4..2a75a3495 100644 --- a/src/platform/locales/en.json +++ b/src/platform/locales/en.json @@ -413,6 +413,7 @@ "menu.build": "Build", "menu.build.buildProject": "Build Project", "menu.build.buildModule": "Build Module", + "menu.build.compileFile": "{compileFile, select, yes {Recompile '{compileFileName}'} other {Recompile}}", "menu.build.rebuildProject": "Rebuild Project", "menu.build.buildArtifacts": "Build Artifacts", "menu.toolwindow.build": "Build", diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index ed2a39cee..ebae40742 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -3902,5 +3902,7 @@ "No tests ran. The build may skip them (skipTests, maven.test.skip, a disabled test task) or lack their engine: JUnit 4 tests on the JUnit Platform need junit-vintage-engine.": "No tests ran. The build may skip them (skipTests, maven.test.skip, a disabled test task) or lack their engine: JUnit 4 tests on the JUnit Platform need junit-vintage-engine.", "Downloading the list of PyPI package names…": "Downloading the list of PyPI package names…", "Could not load the list of PyPI package names. Type a package's exact name to look it up.": "Could not load the list of PyPI package names. Type a package's exact name to look it up.", - "Only the first 50 PyPI matches are listed. Type more of the name to narrow them.": "Only the first 50 PyPI matches are listed. Type more of the name to narrow them." + "Only the first 50 PyPI matches are listed. Type more of the name to narrow them.": "Only the first 50 PyPI matches are listed. Type more of the name to narrow them.", + "Recompile": "Recompile", + "Recompile '{name}'": "Recompile '{name}'" } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 3305434c5..ec122fadd 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -10132,5 +10132,7 @@ "No tests ran. The build may skip them (skipTests, maven.test.skip, a disabled test task) or lack their engine: JUnit 4 tests on the JUnit Platform need junit-vintage-engine.": "没有运行任何测试。构建可能跳过了测试(skipTests、maven.test.skip、被禁用的测试任务),或缺少对应的测试引擎:在 JUnit Platform 上运行 JUnit 4 测试需要 junit-vintage-engine。", "Downloading the list of PyPI package names…": "正在下载 PyPI 软件包名称列表…", "Could not load the list of PyPI package names. Type a package's exact name to look it up.": "无法加载 PyPI 软件包名称列表。请输入软件包的准确名称进行查询。", - "Only the first 50 PyPI matches are listed. Type more of the name to narrow them.": "只列出前 50 个 PyPI 匹配项。请输入更完整的名称以缩小范围。" + "Only the first 50 PyPI matches are listed. Type more of the name to narrow them.": "只列出前 50 个 PyPI 匹配项。请输入更完整的名称以缩小范围。", + "Recompile": "重新编译", + "Recompile '{name}'": "重新编译 '{name}'" } diff --git a/src/platform/locales/zh.json b/src/platform/locales/zh.json index 58813d474..35b63a120 100644 --- a/src/platform/locales/zh.json +++ b/src/platform/locales/zh.json @@ -413,6 +413,7 @@ "menu.build": "构建", "menu.build.buildProject": "构建项目", "menu.build.buildModule": "构建模块", + "menu.build.compileFile": "{compileFile, select, yes {重新编译 '{compileFileName}'} other {重新编译}}", "menu.build.rebuildProject": "重新构建项目", "menu.build.buildArtifacts": "构建工件", "menu.toolwindow.build": "构建", diff --git a/src/workbench/MainMenu.interaction.test.tsx b/src/workbench/MainMenu.interaction.test.tsx index 3dac6ef06..f5112c3b1 100644 --- a/src/workbench/MainMenu.interaction.test.tsx +++ b/src/workbench/MainMenu.interaction.test.tsx @@ -1,6 +1,7 @@ import { act, fireEvent, render, screen, within } from "@testing-library/react"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { commands, type Settings } from "@/platform/ipc"; +import { clearContext, setContext } from "@/platform/context"; import { useProject } from "@/platform/project"; import { getAction, registerActions } from "@/platform/actions"; import { usePlatform } from "@/platform/platformInfo"; @@ -362,3 +363,41 @@ it.each(["windows", "linux"] as const)("renders toggle and widget checks in the usePlatform.setState(platform); } }); + +it("shows Recompile '.java' when a Java file is active and disabled Recompile otherwise", async () => { + const off = registerActions([ + { + id: "build.compileFile", + title: "Recompile", + when: "projectOpen", + enabled: ({ ctx }) => typeof ctx.editorPath === "string" && ctx.editorPath.endsWith(".java"), + run: () => {}, + }, + ]); + vi.mocked(commands.menuModel).mockResolvedValue([ + { + kind: "submenu", + id: "build", + label: "Build", + children: [{ kind: "action", id: "build.compileFile", label: "Recompile", hint: null, arg: null, checked: null }], + }, + ]); + setContext("projectOpen", true); + setContext("editorPath", "/p/src/Main.java"); + setStyle("merged"); + try { + render(); + await screen.findByRole("menubar"); + fireEvent.click(titles().getByRole("menuitem", { name: "Build" })); + const activeItem = await screen.findByRole("menuitem", { name: /Recompile 'Main\.java'/ }); + expect(activeItem).not.toHaveAttribute("aria-disabled", "true"); + + act(() => setContext("editorPath", "/p/pom.xml")); + const disabledItem = await screen.findByRole("menuitem", { name: /^Recompile/ }); + expect(disabledItem).toHaveAttribute("aria-disabled", "true"); + } finally { + off(); + clearContext("projectOpen"); + clearContext("editorPath"); + } +}); diff --git a/src/workbench/MainMenu.tsx b/src/workbench/MainMenu.tsx index 56a09c5bf..aab5a4a5a 100644 --- a/src/workbench/MainMenu.tsx +++ b/src/workbench/MainMenu.tsx @@ -1,6 +1,7 @@ /** Main menu for the frameless title bar, with hamburger and persistent title modes. */ import { useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent } from "react"; import clsx from "clsx"; +import { useContextKeys } from "@/platform/context"; import { useProject } from "@/platform/project"; import { lookup, t, useI18n } from "@/platform/i18n"; import { commands, type MenuNode } from "@/platform/ipc"; @@ -8,18 +9,13 @@ import { usePlatform } from "@/platform/platformInfo"; import { Icon, MenuList, Popup, type MenuItem } from "@/ui"; import { useChromeIconSize } from "@/ui/density"; import menuStyles from "@/ui/Menu.module.css"; -import { isDistractionFree } from "./distractionFree"; -import { toolWindowsRestorable } from "./toolwindows/store"; +import { javaFileNameOf, menuLabelParams } from "./menuLabels"; import styles from "./TitleBar.module.css"; function label(id: string, fallback: string): string { const key = `menu.${id}`; if (lookup(key) === undefined) return fallback; - return t(key, { - os: usePlatform.getState().os, - distractionFree: isDistractionFree() ? "on" : "off", - toolWindows: toolWindowsRestorable() ? "hidden" : "shown", - }); + return t(key, menuLabelParams(usePlatform.getState().os)); } type Submenu = Extract; @@ -102,6 +98,7 @@ export function MainMenu({ row = false, ...props }: MainMenuProps) { function MainMenuBar({ merged, row, onExpandedChange }: MainMenuProps & { merged: boolean; row: boolean }) { useI18n((s) => s.locale); + useContextKeys((s) => javaFileNameOf(s.editorPath)); const iconSize = useChromeIconSize(); const [menus, setMenus] = useState([]); const [expanded, setExpanded] = useState(false); diff --git a/src/workbench/menuLabels.ts b/src/workbench/menuLabels.ts new file mode 100644 index 000000000..7437d7d86 --- /dev/null +++ b/src/workbench/menuLabels.ts @@ -0,0 +1,23 @@ +/** Parameters shared between the native menu bridge and the custom title bar menu. */ +import { getContext } from "@/platform/context"; +import { basename } from "@/platform/project"; +import { isVirtualUri } from "@/platform/virtualDocs"; +import { maybeEditorService } from "./contributions"; +import { isDistractionFree } from "./distractionFree"; +import { toolWindowsRestorable } from "./toolwindows/store"; + +export function javaFileNameOf(path: unknown): string | null { + if (typeof path !== "string" || !path || isVirtualUri(path) || !/\.java$/i.test(path)) return null; + return basename(path) || null; +} + +export function menuLabelParams(os: string) { + const compileFileName = javaFileNameOf(getContext().editorPath ?? maybeEditorService()?.activePath()); + return { + os, + distractionFree: isDistractionFree() ? "on" : "off", + toolWindows: toolWindowsRestorable() ? "hidden" : "shown", + compileFile: compileFileName ? "yes" : "no", + compileFileName: compileFileName ?? "", + }; +}