Файли
openidea/crates/ide-build/src/compile/structure.rs
T
RuyimgByCN b7bacc8ff5 feat(build): incremental javac and artifact sync for Project Structure artifacts (#7496)
Building a Project Structure WAR artifact compiles incrementally with the Java build service and syncs only changed files into the artifact, falling back to a full javac build if the incremental build fails. The build streams progress and honours cancellation through the Tomcat run's build step.

Copied files and archives are checked byte for byte, archives are replaced atomically, and old staging directories migrate to a clean layout.

Co-authored-by: RuyimgByCN <[email protected]>
2026-12-02 21:28:30 +08:00

2178 рядки
92 KiB
Rust
Неформатований Анотація Історія

Цей файл містить неоднозначні символи Юнікоду
Цей файл містить символи Юнікоду, які можна сплутати з іншими символами. Якщо ви вважаєте, що це зроблено навмисно, можете сміливо ігнорувати це попередження. Щоб показати їх, скористайтеся кнопкою Escape.
//! A Java project without a build tool, built from its Project Structure: `javac` compiles
//! the source roots to the module's output folder against the project libraries and the
//! 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::{
ArtifactConfig, ArtifactKind, DependencyScope, ModuleStructureSettings, ProjectStructureSettings, jar_files,
split_jar_glob,
};
use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::time::UNIX_EPOCH;
/// The roots of the project as the IDE resolved them (absolute folders).
#[derive(Clone, Debug, Default)]
pub struct StructureRoots {
pub sources: Vec<PathBuf>,
pub tests: Vec<PathBuf>,
pub resources: Vec<PathBuf>,
pub test_resources: Vec<PathBuf>,
pub excluded: Vec<PathBuf>,
}
/// The JDK compiling the project.
#[derive(Clone, Debug)]
pub struct StructureJdk {
pub home: PathBuf,
pub major: u32,
}
/// Where the project's classes go: `<compiler output>/production/<module>` and
/// `<compiler output>/test/<module>` (`out` by default), unless the module names its own.
pub fn structure_outputs(root: &Path, ps: &ProjectStructureSettings) -> (PathBuf, PathBuf) {
let module = root_module(root, ps);
let name = module_name(root);
let base = resolve_dir(root, &ps.compiler_output).unwrap_or_else(|| root.join("out"));
let main = module
.and_then(|m| resolve_dir(root, &m.compiler_output))
.unwrap_or_else(|| base.join("production").join(&name));
let test = module
.and_then(|m| resolve_dir(root, &m.test_compiler_output))
.unwrap_or_else(|| base.join("test").join(&name));
(main, test)
}
/// Whether Rebuild may delete the output folder `dir`: never the project folder or one above
/// it, nor a folder that holds or lies inside a source, test or resource root.
fn deletable_output(dir: &Path, root: &Path, roots: &StructureRoots) -> bool {
let dir = normalize(dir);
let overlaps = |r: &PathBuf| {
let r = normalize(r);
r.starts_with(&dir) || dir.starts_with(&r)
};
!normalize(root).starts_with(&dir)
&& !roots.sources.iter().chain(&roots.tests).chain(&roots.resources).chain(&roots.test_resources).any(overlaps)
}
fn module_name(root: &Path) -> String {
root.file_name().map_or_else(|| "project".to_owned(), |n| n.to_string_lossy().into_owned())
}
fn root_module<'a>(root: &Path, ps: &'a ProjectStructureSettings) -> Option<&'a ModuleStructureSettings> {
ps.modules.get(".").or_else(|| ps.module_settings(root, root))
}
fn resolve_dir(root: &Path, value: &str) -> Option<PathBuf> {
let value = value.trim();
(!value.is_empty()).then(|| root.join(value))
}
/// `.java` files below `dir`, not inside an excluded folder or another root of `skip`.
fn java_files(dir: &Path, excluded: &[PathBuf], out: &mut Vec<PathBuf>) {
let Ok(entries) = fs::read_dir(dir) else { return };
let mut entries: Vec<_> = entries.flatten().collect();
entries.sort_by_key(|e| e.file_name());
for e in entries {
let path = e.path();
match e.file_type() {
Ok(t) if t.is_dir() && !excluded.iter().any(|x| path.starts_with(x)) => {
java_files(&path, excluded, out);
}
Ok(t) if t.is_file() && path.extension().is_some_and(|x| x == "java") => out.push(path),
_ => {}
}
}
}
/// Resolves library classpath items for `scope`, parameterized by how each library path
/// and Web facet `WEB-INF/lib` folder is expanded.
fn collect_libraries<T: PartialEq>(
root: &Path,
ps: &ProjectStructureSettings,
test: bool,
mut on_lib_path: impl FnMut(&str) -> Vec<T>,
mut on_web_lib: impl FnMut(&Path) -> Vec<T>,
) -> Vec<T> {
let wanted = |scope: DependencyScope| match scope {
DependencyScope::Compile | DependencyScope::Provided => true,
DependencyScope::Test => test,
DependencyScope::Runtime => false,
};
let mut out: Vec<T> = Vec::new();
let mut add = |entry: T| {
if !out.contains(&entry) {
out.push(entry);
}
};
let module_deps = root_module(root, ps).map(|m| m.dependencies.as_slice()).unwrap_or_default();
for lib in &ps.libraries {
// A library a module dependency names takes that dependency's scope.
let scope =
module_deps.iter().find(|d| d.kind == "library" && d.target == lib.name).map_or(lib.scope, |d| d.scope);
if wanted(scope) {
for class in &lib.classes {
for entry in on_lib_path(class) {
add(entry);
}
}
}
}
for dep in module_deps.iter().filter(|d| d.kind == "library" && wanted(d.scope)) {
if !ps.libraries.iter().any(|l| l.name == dep.target) && !dep.target.trim().is_empty() {
for entry in on_lib_path(&dep.target) {
add(entry);
}
}
}
for facet in ps.facets.iter().filter(|f| f.kind == "web") {
let lib = web_root(root, facet).join("WEB-INF").join("lib");
if lib.is_dir() {
for entry in on_web_lib(&lib) {
add(entry);
}
}
}
out
}
/// Folders and archives of the libraries a module compiles against, for `scope`.
fn library_entries(root: &Path, ps: &ProjectStructureSettings, test: bool) -> Vec<String> {
collect_libraries(
root,
ps,
test,
|class| class_entries(root, class),
|lib| vec![format!("{}{}*", lib.to_string_lossy(), std::path::MAIN_SEPARATOR)],
)
}
/// Concrete JAR files and class folders a module compiles against, for `scope`.
fn library_paths(root: &Path, ps: &ProjectStructureSettings, test: bool) -> Vec<PathBuf> {
collect_libraries(root, ps, test, |class| library_files(root, class), |lib| jar_files(lib, false))
}
/// 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 folders under `dir` (itself included) that hold `.jar` files, in walk order.
fn jar_dirs(dir: &Path) -> Vec<PathBuf> {
let mut dirs: Vec<PathBuf> = Vec::new();
for jar in jar_files(dir, true) {
if let Some(parent) = jar.parent().filter(|p| !dirs.iter().any(|d| d == p)) {
dirs.push(parent.to_path_buf());
}
}
dirs
}
/// The class archives and folders of a library path (`lib/*.jar`, `lib/**/*.jar`, or a folder
/// containing JARs expands to those JARs; a folder without JARs stays a class folder).
fn library_files(root: &Path, value: &str) -> Vec<PathBuf> {
if let Some((base, recursive)) = split_jar_glob(value) {
return jar_files(&root.join(base), recursive);
}
let path = root.join(value.trim());
if path.is_dir() {
let jars = jar_files(&path, true);
if !jars.is_empty() {
return jars;
}
}
vec![path]
}
/// Classpath entries for a library path: `lib/*.jar` stays `lib/*` for javac to expand; a
/// directory containing JARs expands to `<dir>/*` per folder holding JARs.
fn class_entries(root: &Path, value: &str) -> Vec<String> {
let wildcard = |dir: &Path| format!("{}{}*", dir.to_string_lossy(), std::path::MAIN_SEPARATOR);
if let Some((base, recursive)) = split_jar_glob(value) {
let dir = root.join(base);
let dirs = if recursive { jar_dirs(&dir) } else { Vec::new() };
return if dirs.is_empty() { vec![wildcard(&dir)] } else { dirs.iter().map(|d| wildcard(d)).collect() };
}
let path = root.join(value.trim());
if path.is_dir() {
let dirs = jar_dirs(&path);
if !dirs.is_empty() {
return dirs.iter().map(|d| wildcard(d)).collect();
}
}
vec![path.to_string_lossy().into_owned()]
}
fn classpath(entries: &[String]) -> String {
entries.join(if cfg!(windows) { ";" } else { ":" })
}
/// `"17"`, `"1.8"`, `"JDK_17"` → the release number.
pub fn language_release(level: &str) -> Option<u32> {
let digits = level.trim().trim_start_matches("JDK_").trim_start_matches("jdk").replace('_', ".");
let digits = digits.strip_prefix("1.").unwrap_or(&digits);
digits.split(['.', ' ']).next()?.parse().ok().filter(|n| *n > 0)
}
fn structure_language_level(root: &Path, ps: &ProjectStructureSettings, language_level: &str) -> Option<u32> {
let module = root_module(root, ps);
module
.map(|m| m.language_level.as_str())
.filter(|l| !l.trim().is_empty())
.or(Some(language_level))
.and_then(language_release)
}
fn structure_compiler(
root: &Path,
ps: &ProjectStructureSettings,
jdk: Option<&StructureJdk>,
language_level: &str,
) -> (Option<u32>, BTreeMap<String, String>, String) {
let level = structure_language_level(root, ps, language_level);
let env: BTreeMap<String, String> = 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`.
pub fn structure_plan(
root: &Path,
ps: &ProjectStructureSettings,
roots: &StructureRoots,
jdk: Option<&StructureJdk>,
language_level: &str,
kind: BuildKind,
cache: &Path,
) -> IdeResult<Option<BuildPlan>> {
let mut main_sources = Vec::new();
for dir in &roots.sources {
java_files(dir, &roots.excluded, &mut main_sources);
}
let mut test_sources = Vec::new();
for dir in &roots.tests {
java_files(dir, &roots.excluded, &mut test_sources);
}
if main_sources.is_empty() && test_sources.is_empty() {
return Ok(None);
}
let (main_out, test_out) = structure_outputs(root, ps);
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())))?;
let mut steps = Vec::new();
if kind == BuildKind::Rebuild {
let dirs: Vec<PathBuf> =
[&main_out, &test_out].into_iter().filter(|d| deletable_output(d, root, roots)).cloned().collect();
if !dirs.is_empty() {
steps.push(BuildStep::action(Action::Clean(dirs), root));
}
}
let main_cp = library_entries(root, ps, false);
let compile = |name: &str, sources: &[PathBuf], out: &Path, cp: &[String]| -> IdeResult<BuildStep> {
let args_file = args_dir.join(format!("{name}.args"));
// One quoted path per line: the sources outgrow a command line quickly.
let text: String = sources
.iter()
.map(|p| format!("\"{}\"\n", p.to_string_lossy().replace('\\', "\\\\").replace('"', "\\\"")))
.collect();
fs::write(&args_file, text)
.map_err(|e| IdeError::internal(format!("cannot write {} ({e})", args_file.display())))?;
let mut step = BuildStep::new(&javac, &[], root, Format::Gradle);
step.args.extend(["-encoding".into(), "UTF-8".into(), "-g".into()]);
step.args.extend(["-d".into(), out.to_string_lossy().into_owned()]);
if !cp.is_empty() {
step.args.extend(["-cp".into(), classpath(cp)]);
}
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()];
Ok(step)
};
if !main_sources.is_empty() {
steps.push(compile("production", &main_sources, &main_out, &main_cp)?);
}
steps.push(BuildStep::action(
Action::CopyResources {
from: roots.sources.iter().chain(&roots.resources).cloned().collect(),
to: main_out.clone(),
},
root,
));
// 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)?);
steps.push(BuildStep::action(
Action::CopyResources {
from: roots.tests.iter().chain(&roots.test_resources).cloned().collect(),
to: test_out.clone(),
},
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 }))
}
/// 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<BuildPlan> {
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<String> = 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<PathBuf> = 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/<name>`.
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 (`<output>/<name>.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<BuildStep> {
let libraries: Vec<PathBuf> = 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("staging").join(file_name(&artifact.name));
let staging_record = cache.join("artifacts").join(format!("{}.staging.files", file_name(&artifact.name)));
// What the last build laid out in a folder the user chose, so the next one replaces only that.
let record = cache.join("artifacts").join(format!("{}.files", file_name(&artifact.name)));
let archive_stamp = cache.join("artifacts").join(format!("{}.archive.stamp", 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<String> =
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())],
record: Some(staging_record),
},
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(),
record: Some(record),
},
root,
));
steps.push(BuildStep::action(
Action::Archive {
from: staging,
to: artifact_file(root, artifact),
manifest: Some(manifest),
stamp: Some(archive_stamp),
},
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))));
}
// The exploded output may be a folder the user chose; the staging folder is the IDE's own.
let record = Some(if exploded == staging { staging_record } else { record });
steps.push(BuildStep::action(Action::Layout { into: exploded.clone(), entries, record }, 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, stamp: Some(archive_stamp) },
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` for Tomcat's deployment, compiling production classes first.
/// When `war` is `Some`, packs a WAR archive at that path; when `None`, writes to the
/// artifact's own output (`artifact_file`: a `.war` archive for `War`, or the exploded
/// directory for `WarExploded`).
#[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: Option<&Path>,
cache: &Path,
) -> IdeResult<BuildPlan> {
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, 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 {
/// Deletes these output folders (Rebuild).
Clean(Vec<PathBuf>),
/// 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<PathBuf>, 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: without `record`, `into`
/// is the IDE's own folder and is laid out afresh; with it, `into` is a folder the user chose
/// and only the files the previous layout recorded there are removed, never anything else.
Layout { into: PathBuf, entries: Vec<(PathBuf, PathBuf)>, record: Option<PathBuf> },
/// Zips the folder `from` into the archive `to`, with this manifest first.
Archive { from: PathBuf, to: PathBuf, manifest: Option<String>, stamp: Option<PathBuf> },
}
impl Action {
pub(crate) fn display(&self, root: &Path) -> String {
let rel = |p: &Path| p.strip_prefix(root).unwrap_or(p).to_string_lossy().replace('\\', "/");
match self {
Action::Clean(dirs) => format!("Clean {}", dirs.iter().map(|d| rel(d)).collect::<Vec<_>>().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)),
}
}
/// Runs the action; the text is a summary for the console.
pub(crate) fn run(&self, cancel: &CancellationToken) -> IdeResult<String> {
match self {
Action::Clean(dirs) => {
for dir in dirs.iter().filter(|d| d.exists()) {
fs::remove_dir_all(dir)
.map_err(|e| IdeError::internal(format!("cannot delete {} ({e})", dir.display())))?;
}
Ok(String::new())
}
Action::CopyResources { from, to } => {
let mut copied = 0;
for dir in from {
copied += copy_resources(dir, dir, to, cancel)?;
}
Ok(format!("{copied} resource file(s) copied"))
}
Action::Layout { into, entries, record } => {
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 record.is_none() && into.exists() {
fs::remove_dir_all(into)
.map_err(|e| IdeError::internal(format!("cannot delete {} ({e})", into.display())))?;
}
let mut planned = BTreeMap::new();
for (from, to) in entries {
let target = into.join(to);
// The folders of the output it goes into (and a folder entry's own) are
// never links; a file in a link's place replaces the link.
let mut at = into.to_path_buf();
let folders = to.components().count().saturating_sub(usize::from(!from.is_dir()));
for c in to.components().take(folders) {
at.push(c);
refuse_link(&at)?;
}
if from.is_dir() {
collect_tree(from, &target, &mut planned, cancel)?;
} else if from.is_file() {
planned.insert(target, from.clone());
}
}
let mut copied = 0usize;
for (target, source) in &planned {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
if copy_file_if_changed(source, target)? {
copied += 1;
}
}
let written: Vec<PathBuf> = planned.into_keys().collect();
let removed = if let Some(record) = record { replace_recorded(into, record, &written)? } else { 0 };
if copied == 0 && removed == 0 {
Ok("Up to date".into())
} else if removed == 0 {
Ok(format!("{copied} file(s) updated"))
} else {
Ok(format!("{copied} file(s) updated, {removed} removed"))
}
}
Action::Archive { from, to, manifest, stamp } => {
if let Some(stamp_path) = stamp {
let fp = archive_fingerprint(from, to, manifest.as_deref(), cancel)?;
if let Ok(saved) = fs::read_to_string(stamp_path)
&& let Some(expected) = saved.strip_prefix(&fp).and_then(|s| s.strip_prefix('\n'))
&& fs::symlink_metadata(to).is_ok_and(|m| m.file_type().is_file())
&& file_digest(to)? == expected
{
return Ok(format!("{} is up to date", to.display()));
}
archive(from, to, manifest.as_deref(), cancel)?;
if let Some(parent) = stamp_path.parent() {
fs::create_dir_all(parent)
.map_err(|e| IdeError::internal(format!("cannot create {} ({e})", parent.display())))?;
}
fs::write(stamp_path, format!("{fp}\n{}", file_digest(to)?))
.map_err(|e| IdeError::internal(format!("cannot write {} ({e})", stamp_path.display())))?;
} else {
archive(from, to, manifest.as_deref(), cancel)?;
}
Ok(format!("Wrote {}", to.display()))
}
}
}
}
fn file_stamp(path: &Path) -> Option<(u64, u128)> {
let meta = fs::symlink_metadata(path).ok().filter(|m| m.file_type().is_file())?;
let mtime = meta.modified().ok()?.duration_since(UNIX_EPOCH).map_or(0, |d| d.as_nanos());
Some((meta.len(), mtime))
}
fn file_digest(path: &Path) -> IdeResult<String> {
Ok(blake3::Hasher::new().update_reader(fs::File::open(path)?)?.finalize().to_hex().to_string())
}
fn copy_file_if_changed(from: &Path, to: &Path) -> IdeResult<bool> {
// A link in the artifact's place is replaced, not written through.
match fs::symlink_metadata(to) {
Ok(m) if m.file_type().is_symlink() => {
fs::remove_file(to).map_err(|e| IdeError::internal(format!("cannot replace {} ({e})", to.display())))?;
}
Ok(m) if m.file_type().is_file() => {
if let Some(src_stamp) = file_stamp(from)
&& Some(src_stamp) == file_stamp(to)
&& file_digest(from)? == file_digest(to)?
{
return Ok(false);
}
}
_ => {}
}
if let Some(parent) = to.parent() {
fs::create_dir_all(parent)
.map_err(|e| IdeError::internal(format!("cannot create {} ({e})", parent.display())))?;
}
if let Err(err) = fs::copy(from, to) {
if err.kind() == std::io::ErrorKind::PermissionDenied && to.exists() {
let _ = fs::remove_file(to);
fs::copy(from, to).map_err(|e| IdeError::internal(format!("cannot copy {} ({e})", from.display())))?;
} else {
return Err(IdeError::internal(format!("cannot copy {} ({err})", from.display())));
}
}
if let Ok(mtime) = fs::metadata(from).and_then(|m| m.modified())
&& let Ok(file) = fs::OpenOptions::new().write(true).open(to)
{
let _ = file.set_modified(mtime);
}
Ok(true)
}
fn refuse_link(folder: &Path) -> IdeResult<()> {
if fs::symlink_metadata(folder).is_ok_and(|m| m.file_type().is_symlink()) {
return Err(IdeError::invalid(format!(
"{} links to another folder; the artifact is not laid out through it",
folder.display()
)));
}
Ok(())
}
fn collect_tree(
from: &Path,
to: &Path,
planned: &mut BTreeMap<PathBuf, PathBuf>,
cancel: &CancellationToken,
) -> IdeResult<()> {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let Ok(entries) = fs::read_dir(from) else { return Ok(()) };
for e in entries.flatten() {
let Ok(t) = e.file_type() else { continue };
let target = to.join(e.file_name());
if t.is_dir() {
refuse_link(&target)?;
collect_tree(&e.path(), &target, planned, cancel)?;
} else if t.is_file() {
planned.insert(target, e.path());
}
}
Ok(())
}
/// Removes the files the previous layout recorded in `into` that this one didn't write
/// (and the folders that leaves empty), then records `written` for the next layout.
fn replace_recorded(into: &Path, record: &Path, written: &[PathBuf]) -> IdeResult<usize> {
let now: std::collections::HashSet<PathBuf> =
written.iter().filter_map(|p| p.strip_prefix(into).ok().map(Path::to_path_buf)).collect();
let before = fs::read_to_string(record).unwrap_or_default();
let mut lines = before.lines();
// The record names its folder first: one made for another output folder removes nothing.
let same = lines.next().is_some_and(|dir| Path::new(dir) == into);
let mut removed = 0usize;
for rel in lines.filter(|_| same).map(PathBuf::from) {
// Only plain relative paths inside `into`: a damaged record must not reach elsewhere.
if rel.as_os_str().is_empty()
|| now.contains(&rel)
|| rel.components().any(|c| !matches!(c, std::path::Component::Normal(_)))
{
continue;
}
let file = into.join(&rel);
// Never through a link: a folder of the output that now links elsewhere (or a file that
// is a link) leads out of what the layout wrote.
let mut at = into.to_path_buf();
let linked = rel.components().any(|c| {
at.push(c);
fs::symlink_metadata(&at).is_ok_and(|m| m.file_type().is_symlink())
});
if !linked && file.is_file() {
match fs::remove_file(&file) {
Ok(()) => (),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
Err(e) => return Err(e.into()),
}
removed += 1;
let mut dir = file.parent();
while let Some(d) = dir.filter(|d| *d != into && d.starts_with(into)) {
if fs::remove_dir(d).is_err() {
break;
}
dir = d.parent();
}
}
}
let mut list: Vec<String> = now.iter().map(|p| p.to_string_lossy().into_owned()).collect();
list.sort();
list.insert(0, into.to_string_lossy().into_owned());
if let Some(parent) = record.parent() {
fs::create_dir_all(parent)
.map_err(|e| IdeError::internal(format!("cannot create {} ({e})", parent.display())))?;
}
fs::write(record, list.join("\n"))
.map_err(|e| IdeError::internal(format!("cannot write {} ({e})", record.display())))?;
Ok(removed)
}
fn archive_fingerprint(
from: &Path,
to: &Path,
manifest: Option<&str>,
cancel: &CancellationToken,
) -> IdeResult<String> {
let mut entries = Vec::new();
let mut stack = vec![from.to_path_buf()];
while let Some(dir) = stack.pop() {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let Ok(read) = fs::read_dir(&dir) else { continue };
for e in read.flatten() {
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() => {
entries.push((name, None));
stack.push(path);
}
Ok(t) if t.is_file() => entries.push((name, Some(file_digest(&path)?))),
_ => {}
}
}
}
entries.sort();
let payload = serde_json::to_vec(&(to.to_string_lossy(), manifest, entries))
.map_err(|e| IdeError::internal(e.to_string()))?;
Ok(blake3::hash(&payload).to_hex().to_string())
}
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()));
let parent = to.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or_else(|| Path::new("."));
fs::create_dir_all(parent).map_err(|e| err(&e))?;
let temp = tempfile::Builder::new();
#[cfg(unix)]
let temp = {
use std::os::unix::fs::PermissionsExt;
let mut temp = temp;
temp.permissions(fs::metadata(to).map_or_else(|_| fs::Permissions::from_mode(0o666), |m| m.permissions()));
temp
};
let mut file = temp.tempfile_in(parent).map_err(|e| err(&e))?;
let mut zip = zip::ZipWriter::new(file.as_file_mut());
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))?;
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
file.persist(to).map_err(|e| err(&e))?;
Ok(())
}
fn copy_resources(base: &Path, dir: &Path, to: &Path, cancel: &CancellationToken) -> IdeResult<usize> {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let Ok(entries) = fs::read_dir(dir) else { return Ok(0) };
let mut copied = 0;
for e in entries.flatten() {
let path = e.path();
let Ok(t) = e.file_type() else { continue };
if t.is_dir() {
// The output folder can sit inside a source root (`src` holding `classes`).
if path != to && !path.starts_with(to) {
copied += copy_resources(base, &path, to, cancel)?;
}
continue;
}
if !t.is_file() || path.extension().is_some_and(|x| x == "java") {
continue;
}
let target = to.join(path.strip_prefix(base).unwrap_or(&path));
if copy_file_if_changed(&path, &target)? {
copied += 1;
}
}
Ok(copied)
}
fn collect_resource_files(
base: &Path,
dir: &Path,
to: &Path,
excluded: &[PathBuf],
planned: &mut BTreeMap<PathBuf, PathBuf>,
cancel: &CancellationToken,
) -> IdeResult<()> {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
let Ok(entries) = fs::read_dir(dir) else { return Ok(()) };
for e in entries.flatten() {
let path = e.path();
let Ok(t) = e.file_type() else { continue };
if t.is_dir() {
if path != to && !path.starts_with(to) && !excluded.iter().any(|x| path.starts_with(x)) {
collect_resource_files(base, &path, to, excluded, planned, cancel)?;
}
continue;
}
if !t.is_file() || path.extension().is_some_and(|x| x == "java") {
continue;
}
let target = to.join(path.strip_prefix(base).unwrap_or(&path));
planned.insert(target, path);
}
Ok(())
}
/// Incrementally syncs non-`.java` resources into `to` and removes deleted resources recorded in `record`
/// without disturbing `.class` files in `to`.
fn sync_resources_recorded(
from: &[PathBuf],
to: &Path,
excluded: &[PathBuf],
record: &Path,
cancel: &CancellationToken,
) -> IdeResult<(usize, usize)> {
let mut planned = BTreeMap::new();
for dir in from {
collect_resource_files(dir, dir, to, excluded, &mut planned, cancel)?;
}
let mut copied = 0usize;
for (target, source) in &planned {
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
if copy_file_if_changed(source, target)? {
copied += 1;
}
}
let written: Vec<PathBuf> = planned.into_keys().collect();
let removed = replace_recorded(to, record, &written)?;
Ok((copied, removed))
}
/// Inputs for an incremental Project Structure Java build.
pub struct StructureBuildContext<'a> {
pub root: &'a Path,
pub ps: &'a ProjectStructureSettings,
pub roots: &'a StructureRoots,
pub jdk: &'a StructureJdk,
pub language_level: &'a str,
pub cache: &'a Path,
pub jar: &'a Path,
pub service: &'a crate::jbuild::JavaBuildService,
}
fn structure_javac_options(
out: &Path,
cp: &[PathBuf],
generated: &Path,
level: Option<u32>,
jdk_major: u32,
) -> Vec<String> {
let separator = if cfg!(windows) { ";" } else { ":" };
let classpath = std::iter::once(out.to_string_lossy().into_owned())
.chain(cp.iter().filter(|p| *p != out).map(|p| p.to_string_lossy().into_owned()))
.collect::<Vec<_>>()
.join(separator);
let mut args = vec![
"-d".into(),
out.to_string_lossy().into_owned(),
"-classpath".into(),
classpath,
"-sourcepath".into(),
String::new(),
"-s".into(),
generated.to_string_lossy().into_owned(),
"-encoding".into(),
"UTF-8".into(),
"-g".into(),
];
args.extend(single::release_args(level, Some(jdk_major)));
args
}
fn collect_structure_sources(dirs: &[PathBuf], excluded: &[PathBuf]) -> Vec<PathBuf> {
let mut out = Vec::new();
for dir in dirs {
java_files(dir, excluded, &mut out);
}
out.sort();
out.dedup();
out
}
fn finish_structure_result(title: String, success: bool, started: Instant, messages: Vec<BuildMessage>) -> BuildResult {
let errors = messages.iter().filter(|m| m.severity == Severity::Error).count() as u32;
let warnings = messages.iter().filter(|m| m.severity == Severity::Warning).count() as u32;
BuildResult {
system: BuildSystem::Javac,
title,
success,
errors,
warnings,
duration_ms: started.elapsed().as_secs_f64() * 1000.0,
messages,
}
}
#[allow(clippy::too_many_arguments)]
fn build_structure_set(
ctx: &StructureBuildContext<'_>,
set_name: &'static str,
sources: Vec<PathBuf>,
out: &Path,
cp: &[PathBuf],
upstream_states: Vec<(PathBuf, PathBuf)>,
level: Option<u32>,
state_file: &Path,
generated_dir: &Path,
res_dirs: &[PathBuf],
res_record: &Path,
clean: bool,
cancel: &CancellationToken,
on_event: &(dyn Fn(BuildEvent) + Sync),
messages: &mut Vec<BuildMessage>,
any_work: &mut bool,
) -> IdeResult<bool> {
if !sources.is_empty() || state_file.is_file() {
let options = structure_javac_options(out, cp, generated_dir, level, ctx.jdk.major);
let libraries: Vec<PathBuf> =
cp.iter().filter(|e| *e != out && !upstream_states.iter().any(|(u, _)| u == *e)).cloned().collect();
let force = BTreeSet::new();
let set = crate::jbuild::IncrementalSet {
module_name: module_name(ctx.root),
set_name,
cwd: ctx.root.to_path_buf(),
sources,
output: out.to_path_buf(),
options,
libraries,
upstream_states,
processor_path: Vec::new(),
java_home: ctx.jdk.home.clone(),
jvm_args: Vec::new(),
encoding: Some("UTF-8"),
state_file: state_file.to_path_buf(),
generated_dir: generated_dir.to_path_buf(),
force: &force,
jar: ctx.jar,
clean,
};
let outcome = ctx.service.compile_incremental(&set, cancel, on_event, messages)?;
if outcome.compiled_files > 0 || outcome.outputs_changed {
*any_work = true;
}
if outcome.failed {
return Ok(false);
}
}
let (copied, removed) = sync_resources_recorded(res_dirs, out, &ctx.roots.excluded, res_record, cancel)?;
if copied > 0 || removed > 0 {
*any_work = true;
let action = Action::CopyResources { from: res_dirs.to_vec(), to: out.to_path_buf() };
on_event(BuildEvent::Step { command: action.display(ctx.root), cwd: ctx.root.to_path_buf().into() });
let text = match (copied, removed) {
(c, 0) => format!("{c} resource file(s) copied\n"),
(0, r) => format!("{r} resource file(s) removed\n"),
(c, r) => format!("{c} resource file(s) copied, {r} removed\n"),
};
on_event(BuildEvent::Output { text, stderr: false });
}
Ok(true)
}
fn run_action_steps(
steps: &[BuildStep],
cancel: &CancellationToken,
on_event: &(dyn Fn(BuildEvent) + Sync),
messages: &mut Vec<BuildMessage>,
any_work: &mut bool,
) -> IdeResult<bool> {
for step in steps {
let Some((action, command)) = &step.action else { continue };
on_event(BuildEvent::Step { command: command.clone(), cwd: step.cwd.clone().into() });
on_event(BuildEvent::Progress { message: command.clone(), fraction: None });
match action.run(cancel) {
Ok(text) => {
if text != "Up to date" && !text.ends_with(" is up to date") {
*any_work = true;
}
if !text.is_empty() {
on_event(BuildEvent::Output { text: format!("{text}\n"), stderr: false });
}
}
Err(e) if e.kind == ide_core::error::ErrorKind::Cancelled => return Err(e),
Err(e) => {
let m = BuildMessage {
severity: Severity::Error,
text: e.message.clone(),
path: None,
range: None,
code: None,
};
on_event(BuildEvent::Output { text: format!("{}\n", e.message), stderr: true });
on_event(BuildEvent::Message { message: m.clone() });
messages.push(m);
return Ok(false);
}
}
}
Ok(true)
}
/// Incremental Build / Rebuild / Build Artifacts of a Project Structure project using the
/// resident `javac` server and incremental artifact layout. Returns `None` when there are
/// no Java sources and no prior incremental compilation state.
pub fn structure_build(
ctx: &StructureBuildContext<'_>,
kind: BuildKind,
cancel: &CancellationToken,
on_event: &(dyn Fn(BuildEvent) + Sync),
) -> IdeResult<Option<BuildResult>> {
let started = Instant::now();
let state_root = ctx.cache.join("structure-build");
let main_state = state_root.join("state/main-compile.json");
let test_state = state_root.join("state/test-compile.json");
let main_sources = collect_structure_sources(&ctx.roots.sources, &ctx.roots.excluded);
let test_sources = collect_structure_sources(&ctx.roots.tests, &ctx.roots.excluded);
if main_sources.is_empty() && test_sources.is_empty() && !main_state.is_file() && !test_state.is_file() {
return Ok(None);
}
if kind == BuildKind::Artifacts && ctx.ps.artifacts.is_empty() {
return Err(IdeError::invalid("No artifacts are configured: add one in Project Structure › Artifacts"));
}
let lock = ctx.service.lock(&state_root);
let _guard = lock.lock().unwrap();
let title = module_name(ctx.root);
on_event(BuildEvent::Started { system: BuildSystem::Javac, title: title.clone() });
let (main_out, test_out) = structure_outputs(ctx.root, ctx.ps);
let main_gen = state_root.join("generated/main");
let test_gen = state_root.join("generated/test");
let main_res = state_root.join("state/main-resources.files");
let test_res = state_root.join("state/test-resources.files");
let mut messages = Vec::new();
let mut any_work = false;
let clean = kind == BuildKind::Rebuild;
if clean {
let dirs: Vec<PathBuf> =
[&main_out, &test_out].into_iter().filter(|d| deletable_output(d, ctx.root, ctx.roots)).cloned().collect();
if !dirs.is_empty() {
let clean_step = BuildStep::action(Action::Clean(dirs), ctx.root);
if !run_action_steps(&[clean_step], cancel, on_event, &mut messages, &mut any_work)? {
return Ok(Some(finish_structure_result(title, false, started, messages)));
}
}
for path in [&main_state, &test_state, &main_res, &test_res] {
let _ = fs::remove_file(path);
}
for dir in [&main_gen, &test_gen] {
let _ = fs::remove_dir_all(dir);
}
any_work = true;
}
let level = structure_language_level(ctx.root, ctx.ps, ctx.language_level);
let main_libs = library_paths(ctx.root, ctx.ps, false);
let main_res_dirs: Vec<PathBuf> = ctx.roots.sources.iter().chain(&ctx.roots.resources).cloned().collect();
if !build_structure_set(
ctx,
"main",
main_sources,
&main_out,
&main_libs,
Vec::new(),
level,
&main_state,
&main_gen,
&main_res_dirs,
&main_res,
clean,
cancel,
on_event,
&mut messages,
&mut any_work,
)? {
return Ok(Some(finish_structure_result(title, false, started, messages)));
}
if kind != BuildKind::Artifacts && (!test_sources.is_empty() || test_state.is_file()) {
let mut test_cp = vec![main_out.clone()];
for entry in library_paths(ctx.root, ctx.ps, true) {
if !test_cp.contains(&entry) {
test_cp.push(entry);
}
}
let test_res_dirs: Vec<PathBuf> = ctx.roots.tests.iter().chain(&ctx.roots.test_resources).cloned().collect();
if !build_structure_set(
ctx,
"tests",
test_sources,
&test_out,
&test_cp,
vec![(main_out.clone(), main_state.clone())],
level,
&test_state,
&test_gen,
&test_res_dirs,
&test_res,
clean,
cancel,
on_event,
&mut messages,
&mut any_work,
)? {
return Ok(Some(finish_structure_result(title, false, started, messages)));
}
}
if kind == BuildKind::Artifacts {
let mut steps = Vec::new();
for artifact in &ctx.ps.artifacts {
steps.extend(artifact_steps(ctx.root, ctx.ps, artifact, &main_out, None, ctx.cache));
}
if !run_action_steps(&steps, cancel, on_event, &mut messages, &mut any_work)? {
return Ok(Some(finish_structure_result(title, false, started, messages)));
}
}
if !any_work {
on_event(BuildEvent::Output { text: "Up to date: no changes.\n".into(), stderr: false });
}
Ok(Some(finish_structure_result(title, true, started, messages)))
}
/// Incremental build of one Project Structure WAR artifact for Tomcat deployment.
pub fn structure_build_war(
ctx: &StructureBuildContext<'_>,
artifact: &ArtifactConfig,
war: Option<&Path>,
cancel: &CancellationToken,
on_event: &(dyn Fn(BuildEvent) + Sync),
) -> IdeResult<BuildResult> {
let started = Instant::now();
let state_root = ctx.cache.join("structure-build");
let lock = ctx.service.lock(&state_root);
let _guard = lock.lock().unwrap();
let title = artifact.name.clone();
on_event(BuildEvent::Started { system: BuildSystem::Javac, title: title.clone() });
let (main_out, _) = structure_outputs(ctx.root, ctx.ps);
let main_state = state_root.join("state/main-compile.json");
let main_gen = state_root.join("generated/main");
let main_res = state_root.join("state/main-resources.files");
let main_sources = collect_structure_sources(&ctx.roots.sources, &ctx.roots.excluded);
let level = structure_language_level(ctx.root, ctx.ps, ctx.language_level);
let main_libs = library_paths(ctx.root, ctx.ps, false);
let main_res_dirs: Vec<PathBuf> = ctx.roots.sources.iter().chain(&ctx.roots.resources).cloned().collect();
let mut messages = Vec::new();
let mut any_work = false;
if !build_structure_set(
ctx,
"main",
main_sources,
&main_out,
&main_libs,
Vec::new(),
level,
&main_state,
&main_gen,
&main_res_dirs,
&main_res,
false,
cancel,
on_event,
&mut messages,
&mut any_work,
)? {
return Ok(finish_structure_result(title, false, started, messages));
}
let steps = artifact_steps(ctx.root, ctx.ps, artifact, &main_out, war, ctx.cache);
let ok = run_action_steps(&steps, cancel, on_event, &mut messages, &mut any_work)?;
Ok(finish_structure_result(title, ok, started, messages))
}
#[cfg(test)]
mod tests {
use super::*;
use ide_core::settings::{FacetConfig, ModuleDependency, ProjectLibrary};
fn write(path: &Path, text: &str) {
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, text).unwrap();
}
#[test]
fn archive_reuse_checks_copied_bytes_and_the_archive() {
use std::io::Read;
let tmp = tempfile::tempdir().unwrap();
let source = tmp.path().join("input.txt");
let staged = tmp.path().join("staging/input.txt");
let output = tmp.path().join("output.war");
let cancel = CancellationToken::new();
let action = Action::Archive {
from: staged.parent().unwrap().to_path_buf(),
to: output.clone(),
manifest: None,
stamp: Some(tmp.path().join("archive.stamp")),
};
let archived = || {
let mut zip = zip::ZipArchive::new(fs::File::open(&output).unwrap()).unwrap();
let mut text = String::new();
zip.by_name("input.txt").unwrap().read_to_string(&mut text).unwrap();
text
};
write(&source, "old");
assert!(copy_file_if_changed(&source, &staged).unwrap());
action.run(&cancel).unwrap();
assert_eq!(archived(), "old");
let modified = fs::metadata(&source).unwrap().modified().unwrap();
write(&source, "new");
fs::File::options().write(true).open(&source).unwrap().set_modified(modified).unwrap();
assert!(copy_file_if_changed(&source, &staged).unwrap());
action.run(&cancel).unwrap();
assert_eq!(archived(), "new");
write(&output, "replaced externally");
action.run(&cancel).unwrap();
assert_eq!(archived(), "new");
assert!(action.run(&cancel).unwrap().ends_with("is up to date"));
}
#[test]
fn reads_language_levels() {
assert_eq!(language_release("17"), Some(17));
assert_eq!(language_release("1.8"), Some(8));
assert_eq!(language_release("JDK_11"), Some(11));
assert_eq!(language_release(""), None);
}
#[test]
fn plans_javac_over_source_roots_with_libraries_and_web_lib() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("shop");
write(&root.join("src/com/a/A.java"), "package com.a; class A {}");
write(&root.join("src/com/a/app.properties"), "x=1");
write(&root.join("test/com/a/ATest.java"), "package com.a; class ATest {}");
write(&root.join("WebRoot/WEB-INF/web.xml"), "<web-app/>");
write(&root.join("WebRoot/WEB-INF/lib/x.jar"), "");
let ps = ProjectStructureSettings {
libraries: vec![
ProjectLibrary { name: "tools".into(), classes: vec!["lib/*.jar".into()], ..Default::default() },
ProjectLibrary {
name: "junit".into(),
classes: vec!["junit.jar".into()],
scope: DependencyScope::Test,
..Default::default()
},
],
facets: vec![FacetConfig {
kind: "web".into(),
module: ".".into(),
descriptor: "WebRoot/WEB-INF/web.xml".into(),
web_root: String::new(),
}],
..Default::default()
};
let roots =
StructureRoots { sources: vec![root.join("src")], tests: vec![root.join("test")], ..Default::default() };
let jdk = StructureJdk { home: PathBuf::from("/jdk"), major: 21 };
let plan = structure_plan(&root, &ps, &roots, Some(&jdk), "17", BuildKind::Rebuild, &tmp.path().join("cache"))
.unwrap()
.unwrap();
assert_eq!(plan.system, BuildSystem::Javac);
let shown: Vec<String> = plan.steps.iter().map(BuildStep::display).collect();
assert_eq!(shown[0], "Clean out/production/shop, out/test/shop");
let javac = &plan.steps[1];
let cp = |s: &BuildStep| s.args[s.args.iter().position(|a| a == "-cp").unwrap() + 1].clone();
let sep = if cfg!(windows) { ";" } else { ":" };
let main_cp = cp(javac);
let entries: Vec<&str> = main_cp.split(sep).collect();
assert_eq!(entries.len(), 2, "{main_cp}");
assert!(Path::new(entries[0]).ends_with("lib/*"));
assert!(Path::new(entries[1]).ends_with("WEB-INF/lib/*"));
assert!(javac.args.windows(2).any(|w| w == ["--release", "17"]));
let args = fs::read_to_string(tmp.path().join("cache/javac/production.args")).unwrap();
assert!(args.contains("A.java") && !args.contains("ATest.java"));
assert_eq!(shown[2], "Copy resources to out/production/shop");
let test = &plan.steps[3];
let test_cp = cp(test);
assert_eq!(Path::new(test_cp.split(sep).next().unwrap()), root.join("out/production/shop"));
assert!(test_cp.contains("junit.jar"));
}
#[test]
fn a_module_dependency_gives_its_library_a_scope_and_jdk_8_gets_source_and_target() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("p");
write(&root.join("src/A.java"), "class A {}");
let mut ps = ProjectStructureSettings {
libraries: vec![ProjectLibrary {
name: "junit".into(),
classes: vec!["junit.jar".into()],
..Default::default()
}],
compiler_output: "build/classes".into(),
..Default::default()
};
ps.modules.insert(
".".into(),
ModuleStructureSettings {
language_level: "1.8".into(),
dependencies: vec![ModuleDependency {
kind: "library".into(),
target: "junit".into(),
scope: DependencyScope::Test,
exported: false,
}],
..Default::default()
},
);
let roots = StructureRoots { sources: vec![root.join("src")], ..Default::default() };
let jdk = StructureJdk { home: PathBuf::from("/jdk8"), major: 8 };
let plan = structure_plan(&root, &ps, &roots, Some(&jdk), "21", BuildKind::Build, &tmp.path().join("c"))
.unwrap()
.unwrap();
let javac = &plan.steps[0];
assert!(!javac.args.iter().any(|a| a == "-cp"), "{:?}", javac.args);
assert!(javac.args.windows(4).any(|w| w == ["-source", "1.8", "-target", "1.8"]));
assert!(
javac.args.windows(2).any(|w| w[0] == "-d" && Path::new(&w[1]).ends_with("build/classes/production/p"))
);
}
#[test]
fn rebuild_never_cleans_an_output_folder_over_the_project_or_its_sources() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("p");
write(&root.join("src/A.java"), "class A {}");
let roots = StructureRoots { sources: vec![root.join("src")], ..Default::default() };
for (main, test) in [(".", "bin"), ("src", "src/../test-out"), ("src/classes", ".."), ("", "")] {
let mut ps = ProjectStructureSettings::default();
ps.modules.insert(
".".into(),
ModuleStructureSettings {
compiler_output: main.into(),
test_compiler_output: test.into(),
..Default::default()
},
);
let plan = structure_plan(&root, &ps, &roots, None, "17", BuildKind::Rebuild, &tmp.path().join("c"))
.unwrap()
.unwrap();
let clean: Vec<String> =
plan.steps.iter().map(BuildStep::display).filter(|s| s.starts_with("Clean")).collect();
let expected: &[&str] = match main {
"." => &["Clean bin"],
"src" => &["Clean src/../test-out"],
"src/classes" => &[],
_ => &["Clean out/production/p, out/test/p"],
};
assert_eq!(clean, expected, "{main} / {test}");
}
}
#[test]
fn no_plan_without_java_sources() {
let tmp = tempfile::tempdir().unwrap();
let roots = StructureRoots { sources: vec![tmp.path().join("src")], ..Default::default() };
let plan =
structure_plan(tmp.path(), &Default::default(), &roots, None, "", BuildKind::Build, &tmp.path().join("c"));
assert!(plan.unwrap().is_none());
}
#[test]
fn copies_resources_but_not_sources_and_skips_up_to_date_files() {
let tmp = tempfile::tempdir().unwrap();
let src = tmp.path().join("src");
write(&src.join("a/A.java"), "class A {}");
write(&src.join("a/x.xml"), "<x/>");
let out = tmp.path().join("out");
let action = Action::CopyResources { from: vec![src], to: out.clone() };
let cancel = CancellationToken::new();
assert_eq!(action.run(&cancel).unwrap(), "1 resource file(s) copied");
assert!(out.join("a/x.xml").is_file() && !out.join("a/A.java").exists());
assert_eq!(action.run(&cancel).unwrap(), "0 resource file(s) copied");
Action::Clean(vec![out.clone()]).run(&cancel).unwrap();
assert!(!out.exists());
}
fn entries(archive: &Path) -> Vec<String> {
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"), "<web-app/>");
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())],
record: None,
};
assert!(action.run(&CancellationToken::new()).is_err());
assert!(web.join("a.jsp").is_file());
}
#[test]
fn a_chosen_output_folder_keeps_what_the_artifact_did_not_put_there() {
let tmp = tempfile::tempdir().unwrap();
let project = tmp.path().join("project");
write(&project.join("src/A.java"), "class A {}");
write(&project.join(".git/HEAD"), "ref: refs/heads/main");
let libs = tmp.path().join("libs");
write(&libs.join("a.jar"), "a");
write(&libs.join("b.jar"), "b");
let record = tmp.path().join("cache/artifacts/app.files");
let layout = |names: &[&str]| Action::Layout {
into: project.clone(),
entries: names.iter().map(|n| (libs.join(n), PathBuf::from(n))).collect(),
record: Some(record.clone()),
};
layout(&["a.jar", "b.jar"]).run(&CancellationToken::new()).unwrap();
assert!(project.join("a.jar").is_file() && project.join("b.jar").is_file());
// A library dropped from the artifact goes; the project's own files stay.
layout(&["a.jar"]).run(&CancellationToken::new()).unwrap();
assert!(project.join("a.jar").is_file() && !project.join("b.jar").exists());
assert!(project.join("src/A.java").is_file() && project.join(".git/HEAD").is_file());
// A damaged record never reaches outside the folder.
write(&record, &format!("{}\n../outside.txt", project.display()));
write(&tmp.path().join("outside.txt"), "x");
layout(&["a.jar"]).run(&CancellationToken::new()).unwrap();
assert!(tmp.path().join("outside.txt").is_file());
// Nor through a folder of the output that now links elsewhere.
#[cfg(unix)]
{
write(&project.join("assets/x.txt"), "laid out");
write(&record, &format!("{}\nassets/x.txt", project.display()));
fs::remove_dir_all(project.join("assets")).unwrap();
std::os::unix::fs::symlink(project.join("src"), project.join("assets")).unwrap();
write(&project.join("src/x.txt"), "source");
layout(&["a.jar"]).run(&CancellationToken::new()).unwrap();
assert!(project.join("src/x.txt").is_file());
}
// An entry's own folder that links elsewhere stops the layout instead of copying through it.
#[cfg(unix)]
{
fs::remove_file(project.join("assets")).unwrap();
std::os::unix::fs::symlink(project.join("src"), project.join("classes")).unwrap();
write(&tmp.path().join("out/A.class"), "compiled");
let into_link = Action::Layout {
into: project.clone(),
entries: vec![(tmp.path().join("out"), PathBuf::from("classes"))],
record: Some(record.clone()),
};
assert!(into_link.run(&CancellationToken::new()).is_err());
assert!(!project.join("src/A.class").exists());
fs::remove_file(project.join("classes")).unwrap();
}
// Nor does one made for another output folder.
write(&project.join("c.jar"), "mine");
write(&record, "/elsewhere\nc.jar");
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| <ide_core::IpcPath as AsRef<Path>>::as_ref(p) == bad_target)
&& m.range.is_some_and(|r| r.start.line == 2)
}),
"messages={:?}",
bad_result.messages
);
}
#[test]
fn expands_jar_directory_libraries_for_javac_and_artifacts() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("app");
let cache = tmp.path().join("cache");
write(&root.join("src/A.java"), "class A {}");
write(&root.join("WebRoot/WEB-INF/lib/gson.jar"), "jar1");
write(&root.join("WebRoot/WEB-INF/lib/sub/extra.jar"), "jar2");
fs::create_dir_all(root.join("plain-classes")).unwrap();
write(&root.join("plain-classes/Helper.class"), "");
let ps = ProjectStructureSettings {
libraries: vec![
ProjectLibrary {
name: "web-libs".into(),
classes: vec!["WebRoot/WEB-INF/lib".into()],
..Default::default()
},
ProjectLibrary { name: "classes".into(), classes: vec!["plain-classes".into()], ..Default::default() },
],
artifacts: vec![ArtifactConfig {
name: "app:war exploded".into(),
kind: ArtifactKind::WarExploded,
module: ".".into(),
output_directory: "out/artifacts/app_war_exploded".into(),
main_class: String::new(),
include_libraries: vec!["web-libs".into()],
}],
..Default::default()
};
let roots = StructureRoots { sources: vec![root.join("src")], ..Default::default() };
let plan = structure_plan(&root, &ps, &roots, None, "17", BuildKind::Artifacts, &cache).unwrap().unwrap();
let javac = &plan.steps[0];
let cp = &javac.args[javac.args.iter().position(|a| a == "-cp").unwrap() + 1];
let sep = std::path::MAIN_SEPARATOR;
assert!(cp.contains(&format!("lib{sep}*")), "expected JAR dir wildcard in cp: {cp}");
assert!(cp.contains(&format!("sub{sep}*")), "expected nested JAR dir wildcard in cp: {cp}");
assert!(cp.contains("plain-classes") && !cp.contains(&format!("plain-classes{sep}*")), "cp={cp}");
let layout = plan.steps.iter().find_map(|s| match &s.action {
Some((Action::Layout { entries, .. }, _)) => Some(entries),
_ => None,
});
let entries = layout.expect("layout step");
assert!(entries.iter().any(|(_, to)| to == Path::new("WEB-INF/lib/gson.jar")), "{entries:?}");
assert!(entries.iter().any(|(_, to)| to == Path::new("WEB-INF/lib/extra.jar")), "{entries:?}");
assert!(!entries.iter().any(|(_, to)| to == Path::new("WEB-INF/lib/lib")), "{entries:?}");
}
const JAVA_BUILD_JAR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../../java/java-build/openidea-java-build.jar");
fn test_jdk() -> Option<StructureJdk> {
let home = std::env::var_os("JAVA_HOME").map(PathBuf::from).filter(|h| h.join("bin").is_dir())?;
let major = fs::read_to_string(home.join("release"))
.ok()
.and_then(|text| {
text.lines()
.find_map(|l| l.trim().strip_prefix("JAVA_VERSION="))
.map(|v| v.trim().trim_matches(['"', '\'']))
.and_then(language_release)
})
.unwrap_or(17);
Some(StructureJdk { home, major })
}
fn write_bumped(path: &Path, text: &str) {
let prev = fs::metadata(path).and_then(|m| m.modified()).ok();
write(path, text);
if let Some(prev_time) = prev
&& let Ok(file) = fs::OpenOptions::new().write(true).open(path)
{
let target = std::cmp::max(std::time::SystemTime::now(), prev_time + std::time::Duration::from_secs(2));
let _ = file.set_modified(target);
}
}
fn step_commands(events: &[BuildEvent]) -> Vec<String> {
events
.iter()
.filter_map(|e| match e {
BuildEvent::Step { command, .. } => Some(command.clone()),
_ => None,
})
.collect()
}
fn output_texts(events: &[BuildEvent]) -> Vec<String> {
events
.iter()
.filter_map(|e| match e {
BuildEvent::Output { text, .. } => Some(text.clone()),
_ => None,
})
.collect()
}
#[test]
fn structure_javac_options_supports_jdk8_and_modern_jdks() {
let out = Path::new("/tmp/out");
let generated = Path::new("/tmp/gen");
let opts8 = structure_javac_options(out, &[], generated, Some(8), 8);
assert!(opts8.windows(4).any(|w| w == ["-source", "1.8", "-target", "1.8"]), "{opts8:?}");
let opts21 = structure_javac_options(out, &[], generated, Some(17), 21);
assert!(opts21.windows(2).any(|w| w == ["--release", "17"]), "{opts21:?}");
}
#[test]
fn sync_resources_recorded_removes_deleted_resources_without_touching_classes() {
let tmp = tempfile::tempdir().unwrap();
let src = tmp.path().join("src");
let out = tmp.path().join("out");
let record = tmp.path().join("cache/res.files");
write(&out.join("com/a/A.class"), "classbytes");
write(&src.join("com/a/a.xml"), "<a/>");
write(&src.join("com/a/b.xml"), "<b/>");
write(&src.join("com/a/A.java"), "package com.a; class A {}");
let cancel = CancellationToken::new();
assert_eq!(sync_resources_recorded(std::slice::from_ref(&src), &out, &[], &record, &cancel).unwrap(), (2, 0));
assert!(out.join("com/a/a.xml").is_file());
assert!(out.join("com/a/b.xml").is_file());
assert!(out.join("com/a/A.class").is_file());
assert!(!out.join("com/a/A.java").exists());
assert_eq!(sync_resources_recorded(std::slice::from_ref(&src), &out, &[], &record, &cancel).unwrap(), (0, 0));
fs::remove_file(src.join("com/a/b.xml")).unwrap();
assert_eq!(sync_resources_recorded(std::slice::from_ref(&src), &out, &[], &record, &cancel).unwrap(), (0, 1));
assert!(out.join("com/a/a.xml").is_file());
assert!(!out.join("com/a/b.xml").exists());
assert!(out.join("com/a/A.class").is_file());
}
#[test]
fn layout_deduplicates_duplicate_targets_without_ping_pong() {
let tmp = tempfile::tempdir().unwrap();
let web = tmp.path().join("WebRoot");
let extra = tmp.path().join("extra");
let out = tmp.path().join("out/exploded");
let record = tmp.path().join("cache/exploded.files");
write(&web.join("WEB-INF/lib/x.jar"), "old");
write(&extra.join("x.jar"), "new");
let cancel = CancellationToken::new();
let action = Action::Layout {
into: out.clone(),
entries: vec![(web, PathBuf::new()), (extra.join("x.jar"), PathBuf::from("WEB-INF/lib/x.jar"))],
record: Some(record),
};
assert_eq!(action.run(&cancel).unwrap(), "1 file(s) updated");
assert_eq!(fs::read_to_string(out.join("WEB-INF/lib/x.jar")).unwrap(), "new");
assert_eq!(action.run(&cancel).unwrap(), "Up to date");
}
#[test]
fn incremental_structure_build_compiles_only_changed_and_affected_files() {
let Some(jdk) = test_jdk() else {
eprintln!("skipped: needs JAVA_HOME");
return;
};
let jar = Path::new(JAVA_BUILD_JAR);
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap().join("shop");
let cache = tmp.path().join("cache");
write(
&root.join("src/com/a/Base.java"),
"package com.a;\npublic class Base { public int m() { return 1; } }\n",
);
write(&root.join("src/com/a/Sub.java"), "package com.a;\npublic class Sub extends Base {}\n");
write(
&root.join("src/com/a/User.java"),
"package com.a;\npublic class User { int u(Sub s) { return s.m(); } }\n",
);
write(
&root.join("src/com/a/Const.java"),
"package com.a;\npublic class Const { public static final int X = 1; }\n",
);
write(
&root.join("src/com/a/ConstUser.java"),
"package com.a;\nclass ConstUser { int c() { return Const.X; } }\n",
);
write(
&root.join("src/com/a/Other.java"),
"package com.a;\npublic class Other { public int o() { return 1; } }\n",
);
write(
&root.join("test/com/a/BaseTest.java"),
"package com.a;\nclass BaseTest { int t(Sub s) { return s.m(); } }\n",
);
write(
&root.join("test/com/a/ConstTest.java"),
"package com.a;\nclass ConstTest { int t() { return Const.X; } }\n",
);
let ps = ProjectStructureSettings::default();
let roots =
StructureRoots { sources: vec![root.join("src")], tests: vec![root.join("test")], ..Default::default() };
let service = crate::jbuild::JavaBuildService::default();
let level = jdk.major.min(17).to_string();
let ctx = StructureBuildContext {
root: &root,
ps: &ps,
roots: &roots,
jdk: &jdk,
language_level: &level,
cache: &cache,
jar,
service: &service,
};
let cancel = CancellationToken::new();
let run_kind = |kind| {
let events = std::sync::Mutex::new(Vec::new());
let res = structure_build(&ctx, kind, &cancel, &|e| events.lock().unwrap().push(e)).unwrap().unwrap();
assert!(res.success, "{:?}", res.messages);
events.into_inner().unwrap()
};
// 1. Cold build compiles all main and test files.
let steps = step_commands(&run_kind(BuildKind::Build));
assert_eq!(steps, ["javac shop (main, 6 files)", "javac shop (tests, 2 files)"]);
// 2. Unchanged build runs 0 javac invocations.
let evs = run_kind(BuildKind::Build);
assert_eq!(step_commands(&evs), Vec::<String>::new());
assert!(output_texts(&evs).iter().any(|t| t.contains("Up to date")));
// 3. Body-only change compiles only that single file, and skips tests.
write_bumped(
&root.join("src/com/a/Other.java"),
"package com.a;\npublic class Other { public int o() { return 2; } }\n",
);
assert_eq!(step_commands(&run_kind(BuildKind::Build)), ["javac shop (main, 1 of 6 files)"]);
// 4. API change in Base cascades to Sub/User and dependent BaseTest.
write_bumped(
&root.join("src/com/a/Base.java"),
"package com.a;\npublic class Base { public int m() { return 1; } public int n() { return 2; } }\n",
);
assert_eq!(
step_commands(&run_kind(BuildKind::Build)),
["javac shop (main, 1 of 6 files)", "javac shop (main, 2 of 6 files)", "javac shop (tests, 1 of 2 files)",]
);
// 5. Constant change recompiles the rest of main and all tests.
write_bumped(
&root.join("src/com/a/Const.java"),
"package com.a;\npublic class Const { public static final int X = 2; }\n",
);
assert_eq!(
step_commands(&run_kind(BuildKind::Build)),
["javac shop (main, 1 of 6 files)", "javac shop (main, 5 of 6 files)", "javac shop (tests, 2 files)",]
);
// 6. Deleting an unreferenced source removes its .class without running javac.
fs::remove_file(root.join("src/com/a/Other.java")).unwrap();
assert_eq!(step_commands(&run_kind(BuildKind::Build)), Vec::<String>::new());
assert!(!root.join("out/production/shop/com/a/Other.class").exists());
// 7. Rebuild cleans outputs and recompiles everything.
let steps = step_commands(&run_kind(BuildKind::Rebuild));
assert_eq!(
steps,
["Clean out/production/shop, out/test/shop", "javac shop (main, 5 files)", "javac shop (tests, 2 files)",]
);
}
fn write_jar(path: &Path) {
fs::create_dir_all(path.parent().unwrap()).unwrap();
let zip = zip::ZipWriter::new(fs::File::create(path).unwrap());
zip.finish().unwrap();
}
#[test]
fn incremental_structure_war_syncs_only_changed_files_and_skips_unchanged() {
let Some(jdk) = test_jdk() else {
eprintln!("skipped: needs JAVA_HOME");
return;
};
let jar = Path::new(JAVA_BUILD_JAR);
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap().join("webapp");
let cache = tmp.path().join("cache");
write(&root.join("src/com/a/A.java"), "package com.a;\npublic class A { public int v() { return 1; } }\n");
write(&root.join("src/com/a/B.java"), "package com.a;\npublic class B {}\n");
write(&root.join("WebRoot/WEB-INF/web.xml"), "<web-app/>");
write(&root.join("WebRoot/index.jsp"), "<h1>v1</h1>");
write_jar(&root.join("WebRoot/WEB-INF/lib/inside.jar"));
write_jar(&root.join("lib/extra.jar"));
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: "WebRoot".into(),
}],
artifacts: vec![
ArtifactConfig {
name: "webapp:war exploded".into(),
kind: ArtifactKind::WarExploded,
module: ".".into(),
output_directory: "out/artifacts/webapp_war_exploded".into(),
include_libraries: vec!["extra".into()],
..Default::default()
},
ArtifactConfig {
name: "webapp:war".into(),
kind: ArtifactKind::War,
module: ".".into(),
output_directory: "out/artifacts/webapp_war".into(),
include_libraries: vec!["extra".into()],
..Default::default()
},
],
..Default::default()
};
let roots = StructureRoots { sources: vec![root.join("src")], ..Default::default() };
let service = crate::jbuild::JavaBuildService::default();
let level = jdk.major.min(17).to_string();
let ctx = StructureBuildContext {
root: &root,
ps: &ps,
roots: &roots,
jdk: &jdk,
language_level: &level,
cache: &cache,
jar,
service: &service,
};
let cancel = CancellationToken::new();
let run_war = |idx: usize| {
let events = std::sync::Mutex::new(Vec::new());
let res = structure_build_war(&ctx, &ps.artifacts[idx], None, &cancel, &|e| events.lock().unwrap().push(e))
.unwrap();
assert!(res.success, "{:?}", res.messages);
events.into_inner().unwrap()
};
// 1. Initial WarExploded build compiles both classes and lays out the exploded artifact.
let evs1 = run_war(0);
assert_eq!(step_commands(&evs1), ["javac webapp (main, 2 files)", "Lay out out/artifacts/webapp_war_exploded"]);
let exploded = root.join("out/artifacts/webapp_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 jsp_stamp = file_stamp(&exploded.join("index.jsp")).unwrap();
// 2. Unchanged WarExploded build runs 0 javac and skips copying.
let evs2 = run_war(0);
assert_eq!(step_commands(&evs2), ["Lay out out/artifacts/webapp_war_exploded"]);
assert!(output_texts(&evs2).iter().any(|t| t == "Up to date\n"), "{:?}", output_texts(&evs2));
assert_eq!(file_stamp(&exploded.join("index.jsp")).unwrap(), jsp_stamp);
// 3. Single Java edit compiles 1 of 2 files and updates only 1 class in exploded artifact.
write_bumped(
&root.join("src/com/a/A.java"),
"package com.a;\npublic class A { public int v() { return 2; } }\n",
);
let evs3 = run_war(0);
assert_eq!(
step_commands(&evs3),
["javac webapp (main, 1 of 2 files)", "Lay out out/artifacts/webapp_war_exploded"]
);
assert!(output_texts(&evs3).iter().any(|t| t == "1 file(s) updated\n"), "{:?}", output_texts(&evs3));
assert_eq!(file_stamp(&exploded.join("index.jsp")).unwrap(), jsp_stamp);
// 4. Web JSP edit runs 0 javac and updates only index.jsp.
write_bumped(&root.join("WebRoot/index.jsp"), "<h1>v2</h1>");
let evs4 = run_war(0);
assert_eq!(step_commands(&evs4), ["Lay out out/artifacts/webapp_war_exploded"]);
assert!(output_texts(&evs4).iter().any(|t| t == "1 file(s) updated\n"), "{:?}", output_texts(&evs4));
assert_eq!(fs::read_to_string(exploded.join("index.jsp")).unwrap(), "<h1>v2</h1>");
// 5. Deleting B.java and index.jsp removes stale files from output and exploded dir.
fs::remove_file(root.join("src/com/a/B.java")).unwrap();
fs::remove_file(root.join("WebRoot/index.jsp")).unwrap();
let evs5 = run_war(0);
assert_eq!(step_commands(&evs5), ["Lay out out/artifacts/webapp_war_exploded"]);
assert!(!root.join("out/production/webapp/com/a/B.class").exists());
assert!(!exploded.join("WEB-INF/classes/com/a/B.class").exists());
assert!(!exploded.join("index.jsp").exists());
// 6. Adding a jar in WEB-INF/lib invalidates library stamp and recompiles.
write_jar(&root.join("WebRoot/WEB-INF/lib/added.jar"));
let evs6 = run_war(0);
assert_eq!(step_commands(&evs6), ["javac webapp (main, 1 file)", "Lay out out/artifacts/webapp_war_exploded"]);
assert!(exploded.join("WEB-INF/lib/added.jar").is_file());
// 7. Packed WAR skips archive step when inputs are unchanged, and repacks when A.java changes.
let war_evs1 = run_war(1);
assert!(output_texts(&war_evs1).iter().any(|t| t.starts_with("Wrote ")), "{:?}", output_texts(&war_evs1));
let war_evs2 = run_war(1);
assert!(
output_texts(&war_evs2).iter().any(|t| t.ends_with(" is up to date\n")),
"{:?}",
output_texts(&war_evs2)
);
write_bumped(
&root.join("src/com/a/A.java"),
"package com.a;\npublic class A { public int v() { return 3; } }\n",
);
let war_evs3 = run_war(1);
assert!(output_texts(&war_evs3).iter().any(|t| t.starts_with("Wrote ")), "{:?}", output_texts(&war_evs3));
}
}