From efa4fb3b436c035992f733b1a360bed11fa117ad Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Mon, 16 Nov 2026 09:54:52 +0800 Subject: [PATCH] feat(build): Build Artifacts and Tomcat deployment for projects without a build tool (#3629) Build Artifacts on a Java project without Maven or Gradle compiles the production classes with javac and lays out each Project Structure artifact: exploded WAR (web root, WEB-INF/classes, WEB-INF/lib), WAR packed from it, or JAR with a manifest (Main-Class, Class-Path) and its libraries next to it. Layouts are rebuilt from scratch and refuse an output folder holding their inputs. The WAR artifacts are offered to Tomcat run configurations; Build before launch packs the WAR in the IDE and records it for deployment. Part of #3571, closes #2875 --- crates/ide-build/src/compile/mod.rs | 5 +- crates/ide-build/src/compile/structure.rs | 385 +++++++++++++++++- crates/ide-host/src/ops/build.rs | 48 ++- crates/ide-host/src/ops/run/commands.rs | 83 +++- .../languages/ProjectStructurePage.tsx | 3 +- 5 files changed, 492 insertions(+), 32 deletions(-) diff --git a/crates/ide-build/src/compile/mod.rs b/crates/ide-build/src/compile/mod.rs index fe2ffcfca..4a582ad7f 100644 --- a/crates/ide-build/src/compile/mod.rs +++ b/crates/ide-build/src/compile/mod.rs @@ -16,7 +16,10 @@ pub use single::{ SingleFileTarget, compile_file_plan, find_javac, javac_step, module_classpath, single_file_classpath, single_file_target, }; -pub use structure::{StructureJdk, StructureRoots, language_release, structure_outputs, structure_plan}; +pub use structure::{ + StructureJdk, StructureRoots, artifact_file, artifact_output, language_release, structure_outputs, structure_plan, + structure_war_plan, structure_web_artifacts, +}; pub use up_to_date::{menu_up_to_date, record_menu_build}; use crate::process::{self, Stream}; diff --git a/crates/ide-build/src/compile/structure.rs b/crates/ide-build/src/compile/structure.rs index d4ea37936..62dadf40e 100644 --- a/crates/ide-build/src/compile/structure.rs +++ b/crates/ide-build/src/compile/structure.rs @@ -3,7 +3,9 @@ //! Web facet's `WEB-INF/lib`, and the resources are copied next to the classes; tests the //! same way into the test output, which also sees the production classes. use super::*; -use ide_core::settings::{DependencyScope, ModuleStructureSettings, ProjectStructureSettings}; +use ide_core::settings::{ + ArtifactConfig, ArtifactKind, DependencyScope, ModuleStructureSettings, ProjectStructureSettings, +}; use std::fs; /// The roots of the project as the IDE resolved them (absolute folders). @@ -100,12 +102,7 @@ fn library_entries(root: &Path, ps: &ProjectStructureSettings, test: bool) -> Ve } } for facet in ps.facets.iter().filter(|f| f.kind == "web") { - let web_root = if facet.web_root.trim().is_empty() { - facet.descriptor.trim().strip_suffix("/WEB-INF/web.xml").unwrap_or("").to_owned() - } else { - facet.web_root.trim().to_owned() - }; - let lib = root.join(&web_root).join("WEB-INF").join("lib"); + let lib = web_root(root, facet).join("WEB-INF").join("lib"); if lib.is_dir() { add(format!("{}{}*", lib.to_string_lossy(), std::path::MAIN_SEPARATOR)); } @@ -113,6 +110,32 @@ fn library_entries(root: &Path, ps: &ProjectStructureSettings, test: bool) -> Ve out } +/// The web resource folder of a Web facet: its own, else the folder holding `WEB-INF/web.xml`. +fn web_root(root: &Path, facet: &ide_core::settings::FacetConfig) -> PathBuf { + let dir = facet.web_root.trim(); + let dir = if dir.is_empty() { + facet.descriptor.trim().replace('\\', "/").strip_suffix("/WEB-INF/web.xml").unwrap_or("").to_owned() + } else { + dir.to_owned() + }; + root.join(dir) +} + +/// The class archives and folders of a library path (`lib/*.jar` lists the folder's jars). +fn library_files(root: &Path, value: &str) -> Vec { + let entry = class_entry(root, value); + match entry.strip_suffix('*') { + Some(dir) => { + let mut jars: Vec = fs::read_dir(dir) + .map(|d| d.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "jar")).collect()) + .unwrap_or_default(); + jars.sort(); + jars + } + None => vec![PathBuf::from(entry)], + } +} + /// A classpath entry for a library path: a folder of jars (`lib/*`) stays a wildcard javac expands. fn class_entry(root: &Path, value: &str) -> String { let path = root.join(value.trim()); @@ -218,7 +241,8 @@ pub fn structure_plan( }, root, )); - if !test_sources.is_empty() { + // Artifacts hold production classes only. + if !test_sources.is_empty() && kind != BuildKind::Artifacts { let mut test_cp = vec![main_out.to_string_lossy().into_owned()]; test_cp.extend(library_entries(root, ps, true)); steps.push(compile("test", &test_sources, &test_out, &test_cp)?); @@ -230,9 +254,150 @@ pub fn structure_plan( root, )); } + if kind == BuildKind::Artifacts { + if ps.artifacts.is_empty() { + return Err(IdeError::invalid("No artifacts are configured: add one in Project Structure › Artifacts")); + } + for artifact in &ps.artifacts { + steps.extend(artifact_steps(root, ps, artifact, &main_out, None, cache)); + } + } Ok(Some(BuildPlan { system: BuildSystem::Javac, title: module_name(root), steps })) } +/// 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) + .unwrap_or_else(|| root.join("out").join("artifacts").join(file_name(&artifact.name))) +} + +/// An artifact name as a file name (`shop:war exploded` → `shop_war_exploded`). +fn file_name(name: &str) -> String { + name.chars().map(|c| if c.is_alphanumeric() || c == '-' || c == '.' { c } else { '_' }).collect() +} + +/// The archive a `jar` / `war` artifact writes (`/.war`), or its folder (exploded). +pub fn artifact_file(root: &Path, artifact: &ArtifactConfig) -> PathBuf { + let out = artifact_output(root, artifact); + let base = artifact.name.split(':').next().filter(|n| !n.trim().is_empty()).unwrap_or(&artifact.name); + match artifact.kind { + ArtifactKind::Jar => out.join(format!("{}.jar", file_name(base))), + ArtifactKind::War => out.join(format!("{}.war", file_name(base))), + ArtifactKind::WarExploded => out, + } +} + +/// The steps laying out one artifact from the module output `classes`; `war`: write a +/// WAR there instead of the artifact's own output (an application server's deployment). +fn artifact_steps( + root: &Path, + ps: &ProjectStructureSettings, + artifact: &ArtifactConfig, + classes: &Path, + war: Option<&Path>, + cache: &Path, +) -> Vec { + let libraries: Vec = ps + .libraries + .iter() + .filter(|l| artifact.include_libraries.contains(&l.name)) + .flat_map(|l| l.classes.iter().flat_map(|c| library_files(root, c))) + .collect(); + let facet = ps + .facets + .iter() + .filter(|f| f.kind == "web") + .find(|f| f.module == artifact.module || f.module.is_empty() && artifact.module == ".") + .or_else(|| ps.facets.iter().find(|f| f.kind == "web")); + let staging = cache.join("artifacts").join(file_name(&artifact.name)); + let mut steps = Vec::new(); + match (artifact.kind, war) { + (ArtifactKind::Jar, None) => { + let out = artifact_output(root, artifact); + let mut manifest = String::from("Manifest-Version: 1.0\r\n"); + if !artifact.main_class.trim().is_empty() { + manifest.push_str(&format!("Main-Class: {}\r\n", artifact.main_class.trim())); + } + let names: Vec = + libraries.iter().filter_map(|l| l.file_name()).map(|n| n.to_string_lossy().into_owned()).collect(); + if !names.is_empty() { + manifest.push_str(&format!("Class-Path: {}\r\n", names.join(" "))); + } + steps.push(BuildStep::action( + Action::Layout { into: staging.clone(), entries: vec![(classes.to_path_buf(), PathBuf::new())] }, + root, + )); + // The jar's Class-Path names the libraries next to it. + steps.push(BuildStep::action( + Action::Layout { + into: out.clone(), + entries: libraries.iter().map(|l| (l.clone(), file_of(l))).collect(), + }, + root, + )); + steps.push(BuildStep::action( + Action::Archive { from: staging, to: artifact_file(root, artifact), manifest: Some(manifest) }, + root, + )); + } + (kind, war) => { + let exploded = match (kind, war) { + (ArtifactKind::WarExploded, None) => artifact_output(root, artifact), + _ => staging.clone(), + }; + let mut entries = Vec::new(); + if let Some(facet) = facet { + entries.push((web_root(root, facet), PathBuf::new())); + } + entries.push((classes.to_path_buf(), PathBuf::from("WEB-INF/classes"))); + for lib in &libraries { + entries.push((lib.clone(), Path::new("WEB-INF/lib").join(file_of(lib)))); + } + steps.push(BuildStep::action(Action::Layout { into: exploded.clone(), entries }, root)); + let archive = war + .map(Path::to_path_buf) + .or_else(|| (kind != ArtifactKind::WarExploded).then(|| artifact_file(root, artifact))); + if let Some(to) = archive { + steps.push(BuildStep::action(Action::Archive { from: exploded, to, manifest: None }, root)); + } + } + } + steps +} + +fn file_of(path: &Path) -> PathBuf { + path.file_name().map(PathBuf::from).unwrap_or_default() +} + +/// The WAR artifacts of a project without a build tool: an application server deploys them. +pub fn structure_web_artifacts(ps: &ProjectStructureSettings) -> Vec<&ArtifactConfig> { + ps.artifacts.iter().filter(|a| matches!(a.kind, ArtifactKind::War | ArtifactKind::WarExploded)).collect() +} + +/// A build of `artifact` into the WAR `war` (Tomcat's deployment), compiling first. +#[allow(clippy::too_many_arguments)] +pub fn structure_war_plan( + root: &Path, + ps: &ProjectStructureSettings, + roots: &StructureRoots, + jdk: Option<&StructureJdk>, + language_level: &str, + artifact: &ArtifactConfig, + war: &Path, + cache: &Path, +) -> IdeResult { + let mut plan = structure_plan(root, ps, roots, jdk, language_level, BuildKind::Build, cache)? + .unwrap_or_else(|| BuildPlan { system: BuildSystem::Javac, title: module_name(root), steps: Vec::new() }); + let (main_out, _) = structure_outputs(root, ps); + // Tests are not part of a deployment. + plan.steps.retain(|s| !s.args.iter().any(|a| a.ends_with("test.args"))); + plan.steps + .retain(|s| !matches!(&s.action, Some((Action::CopyResources { to, .. }, _)) if !to.starts_with(&main_out))); + plan.steps.extend(artifact_steps(root, ps, artifact, &main_out, Some(war), cache)); + plan.title = artifact.name.clone(); + Ok(plan) +} + /// Work a build does in the IDE itself rather than through a tool. #[derive(Clone, Debug, PartialEq)] pub(crate) enum Action { @@ -241,6 +406,11 @@ pub(crate) enum Action { /// Copies the files of these folders that are not Java sources into `to`, keeping their /// relative paths; files that are already up to date are left alone. CopyResources { from: Vec, to: PathBuf }, + /// Lays out an artifact in `into`: each folder's content or file goes to its relative + /// place (`""` = the top). What is no longer laid out is removed. + Layout { into: PathBuf, entries: Vec<(PathBuf, PathBuf)> }, + /// Zips the folder `from` into the archive `to`, with this manifest first. + Archive { from: PathBuf, to: PathBuf, manifest: Option }, } impl Action { @@ -249,6 +419,8 @@ impl Action { match self { Action::Clean(dirs) => format!("Clean {}", dirs.iter().map(|d| rel(d)).collect::>().join(", ")), Action::CopyResources { to, .. } => format!("Copy resources to {}", rel(to)), + Action::Layout { into, .. } => format!("Lay out {}", rel(into)), + Action::Archive { to, .. } => format!("Pack {}", rel(to)), } } @@ -269,10 +441,113 @@ impl Action { } Ok(format!("{copied} resource file(s) copied")) } + Action::Layout { into, entries } => { + // A fresh layout: files dropped from the sources must not linger in the artifact. + if entries.iter().any(|(from, _)| from.starts_with(into)) { + return Err(IdeError::invalid(format!( + "The artifact output folder {} holds files the artifact is made of", + into.display() + ))); + } + if into.exists() { + fs::remove_dir_all(into) + .map_err(|e| IdeError::internal(format!("cannot delete {} ({e})", into.display())))?; + } + let mut copied = 0; + for (from, to) in entries { + let target = into.join(to); + if from.is_dir() { + copied += copy_tree(from, &target, cancel)?; + } else if from.is_file() { + copy_file(from, &target)?; + copied += 1; + } + } + Ok(format!("{copied} file(s) laid out")) + } + Action::Archive { from, to, manifest } => { + archive(from, to, manifest.as_deref(), cancel)?; + Ok(format!("Wrote {}", to.display())) + } } } } +fn copy_file(from: &Path, to: &Path) -> IdeResult<()> { + if let Some(parent) = to.parent() { + fs::create_dir_all(parent) + .map_err(|e| IdeError::internal(format!("cannot create {} ({e})", parent.display())))?; + } + fs::copy(from, to).map_err(|e| IdeError::internal(format!("cannot copy {} ({e})", from.display())))?; + Ok(()) +} + +fn copy_tree(from: &Path, to: &Path, cancel: &CancellationToken) -> IdeResult { + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + let Ok(entries) = fs::read_dir(from) else { return Ok(0) }; + let mut copied = 0; + for e in entries.flatten() { + let Ok(t) = e.file_type() else { continue }; + let target = to.join(e.file_name()); + if t.is_dir() { + copied += copy_tree(&e.path(), &target, cancel)?; + } else if t.is_file() { + copy_file(&e.path(), &target)?; + copied += 1; + } + } + Ok(copied) +} + +fn archive(from: &Path, to: &Path, manifest: Option<&str>, cancel: &CancellationToken) -> IdeResult<()> { + use std::io::Write; + let err = |e: &dyn std::fmt::Display| IdeError::internal(format!("cannot write {} ({e})", to.display())); + if let Some(parent) = to.parent() { + fs::create_dir_all(parent).map_err(|e| err(&e))?; + } + let mut zip = zip::ZipWriter::new(fs::File::create(to).map_err(|e| err(&e))?); + let options = zip::write::SimpleFileOptions::default(); + if let Some(manifest) = manifest { + zip.add_directory("META-INF/", options).map_err(|e| err(&e))?; + zip.start_file("META-INF/MANIFEST.MF", options).map_err(|e| err(&e))?; + zip.write_all(manifest.as_bytes()).map_err(|e| err(&e))?; + } + let mut stack = vec![from.to_path_buf()]; + while let Some(dir) = stack.pop() { + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + let Ok(entries) = fs::read_dir(&dir) else { continue }; + let mut entries: Vec<_> = entries.flatten().collect(); + entries.sort_by_key(|e| e.file_name()); + for e in entries { + let path = e.path(); + let name = path.strip_prefix(from).unwrap_or(&path).to_string_lossy().replace('\\', "/"); + if manifest.is_some() && name.eq_ignore_ascii_case("META-INF/MANIFEST.MF") { + continue; + } + match e.file_type() { + Ok(t) if t.is_dir() => { + if !(manifest.is_some() && name == "META-INF") { + zip.add_directory(format!("{name}/"), options).map_err(|e| err(&e))?; + } + stack.push(path); + } + Ok(t) if t.is_file() => { + zip.start_file(name, options).map_err(|e| err(&e))?; + let mut file = fs::File::open(&path).map_err(|e| err(&e))?; + std::io::copy(&mut file, &mut zip).map_err(|e| err(&e))?; + } + _ => {} + } + } + } + zip.finish().map_err(|e| err(&e))?; + Ok(()) +} + fn copy_resources(base: &Path, dir: &Path, to: &Path, cancel: &CancellationToken) -> IdeResult { if cancel.is_cancelled() { return Err(IdeError::cancelled()); @@ -445,4 +720,98 @@ mod tests { Action::Clean(vec![out.clone()]).run(&cancel).unwrap(); assert!(!out.exists()); } + + fn entries(archive: &Path) -> Vec { + let mut zip = zip::ZipArchive::new(fs::File::open(archive).unwrap()).unwrap(); + (0..zip.len()).map(|i| zip.by_index(i).unwrap().name().unwrap().into_owned()).collect() + } + + fn run_plan(plan: &BuildPlan) { + let cancel = CancellationToken::new(); + for step in &plan.steps { + if let Some((action, _)) = &step.action { + action.run(&cancel).unwrap(); + } + } + } + + #[test] + fn lays_out_war_jar_and_exploded_artifacts() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path().join("shop"); + write(&root.join("WebRoot/index.jsp"), "hi"); + write(&root.join("WebRoot/WEB-INF/web.xml"), ""); + write(&root.join("WebRoot/WEB-INF/lib/inside.jar"), ""); + write(&root.join("lib/extra.jar"), ""); + let classes = root.join("out/production/shop"); + write(&classes.join("com/a/A.class"), ""); + let artifact = |name: &str, kind| ArtifactConfig { + name: name.into(), + kind, + module: ".".into(), + include_libraries: vec!["extra".into()], + main_class: "com.a.A".into(), + ..Default::default() + }; + let ps = ProjectStructureSettings { + libraries: vec![ProjectLibrary { + name: "extra".into(), + classes: vec!["lib/*.jar".into()], + ..Default::default() + }], + facets: vec![FacetConfig { + kind: "web".into(), + module: ".".into(), + descriptor: "WebRoot/WEB-INF/web.xml".into(), + web_root: String::new(), + }], + artifacts: vec![ + artifact("shop:war", ArtifactKind::War), + artifact("shop:war exploded", ArtifactKind::WarExploded), + artifact("shop:jar", ArtifactKind::Jar), + ], + ..Default::default() + }; + let cache = tmp.path().join("cache"); + for a in &ps.artifacts { + let plan = BuildPlan { + system: BuildSystem::Javac, + title: String::new(), + steps: artifact_steps(&root, &ps, a, &classes, None, &cache), + }; + run_plan(&plan); + } + let war = entries(&root.join("out/artifacts/shop_war/shop.war")); + for name in [ + "index.jsp", + "WEB-INF/web.xml", + "WEB-INF/lib/inside.jar", + "WEB-INF/lib/extra.jar", + "WEB-INF/classes/com/a/A.class", + ] { + assert!(war.iter().any(|e| e == name), "{name} in {war:?}"); + } + let exploded = root.join("out/artifacts/shop_war_exploded"); + assert!(exploded.join("WEB-INF/classes/com/a/A.class").is_file()); + assert!(exploded.join("WEB-INF/lib/extra.jar").is_file()); + let jar_dir = root.join("out/artifacts/shop_jar"); + let jar = entries(&jar_dir.join("shop.jar")); + assert_eq!(jar[..2], ["META-INF/".to_owned(), "META-INF/MANIFEST.MF".to_owned()]); + assert!(jar.iter().any(|e| e == "com/a/A.class")); + assert!(jar_dir.join("extra.jar").is_file()); + let mut zip = zip::ZipArchive::new(fs::File::open(jar_dir.join("shop.jar")).unwrap()).unwrap(); + let mut manifest = String::new(); + std::io::Read::read_to_string(&mut zip.by_name("META-INF/MANIFEST.MF").unwrap(), &mut manifest).unwrap(); + assert!(manifest.contains("Main-Class: com.a.A") && manifest.contains("Class-Path: extra.jar")); + } + + #[test] + fn never_lays_out_over_its_own_sources() { + let tmp = tempfile::tempdir().unwrap(); + let web = tmp.path().join("WebRoot"); + write(&web.join("a.jsp"), ""); + let action = Action::Layout { into: tmp.path().to_path_buf(), entries: vec![(web.clone(), PathBuf::new())] }; + assert!(action.run(&CancellationToken::new()).is_err()); + assert!(web.join("a.jsp").is_file()); + } } diff --git a/crates/ide-host/src/ops/build.rs b/crates/ide-host/src/ops/build.rs index 4d6457861..1cb40aeb4 100644 --- a/crates/ide-host/src/ops/build.rs +++ b/crates/ide-host/src/ops/build.rs @@ -641,8 +641,8 @@ pub async fn maven_exclude_dependency( .map_err(join_err)? } -/// Build / Rebuild of a Java project without a build tool, from its Project Structure; -/// `None` when it has no Java sources under its source roots. +/// Build / Rebuild / Build Artifacts of a Java project without a build tool, from its +/// Project Structure; `None` when it has no Java sources under its source roots. fn structure_plan( root: &Path, settings: &Settings, @@ -650,10 +650,25 @@ fn structure_plan( kind: BuildKind, cache: &Path, ) -> IdeResult> { + let (roots, jdk) = structure_inputs(root, settings, detected); + compile::structure_plan( + root, + &settings.project_structure, + &roots, + jdk.as_ref(), + &settings.languages.java.language_level, + kind, + cache, + ) +} + +/// The roots and JDK a build of a project without a build tool uses. +pub(crate) fn structure_inputs( + root: &Path, + settings: &Settings, + detected: &[ide_workspace::roots::SourceFolder], +) -> (compile::StructureRoots, Option) { use ide_workspace::roots::{ProjectRoots, RootKind}; - if kind == BuildKind::Artifacts { - return Ok(None); - } let roots = ProjectRoots::compute(detected.to_vec(), &settings.project_structure); let of = |kind: RootKind| roots.roots.iter().filter(|r| r.kind == kind).map(|r| root.join(&r.path)).collect(); let module = settings.project_structure.module_settings(root, root); @@ -668,21 +683,14 @@ fn structure_plan( ide_sdk::java::pick_jdk(&installed, compile::language_release(level)).cloned() }) .map(|j| compile::StructureJdk { home: j.home, major: j.major }); - compile::structure_plan( - root, - &settings.project_structure, - &compile::StructureRoots { - sources: of(RootKind::Source), - tests: of(RootKind::Test), - resources: of(RootKind::Resources), - test_resources: of(RootKind::TestResources), - excluded: of(RootKind::Excluded), - }, - jdk.as_ref(), - &settings.languages.java.language_level, - kind, - cache, - ) + let roots = compile::StructureRoots { + sources: of(RootKind::Source), + tests: of(RootKind::Test), + resources: of(RootKind::Resources), + test_resources: of(RootKind::TestResources), + excluded: of(RootKind::Excluded), + }; + (roots, jdk) } fn cmake_plan(root: &Path, kind: BuildKind, configs: &[ide_run::RunConfig], id: &str) -> IdeResult { diff --git a/crates/ide-host/src/ops/run/commands.rs b/crates/ide-host/src/ops/run/commands.rs index c3beb6685..92af54eb1 100644 --- a/crates/ide-host/src/ops/run/commands.rs +++ b/crates/ide-host/src/ops/run/commands.rs @@ -202,12 +202,85 @@ pub async fn run_tomcat_installations( .map_err(|e| IdeError::internal(e.to_string())) } +/// Id prefix of a Project Structure WAR artifact (a project without a build tool). +const PROJECT_ARTIFACT: &str = "project:"; + +fn project_web_artifacts(settings: &ide_core::settings::Settings) -> Vec { + ide_build::compile::structure_web_artifacts(&settings.project_structure) + .into_iter() + .map(|a| ide_build::web::WebArtifact { + id: format!("{PROJECT_ARTIFACT}{}", a.name), + name: a.name.split(':').next().unwrap_or(&a.name).to_owned(), + module: if a.module == "." { String::new() } else { a.module.clone() }, + tool: "project".into(), + }) + .collect() +} + +/// Compiles the project and packs the Project Structure artifact `name` as the WAR Tomcat +/// deploys, recorded in `base` like a build tool's archive. +fn build_project_war( + root: &std::path::Path, + settings: &ide_core::settings::Settings, + detected: &[ide_workspace::roots::SourceFolder], + name: &str, + base: &std::path::Path, + cache: &std::path::Path, +) -> IdeResult<()> { + use ide_build::compile; + let artifact = settings + .project_structure + .artifacts + .iter() + .find(|a| a.name == name) + .ok_or_else(|| IdeError::invalid(format!("No artifact named {name} in Project Structure › Artifacts")))?; + let (roots, jdk) = crate::ops::build::structure_inputs(root, settings, detected); + let war = base.join("artifact").join(format!( + "{}.war", + name.split(':').next().unwrap_or(name).replace(|c: char| !c.is_alphanumeric() && c != '-', "_") + )); + let plan = compile::structure_war_plan( + root, + &settings.project_structure, + &roots, + jdk.as_ref(), + &settings.languages.java.language_level, + artifact, + &war, + cache, + )?; + let result = compile::run(root, &plan, &ide_core::CancellationToken::new(), &|_| {})?; + if !result.success { + let first = result.messages.iter().find(|m| m.severity == ide_core::Severity::Error); + let text = match first { + Some(m) => match (&m.path, m.range) { + (Some(path), Some(range)) => { + format!("{}:{}: {}", std::path::PathBuf::from(path.clone()).display(), range.start.line + 1, m.text) + } + _ => m.text.clone(), + }, + None => "the build failed".into(), + }; + return Err(IdeError::invalid(format!("Cannot build {name}: {text}"))); + } + std::fs::create_dir_all(base)?; + std::fs::write(base.join("artifact-id.txt"), format!("{PROJECT_ARTIFACT}{name}"))?; + std::fs::write(base.join("artifact-path.txt"), war.to_string_lossy().as_bytes())?; + Ok(()) +} + pub async fn run_tomcat_artifacts(host: &Host, window: &str) -> IdeResult> { host.require_trust(window)?; let project = host.project(window)?; tokio::task::spawn_blocking(move || { - let model = crate::ops::build::load(&project.root, &project.build_cache_dir(), &project.settings.effective()); - ide_build::web::artifacts(&project.root, &model) + let settings = project.settings.effective(); + let model = crate::ops::build::load(&project.root, &project.build_cache_dir(), &settings); + let mut artifacts = ide_build::web::artifacts(&project.root, &model); + // Without a build tool, the Project Structure's WAR artifacts are built by the IDE. + if model.maven.is_none() && model.gradle.is_empty() { + artifacts.extend(project_web_artifacts(&settings)); + } + artifacts }) .await .map_err(|e| IdeError::internal(e.to_string())) @@ -230,6 +303,12 @@ pub async fn run_tomcat_build(host: &Host, window: &str, config: RunConfig) -> I .or_else(|| artifacts.first().map(|a| &a.id)) .ok_or_else(|| IdeError::invalid("Choose a WAR artifact"))?; let base = ide_run::tomcat::effective_base_dir(&project.root, &project.cache_dir, &config)?; + if let Some(name) = id.strip_prefix(PROJECT_ARTIFACT) { + let settings = project.settings.effective(); + let detected = project.detected_roots.read().clone(); + build_project_war(&project.root, &settings, &detected, name, &base, &project.build_cache_dir())?; + return Ok(None); + } // "Build before launch" is skipped when the built WAR is already newer than the // sources of every module in the build, so a repeated run does not rebuild (IDEA's // up-to-date check) but a change in a dependency module does. diff --git a/src/features/settings/languages/ProjectStructurePage.tsx b/src/features/settings/languages/ProjectStructurePage.tsx index 3e3b0b1b1..e3b874e5c 100644 --- a/src/features/settings/languages/ProjectStructurePage.tsx +++ b/src/features/settings/languages/ProjectStructurePage.tsx @@ -1576,7 +1576,8 @@ function ArtifactsSection() { if (!root || !isTauri()) return; let live = true; call(commands.runTomcatArtifacts()) - .then((list) => live && setWebArtifacts(list)) + // Artifacts the IDE builds itself are the ones this page configures. + .then((list) => live && setWebArtifacts(list.filter((a) => a.tool !== "project"))) .catch(() => {}); return () => { live = false;