дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-04 17:21:13 +02:00
feat(java): build Maven and Gradle modules with a resident, incremental javac build service (#5854)
Implements #4078 steps 2–4: an IDE-owned Java build service that compiles Maven and Gradle modules with a resident javac, class by class, for launches and the Build menu. ## What changes - **Model.** The build tool records each project's source roots, compile/runtime classpaths, resources and the compiler configuration it actually uses (release/source/target, encoding, `-parameters`, debug level, `proc`, compiler args, includes/excludes, resolved annotation processor path): - Maven: a core extension (`java/java-build`, `BuildModel`) during `process-resources resources:testResources`. - Gradle: an init script (`gradle-build.init.gradle`) with an `openideaBuildModel` task that runs source generators and `processResources`. The prepare run happens only when what the model is built from changes: build scripts, settings, toolchains, the launcher, the JDK, generator inputs (`src/*/proto`, `antlr4`…), or a generated root that is gone. - **Outputs.** Every project writes to `<cache>/java-build/<build>/out/<group>.<name>/classes|test-classes`, and dependencies on other projects of the build resolve to those folders. jdtls and a terminal `mvn`/`gradle` never write the classes a launch runs. - **Compile.** A resident javac process per JDK (and `.mvn/jvm.config`) compiles source sets in dependency order, without `-am` or the full lifecycle. - **Class-level incremental compilation.** Each source set records, per class: its source, supertypes, the classes its constant pool references, and fingerprints of its API and compile-time constants (read from the class files, private and synthetic members excluded). - A build compiles the changed sources. - It then compiles, round after round, the sources of classes that reference a class whose API changed (or one of its subclasses), and the sources a new class could shadow. - Downstream sets follow an API change log. - A changed constant recompiles the set and everything compiled against it. - Sources a failed compile left behind stay dirty. - Sets whose annotation processors aggregate compile from scratch. - **Build menu.** - Build Project and Build Module compile with the service. - Recompile compiles the file with the service and publishes javac's diagnostics. - **Events.** Steps, positioned javac diagnostics and progress stream on the `BuildEvent` channel from #5801. - **When it applies.** - Maven modules, unless Settings › Maven › *Delegate IDE build/run actions to Maven* is on. - Gradle modules when Settings › Gradle › *Build and run using* is the IDE. - Debug launches keep jdtls' build, because java-debug's HotSwap reloads what jdtls compiles. - jdtls keeps autobuild on: cross-module diagnostics depend on it (verified with a real jdtls, see the ignored test below). - **Fallback.** These go to the build tool's own build: - modules that need it: another compiler (Kotlin, Groovy, AspectJ…), a non-javac compiler id, multi-release output, Java modules, unresolvable dependencies or processor paths, composite Gradle builds; - a failed prepare run. The javac server and the Maven extension are built reproducibly with `--release 8` against Maven 3.9.11 (`java/java-build/build.py`, dependencies pinned) and embedded by `ide-sdk`. ## Tests - `ide-build` `jbuild::tests`, run against a real Maven/Gradle and JDK (skipped when missing): - first build, no-op build, only changed files recompile; - API changes reach dependents, including through subclasses and across modules; - constant changes recompile dependents; - resource changes run only the resources step; - deleted sources, compile errors with positions, the test source set; - Recompile and Build Project; - Gradle projects; - fallback for Gradle projects with other compilers; - plus class-file parsing, the API change log, javac options and Ant patterns. - `ide-host` `tests/java_build.rs`: Maven and Gradle launches through `java_resolve_launch` compile with javac into the IDE's outputs, and Build Project reports javac's errors. - `tests/workspaces.rs`: a Maven that writes no build model falls back to `mvn -pl app -am`. - `ide-lsp` (ignored, needs jdtls): jdtls reports cross-module errors in open and closed files with autobuild on.
Цей коміт міститься в:
1 джерело
e5c5915f2e
коміт
536f85b9df
35 files changed
+5040
-50
No files matched your search
@@ -6,7 +6,7 @@ use std::io::Read;
|
||||
use std::time::SystemTime;
|
||||
|
||||
/// `(byte length, mtime, blake3 hex)`; the hash is recorded for files inside the project only.
|
||||
type Stamp = (u64, SystemTime, Option<String>);
|
||||
pub(crate) type Stamp = (u64, SystemTime, Option<String>);
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct LaunchFingerprint {
|
||||
@@ -182,7 +182,7 @@ fn collect(
|
||||
}
|
||||
|
||||
/// Scans every input, storing project inputs relative to the project.
|
||||
pub(super) fn scan_all(
|
||||
pub(crate) fn scan_all(
|
||||
root: &Path,
|
||||
inputs: Vec<PathBuf>,
|
||||
cancel: &CancellationToken,
|
||||
@@ -282,6 +282,11 @@ pub(super) fn module_fingerprint(
|
||||
}
|
||||
|
||||
impl LaunchFingerprint {
|
||||
/// The fingerprint of `parameters` and the files under `inputs` (see [`scan_all`]).
|
||||
pub(crate) fn new(parameters: String, files: BTreeMap<PathBuf, Option<Stamp>>) -> Self {
|
||||
LaunchFingerprint { version: 2, parameters, files }
|
||||
}
|
||||
|
||||
/// Folders (relative to the project) of the Maven projects whose POM is an input.
|
||||
pub(super) fn project_dirs(&self) -> impl Iterator<Item = &Path> {
|
||||
self.files
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! background with cancellation and parses the compiler output into messages
|
||||
//! for the Build tool window, the Problems view and the editor.
|
||||
|
||||
mod fingerprint;
|
||||
pub(crate) mod fingerprint;
|
||||
mod launch_resources;
|
||||
mod modules;
|
||||
mod parse;
|
||||
@@ -845,6 +845,28 @@ fn reactor_projects<'a>(m: &'a maven::MavenModel, top: &'a maven::MavenProject)
|
||||
projects
|
||||
}
|
||||
|
||||
/// A step running Maven, its output parsed as Maven's.
|
||||
pub(crate) fn maven_build_step(program: &str, args: &[&str], cwd: &Path) -> BuildStep {
|
||||
BuildStep::new(program, args, cwd, Format::Maven)
|
||||
}
|
||||
|
||||
pub(crate) fn gradle_build_step(program: &str, args: &[&str], cwd: &Path) -> BuildStep {
|
||||
BuildStep::new(program, args, cwd, Format::Gradle)
|
||||
}
|
||||
|
||||
/// The linked reactor root building the project at `module` (project-relative).
|
||||
pub(crate) fn maven_reactor_dir<'a>(m: &'a maven::MavenModel, module: &str) -> Option<&'a maven::MavenProject> {
|
||||
maven_reactor(m, module)
|
||||
}
|
||||
|
||||
/// The projects of the reactor `top`.
|
||||
pub(crate) fn reactor_projects_of<'a>(
|
||||
m: &'a maven::MavenModel,
|
||||
top: &'a maven::MavenProject,
|
||||
) -> Vec<&'a maven::MavenProject> {
|
||||
reactor_projects(m, top)
|
||||
}
|
||||
|
||||
fn maven_reactor<'a>(m: &'a maven::MavenModel, module: &str) -> Option<&'a maven::MavenProject> {
|
||||
m.projects.iter().filter(|p| !p.aggregated).find(|top| reactor_projects(m, top).iter().any(|p| p.dir == module))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,482 @@
|
||||
//! What the incremental build needs from a class file (JVMS §4): its name, supertypes, the
|
||||
//! classes its constant pool refers to, and fingerprints of its API and of its compile-time
|
||||
//! constants. Bounds-checked: a malformed file is `None`, never a panic.
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
/// A class file, as the dependency graph and the API diff see it.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ClassFile {
|
||||
/// Internal name (`com/acme/Order$Line`).
|
||||
pub name: String,
|
||||
pub super_name: Option<String>,
|
||||
pub interfaces: Vec<String>,
|
||||
/// Classes named in the constant pool: references, descriptors, signatures, annotation types.
|
||||
pub refs: BTreeSet<String>,
|
||||
/// What other classes compile against: non-private, non-synthetic members and their
|
||||
/// signatures, supertypes, nested classes, permitted subclasses, record components.
|
||||
pub api: u64,
|
||||
/// The compile-time constants (`static final` fields with a `ConstantValue`), which javac
|
||||
/// copies into the classes that use them: a change can't be traced through references.
|
||||
pub constants: u64,
|
||||
}
|
||||
|
||||
const ACC_PRIVATE: u16 = 0x0002;
|
||||
const ACC_SYNTHETIC: u16 = 0x1000;
|
||||
|
||||
struct Bytes<'a> {
|
||||
data: &'a [u8],
|
||||
pos: usize,
|
||||
}
|
||||
|
||||
impl<'a> Bytes<'a> {
|
||||
fn take(&mut self, n: usize) -> Option<&'a [u8]> {
|
||||
let end = self.pos.checked_add(n)?;
|
||||
let slice = self.data.get(self.pos..end)?;
|
||||
self.pos = end;
|
||||
Some(slice)
|
||||
}
|
||||
fn u1(&mut self) -> Option<u8> {
|
||||
Some(self.take(1)?[0])
|
||||
}
|
||||
fn u2(&mut self) -> Option<u16> {
|
||||
let b = self.take(2)?;
|
||||
Some(u16::from_be_bytes([b[0], b[1]]))
|
||||
}
|
||||
fn u4(&mut self) -> Option<u32> {
|
||||
let b = self.take(4)?;
|
||||
Some(u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
enum Entry {
|
||||
Empty,
|
||||
Utf8(String),
|
||||
Class(u16),
|
||||
String(u16),
|
||||
/// Integer, float, long, double: the raw bytes.
|
||||
Number(Vec<u8>),
|
||||
NameAndType(u16),
|
||||
MethodType(u16),
|
||||
Other,
|
||||
}
|
||||
|
||||
struct Pool(Vec<Entry>);
|
||||
|
||||
impl Pool {
|
||||
fn utf8(&self, index: u16) -> Option<&str> {
|
||||
match self.0.get(index as usize)? {
|
||||
Entry::Utf8(s) => Some(s),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
fn class(&self, index: u16) -> Option<&str> {
|
||||
match self.0.get(index as usize)? {
|
||||
Entry::Class(name) => self.utf8(*name),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// A `ConstantValue`'s value, as bytes.
|
||||
fn constant(&self, index: u16) -> Option<Vec<u8>> {
|
||||
match self.0.get(index as usize)? {
|
||||
Entry::Number(bytes) => Some(bytes.clone()),
|
||||
Entry::String(utf8) => Some(self.utf8(*utf8)?.as_bytes().to_vec()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// FNV-1a: stable across Rust versions, so recorded fingerprints stay comparable.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Fnv(u64);
|
||||
|
||||
impl Fnv {
|
||||
fn new() -> Self {
|
||||
Fnv(0xcbf2_9ce4_8422_2325)
|
||||
}
|
||||
fn bytes(&mut self, bytes: &[u8]) {
|
||||
for b in bytes {
|
||||
self.0 = (self.0 ^ u64::from(*b)).wrapping_mul(0x100_0000_01b3);
|
||||
}
|
||||
// A separator, so `ab`+`c` and `a`+`bc` differ.
|
||||
self.0 = (self.0 ^ 0xff).wrapping_mul(0x100_0000_01b3);
|
||||
}
|
||||
fn str(&mut self, s: &str) {
|
||||
self.bytes(s.as_bytes());
|
||||
}
|
||||
fn u16(&mut self, v: u16) {
|
||||
self.bytes(&v.to_be_bytes());
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds the class names a descriptor or signature mentions (`Lcom/acme/Order<Lx/Y;>;`).
|
||||
fn descriptor_refs(text: &str, out: &mut BTreeSet<String>) {
|
||||
let bytes = text.as_bytes();
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
if bytes[i] == b'L'
|
||||
&& (i == 0
|
||||
|| matches!(
|
||||
bytes[i - 1],
|
||||
b'(' | b')'
|
||||
| b'['
|
||||
| b';'
|
||||
| b'<'
|
||||
| b'>'
|
||||
| b'+'
|
||||
| b'-'
|
||||
| b':'
|
||||
| b'*'
|
||||
| b'I'
|
||||
| b'J'
|
||||
| b'Z'
|
||||
| b'B'
|
||||
| b'C'
|
||||
| b'S'
|
||||
| b'F'
|
||||
| b'D'
|
||||
| b'V'
|
||||
| b'^'
|
||||
))
|
||||
{
|
||||
let start = i + 1;
|
||||
let mut end = start;
|
||||
while end < bytes.len() && !matches!(bytes[end], b';' | b'<' | b'.') {
|
||||
end += 1;
|
||||
}
|
||||
if end < bytes.len() && end > start {
|
||||
let name = &text[start..end];
|
||||
if name.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'/' | b'$' | b'_') || b >= 0x80) {
|
||||
out.insert(name.to_owned());
|
||||
}
|
||||
}
|
||||
i = end;
|
||||
} else {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn class_ref(name: &str, out: &mut BTreeSet<String>) {
|
||||
if name.starts_with('[') {
|
||||
descriptor_refs(name, out);
|
||||
} else {
|
||||
out.insert(name.to_owned());
|
||||
}
|
||||
}
|
||||
|
||||
struct Member {
|
||||
access: u16,
|
||||
name: String,
|
||||
descriptor: String,
|
||||
/// Fingerprint of the attributes that are part of the API.
|
||||
extra: u64,
|
||||
constant: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
fn attributes(r: &mut Bytes, pool: &Pool, mut on: impl FnMut(&str, &[u8])) -> Option<()> {
|
||||
let count = r.u2()?;
|
||||
for _ in 0..count {
|
||||
let name = pool.utf8(r.u2()?)?.to_owned();
|
||||
let len = r.u4()? as usize;
|
||||
let body = r.take(len)?;
|
||||
on(&name, body);
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
fn members(r: &mut Bytes, pool: &Pool, refs: &mut BTreeSet<String>) -> Option<Vec<Member>> {
|
||||
let count = r.u2()?;
|
||||
let mut out = Vec::with_capacity(count as usize);
|
||||
for _ in 0..count {
|
||||
let access = r.u2()?;
|
||||
let name = pool.utf8(r.u2()?)?.to_owned();
|
||||
let descriptor = pool.utf8(r.u2()?)?.to_owned();
|
||||
descriptor_refs(&descriptor, refs);
|
||||
let mut extra = Fnv::new();
|
||||
let mut constant = None;
|
||||
attributes(r, pool, |attr, body| {
|
||||
let mut b = Bytes { data: body, pos: 0 };
|
||||
match attr {
|
||||
"Signature" => {
|
||||
if let Some(sig) = b.u2().and_then(|i| pool.utf8(i)) {
|
||||
descriptor_refs(sig, refs);
|
||||
extra.str("S");
|
||||
extra.str(sig);
|
||||
}
|
||||
}
|
||||
"ConstantValue" => constant = b.u2().and_then(|i| pool.constant(i)),
|
||||
"Exceptions" => {
|
||||
let mut names: Vec<&str> = Vec::new();
|
||||
if let Some(n) = b.u2() {
|
||||
for _ in 0..n {
|
||||
if let Some(c) = b.u2().and_then(|i| pool.class(i)) {
|
||||
names.push(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
names.sort_unstable();
|
||||
extra.str("E");
|
||||
for n in names {
|
||||
extra.str(n);
|
||||
}
|
||||
}
|
||||
// An annotation element's default value is compiled into its uses.
|
||||
"AnnotationDefault" => {
|
||||
extra.str("D");
|
||||
element_value(&mut b, pool, refs, &mut extra);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
})?;
|
||||
out.push(Member { access, name, descriptor, extra: extra.0, constant });
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Parses a class file; `None` when it isn't a well-formed one.
|
||||
pub fn parse(data: &[u8]) -> Option<ClassFile> {
|
||||
let mut r = Bytes { data, pos: 0 };
|
||||
if r.u4()? != 0xCAFE_BABE {
|
||||
return None;
|
||||
}
|
||||
r.u2()?;
|
||||
r.u2()?;
|
||||
let count = r.u2()?;
|
||||
let mut entries = vec![Entry::Empty];
|
||||
let mut i = 1;
|
||||
while i < count {
|
||||
let tag = r.u1()?;
|
||||
let entry = match tag {
|
||||
1 => {
|
||||
let len = r.u2()? as usize;
|
||||
Entry::Utf8(String::from_utf8_lossy(r.take(len)?).into_owned())
|
||||
}
|
||||
3 | 4 => Entry::Number(r.take(4)?.to_vec()),
|
||||
5 | 6 => Entry::Number(r.take(8)?.to_vec()),
|
||||
7 => Entry::Class(r.u2()?),
|
||||
8 => Entry::String(r.u2()?),
|
||||
9..=11 => {
|
||||
r.take(4)?;
|
||||
Entry::Other
|
||||
}
|
||||
12 => {
|
||||
r.u2()?;
|
||||
Entry::NameAndType(r.u2()?)
|
||||
}
|
||||
15 => {
|
||||
r.take(3)?;
|
||||
Entry::Other
|
||||
}
|
||||
16 => Entry::MethodType(r.u2()?),
|
||||
17 | 18 => {
|
||||
r.take(4)?;
|
||||
Entry::Other
|
||||
}
|
||||
19 | 20 => {
|
||||
r.take(2)?;
|
||||
Entry::Other
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
let wide = matches!(tag, 5 | 6);
|
||||
entries.push(entry);
|
||||
i += 1;
|
||||
if wide {
|
||||
entries.push(Entry::Empty);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
let pool = Pool(entries);
|
||||
let mut refs = BTreeSet::new();
|
||||
for entry in &pool.0 {
|
||||
match entry {
|
||||
Entry::Class(name) => class_ref(pool.utf8(*name)?, &mut refs),
|
||||
Entry::NameAndType(descriptor) | Entry::MethodType(descriptor) => {
|
||||
descriptor_refs(pool.utf8(*descriptor)?, &mut refs)
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let access = r.u2()?;
|
||||
let name = pool.class(r.u2()?)?.to_owned();
|
||||
let super_index = r.u2()?;
|
||||
let super_name = if super_index == 0 { None } else { Some(pool.class(super_index)?.to_owned()) };
|
||||
let mut interfaces = Vec::new();
|
||||
for _ in 0..r.u2()? {
|
||||
interfaces.push(pool.class(r.u2()?)?.to_owned());
|
||||
}
|
||||
let fields = members(&mut r, &pool, &mut refs)?;
|
||||
let methods = members(&mut r, &pool, &mut refs)?;
|
||||
|
||||
let mut api = Fnv::new();
|
||||
// ACC_SUPER and ACC_SYNTHETIC say nothing about what compiles against the class.
|
||||
api.u16(access & !(0x0020 | ACC_SYNTHETIC));
|
||||
api.str(&name);
|
||||
api.str(super_name.as_deref().unwrap_or(""));
|
||||
let mut sorted = interfaces.clone();
|
||||
sorted.sort();
|
||||
for i in &sorted {
|
||||
api.str(i);
|
||||
}
|
||||
let mut class_attrs: Vec<(String, u64)> = Vec::new();
|
||||
attributes(&mut r, &pool, |attr, body| {
|
||||
let mut b = Bytes { data: body, pos: 0 };
|
||||
let mut h = Fnv::new();
|
||||
match attr {
|
||||
"Signature" => {
|
||||
if let Some(sig) = b.u2().and_then(|i| pool.utf8(i)) {
|
||||
descriptor_refs(sig, &mut refs);
|
||||
h.str(sig);
|
||||
}
|
||||
}
|
||||
"PermittedSubclasses" => {
|
||||
let mut names = Vec::new();
|
||||
for _ in 0..b.u2().unwrap_or(0) {
|
||||
if let Some(c) = b.u2().and_then(|i| pool.class(i)) {
|
||||
names.push(c.to_owned());
|
||||
}
|
||||
}
|
||||
names.sort();
|
||||
names.iter().for_each(|n| h.str(n));
|
||||
}
|
||||
"Record" => {
|
||||
for _ in 0..b.u2().unwrap_or(0) {
|
||||
let (Some(n), Some(d)) = (b.u2().and_then(|i| pool.utf8(i)), b.u2().and_then(|i| pool.utf8(i)))
|
||||
else {
|
||||
break;
|
||||
};
|
||||
h.str(n);
|
||||
h.str(d);
|
||||
let mut component = |attr: &str, body: &[u8]| {
|
||||
if attr == "Signature"
|
||||
&& let Some(sig) = (Bytes { data: body, pos: 0 }).u2().and_then(|i| pool.utf8(i))
|
||||
{
|
||||
h.str(sig);
|
||||
}
|
||||
};
|
||||
if attributes(&mut b, &pool, &mut component).is_none() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Nested classes this class declares, and their access.
|
||||
"InnerClasses" => {
|
||||
let mut nested = Vec::new();
|
||||
for _ in 0..b.u2().unwrap_or(0) {
|
||||
let (Some(inner), Some(outer), Some(_), Some(flags)) = (b.u2(), b.u2(), b.u2(), b.u2()) else {
|
||||
break;
|
||||
};
|
||||
let inner = pool.class(inner).unwrap_or("");
|
||||
if outer != 0 && pool.class(outer) == Some(name.as_str()) && flags & ACC_PRIVATE == 0 {
|
||||
nested.push(format!("{inner}:{flags}"));
|
||||
}
|
||||
}
|
||||
nested.sort();
|
||||
nested.iter().for_each(|n| h.str(n));
|
||||
}
|
||||
"RuntimeVisibleAnnotations" | "RuntimeInvisibleAnnotations" => {
|
||||
// Annotation types are dependencies; their values aren't API.
|
||||
annotation_types(body, &pool, &mut refs);
|
||||
return;
|
||||
}
|
||||
_ => return,
|
||||
}
|
||||
class_attrs.push((attr.to_owned(), h.0));
|
||||
})?;
|
||||
class_attrs.sort();
|
||||
for (attr, h) in &class_attrs {
|
||||
api.str(attr);
|
||||
api.bytes(&h.to_be_bytes());
|
||||
}
|
||||
let mut constants = Fnv::new();
|
||||
let mut api_members: Vec<(u8, &str, &str, u16, u64)> = Vec::new();
|
||||
for (kind, list) in [(0u8, &fields), (1u8, &methods)] {
|
||||
for m in list.iter() {
|
||||
if kind == 0
|
||||
&& let Some(value) = &m.constant
|
||||
{
|
||||
// Private constants are inlined too, but only in their own class.
|
||||
if m.access & ACC_PRIVATE == 0 {
|
||||
constants.str(&m.name);
|
||||
constants.str(&m.descriptor);
|
||||
constants.bytes(value);
|
||||
}
|
||||
}
|
||||
if m.access & (ACC_PRIVATE | ACC_SYNTHETIC) != 0 || m.name == "<clinit>" {
|
||||
continue;
|
||||
}
|
||||
api_members.push((kind, &m.name, &m.descriptor, m.access & !ACC_SYNTHETIC, m.extra));
|
||||
}
|
||||
}
|
||||
api_members.sort();
|
||||
for (kind, name, descriptor, access, extra) in api_members {
|
||||
api.bytes(&[kind]);
|
||||
api.str(name);
|
||||
api.str(descriptor);
|
||||
api.u16(access);
|
||||
api.bytes(&extra.to_be_bytes());
|
||||
}
|
||||
refs.remove(&name);
|
||||
refs.retain(|r| !r.starts_with("java/"));
|
||||
Some(ClassFile { name, super_name, interfaces, refs, api: api.0, constants: constants.0 })
|
||||
}
|
||||
|
||||
/// Adds the types of the annotations in a `Runtime*Annotations` attribute.
|
||||
fn annotation_types(body: &[u8], pool: &Pool, refs: &mut BTreeSet<String>) {
|
||||
let mut b = Bytes { data: body, pos: 0 };
|
||||
let Some(count) = b.u2() else { return };
|
||||
let mut ignored = Fnv::new();
|
||||
for _ in 0..count {
|
||||
if annotation(&mut b, pool, refs, &mut ignored).is_none() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn annotation(b: &mut Bytes, pool: &Pool, refs: &mut BTreeSet<String>, h: &mut Fnv) -> Option<()> {
|
||||
let ty = pool.utf8(b.u2()?)?;
|
||||
descriptor_refs(ty, refs);
|
||||
h.str(ty);
|
||||
for _ in 0..b.u2()? {
|
||||
h.str(pool.utf8(b.u2()?)?);
|
||||
element_value(b, pool, refs, h)?;
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// An annotation element value: its class names go to `refs`, its value (resolved, not the
|
||||
/// constant pool indices) to `h`.
|
||||
fn element_value(b: &mut Bytes, pool: &Pool, refs: &mut BTreeSet<String>, h: &mut Fnv) -> Option<()> {
|
||||
let tag = b.u1()?;
|
||||
h.bytes(&[tag]);
|
||||
match tag {
|
||||
b'B' | b'C' | b'D' | b'F' | b'I' | b'J' | b'S' | b'Z' => h.bytes(&pool.constant(b.u2()?)?),
|
||||
b's' => h.str(pool.utf8(b.u2()?)?),
|
||||
b'e' => {
|
||||
let ty = pool.utf8(b.u2()?)?;
|
||||
descriptor_refs(ty, refs);
|
||||
h.str(ty);
|
||||
h.str(pool.utf8(b.u2()?)?);
|
||||
}
|
||||
b'c' => {
|
||||
let ty = pool.utf8(b.u2()?)?;
|
||||
descriptor_refs(ty, refs);
|
||||
h.str(ty);
|
||||
}
|
||||
b'@' => annotation(b, pool, refs, h)?,
|
||||
b'[' => {
|
||||
for _ in 0..b.u2()? {
|
||||
element_value(b, pool, refs, h)?;
|
||||
}
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// The simple name of a class (`com/acme/Order$Line` → `Line`), which a new class can shadow.
|
||||
pub fn simple_name(name: &str) -> &str {
|
||||
let tail = name.rsplit('/').next().unwrap_or(name);
|
||||
tail.rsplit('$').next().unwrap_or(tail)
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
// OpenIDEA's Java build of a Gradle build (ide_build::jbuild). With -Popenidea.build.output=<dir>,
|
||||
// every Java source set writes its classes and resources to <dir>/[<group>.]<project>/classes|test-classes,
|
||||
// so neither the language server nor a terminal `gradle` writes what the IDE runs. The task
|
||||
// `openideaBuildModel` (-Popenidea.build.model=<file>) runs what generates sources, processes the
|
||||
// resources and writes, as JSON, each source set's roots, classpaths and how JavaCompile compiles it:
|
||||
// the same model the Maven extension writes (java/java-build, BuildModel).
|
||||
import groovy.json.JsonOutput
|
||||
import org.gradle.api.tasks.compile.AbstractCompile
|
||||
import org.gradle.api.tasks.compile.JavaCompile
|
||||
import org.gradle.jvm.tasks.Jar
|
||||
|
||||
def property = { String name -> gradle.startParameter.projectProperties[name] }
|
||||
def outRoot = property('openidea.build.output')
|
||||
if (outRoot == null || gradle.parent != null) return
|
||||
|
||||
// The project's name in the build: unique, unlike `name`.
|
||||
def nameOf = { Project p -> p == p.rootProject ? p.name : p.path.substring(1).replace(':', '.') }
|
||||
def outputOf = { Project p, String set ->
|
||||
def folder = p.group ? "${p.group}.${nameOf(p)}" : nameOf(p)
|
||||
new File(outRoot, folder + '/' + (set == 'main' ? 'classes' : 'test-classes'))
|
||||
}
|
||||
def javaSets = { Project p ->
|
||||
def sets = p.extensions.findByName('sourceSets')
|
||||
sets == null ? [] : ['main', 'test'].collect { sets.findByName(it) }.findAll { it != null }
|
||||
}
|
||||
|
||||
gradle.projectsEvaluated {
|
||||
def root = gradle.rootProject
|
||||
root.allprojects.each { p ->
|
||||
javaSets(p).each { ss ->
|
||||
def out = outputOf(p, ss.name)
|
||||
ss.java.destinationDirectory.set(out)
|
||||
ss.output.resourcesDir = out
|
||||
p.tasks.named(ss.processResourcesTaskName).configure { destinationDir = out }
|
||||
}
|
||||
}
|
||||
root.tasks.register('openideaBuildModel') {
|
||||
// What compiling needs from the same project (generated sources), and the resources.
|
||||
dependsOn {
|
||||
root.allprojects.collectMany { p ->
|
||||
javaSets(p).collectMany { ss ->
|
||||
def compile = p.tasks.getByName(ss.compileJavaTaskName)
|
||||
def generators = compile.taskDependencies.getDependencies(compile).findAll {
|
||||
it.project == p && !(it instanceof AbstractCompile) && !(it instanceof Jar)
|
||||
}
|
||||
generators + [p.tasks.getByName(ss.processResourcesTaskName)]
|
||||
}
|
||||
}
|
||||
}
|
||||
doLast {
|
||||
// Project artifacts resolve to the projects' outputs.
|
||||
def artifacts = [:]
|
||||
root.allprojects.each { p ->
|
||||
def main = javaSets(p).find { it.name == 'main' }
|
||||
if (main == null) return
|
||||
def jar = p.tasks.findByName('jar')
|
||||
if (jar instanceof Jar) artifacts[jar.archiveFile.get().asFile.canonicalPath] = outputOf(p, 'main')
|
||||
}
|
||||
def files = { collection ->
|
||||
def out = []
|
||||
try {
|
||||
collection?.files?.each { f ->
|
||||
def mapped = artifacts[f.canonicalPath] ?: f
|
||||
if (!out.contains(mapped.canonicalPath)) out << mapped.canonicalPath
|
||||
}
|
||||
} catch (e) {
|
||||
out << "!${e.message}".toString()
|
||||
}
|
||||
out
|
||||
}
|
||||
def included = gradle.includedBuilds.collect { it.name }
|
||||
def projects = root.allprojects.findAll { !javaSets(it).isEmpty() }.collect { p ->
|
||||
def problems = included.isEmpty() ? [] : ["it is a composite build (${included.join(', ')})".toString()]
|
||||
def others = p.tasks.withType(AbstractCompile).findAll {
|
||||
!(it instanceof JavaCompile) && it.name ==~ /(?i)compile.*(Kotlin|Groovy|Scala|Aspectj).*/
|
||||
}.collect { "${it.class.name.replace('_Decorated', '')}@${it.name}".toString() }
|
||||
def setModel = { String name ->
|
||||
def ss = javaSets(p).find { it.name == name }
|
||||
if (ss == null) return [sourceRoots: [], output: outputOf(p, name).path, classpath: [], runtimeClasspath: []]
|
||||
JavaCompile compile = p.tasks.getByName(ss.compileJavaTaskName)
|
||||
def o = compile.options
|
||||
def classpath = files(compile.classpath)
|
||||
def runtime = files(ss.runtimeClasspath)
|
||||
(classpath + runtime).findAll { it.startsWith('!') }.each { problems << "Cannot resolve the dependencies: ${it.substring(1)}".toString() }
|
||||
def processorPath = files(o.annotationProcessorPath)
|
||||
def processorProblems = processorPath.findAll { it.startsWith('!') }
|
||||
def projectProcessors = processorPath.findAll { path -> artifacts.values().any { it.canonicalPath == path } }
|
||||
def home = null
|
||||
try { home = compile.javaCompiler.orNull?.metadata?.installationPath?.asFile?.canonicalPath } catch (ignored) {}
|
||||
[
|
||||
sourceRoots: ss.java.srcDirs.collect { it.canonicalPath },
|
||||
output: outputOf(p, name).canonicalPath,
|
||||
classpath: classpath.findAll { !it.startsWith('!') },
|
||||
runtimeClasspath: runtime.findAll { !it.startsWith('!') },
|
||||
resources: ss.resources.srcDirs.collect { [directory: it.canonicalPath, filtering: false] },
|
||||
compiler: [
|
||||
compilerId: 'javac',
|
||||
source: compile.sourceCompatibility,
|
||||
target: compile.targetCompatibility,
|
||||
release: o.release.orNull?.toString(),
|
||||
encoding: o.encoding,
|
||||
debug: o.debug,
|
||||
debuglevel: o.debugOptions.debugLevel,
|
||||
showWarnings: o.warnings,
|
||||
showDeprecation: o.deprecation,
|
||||
fork: home != null,
|
||||
executable: home == null ? null : new File(home, 'bin/javac').path,
|
||||
generatedSourcesDirectory: o.generatedSourceOutputDirectory.asFile.orNull?.canonicalPath,
|
||||
includes: ss.java.includes as List,
|
||||
excludes: ss.java.excludes as List,
|
||||
compilerArgs: o.allCompilerArgs.collect { it.toString() },
|
||||
processorPath: processorProblems.isEmpty() && projectProcessors.isEmpty() ? processorPath : null,
|
||||
processorPathError: !processorProblems.isEmpty()
|
||||
? processorProblems[0].substring(1)
|
||||
: (projectProcessors.isEmpty() ? null : 'its annotation processors are built in the same build'),
|
||||
],
|
||||
]
|
||||
}
|
||||
def mainModel = setModel('main')
|
||||
def testModel = setModel('test')
|
||||
// Gradle compiles tests against the main classes: they're the main output here.
|
||||
[
|
||||
dir: p.projectDir.canonicalPath,
|
||||
groupId: (p.group ?: '').toString(),
|
||||
artifactId: nameOf(p),
|
||||
version: p.version.toString(),
|
||||
packaging: 'jar',
|
||||
main: mainModel,
|
||||
test: testModel,
|
||||
otherCompilers: others,
|
||||
testGenerators: [],
|
||||
problems: problems,
|
||||
gradlePath: p.path,
|
||||
]
|
||||
}
|
||||
def modelFile = property('openidea.build.model')
|
||||
if (modelFile != null) {
|
||||
def file = new File(modelFile)
|
||||
def temporary = new File(file.parentFile, file.name + '.tmp')
|
||||
temporary.text = JsonOutput.toJson([version: 1, projects: projects])
|
||||
temporary.renameTo(file) || { file.delete(); temporary.renameTo(file) }()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
//! Class-level incremental compilation (#4078 step 3). Each source set records, per class it
|
||||
//! compiled, the source it came from, its supertypes, the classes its constant pool names and
|
||||
//! fingerprints of its API and constants ([`super::classfile`]). A build compiles the changed
|
||||
//! sources, then the sources of classes that refer to a class whose API changed (or to a
|
||||
//! subclass of one), round after round until no API changes. Sets compiled against this one
|
||||
//! read its log of API changes; a changed compile-time constant, which javac copies into the
|
||||
//! classes that use it, recompiles the whole set and every set compiled against it.
|
||||
use super::*;
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
|
||||
pub(super) struct ClassRecord {
|
||||
/// The source javac compiled it from; `None` for classes an annotation processor wrote
|
||||
/// without naming an originating source.
|
||||
pub source: Option<PathBuf>,
|
||||
pub file: PathBuf,
|
||||
pub super_name: Option<String>,
|
||||
#[serde(default)]
|
||||
pub interfaces: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub refs: Vec<String>,
|
||||
pub api: u64,
|
||||
pub constants: u64,
|
||||
}
|
||||
|
||||
impl ClassRecord {
|
||||
pub fn new(class: classfile::ClassFile, file: PathBuf, source: Option<PathBuf>) -> (String, Self) {
|
||||
let record = ClassRecord {
|
||||
source,
|
||||
file,
|
||||
super_name: class.super_name,
|
||||
interfaces: class.interfaces,
|
||||
refs: class.refs.into_iter().collect(),
|
||||
api: class.api,
|
||||
constants: class.constants,
|
||||
};
|
||||
(class.name, record)
|
||||
}
|
||||
|
||||
fn has_constants(&self) -> bool {
|
||||
self.constants != NO_CONSTANTS
|
||||
}
|
||||
}
|
||||
|
||||
/// The constant fingerprint of a class without compile-time constants.
|
||||
pub(super) const NO_CONSTANTS: u64 = 0xcbf2_9ce4_8422_2325;
|
||||
|
||||
/// The classes whose API one compilation of a set changed.
|
||||
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
|
||||
pub(super) struct ApiChange {
|
||||
/// The set's generation before and after the compilation.
|
||||
pub since: u64,
|
||||
pub generation: u64,
|
||||
pub classes: Vec<String>,
|
||||
/// Everything counts as changed: a constant changed, or there was nothing to compare with.
|
||||
pub all: bool,
|
||||
}
|
||||
|
||||
/// How many compilations' API changes a set keeps for the sets compiled against it; one that
|
||||
/// fell further behind compiles from scratch.
|
||||
const CHANGE_LOG: usize = 64;
|
||||
|
||||
/// The inputs of a source set that, when changed, compile it from scratch.
|
||||
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
|
||||
pub(super) struct SetStamp {
|
||||
pub options: Vec<String>,
|
||||
/// Classpath entries outside the reactor's outputs, with their stamps (folders have none).
|
||||
pub libraries: Vec<(PathBuf, Option<FileStamp>)>,
|
||||
/// The reactor outputs on the classpath, in order.
|
||||
pub reactor: Vec<PathBuf>,
|
||||
pub processor_path: Vec<(PathBuf, Option<FileStamp>)>,
|
||||
pub java_home: PathBuf,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Deserialize, Serialize)]
|
||||
pub(super) struct SetState {
|
||||
pub stamp: SetStamp,
|
||||
/// The sources as of the last compilation.
|
||||
pub sources: BTreeMap<PathBuf, FileStamp>,
|
||||
/// Changes whenever the set's classes do.
|
||||
pub generation: u64,
|
||||
/// The generation of each reactor output it was compiled against.
|
||||
pub upstream: BTreeMap<PathBuf, u64>,
|
||||
pub classes: BTreeMap<String, ClassRecord>,
|
||||
/// Sources a failed compilation left uncompiled.
|
||||
pub dirty: BTreeSet<PathBuf>,
|
||||
pub changes: Vec<ApiChange>,
|
||||
/// Sources annotation processors wrote, and other files they wrote without an originating
|
||||
/// source (`META-INF/services`…): processors that aggregate. While there are any, a change
|
||||
/// compiles the set from scratch.
|
||||
pub generated: Vec<PathBuf>,
|
||||
pub unowned: Vec<PathBuf>,
|
||||
pub success: bool,
|
||||
}
|
||||
|
||||
impl SetState {
|
||||
/// The classes whose API changed since generation `since`; `None` when unknown (the log
|
||||
/// doesn't reach back that far) or when everything counts as changed.
|
||||
pub fn changes_since(&self, since: u64) -> Option<BTreeSet<String>> {
|
||||
let mut changed = BTreeSet::new();
|
||||
let mut at = since;
|
||||
while at != self.generation {
|
||||
let change = self.changes.iter().find(|c| c.since == at)?;
|
||||
if change.all {
|
||||
return None;
|
||||
}
|
||||
changed.extend(change.classes.iter().cloned());
|
||||
at = change.generation;
|
||||
}
|
||||
Some(changed)
|
||||
}
|
||||
|
||||
pub fn log(&mut self, generation: u64, classes: BTreeSet<String>, all: bool) {
|
||||
self.changes.push(ApiChange {
|
||||
since: self.generation,
|
||||
generation,
|
||||
classes: classes.into_iter().collect(),
|
||||
all,
|
||||
});
|
||||
if self.changes.len() > CHANGE_LOG {
|
||||
self.changes.drain(..self.changes.len() - CHANGE_LOG);
|
||||
}
|
||||
self.generation = generation;
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn load_state(path: &Path) -> Option<SetState> {
|
||||
serde_json::from_slice(&std::fs::read(path).ok()?).ok()
|
||||
}
|
||||
|
||||
/// `seeds` and the classes of `classes` that extend or implement one of them, transitively:
|
||||
/// a class that inherits a changed member changes for the classes that use it.
|
||||
pub(super) fn with_subclasses(classes: &BTreeMap<String, ClassRecord>, seeds: &BTreeSet<String>) -> BTreeSet<String> {
|
||||
let mut out = seeds.clone();
|
||||
loop {
|
||||
let before = out.len();
|
||||
for (name, record) in classes {
|
||||
if !out.contains(name)
|
||||
&& (record.super_name.as_ref().is_some_and(|s| out.contains(s))
|
||||
|| record.interfaces.iter().any(|i| out.contains(i)))
|
||||
{
|
||||
out.insert(name.clone());
|
||||
}
|
||||
}
|
||||
if out.len() == before {
|
||||
return out;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The sources of the classes that refer to one of `affected`.
|
||||
pub(super) fn dependent_sources(
|
||||
classes: &BTreeMap<String, ClassRecord>,
|
||||
affected: &BTreeSet<String>,
|
||||
) -> BTreeSet<PathBuf> {
|
||||
if affected.is_empty() {
|
||||
return BTreeSet::new();
|
||||
}
|
||||
classes
|
||||
.iter()
|
||||
.filter(|(name, r)| affected.contains(*name) || r.refs.iter().any(|x| affected.contains(x)))
|
||||
.filter_map(|(_, r)| r.source.clone())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The sources of the classes that refer to a class with the same simple name as one of
|
||||
/// `added`: a new class can take a simple name over from an on-demand import.
|
||||
pub(super) fn shadowed_sources(classes: &BTreeMap<String, ClassRecord>, added: &BTreeSet<String>) -> BTreeSet<PathBuf> {
|
||||
let names: BTreeSet<&str> = added.iter().map(|n| classfile::simple_name(n)).collect();
|
||||
if names.is_empty() {
|
||||
return BTreeSet::new();
|
||||
}
|
||||
classes
|
||||
.iter()
|
||||
.filter(|(name, r)| {
|
||||
!added.contains(*name)
|
||||
&& r.refs.iter().any(|x| !added.contains(x) && names.contains(classfile::simple_name(x)))
|
||||
})
|
||||
.filter_map(|(_, r)| r.source.clone())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// What one round's classes changed, compared with the classes the round replaced.
|
||||
#[derive(Debug, Default)]
|
||||
pub(super) struct RoundDiff {
|
||||
pub api: BTreeSet<String>,
|
||||
pub added: BTreeSet<String>,
|
||||
pub constants: bool,
|
||||
}
|
||||
|
||||
pub(super) fn diff(old: &BTreeMap<String, ClassRecord>, new: &BTreeMap<String, ClassRecord>) -> RoundDiff {
|
||||
let mut out = RoundDiff::default();
|
||||
for (name, record) in new {
|
||||
match old.get(name) {
|
||||
Some(before) => {
|
||||
if before.api != record.api {
|
||||
out.api.insert(name.clone());
|
||||
}
|
||||
if before.constants != record.constants {
|
||||
out.constants = true;
|
||||
}
|
||||
}
|
||||
None => {
|
||||
out.api.insert(name.clone());
|
||||
out.added.insert(name.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
for (name, before) in old {
|
||||
if !new.contains_key(name) {
|
||||
out.api.insert(name.clone());
|
||||
out.constants |= before.has_constants();
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
//! Resident javac processes (`java/java-build`, `ai.openidea.javac.Server`): one JVM per JDK
|
||||
//! and JVM options, kept warm between builds, compiling one request at a time in process.
|
||||
use super::*;
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::process::{Child, ChildStdin, Command, Stdio};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::sync::mpsc;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
/// A message of the server about one request.
|
||||
#[derive(Clone, Debug, Deserialize, PartialEq)]
|
||||
#[serde(tag = "kind", rename_all = "kebab-case", rename_all_fields = "camelCase")]
|
||||
pub enum Reply {
|
||||
Diagnostic {
|
||||
severity: String,
|
||||
path: Option<PathBuf>,
|
||||
/// 1-based.
|
||||
line: Option<u32>,
|
||||
/// 0-based UTF-16.
|
||||
column: Option<u32>,
|
||||
end_line: Option<u32>,
|
||||
end_column: Option<u32>,
|
||||
code: Option<String>,
|
||||
message: String,
|
||||
},
|
||||
/// A class (or resource) file javac wrote, and the source it came from.
|
||||
Output {
|
||||
path: PathBuf,
|
||||
source: Option<PathBuf>,
|
||||
},
|
||||
/// A source file an annotation processor wrote.
|
||||
Generated {
|
||||
path: PathBuf,
|
||||
source: Option<PathBuf>,
|
||||
},
|
||||
OutputText {
|
||||
text: String,
|
||||
},
|
||||
Done {
|
||||
success: bool,
|
||||
cancelled: bool,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct Request<'a> {
|
||||
id: u64,
|
||||
op: &'static str,
|
||||
options: &'a [String],
|
||||
sources: &'a [PathBuf],
|
||||
encoding: Option<&'a str>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
|
||||
pub struct ServerKey {
|
||||
pub java_home: PathBuf,
|
||||
/// Options of the compiler's JVM (`.mvn/jvm.config`: `--add-opens` for processors).
|
||||
pub jvm_args: Vec<String>,
|
||||
}
|
||||
|
||||
type Pending = Arc<Mutex<HashMap<u64, mpsc::Sender<Reply>>>>;
|
||||
|
||||
pub struct JavacServer {
|
||||
child: Mutex<Child>,
|
||||
stdin: Mutex<ChildStdin>,
|
||||
pending: Pending,
|
||||
alive: Arc<AtomicBool>,
|
||||
next: AtomicU64,
|
||||
pub version: String,
|
||||
}
|
||||
|
||||
impl JavacServer {
|
||||
fn start(jar: &Path, key: &ServerKey) -> IdeResult<Self> {
|
||||
let java = key.java_home.join("bin").join(if cfg!(windows) { "java.exe" } else { "java" });
|
||||
let mut cmd = Command::new(&java);
|
||||
cmd.args(&key.jvm_args)
|
||||
.args(["-XX:+UseSerialGC", "-XX:TieredStopAtLevel=1", "-Dfile.encoding=UTF-8", "-cp"])
|
||||
.arg(jar)
|
||||
.arg("ai.openidea.javac.Server")
|
||||
.env("JAVA_HOME", &key.java_home)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null());
|
||||
ide_core::process::prepare(&mut cmd);
|
||||
ide_core::process::own_group(&mut cmd);
|
||||
let mut child =
|
||||
cmd.spawn().map_err(|e| IdeError::unavailable(format!("Cannot start javac ({}): {e}", java.display())))?;
|
||||
let stdin = child.stdin.take().expect("piped");
|
||||
let stdout = child.stdout.take().expect("piped");
|
||||
let pending: Pending = Arc::default();
|
||||
let alive = Arc::new(AtomicBool::new(true));
|
||||
let (ready_tx, ready_rx) = mpsc::channel::<Result<String, String>>();
|
||||
{
|
||||
let (pending, alive) = (pending.clone(), alive.clone());
|
||||
std::thread::Builder::new()
|
||||
.name("javac-server".into())
|
||||
.spawn(move || {
|
||||
let mut ready = Some(ready_tx);
|
||||
for line in BufReader::new(stdout).lines() {
|
||||
let Ok(line) = line else { break };
|
||||
let Ok(value) = serde_json::from_str::<serde_json::Value>(&line) else { continue };
|
||||
match value.get("kind").and_then(|k| k.as_str()) {
|
||||
Some("ready") => {
|
||||
let version = value.get("version").and_then(|v| v.as_str()).unwrap_or("").to_owned();
|
||||
if let Some(ready) = ready.take() {
|
||||
let _ = ready.send(Ok(version));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Some("fatal") => {
|
||||
let message = value.get("message").and_then(|v| v.as_str()).unwrap_or("").to_owned();
|
||||
if let Some(ready) = ready.take() {
|
||||
let _ = ready.send(Err(message));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let Some(id) = value.get("id").and_then(|v| v.as_u64()) else { continue };
|
||||
let Ok(reply) = serde_json::from_value::<Reply>(value) else { continue };
|
||||
let done = matches!(reply, Reply::Done { .. });
|
||||
let mut pending = pending.lock().unwrap();
|
||||
if let Some(tx) = pending.get(&id) {
|
||||
let _ = tx.send(reply);
|
||||
}
|
||||
if done {
|
||||
pending.remove(&id);
|
||||
}
|
||||
}
|
||||
alive.store(false, Ordering::SeqCst);
|
||||
// Requests still waiting learn that the server is gone.
|
||||
for (_, tx) in pending.lock().unwrap().drain() {
|
||||
let _ = tx.send(Reply::Diagnostic {
|
||||
severity: "error".into(),
|
||||
path: None,
|
||||
line: None,
|
||||
column: None,
|
||||
end_line: None,
|
||||
end_column: None,
|
||||
code: None,
|
||||
message: "The javac process exited".into(),
|
||||
});
|
||||
let _ = tx.send(Reply::Done { success: false, cancelled: false });
|
||||
}
|
||||
if let Some(ready) = ready.take() {
|
||||
let _ = ready.send(Err("The javac process exited while starting".into()));
|
||||
}
|
||||
})
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
}
|
||||
let version = match ready_rx.recv_timeout(Duration::from_secs(60)) {
|
||||
Ok(Ok(version)) => version,
|
||||
Ok(Err(message)) => {
|
||||
ide_core::process::kill_tree(&mut child);
|
||||
return Err(IdeError::unavailable(format!("Cannot start javac ({}): {message}", java.display())));
|
||||
}
|
||||
Err(_) => {
|
||||
ide_core::process::kill_tree(&mut child);
|
||||
return Err(IdeError::unavailable(format!("javac ({}) did not start", java.display())));
|
||||
}
|
||||
};
|
||||
Ok(JavacServer {
|
||||
child: Mutex::new(child),
|
||||
stdin: Mutex::new(stdin),
|
||||
pending,
|
||||
alive,
|
||||
next: AtomicU64::new(1),
|
||||
version,
|
||||
})
|
||||
}
|
||||
|
||||
fn alive(&self) -> bool {
|
||||
self.alive.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
fn send(&self, value: &impl Serialize) -> IdeResult<()> {
|
||||
let mut line = serde_json::to_vec(value).map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
line.push(b'\n');
|
||||
let mut stdin = self.stdin.lock().unwrap();
|
||||
stdin.write_all(&line).and_then(|()| stdin.flush()).map_err(|e| IdeError::internal(format!("javac: {e}")))
|
||||
}
|
||||
|
||||
/// Compiles `sources` with javac `options`, passing each reply to `on_reply`, until the
|
||||
/// compilation ends. Cancelling stops javac at its next phase.
|
||||
pub fn compile(
|
||||
&self,
|
||||
options: &[String],
|
||||
sources: &[PathBuf],
|
||||
encoding: Option<&str>,
|
||||
cancel: &CancellationToken,
|
||||
mut on_reply: impl FnMut(&Reply),
|
||||
) -> IdeResult<bool> {
|
||||
let id = self.next.fetch_add(1, Ordering::SeqCst);
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.pending.lock().unwrap().insert(id, tx);
|
||||
if let Err(e) = self.send(&Request { id, op: "compile", options, sources, encoding }) {
|
||||
self.pending.lock().unwrap().remove(&id);
|
||||
return Err(e);
|
||||
}
|
||||
let mut cancelled = false;
|
||||
loop {
|
||||
match rx.recv_timeout(Duration::from_millis(100)) {
|
||||
Ok(reply) => {
|
||||
if let Reply::Done { success, cancelled: stopped } = reply {
|
||||
if stopped || cancelled {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
return Ok(success);
|
||||
}
|
||||
on_reply(&reply);
|
||||
}
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => {
|
||||
if cancel.is_cancelled() && !cancelled {
|
||||
cancelled = true;
|
||||
let _ = self.send(&serde_json::json!({ "op": "cancel", "id": id }));
|
||||
}
|
||||
}
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => {
|
||||
return Err(IdeError::internal("The javac process exited"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for JavacServer {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.send(&serde_json::json!({ "op": "exit" }));
|
||||
let mut child = self.child.lock().unwrap();
|
||||
for _ in 0..20 {
|
||||
if child.try_wait().ok().flatten().is_some() {
|
||||
return;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
ide_core::process::kill_tree(&mut child);
|
||||
}
|
||||
}
|
||||
|
||||
/// The resident javac servers of one IDE process.
|
||||
#[derive(Default)]
|
||||
pub struct JavacPool {
|
||||
servers: Mutex<HashMap<ServerKey, Arc<JavacServer>>>,
|
||||
}
|
||||
|
||||
impl JavacPool {
|
||||
/// The running server for `key`, started on first use (or after it died).
|
||||
pub fn server(&self, jar: &Path, key: &ServerKey) -> IdeResult<Arc<JavacServer>> {
|
||||
let mut servers = self.servers.lock().unwrap();
|
||||
if let Some(server) = servers.get(key).filter(|s| s.alive()) {
|
||||
return Ok(server.clone());
|
||||
}
|
||||
let server = Arc::new(JavacServer::start(jar, key)?);
|
||||
servers.insert(key.clone(), server.clone());
|
||||
Ok(server)
|
||||
}
|
||||
|
||||
/// Stops every server (the project closed).
|
||||
pub fn shutdown(&self) {
|
||||
self.servers.lock().unwrap().clear();
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,342 @@
|
||||
//! The build model of a Maven reactor or Gradle build as the build tool itself configures it,
|
||||
//! recorded by the prepare run (`java/java-build` `BuildModel`, `gradle-build.init.gradle`), and when that run is due.
|
||||
use super::*;
|
||||
use std::fs;
|
||||
|
||||
/// `model.json` of the prepare run (see `BuildModel.java`).
|
||||
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ReactorModel {
|
||||
pub version: u32,
|
||||
pub projects: Vec<ProjectModel>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ProjectModel {
|
||||
/// Absolute project directory.
|
||||
pub dir: PathBuf,
|
||||
pub group_id: String,
|
||||
pub artifact_id: String,
|
||||
pub version: String,
|
||||
pub packaging: String,
|
||||
pub main: SourceSet,
|
||||
pub test: SourceSet,
|
||||
/// Executions in the compile phases that aren't javac (`group:artifact:goal@id`).
|
||||
#[serde(default)]
|
||||
pub other_compilers: Vec<String>,
|
||||
/// Test source generators the prepare run doesn't reach.
|
||||
#[serde(default)]
|
||||
pub test_generators: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub problems: Vec<String>,
|
||||
/// The Gradle project path (`:`, `:app`); `None` for Maven.
|
||||
#[serde(default)]
|
||||
pub gradle_path: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SourceSet {
|
||||
pub source_roots: Vec<PathBuf>,
|
||||
pub output: PathBuf,
|
||||
pub classpath: Vec<PathBuf>,
|
||||
pub runtime_classpath: Vec<PathBuf>,
|
||||
#[serde(default)]
|
||||
pub resources: Vec<ResourceRoot>,
|
||||
pub compiler: Option<CompilerConfig>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ResourceRoot {
|
||||
pub directory: PathBuf,
|
||||
#[serde(default)]
|
||||
pub filtering: bool,
|
||||
pub target_path: Option<String>,
|
||||
#[serde(default)]
|
||||
pub includes: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub excludes: Vec<String>,
|
||||
}
|
||||
|
||||
/// maven-compiler-plugin's configuration of one source set, as its mojo was configured.
|
||||
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CompilerConfig {
|
||||
pub compiler_id: Option<String>,
|
||||
pub source: Option<String>,
|
||||
pub target: Option<String>,
|
||||
pub release: Option<String>,
|
||||
pub encoding: Option<String>,
|
||||
pub parameters: Option<bool>,
|
||||
pub debug: Option<bool>,
|
||||
pub debuglevel: Option<String>,
|
||||
pub proc: Option<String>,
|
||||
pub enable_preview: Option<bool>,
|
||||
pub fork: Option<bool>,
|
||||
pub executable: Option<String>,
|
||||
pub skip: Option<bool>,
|
||||
pub show_warnings: Option<bool>,
|
||||
pub show_deprecation: Option<bool>,
|
||||
pub generated_sources_directory: Option<PathBuf>,
|
||||
#[serde(default)]
|
||||
pub includes: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub excludes: Vec<String>,
|
||||
pub annotation_processors: Option<Vec<String>>,
|
||||
#[serde(default)]
|
||||
pub compiler_args: Vec<String>,
|
||||
pub compiler_argument: Option<String>,
|
||||
#[serde(default)]
|
||||
pub compiler_arguments: BTreeMap<String, Option<String>>,
|
||||
pub multi_release_output: Option<bool>,
|
||||
pub processor_path: Option<Vec<PathBuf>>,
|
||||
pub processor_path_error: Option<String>,
|
||||
}
|
||||
|
||||
impl ProjectModel {
|
||||
pub fn key(&self) -> String {
|
||||
format!("{}:{}", self.group_id, self.artifact_id)
|
||||
}
|
||||
|
||||
pub fn set(&self, test: bool) -> &SourceSet {
|
||||
if test { &self.test } else { &self.main }
|
||||
}
|
||||
|
||||
/// Why the IDE can't compile this project with javac itself, if it can't.
|
||||
pub fn unsupported(&self, test: bool) -> Option<String> {
|
||||
// What the build tool couldn't resolve or read: the model would be incomplete.
|
||||
if let Some(problem) = self.problems.first() {
|
||||
return Some(format!("{}: {problem}", self.artifact_id));
|
||||
}
|
||||
if !self.other_compilers.is_empty() {
|
||||
return Some(format!("{} also compiles with {}", self.artifact_id, self.other_compilers.join(", ")));
|
||||
}
|
||||
if test && !self.test_generators.is_empty() {
|
||||
return Some(format!(
|
||||
"{} generates test sources with {}",
|
||||
self.artifact_id,
|
||||
self.test_generators.join(", ")
|
||||
));
|
||||
}
|
||||
for set in [&self.main, &self.test] {
|
||||
let Some(c) = &set.compiler else { continue };
|
||||
if c.compiler_id.as_deref().is_some_and(|id| id != "javac") {
|
||||
return Some(format!("{} compiles with {}", self.artifact_id, c.compiler_id.as_deref().unwrap()));
|
||||
}
|
||||
if c.multi_release_output == Some(true) {
|
||||
return Some(format!("{} is a multi-release jar", self.artifact_id));
|
||||
}
|
||||
if let Some(error) = &c.processor_path_error {
|
||||
return Some(format!("{}: {error}", self.artifact_id));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the IDE's build of the reactor at `top_dir` keeps its model and outputs.
|
||||
pub(super) fn reactor_dir(cache: &Path, top_dir: &str) -> PathBuf {
|
||||
let base = cache.join("java-build");
|
||||
if top_dir.is_empty() { base.join("_root") } else { base.join(top_dir) }
|
||||
}
|
||||
|
||||
/// The outputs of every project, `<out>/<groupId>.<artifactId>/classes`, as the extension
|
||||
/// redirects them (`-Dopenidea.build.output=<out>`).
|
||||
pub(super) fn output_root(cache: &Path, top_dir: &str) -> PathBuf {
|
||||
reactor_dir(cache, top_dir).join("out")
|
||||
}
|
||||
|
||||
/// What the recorded model was prepared from.
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
pub(super) struct PrepareRecord {
|
||||
pub fingerprint: LaunchFingerprint,
|
||||
pub model: ReactorModel,
|
||||
}
|
||||
|
||||
const MODEL_VERSION: u32 = 1;
|
||||
|
||||
/// Files the model depends on: the POM chains, settings, toolchains, the Maven launcher,
|
||||
/// and generator inputs (any `src/<set>/<dir>` that isn't Java sources or resources:
|
||||
/// `proto`, `antlr4`, `avro`…), but not the Java sources and resources themselves.
|
||||
pub(super) fn prepare_fingerprint(
|
||||
root: &Path,
|
||||
reactor: &[&maven::MavenProject],
|
||||
step: &BuildStep,
|
||||
local_repo: Option<PathBuf>,
|
||||
jar_version: &str,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Option<LaunchFingerprint>> {
|
||||
let Some(mut inputs) = maven::model_inputs(root, reactor, local_repo) else { return Ok(None) };
|
||||
for project in reactor {
|
||||
let src = subdir(root, &project.dir).join("src");
|
||||
for set in fs::read_dir(&src).into_iter().flatten().flatten() {
|
||||
for dir in fs::read_dir(set.path()).into_iter().flatten().flatten() {
|
||||
let name = dir.file_name();
|
||||
if dir.path().is_dir() && !matches!(name.to_str(), Some("java" | "resources")) {
|
||||
inputs.push(dir.path());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for dir in step.cwd.ancestors() {
|
||||
inputs.extend([dir.join(".mvn"), dir.join("mvnw"), dir.join("mvnw.cmd")]);
|
||||
if dir == root {
|
||||
break;
|
||||
}
|
||||
}
|
||||
inputs.push(process::program_path(&step.program, &step.env, &step.cwd));
|
||||
if let Some(home) = dirs::home_dir() {
|
||||
inputs.extend([home.join(".m2/settings.xml"), home.join(".m2/toolchains.xml")]);
|
||||
}
|
||||
if let Some(home) = step.env.get("JAVA_HOME") {
|
||||
inputs.push(Path::new(home).join("release"));
|
||||
}
|
||||
inputs.sort();
|
||||
inputs.dedup();
|
||||
let parameters = serde_json::to_string(&(MODEL_VERSION, jar_version, &step.program, &step.args, &step.env))
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
Ok(Some(LaunchFingerprint::new(parameters, fingerprint::scan_all(root, inputs, cancel)?)))
|
||||
}
|
||||
|
||||
pub(super) fn load_record(dir: &Path) -> Option<PrepareRecord> {
|
||||
let record: PrepareRecord = serde_json::from_slice(&fs::read(dir.join("prepare.json")).ok()?).ok()?;
|
||||
(record.model.version == MODEL_VERSION).then_some(record)
|
||||
}
|
||||
|
||||
pub(super) fn save_record(dir: &Path, record: &PrepareRecord) -> IdeResult<()> {
|
||||
write_json(&dir.join("prepare.json"), record)
|
||||
}
|
||||
|
||||
pub(super) fn write_json(path: &Path, value: &impl Serialize) -> IdeResult<()> {
|
||||
let parent = path.parent().ok_or_else(|| IdeError::internal("no parent folder"))?;
|
||||
fs::create_dir_all(parent)?;
|
||||
let mut file = tempfile::NamedTempFile::new_in(parent)?;
|
||||
serde_json::to_writer(file.as_file_mut(), value).map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
file.persist(path).map_err(|e| IdeError::from(e.error))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether the generated source roots the model lists still exist: `mvn clean` removes them.
|
||||
pub(super) fn generated_roots_exist(model: &ReactorModel) -> bool {
|
||||
model.projects.iter().all(|p| {
|
||||
[&p.main, &p.test].iter().all(|set| {
|
||||
set.source_roots.iter().all(|root| {
|
||||
root.exists() || !root.components().any(|c| c.as_os_str() == "target") || is_processor_output(set, root)
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// The annotation processors' output folder, which javac writes into and never reads as a root.
|
||||
pub(super) fn is_processor_output(set: &SourceSet, root: &Path) -> bool {
|
||||
set.compiler.as_ref().and_then(|c| c.generated_sources_directory.as_deref()).is_some_and(|dir| dir == root)
|
||||
}
|
||||
|
||||
/// A Maven step at the reactor root running `goals` with the IDE's extension loaded.
|
||||
pub(super) fn maven_step(
|
||||
root: &Path,
|
||||
top: &maven::MavenProject,
|
||||
jar: &Path,
|
||||
output_root: &Path,
|
||||
model_file: Option<&Path>,
|
||||
extra: &[String],
|
||||
) -> BuildStep {
|
||||
let mut step = maven_build_step(
|
||||
&top.command,
|
||||
&["-B", "-Dstyle.color=never", maven::LOCAL_REPO_TRACKING_ARG],
|
||||
&subdir(root, &top.dir),
|
||||
);
|
||||
step.args.extend(top.options.iter().cloned());
|
||||
step.args.push(format!("-Dmaven.ext.class.path={}", jar.display()));
|
||||
step.args.push(format!("-Dopenidea.build.output={}", output_root.display()));
|
||||
if let Some(file) = model_file {
|
||||
step.args.push(format!("-Dopenidea.build.model={}", file.display()));
|
||||
}
|
||||
step.args.extend(extra.iter().cloned());
|
||||
step.env = top.env.clone();
|
||||
step
|
||||
}
|
||||
|
||||
/// The init script that gives a Gradle build the IDE's outputs and writes its model.
|
||||
const GRADLE_INIT_SCRIPT: &str = include_str!("gradle-build.init.gradle");
|
||||
|
||||
/// Writes the init script into the build's state folder, and returns its path.
|
||||
pub(super) fn gradle_init_script(dir: &Path) -> IdeResult<PathBuf> {
|
||||
fs::create_dir_all(dir)?;
|
||||
let path = dir.join("openidea-build.init.gradle");
|
||||
if fs::read_to_string(&path).ok().as_deref() != Some(GRADLE_INIT_SCRIPT) {
|
||||
fs::write(&path, GRADLE_INIT_SCRIPT)?;
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
/// A Gradle step at the build's root running `tasks` with the IDE's init script.
|
||||
pub(super) fn gradle_step(
|
||||
root: &Path,
|
||||
g: &crate::GradleModel,
|
||||
init: &Path,
|
||||
output_root: &Path,
|
||||
model_file: Option<&Path>,
|
||||
tasks: &[String],
|
||||
) -> BuildStep {
|
||||
let mut step = gradle_build_step(
|
||||
&g.command,
|
||||
// The init script configures the evaluated projects, which a configuration cache skips.
|
||||
&["--console=plain", "--no-configuration-cache"],
|
||||
&subdir(root, &g.dir),
|
||||
);
|
||||
step.args.extend(["--init-script".to_owned(), init.to_string_lossy().into_owned()]);
|
||||
step.args.push(format!("-Popenidea.build.output={}", output_root.display()));
|
||||
if let Some(file) = model_file {
|
||||
step.args.push(format!("-Popenidea.build.model={}", file.display()));
|
||||
}
|
||||
step.args.extend(tasks.iter().cloned());
|
||||
step.env = g.env.clone();
|
||||
step
|
||||
}
|
||||
|
||||
/// Files a Gradle build's model depends on: settings and build scripts (with what they apply),
|
||||
/// properties, the wrapper and catalogs, `buildSrc`, and generator inputs.
|
||||
pub(super) fn gradle_prepare_fingerprint(
|
||||
root: &Path,
|
||||
g: &crate::GradleModel,
|
||||
step: &BuildStep,
|
||||
jar_version: &str,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<LaunchFingerprint> {
|
||||
let mut inputs = crate::gradle::build_files(root, g);
|
||||
let dir = subdir(root, &g.dir);
|
||||
inputs.extend([dir.join("buildSrc"), dir.join("gradle"), dir.join("gradlew"), dir.join("gradlew.bat")]);
|
||||
for project in &g.projects {
|
||||
let src = subdir(root, &project.dir).join("src");
|
||||
for set in fs::read_dir(&src).into_iter().flatten().flatten() {
|
||||
for generator in fs::read_dir(set.path()).into_iter().flatten().flatten() {
|
||||
let name = generator.file_name();
|
||||
if generator.path().is_dir() && !matches!(name.to_str(), Some("java" | "resources")) {
|
||||
inputs.push(generator.path());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
inputs.push(process::program_path(&step.program, &step.env, &step.cwd));
|
||||
if let Some(home) = dirs::home_dir() {
|
||||
inputs.push(home.join(".gradle/gradle.properties"));
|
||||
inputs.push(home.join(".gradle/init.d"));
|
||||
}
|
||||
if let Some(home) = step.env.get("JAVA_HOME") {
|
||||
inputs.push(Path::new(home).join("release"));
|
||||
}
|
||||
inputs.sort();
|
||||
inputs.dedup();
|
||||
let parameters =
|
||||
serde_json::to_string(&(MODEL_VERSION, jar_version, GRADLE_INIT_SCRIPT, &step.program, &step.args, &step.env))
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
Ok(LaunchFingerprint::new(parameters, fingerprint::scan_all(root, inputs, cancel)?))
|
||||
}
|
||||
|
||||
pub(super) fn read_model(path: &Path) -> IdeResult<ReactorModel> {
|
||||
let bytes = fs::read(path).map_err(|e| IdeError::internal(format!("The build wrote no model ({e})")))?;
|
||||
serde_json::from_slice(&bytes).map_err(|e| IdeError::internal(format!("Unreadable build model: {e}")))
|
||||
}
|
||||
@@ -0,0 +1,544 @@
|
||||
use super::*;
|
||||
use crate::BuildModel;
|
||||
use std::fs;
|
||||
use std::sync::Mutex as StdMutex;
|
||||
|
||||
const JAR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../../java/java-build/openidea-java-build.jar");
|
||||
|
||||
fn write(root: &Path, rel: &str, text: &str) {
|
||||
let path = root.join(rel);
|
||||
fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
fs::write(path, text).unwrap();
|
||||
}
|
||||
|
||||
/// A JDK (`JAVA_HOME`) and Maven on the search path, else `None` (the test is skipped).
|
||||
fn tools() -> Option<(PathBuf, PathBuf)> {
|
||||
let home = std::env::var_os("JAVA_HOME").map(PathBuf::from).filter(|h| h.join("bin").is_dir())?;
|
||||
let mvn = ide_core::process::find_executable("mvn", &ide_core::tool_path::search_path())?;
|
||||
Some((home, mvn))
|
||||
}
|
||||
|
||||
const ROOT_POM: &str = r#"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>root</artifactId><version>1</version><packaging>pom</packaging>
|
||||
<modules><module>lib</module><module>app</module></modules>
|
||||
<properties><maven.compiler.release>11</maven.compiler.release><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties>
|
||||
<build><pluginManagement><plugins><plugin><artifactId>maven-compiler-plugin</artifactId><version>3.13.0</version>
|
||||
<configuration><parameters>true</parameters></configuration></plugin></plugins></pluginManagement></build></project>"#;
|
||||
const LIB_POM: &str = r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>lib</artifactId></project>"#;
|
||||
const APP_POM: &str = r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>app</artifactId>
|
||||
<dependencies><dependency><groupId>t</groupId><artifactId>lib</artifactId><version>1</version></dependency></dependencies>
|
||||
<build><resources><resource><directory>src/main/resources</directory><filtering>true</filtering></resource></resources></build></project>"#;
|
||||
|
||||
/// A `lib` ← `app` reactor built by the IDE's Java build with a real Maven and JDK.
|
||||
struct Fixture {
|
||||
_tmp: tempfile::TempDir,
|
||||
root: PathBuf,
|
||||
cache: PathBuf,
|
||||
model: BuildModel,
|
||||
/// Where the build keeps its state under the cache (`Reactor::key`).
|
||||
key: &'static str,
|
||||
service: JavaBuildService,
|
||||
events: StdMutex<Vec<BuildEvent>>,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
fn new(files: &[(&str, &str)]) -> Option<Self> {
|
||||
let Some((home, mvn)) = tools() else {
|
||||
eprintln!("skipped: needs JAVA_HOME and mvn");
|
||||
return None;
|
||||
};
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
for (rel, text) in
|
||||
[("pom.xml", ROOT_POM), ("lib/pom.xml", LIB_POM), ("app/pom.xml", APP_POM)].iter().chain(files)
|
||||
{
|
||||
write(&root, rel, text);
|
||||
}
|
||||
let cache = root.join(".cache");
|
||||
let mut model = crate::load(&root, &cache, None);
|
||||
for p in &mut model.maven.as_mut().unwrap().projects {
|
||||
p.command = mvn.to_string_lossy().into_owned();
|
||||
p.env.insert("JAVA_HOME".into(), home.to_string_lossy().into_owned());
|
||||
}
|
||||
Some(Fixture {
|
||||
_tmp: tmp,
|
||||
root,
|
||||
cache,
|
||||
model,
|
||||
key: "",
|
||||
service: JavaBuildService::default(),
|
||||
events: StdMutex::default(),
|
||||
})
|
||||
}
|
||||
|
||||
/// The same `lib` ← `app` build with Gradle (`OPENIDEA_TEST_GRADLE`, else `gradle` on the
|
||||
/// search path).
|
||||
fn gradle(files: &[(&str, &str)]) -> Option<Self> {
|
||||
let home = std::env::var_os("JAVA_HOME").map(PathBuf::from).filter(|h| h.join("bin").is_dir());
|
||||
let gradle = std::env::var_os("OPENIDEA_TEST_GRADLE")
|
||||
.map(PathBuf::from)
|
||||
.or_else(|| ide_core::process::find_executable("gradle", &ide_core::tool_path::search_path()));
|
||||
let (Some(home), Some(gradle)) = (home, gradle) else {
|
||||
eprintln!("skipped: needs JAVA_HOME and gradle (OPENIDEA_TEST_GRADLE)");
|
||||
return None;
|
||||
};
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let build = [
|
||||
("settings.gradle", "rootProject.name = 'root'\ninclude 'lib', 'app'\n"),
|
||||
(
|
||||
"build.gradle",
|
||||
"subprojects {\n apply plugin: 'java'\n group = 't'\n tasks.withType(JavaCompile).configureEach { options.release = 11; options.encoding = 'UTF-8' }\n}\n",
|
||||
),
|
||||
("lib/build.gradle", ""),
|
||||
(
|
||||
"app/build.gradle",
|
||||
"dependencies { implementation project(':lib') }\nprocessResources { filesMatching('*.properties') { expand(version: '1') } }\n",
|
||||
),
|
||||
];
|
||||
for (rel, text) in build.iter().chain(files) {
|
||||
write(&root, rel, text);
|
||||
}
|
||||
let cache = root.join(".cache");
|
||||
let mut model = crate::load(&root, &cache, None);
|
||||
assert_eq!(model.gradle.len(), 1, "{model:?}");
|
||||
let g = &mut model.gradle[0];
|
||||
g.command = gradle.to_string_lossy().into_owned();
|
||||
g.env.insert("JAVA_HOME".into(), home.to_string_lossy().into_owned());
|
||||
Some(Fixture {
|
||||
_tmp: tmp,
|
||||
root,
|
||||
cache,
|
||||
model,
|
||||
key: "_gradle",
|
||||
service: JavaBuildService::default(),
|
||||
events: StdMutex::default(),
|
||||
})
|
||||
}
|
||||
|
||||
fn write(&self, rel: &str, text: &str) {
|
||||
write(&self.root, rel, text);
|
||||
}
|
||||
|
||||
fn out(&self, rel: &str) -> PathBuf {
|
||||
model::output_root(&self.cache, self.key).join(rel)
|
||||
}
|
||||
|
||||
/// Builds the launch of `app` (its tests when `test`).
|
||||
fn launch(&self, test: bool) -> LaunchOutputs {
|
||||
self.build(Target::Launch { module: &self.root.join("app"), test })
|
||||
}
|
||||
|
||||
fn build(&self, target: Target) -> LaunchOutputs {
|
||||
let jdk = |_: Option<u32>| None;
|
||||
let build = JavaBuild {
|
||||
root: &self.root,
|
||||
model: &self.model,
|
||||
cache: &self.cache,
|
||||
jar: Path::new(JAR),
|
||||
jar_version: "test",
|
||||
local_repo: None,
|
||||
service: &self.service,
|
||||
jdk: &jdk,
|
||||
};
|
||||
let on_event = |e: BuildEvent| self.events.lock().unwrap().push(e);
|
||||
match build.build(target, BuildKind::Build, &CancellationToken::new(), &on_event) {
|
||||
Ok(Built::Done(outputs)) => outputs,
|
||||
Ok(Built::Unsupported(reason)) => panic!("unsupported: {reason}"),
|
||||
Err(e) => panic!("{e:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The steps of the launch builds since the last call.
|
||||
fn steps(&self) -> Vec<String> {
|
||||
self.events
|
||||
.lock()
|
||||
.unwrap()
|
||||
.drain(..)
|
||||
.filter_map(|e| match e {
|
||||
BuildEvent::Step { command, .. } => Some(command),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Builds and returns the steps it took, which must succeed.
|
||||
fn steps_of_launch(&self) -> Vec<String> {
|
||||
self.steps();
|
||||
let built = self.launch(false);
|
||||
assert_eq!(built.failure, None, "{:?}", built.messages);
|
||||
self.steps()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_maven_modules_with_javac_and_only_what_changed() {
|
||||
let Some(f) = Fixture::new(&[
|
||||
(
|
||||
"lib/src/main/java/l/L.java",
|
||||
"package l;\npublic class L { public static String name() { return \"lib\"; } }\n",
|
||||
),
|
||||
(
|
||||
"app/src/main/java/a/A.java",
|
||||
"package a;\npublic class A { public static void main(String[] args) { System.out.println(l.L.name()); } }\n",
|
||||
),
|
||||
("app/src/main/resources/app.properties", "version=${project.version}\n"),
|
||||
("app/src/test/java/a/ATest.java", "package a;\npublic class ATest { String s = l.L.name(); }\n"),
|
||||
]) else {
|
||||
return;
|
||||
};
|
||||
|
||||
// First build: Maven prepares the model, javac compiles lib then app into the IDE's outputs.
|
||||
let first = f.launch(false);
|
||||
assert_eq!(first.failure, None, "{:?}", first.messages);
|
||||
assert_eq!(first.class_paths[0], f.out("t.app/classes"));
|
||||
assert!(first.class_paths.contains(&f.out("t.lib/classes")), "{:?}", first.class_paths);
|
||||
assert!(f.out("t.app/classes/a/A.class").is_file());
|
||||
assert!(f.out("t.lib/classes/l/L.class").is_file());
|
||||
assert!(!f.root.join("app/target/classes/a/A.class").exists());
|
||||
assert_eq!(fs::read_to_string(f.out("t.app/classes/app.properties")).unwrap(), "version=1\n");
|
||||
let steps = f.steps();
|
||||
assert!(steps[0].contains("process-resources"), "{steps:?}");
|
||||
assert_eq!(steps[1..], ["javac lib (main, 1 file)", "javac app (main, 1 file)"]);
|
||||
|
||||
// Nothing changed: no Maven, no javac.
|
||||
assert_eq!(f.steps_of_launch(), Vec::<String>::new());
|
||||
|
||||
// A change inside a method compiles that class only, without Maven.
|
||||
f.write(
|
||||
"lib/src/main/java/l/L.java",
|
||||
"package l;\npublic class L { public static String name() { return \"lib 2\"; } }\n",
|
||||
);
|
||||
assert_eq!(f.steps_of_launch(), ["javac lib (main, 1 file)"]);
|
||||
|
||||
// A resource change is processed by Maven (it filters), and compiles nothing.
|
||||
f.write("app/src/main/resources/app.properties", "version=${project.version}\nmore=1\n");
|
||||
let steps = f.steps_of_launch();
|
||||
assert_eq!(steps.len(), 1, "{steps:?}");
|
||||
assert!(steps[0].contains("resources:resources") && steps[0].contains("-pl app"), "{steps:?}");
|
||||
assert_eq!(fs::read_to_string(f.out("t.app/classes/app.properties")).unwrap(), "version=1\nmore=1\n");
|
||||
|
||||
// A deleted source leaves no class behind.
|
||||
f.write("app/src/main/java/a/Gone.java", "package a;\nclass Gone {}\n");
|
||||
assert_eq!(f.steps_of_launch(), ["javac app (main, 1 of 2 files)"]);
|
||||
assert!(f.out("t.app/classes/a/Gone.class").is_file());
|
||||
fs::remove_file(f.root.join("app/src/main/java/a/Gone.java")).unwrap();
|
||||
assert_eq!(f.steps_of_launch(), Vec::<String>::new());
|
||||
assert!(!f.out("t.app/classes/a/Gone.class").exists());
|
||||
|
||||
// Compile errors fail the build with positioned messages.
|
||||
f.write("app/src/main/java/a/A.java", "package a;\npublic class A { int x = \"s\"; }\n");
|
||||
let failed = f.launch(false);
|
||||
let failure = failed.failure.expect("fails");
|
||||
assert!(failure.contains("incompatible types"), "{failure}");
|
||||
let error = failed.messages.iter().find(|m| m.severity == Severity::Error).unwrap();
|
||||
assert_eq!(error.path.as_deref(), Some(f.root.join("app/src/main/java/a/A.java").as_path()));
|
||||
assert_eq!(error.range.unwrap().start, Pos::new(1, 25));
|
||||
// It compiles again next time, even unchanged.
|
||||
f.steps();
|
||||
assert!(f.launch(false).failure.is_some());
|
||||
assert_eq!(f.steps(), ["javac app (main, 1 file)"]);
|
||||
|
||||
// A test launch compiles the module's tests after its main classes.
|
||||
f.write(
|
||||
"app/src/main/java/a/A.java",
|
||||
"package a;\npublic class A { public static void main(String[] args) { System.out.println(l.L.name()); } }\n",
|
||||
);
|
||||
let tests = f.launch(true);
|
||||
assert_eq!(tests.failure, None, "{:?}", tests.messages);
|
||||
assert_eq!(tests.class_paths[..2], [f.out("t.app/test-classes"), f.out("t.app/classes")]);
|
||||
assert!(f.out("t.app/test-classes/a/ATest.class").is_file());
|
||||
|
||||
// Recompile compiles the file even unchanged.
|
||||
f.steps();
|
||||
let file = f.root.join("app/src/main/java/a/A.java");
|
||||
assert_eq!(f.build(Target::File(&file)).failure, None);
|
||||
assert_eq!(f.steps(), ["javac app (main, 1 file)"]);
|
||||
// Build Project builds every module's main and test classes.
|
||||
f.write("lib/src/test/java/l/LTest.java", "package l;\nclass LTest { String s = L.name(); }\n");
|
||||
assert_eq!(f.build(Target::Project).failure, None);
|
||||
assert_eq!(f.steps(), ["javac lib (tests, 1 file)"]);
|
||||
assert!(f.out("t.lib/test-classes/l/LTest.class").is_file());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recompiles_the_classes_an_api_change_reaches() {
|
||||
let Some(f) = Fixture::new(&[
|
||||
("lib/src/main/java/l/Base.java", "package l;\npublic class Base { public int m() { return 1; } }\n"),
|
||||
("lib/src/main/java/l/Sub.java", "package l;\npublic class Sub extends Base {}\n"),
|
||||
("lib/src/main/java/l/User.java", "package l;\nclass User { int u(Sub s) { return s.m(); } }\n"),
|
||||
("lib/src/main/java/l/Const.java", "package l;\npublic class Const { public static final int X = 1; }\n"),
|
||||
("lib/src/main/java/l/ConstUser.java", "package l;\nclass ConstUser { int c() { return Const.X; } }\n"),
|
||||
("lib/src/main/java/l/Other.java", "package l;\npublic class Other { public int o() { return 1; } }\n"),
|
||||
("app/src/main/java/a/A.java", "package a;\nclass A { int a() { return new l.Other().o(); } }\n"),
|
||||
("app/src/main/java/a/B.java", "package a;\nclass B { int b() { return l.Const.X; } }\n"),
|
||||
]) else {
|
||||
return;
|
||||
};
|
||||
assert_eq!(f.steps_of_launch()[1..], ["javac lib (main, 6 files)", "javac app (main, 2 files)"]);
|
||||
|
||||
// A body change: that class only, and nothing downstream.
|
||||
f.write("lib/src/main/java/l/Other.java", "package l;\npublic class Other { public int o() { return 2; } }\n");
|
||||
assert_eq!(f.steps_of_launch(), ["javac lib (main, 1 of 6 files)"]);
|
||||
|
||||
// An API change reaches the classes that use the class or a subclass of it.
|
||||
f.write(
|
||||
"lib/src/main/java/l/Base.java",
|
||||
"package l;\npublic class Base { public int m() { return 1; } public int n() { return 2; } }\n",
|
||||
);
|
||||
assert_eq!(f.steps_of_launch(), ["javac lib (main, 1 of 6 files)", "javac lib (main, 2 of 6 files)"]);
|
||||
|
||||
// Across modules: only the classes that use it.
|
||||
f.write(
|
||||
"lib/src/main/java/l/Other.java",
|
||||
"package l;\npublic class Other { public int o() { return 2; } public void p() {} }\n",
|
||||
);
|
||||
assert_eq!(f.steps_of_launch(), ["javac lib (main, 1 of 6 files)", "javac app (main, 1 of 2 files)"]);
|
||||
|
||||
// A compile-time constant is copied into its uses: everything compiled against it compiles again.
|
||||
f.write("lib/src/main/java/l/Const.java", "package l;\npublic class Const { public static final int X = 2; }\n");
|
||||
assert_eq!(
|
||||
f.steps_of_launch(),
|
||||
["javac lib (main, 1 of 6 files)", "javac lib (main, 5 of 6 files)", "javac app (main, 2 files)"]
|
||||
);
|
||||
|
||||
// A removed method fails the classes that still call it.
|
||||
f.write("lib/src/main/java/l/Base.java", "package l;\npublic class Base { public int n() { return 2; } }\n");
|
||||
let failed = f.launch(false);
|
||||
assert!(failed.failure.expect("fails").contains("User.java"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_api_change_from_a_failed_build_still_reaches_other_modules() {
|
||||
let Some(f) = Fixture::new(&[
|
||||
("lib/src/main/java/l/L.java", "package l;\npublic class L { public static int m() { return 1; } }\n"),
|
||||
("lib/src/main/java/l/U.java", "package l;\nclass U { int u() { return L.m(); } }\n"),
|
||||
("app/src/main/java/a/A.java", "package a;\nclass A { int a() { return l.L.m(); } }\n"),
|
||||
]) else {
|
||||
return;
|
||||
};
|
||||
assert_eq!(f.launch(false).failure, None);
|
||||
|
||||
// L compiles, then U, which still calls the removed method, fails lib before app compiles.
|
||||
f.write("lib/src/main/java/l/L.java", "package l;\npublic class L { public static int n() { return 1; } }\n");
|
||||
assert!(f.launch(false).failure.expect("lib fails").contains("U.java"));
|
||||
|
||||
// Once lib compiles, app learns that L changed, and A fails too instead of keeping a class
|
||||
// that calls a method L no longer has.
|
||||
f.write("lib/src/main/java/l/U.java", "package l;\nclass U { int u() { return L.n(); } }\n");
|
||||
let failed = f.launch(false);
|
||||
assert!(failed.failure.expect("app fails").contains("A.java"), "{:?}", failed.messages);
|
||||
|
||||
// So does a changed constant: C compiles, then the whole set, where U fails.
|
||||
f.write("app/src/main/java/a/A.java", "package a;\nclass A { int a() { return l.L.n() + l.C.X; } }\n");
|
||||
let c = |x: u32, y: &str| format!("package l;\npublic class C {{ public static final int X = {x};{y} }}\n");
|
||||
f.write("lib/src/main/java/l/C.java", &c(1, " public static int y() { return 0; }"));
|
||||
f.write("lib/src/main/java/l/U.java", "package l;\nclass U { int u() { return L.n() + C.y(); } }\n");
|
||||
assert_eq!(f.launch(false).failure, None);
|
||||
f.write("lib/src/main/java/l/C.java", &c(2, ""));
|
||||
assert!(f.launch(false).failure.expect("lib fails").contains("U.java"));
|
||||
f.write("lib/src/main/java/l/U.java", "package l;\nclass U { int u() { return L.n(); } }\n");
|
||||
f.steps();
|
||||
assert_eq!(f.launch(false).failure, None);
|
||||
let steps = f.steps();
|
||||
assert!(steps.contains(&"javac app (main, 1 file)".to_owned()), "{steps:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_what_a_class_file_declares() {
|
||||
let Some((home, _)) = tools() else { return };
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let compile = |text: &str| {
|
||||
write(tmp.path(), "p/C.java", text);
|
||||
let status = std::process::Command::new(home.join("bin/javac"))
|
||||
.args(["-d", "out", "p/C.java"])
|
||||
.current_dir(tmp.path())
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(status.success());
|
||||
classfile::parse(&fs::read(tmp.path().join("out/p/C.class")).unwrap()).unwrap()
|
||||
};
|
||||
let a = compile(
|
||||
"package p;\nimport java.util.List;\npublic class C extends Thread implements Runnable {\n public static final String K = \"k\";\n @Deprecated public List<javax.swing.JButton> f;\n public x.Y g() { return null; }\n private int hidden() { return 1; }\n}\nclass Z {}\n"
|
||||
.replace("x.Y", "Object")
|
||||
.as_str(),
|
||||
);
|
||||
assert_eq!(a.name, "p/C");
|
||||
assert_eq!(a.super_name.as_deref(), Some("java/lang/Thread"));
|
||||
assert_eq!(a.interfaces, ["java/lang/Runnable"]);
|
||||
assert!(a.refs.contains("javax/swing/JButton"), "{:?}", a.refs);
|
||||
assert!(!a.refs.iter().any(|r| r.starts_with("java/")), "{:?}", a.refs);
|
||||
// Private members and method bodies aren't API; constants have their own fingerprint.
|
||||
let b = compile(
|
||||
"package p;\nimport java.util.List;\npublic class C extends Thread implements Runnable {\n public static final String K = \"k\";\n @Deprecated public List<javax.swing.JButton> f;\n public Object g() { return \"x\"; }\n private long hidden2() { return 1; }\n}\nclass Z {}\n",
|
||||
);
|
||||
assert_eq!((a.api, a.constants), (b.api, b.constants));
|
||||
let c = compile(
|
||||
"package p;\nimport java.util.List;\npublic class C extends Thread implements Runnable {\n public static final String K = \"changed\";\n @Deprecated public List<javax.swing.JButton> f;\n public Object g() { return \"x\"; }\n}\nclass Z {}\n",
|
||||
);
|
||||
assert_eq!(a.api, c.api);
|
||||
assert_ne!(a.constants, c.constants);
|
||||
let d = compile(
|
||||
"package p;\nimport java.util.List;\npublic class C extends Thread implements Runnable {\n public static final String K = \"k\";\n @Deprecated public List<javax.swing.JLabel> f;\n public Object g() { return \"x\"; }\n}\nclass Z {}\n",
|
||||
);
|
||||
assert_ne!(a.api, d.api);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn follows_api_changes_through_the_log() {
|
||||
let mut state = SetState { generation: 1, ..Default::default() };
|
||||
state.log(2, ["a/A".to_owned()].into(), false);
|
||||
state.log(3, ["a/B".to_owned()].into(), false);
|
||||
assert_eq!(state.changes_since(3), Some(BTreeSet::new()));
|
||||
assert_eq!(state.changes_since(2), Some(["a/B".to_owned()].into()));
|
||||
assert_eq!(state.changes_since(1), Some(["a/A".to_owned(), "a/B".to_owned()].into()));
|
||||
// Unknown generations, and a log entry where everything changed, mean everything.
|
||||
assert_eq!(state.changes_since(0), None);
|
||||
state.log(4, BTreeSet::new(), true);
|
||||
assert_eq!(state.changes_since(3), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ant_patterns_match_like_maven() {
|
||||
assert!(ant_match("**/*.java", "a/b/C.java"));
|
||||
assert!(ant_match("**/*.java", "C.java"));
|
||||
assert!(ant_match("com/acme/**", "com/acme/x/Y.java"));
|
||||
assert!(!ant_match("com/acme/**", "com/other/Y.java"));
|
||||
assert!(ant_match("**/generated/", "x/generated/Y.java"));
|
||||
assert!(ant_match("**/*Test?.java", "a/FooTest1.java"));
|
||||
assert!(!ant_match("*.java", "a/B.java"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn javac_options_follow_the_compiler_configuration() {
|
||||
let set = SourceSet {
|
||||
output: PathBuf::from("/o"),
|
||||
compiler: Some(CompilerConfig {
|
||||
release: Some("17".into()),
|
||||
source: Some("1.8".into()),
|
||||
encoding: Some("UTF-8".into()),
|
||||
parameters: Some(true),
|
||||
debuglevel: Some("lines,vars".into()),
|
||||
proc: Some("none".into()),
|
||||
processor_path: Some(vec![PathBuf::from("/p.jar")]),
|
||||
annotation_processors: Some(vec!["a.P".into()]),
|
||||
compiler_args: vec!["-Xlint:unchecked".into()],
|
||||
compiler_arguments: [("Akey=v".to_owned(), None)].into(),
|
||||
show_warnings: Some(false),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
let args = javac_options(&set, &[PathBuf::from("/lib.jar")], Path::new("/gen"), Some(21));
|
||||
let joined = args.join(" ");
|
||||
let separator = if cfg!(windows) { ";" } else { ":" };
|
||||
assert!(joined.starts_with(&format!("-d /o -classpath /o{separator}/lib.jar -sourcepath -s /gen")), "{joined}");
|
||||
for expected in [
|
||||
"-processorpath /p.jar",
|
||||
"-processor a.P",
|
||||
"-proc:none",
|
||||
"-g:lines,vars",
|
||||
"-parameters",
|
||||
"-nowarn",
|
||||
"-encoding UTF-8",
|
||||
"--release 17",
|
||||
"-Akey=v",
|
||||
] {
|
||||
assert!(joined.contains(expected), "{expected} in {joined}");
|
||||
}
|
||||
assert!(joined.ends_with("-Xlint:unchecked"), "{joined}");
|
||||
// JDK 8 has no --release: source and target instead.
|
||||
let old = javac_options(&set, &[], Path::new("/gen"), Some(8)).join(" ");
|
||||
assert!(old.contains("-source 1.8") && !old.contains("--release"), "{old}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_gradle_projects_with_javac_and_only_what_changed() {
|
||||
let Some(f) = Fixture::gradle(&[
|
||||
(
|
||||
"lib/src/main/java/l/L.java",
|
||||
"package l;\npublic class L { public static String name() { return \"lib\"; } }\n",
|
||||
),
|
||||
(
|
||||
"app/src/main/java/a/A.java",
|
||||
"package a;\npublic class A { public static void main(String[] args) { System.out.println(l.L.name()); } }\n",
|
||||
),
|
||||
("app/src/main/resources/app.properties", "version=${version}\n"),
|
||||
("app/src/test/java/a/ATest.java", "package a;\npublic class ATest { String s = l.L.name(); }\n"),
|
||||
]) else {
|
||||
return;
|
||||
};
|
||||
let steps = f.steps_of_launch();
|
||||
assert_eq!(steps.len(), 3, "{steps:?}");
|
||||
assert!(steps[0].contains("openideaBuildModel"), "{steps:?}");
|
||||
assert!(steps[1].starts_with("javac lib (main"), "{steps:?}");
|
||||
assert!(steps[2].starts_with("javac app (main"), "{steps:?}");
|
||||
assert!(f.out("t.lib/classes/l/L.class").is_file());
|
||||
assert!(f.out("t.app/classes/a/A.class").is_file());
|
||||
assert_eq!(fs::read_to_string(f.out("t.app/classes/app.properties")).unwrap(), "version=1\n");
|
||||
// Gradle's own outputs stay untouched.
|
||||
assert!(!f.root.join("app/build/classes").exists());
|
||||
|
||||
let built = f.launch(false);
|
||||
assert!(built.class_paths.iter().any(|p| p.ends_with("t.lib/classes")), "{:?}", built.class_paths);
|
||||
assert!(!built.class_paths.iter().any(|p| p.extension().is_some_and(|e| e == "jar")), "{:?}", built.class_paths);
|
||||
assert_eq!(f.steps(), Vec::<String>::new(), "nothing changed");
|
||||
|
||||
f.write(
|
||||
"app/src/main/java/a/A.java",
|
||||
"package a;\npublic class A { public static void main(String[] args) { System.out.println(l.L.name() + 1); } }\n",
|
||||
);
|
||||
let steps = f.steps_of_launch();
|
||||
assert_eq!(steps.len(), 1, "{steps:?}");
|
||||
assert!(steps[0].starts_with("javac app (main"), "{steps:?}");
|
||||
|
||||
f.write("app/src/main/resources/app.properties", "version=${version}\nname=app\n");
|
||||
let steps = f.steps_of_launch();
|
||||
assert_eq!(steps.len(), 1, "{steps:?}");
|
||||
assert!(steps[0].contains(":app:processResources"), "{steps:?}");
|
||||
assert_eq!(fs::read_to_string(f.out("t.app/classes/app.properties")).unwrap(), "version=1\nname=app\n");
|
||||
|
||||
// Tests compile against the main classes.
|
||||
f.steps();
|
||||
let built = f.launch(true);
|
||||
assert_eq!(built.failure, None, "{:?}", built.messages);
|
||||
assert!(f.out("t.app/test-classes/a/ATest.class").is_file());
|
||||
|
||||
// A changed build script prepares again.
|
||||
f.write("lib/build.gradle", "// changed\n");
|
||||
let steps = f.steps_of_launch();
|
||||
assert!(steps[0].contains("openideaBuildModel"), "{steps:?}");
|
||||
|
||||
// An error is a javac diagnostic on the source.
|
||||
f.write("lib/src/main/java/l/L.java", "package l;\npublic class L { public static String name() { return 1; } }\n");
|
||||
let built = f.launch(false);
|
||||
assert!(built.failure.is_some());
|
||||
let error = built.messages.iter().find(|m| m.severity == Severity::Error).expect("an error");
|
||||
assert_eq!(error.path.as_deref(), Some(f.root.join("lib/src/main/java/l/L.java").as_path()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leaves_gradle_projects_with_other_compilers_to_gradle() {
|
||||
let Some(f) = Fixture::gradle(&[
|
||||
("app/build.gradle", "apply plugin: 'groovy'\ndependencies { implementation project(':lib') }\n"),
|
||||
("app/src/main/java/a/A.java", "package a;\npublic class A {}\n"),
|
||||
]) else {
|
||||
return;
|
||||
};
|
||||
let jdk = |_: Option<u32>| None;
|
||||
let build = JavaBuild {
|
||||
root: &f.root,
|
||||
model: &f.model,
|
||||
cache: &f.cache,
|
||||
jar: Path::new(JAR),
|
||||
jar_version: "test",
|
||||
local_repo: None,
|
||||
service: &f.service,
|
||||
jdk: &jdk,
|
||||
};
|
||||
let target = Target::Launch { module: &f.root.join("app"), test: false };
|
||||
match build.build(target, BuildKind::Build, &CancellationToken::new(), &|_| {}) {
|
||||
Ok(Built::Unsupported(reason)) => assert!(reason.contains("GroovyCompile"), "{reason}"),
|
||||
Ok(Built::Done(outputs)) => panic!("built: {outputs:?}"),
|
||||
Err(e) => panic!("{e:?}"),
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ pub mod application_update;
|
||||
pub mod compile;
|
||||
pub mod gradle;
|
||||
mod gradle_deps;
|
||||
pub mod jbuild;
|
||||
pub mod kotlin_bridge;
|
||||
pub mod maven;
|
||||
pub mod pom_edit;
|
||||
|
||||
@@ -753,7 +753,26 @@ pub(crate) fn launch_inputs(
|
||||
projects: &[&MavenProject],
|
||||
local_repo: Option<PathBuf>,
|
||||
) -> Option<Vec<PathBuf>> {
|
||||
fn roots(el: &Element, parent: &str, dir: &Path, out: &mut Vec<PathBuf>) -> Option<()> {
|
||||
project_inputs(root, projects, local_repo, true)
|
||||
}
|
||||
|
||||
/// The POM chains (with imported BOMs) of `projects` and the files their profiles activate
|
||||
/// on: what Maven's model of them is built from, without their sources.
|
||||
pub(crate) fn model_inputs(
|
||||
root: &Path,
|
||||
projects: &[&MavenProject],
|
||||
local_repo: Option<PathBuf>,
|
||||
) -> Option<Vec<PathBuf>> {
|
||||
project_inputs(root, projects, local_repo, false)
|
||||
}
|
||||
|
||||
fn project_inputs(
|
||||
root: &Path,
|
||||
projects: &[&MavenProject],
|
||||
local_repo: Option<PathBuf>,
|
||||
sources: bool,
|
||||
) -> Option<Vec<PathBuf>> {
|
||||
fn roots(el: &Element, parent: &str, dir: &Path, sources: bool, out: &mut Vec<PathBuf>) -> Option<()> {
|
||||
let input =
|
||||
matches!(el.name.as_str(), "sourceDirectory" | "testSourceDirectory" | "sourceDir" | "testSourceDir")
|
||||
|| (matches!(parent, "sources" | "sourceDirs" | "testSources" | "testSourceDirs")
|
||||
@@ -762,6 +781,7 @@ pub(crate) fn launch_inputs(
|
||||
|| (parent == "filters" && el.name == "filter");
|
||||
// Profile activation may depend on the presence of an otherwise unrelated file.
|
||||
let activation = parent == "file" && matches!(el.name.as_str(), "exists" | "missing");
|
||||
let input = input && sources;
|
||||
if input || activation {
|
||||
// A source root under Maven's build directory is generated by the build itself.
|
||||
// Skip it without resolving the property: `<build><directory>` may be custom, and
|
||||
@@ -787,7 +807,7 @@ pub(crate) fn launch_inputs(
|
||||
}
|
||||
}
|
||||
for child in &el.children {
|
||||
roots(child, &el.name, dir, out)?;
|
||||
roots(child, &el.name, dir, sources, out)?;
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
@@ -796,7 +816,9 @@ pub(crate) fn launch_inputs(
|
||||
for project in projects {
|
||||
let dir = root.join(&project.dir);
|
||||
// Include all conventional language/resource roots, including nonstandard files under src.
|
||||
out.push(dir.join("src"));
|
||||
if sources {
|
||||
out.push(dir.join("src"));
|
||||
}
|
||||
let pom = root.join(&project.pom);
|
||||
resolver.context(&pom, 0);
|
||||
let mut path = pom;
|
||||
@@ -808,7 +830,7 @@ pub(crate) fn launch_inputs(
|
||||
}
|
||||
out.push(path.clone());
|
||||
let text = xml::read_text(&path)?;
|
||||
roots(&xml::parse(&text)?, "", &dir, &mut out)?;
|
||||
roots(&xml::parse(&text)?, "", &dir, sources, &mut out)?;
|
||||
let raw = resolver.pom(&path)?;
|
||||
let Some(parent) = raw.parent else { break };
|
||||
path = resolver.parent_path(path.parent()?, &parent)?;
|
||||
|
||||
@@ -118,6 +118,8 @@ pub struct Host {
|
||||
pub(crate) heap_windows: Mutex<HashMap<ide_heap::HeapSnapshotId, String>>,
|
||||
pub(crate) heap_requests: ops::heap::HeapRequests,
|
||||
pub(crate) rebase_editors: Arc<ops::vcs::RebaseEditors>,
|
||||
/// The IDE's Java build: resident javac processes shared by every window's launches.
|
||||
pub(crate) java_build: Arc<ide_build::jbuild::JavaBuildService>,
|
||||
/// SSH connections of Settings › SSH Configurations.
|
||||
pub ssh: Arc<ide_ssh::SshManager>,
|
||||
/// SFTP deployment, remote file editing and runs on run targets.
|
||||
@@ -227,6 +229,7 @@ impl Host {
|
||||
heap_windows: Mutex::default(),
|
||||
heap_requests: Default::default(),
|
||||
rebase_editors: Default::default(),
|
||||
java_build: Default::default(),
|
||||
languages,
|
||||
syntax,
|
||||
config_dir,
|
||||
|
||||
@@ -513,6 +513,7 @@ async fn resolve_jvm_application(
|
||||
call.window(),
|
||||
std::path::PathBuf::from(&module),
|
||||
test == Some(true),
|
||||
false,
|
||||
policy,
|
||||
&cancel,
|
||||
None,
|
||||
|
||||
@@ -9,6 +9,7 @@ use crate::{Host, Project};
|
||||
use ide_command::command;
|
||||
|
||||
use ide_build::compile::{self, BuildEvent, BuildKind, BuildResult};
|
||||
use ide_build::jbuild::Target;
|
||||
use ide_build::maven::completion::{PomCompletion, PomCompletionOption};
|
||||
use ide_build::maven::sources;
|
||||
use ide_build::maven::{PomGoto, PomManagedDeclaration, PomNavigationOptions};
|
||||
@@ -975,11 +976,38 @@ pub async fn build_run(
|
||||
let config_dir = host.config_dir.clone();
|
||||
let token = host.begin_project_request(window, request);
|
||||
let launch_project = project.clone();
|
||||
let (service, data_dir) = (host.java_build.clone(), host.local_data_dir.clone());
|
||||
let result = blocking(move || {
|
||||
let single = cmake.is_none() && ide_workspace::workspace::Workspace::load(&root)?.is_none();
|
||||
// A Maven or Gradle project builds with the IDE's Java build (#4078), unless its
|
||||
// settings ask for the build tool, or it can't.
|
||||
if single {
|
||||
let model = with_profiles(load(&root, &cache, &settings), &cache);
|
||||
let served = match file.as_deref() {
|
||||
Some(module) => super::java::served_by_service(&root, &model, &settings, module),
|
||||
None => super::java::project_served_by_service(&model, &settings),
|
||||
};
|
||||
if served {
|
||||
let service = super::java::ServiceBuild {
|
||||
service: &service,
|
||||
data_dir: &data_dir,
|
||||
root: &root,
|
||||
cache: &cache,
|
||||
settings: &settings,
|
||||
model: &model,
|
||||
};
|
||||
let target = match file.as_deref() {
|
||||
Some(file) => Target::Module(file),
|
||||
None => Target::Project,
|
||||
};
|
||||
if let Some(result) = service_build_result(&service, target, kind, &clear, &sink, &token, &on_event)? {
|
||||
return Ok(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Fast path (#2476): an unchanged single-project Maven build skips
|
||||
// Maven entirely. Previous diagnostics stay: nothing changed, so they
|
||||
// are still accurate.
|
||||
let single = cmake.is_none() && ide_workspace::workspace::Workspace::load(&root)?.is_none();
|
||||
if single && kind == BuildKind::Build {
|
||||
let model = with_profiles(load(&root, &cache, &settings), &cache);
|
||||
if compile::menu_up_to_date(&cache, &root, &model, file.as_deref(), &token) {
|
||||
@@ -1102,13 +1130,59 @@ pub async fn build_run(
|
||||
let outcome = result?;
|
||||
// Maven generated sources (protobuf, gRPC) stay invisible to jdtls until the
|
||||
// folders the build wrote are attached. An up-to-date build skips Maven and
|
||||
// still needs this: the classes can already be on disk.
|
||||
if outcome.system == ide_build::compile::BuildSystem::Maven {
|
||||
// still needs this: the classes can already be on disk. The IDE's Java build
|
||||
// generates them with Maven too.
|
||||
if matches!(outcome.system, ide_build::compile::BuildSystem::Maven | ide_build::compile::BuildSystem::Javac) {
|
||||
project.lsp.sync_maven_generated_sources(&project.root).await;
|
||||
}
|
||||
Ok(outcome)
|
||||
}
|
||||
|
||||
/// A menu build by the IDE's Java build, as the Build window shows it; `None` when Maven builds.
|
||||
/// Diagnostics of `clear` are cleared once the service builds; its messages are published.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn service_build_result(
|
||||
service: &super::java::ServiceBuild,
|
||||
target: Target,
|
||||
kind: BuildKind,
|
||||
clear: &[std::path::PathBuf],
|
||||
sink: &ide_core::SharedSink,
|
||||
token: &CancellationToken,
|
||||
on_event: &Channel<BuildEvent>,
|
||||
) -> IdeResult<Option<BuildResult>> {
|
||||
let started = std::time::Instant::now();
|
||||
let title = std::sync::Mutex::new(String::new());
|
||||
let forward = |event: BuildEvent| {
|
||||
if let BuildEvent::Started { title: t, .. } = &event {
|
||||
*title.lock().unwrap() = t.clone();
|
||||
}
|
||||
let _ = on_event.send(event);
|
||||
};
|
||||
let built = service.build(target, kind, token, &forward)?;
|
||||
let Some(outputs) = built else { return Ok(None) };
|
||||
for path in clear {
|
||||
sink.emit(IdeEvent::Diagnostics {
|
||||
path: path.clone().into(),
|
||||
source: compile::DIAGNOSTICS_SOURCE.into(),
|
||||
items: Vec::new(),
|
||||
});
|
||||
}
|
||||
for (path, items) in compile::diagnostics(&outputs.messages) {
|
||||
sink.emit(IdeEvent::Diagnostics { path: path.into(), source: compile::DIAGNOSTICS_SOURCE.into(), items });
|
||||
}
|
||||
let count =
|
||||
|severity: ide_core::Severity| outputs.messages.iter().filter(|m| m.severity == severity).count() as u32;
|
||||
Ok(Some(BuildResult {
|
||||
system: compile::BuildSystem::Javac,
|
||||
title: title.into_inner().unwrap(),
|
||||
success: outputs.failure.is_none(),
|
||||
errors: count(ide_core::Severity::Error),
|
||||
warnings: count(ide_core::Severity::Warning),
|
||||
duration_ms: started.elapsed().as_secs_f64() * 1000.0,
|
||||
messages: outputs.messages,
|
||||
}))
|
||||
}
|
||||
|
||||
fn plan_compile_file(
|
||||
root: &Path,
|
||||
cache: &Path,
|
||||
@@ -1167,7 +1241,26 @@ pub async fn build_compile_file(
|
||||
};
|
||||
let sink = project.sink.clone();
|
||||
let token = host.begin_project_request(window, request);
|
||||
let (service, data_dir) = (host.java_build.clone(), host.local_data_dir.clone());
|
||||
let result = blocking(move || {
|
||||
{
|
||||
let model = with_profiles(load(&scope.root, &scope.cache, &scope.settings), &scope.cache);
|
||||
if super::java::served_by_service(&scope.root, &model, &scope.settings, &file) {
|
||||
let service = super::java::ServiceBuild {
|
||||
service: &service,
|
||||
data_dir: &data_dir,
|
||||
root: &scope.root,
|
||||
cache: &scope.cache,
|
||||
settings: &scope.settings,
|
||||
model: &model,
|
||||
};
|
||||
let target = Target::File(&file);
|
||||
let kind = BuildKind::Build;
|
||||
if let Some(result) = service_build_result(&service, target, kind, &clear, &sink, &token, &on_event)? {
|
||||
return Ok(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
for path in clear {
|
||||
sink.emit(IdeEvent::Diagnostics {
|
||||
path: path.into(),
|
||||
@@ -1190,7 +1283,7 @@ pub async fn build_compile_file(
|
||||
.await;
|
||||
host.end_request(request);
|
||||
let outcome = result?;
|
||||
if outcome.system == ide_build::compile::BuildSystem::Maven {
|
||||
if matches!(outcome.system, ide_build::compile::BuildSystem::Maven | ide_build::compile::BuildSystem::Javac) {
|
||||
project.lsp.sync_maven_generated_sources(&scope_root).await;
|
||||
}
|
||||
Ok(outcome)
|
||||
|
||||
@@ -9,6 +9,7 @@ use super::build::{load, with_profiles, workspace};
|
||||
use cache::LaunchEvents;
|
||||
use ide_build::BuildModel;
|
||||
use ide_build::compile::{self, BuildEvent};
|
||||
use ide_build::jbuild::{Built, JavaBuild, JavaBuildService, LaunchOutputs, Target};
|
||||
use ide_core::error::ErrorKind;
|
||||
use ide_core::settings::Settings;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult, RequestId};
|
||||
@@ -22,12 +23,16 @@ use std::path::{Path, PathBuf};
|
||||
/// A module with Kotlin / Groovy / Scala sources is built by its build system, whose class directories come first.
|
||||
/// The build streams its console, messages and progress on `on_event` while it runs; a launch
|
||||
/// whose build another launch's build joins receives that build's events.
|
||||
/// A Maven module is built by the IDE's Java build, except for a `debug` launch the language
|
||||
/// server serves: java-debug's HotSwap reloads the classes the language server compiles.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[command(trust = trusted)]
|
||||
pub async fn java_resolve_launch(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
module: PathBuf,
|
||||
test: bool,
|
||||
debug: bool,
|
||||
policy: BuildPolicy,
|
||||
request: RequestId,
|
||||
on_event: Channel<BuildEvent>,
|
||||
@@ -39,16 +44,18 @@ pub async fn java_resolve_launch(
|
||||
let events: LaunchEvents = std::sync::Arc::new(move |event| {
|
||||
let _ = on_event.send(event);
|
||||
});
|
||||
let result = resolve_launch(host, window, module, test, policy, &cancel, Some(events)).await;
|
||||
let result = resolve_launch(host, window, module, test, debug, policy, &cancel, Some(events)).await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) async fn resolve_launch(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
module: PathBuf,
|
||||
test: bool,
|
||||
debug: bool,
|
||||
policy: BuildPolicy,
|
||||
cancel: &CancellationToken,
|
||||
events: Option<LaunchEvents>,
|
||||
@@ -73,13 +80,12 @@ pub(crate) async fn resolve_launch(
|
||||
}
|
||||
let scope = std::sync::Arc::new(scope);
|
||||
let launches = project.java_launches.for_cache(&scope.cache);
|
||||
let waiting = launches.waiting.add(module.clone(), test, policy, events.clone());
|
||||
let prefer_maven = scope.settings.languages.java.maven.delegate_build;
|
||||
// A launch builds incrementally unless the configuration asks for Rebuild or NoBuild.
|
||||
let build = policy != BuildPolicy::NoBuild;
|
||||
let full = policy == BuildPolicy::Rebuild;
|
||||
let build_kind = if full { compile::BuildKind::Rebuild } else { compile::BuildKind::Build };
|
||||
let (model, external, mut delegated, is_maven) = {
|
||||
let (model, external, mut delegated, is_maven, non_java, served) = {
|
||||
let scope = scope.clone();
|
||||
let launches = launches.clone();
|
||||
let module = module.clone();
|
||||
@@ -89,6 +95,7 @@ pub(crate) async fn resolve_launch(
|
||||
let model = load_launch_model(&scope);
|
||||
let non_java = build && compile::launch_has_non_java_sources(root, &model, &module, test);
|
||||
let is_maven = is_maven_module(root, &model, &module);
|
||||
let served = served_by_service(root, &model, &scope.settings, &module);
|
||||
let delegated = build
|
||||
&& delegates_to_external_build(
|
||||
is_maven,
|
||||
@@ -98,11 +105,65 @@ pub(crate) async fn resolve_launch(
|
||||
prefer_maven,
|
||||
);
|
||||
let external = non_java || delegated;
|
||||
(model, external, delegated, is_maven)
|
||||
(std::sync::Arc::new(model), external, delegated, is_maven, non_java, served)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
};
|
||||
// A Maven or Gradle module is built by the IDE's Java build ([`served_by_service`]), unless
|
||||
// the launch debugs with java-debug, whose HotSwap reloads what jdtls compiles (ecj's
|
||||
// classes differ from javac's: lambda names). jdtls keeps building for its diagnostics
|
||||
// either way.
|
||||
if served && !non_java && !debug {
|
||||
let built = {
|
||||
let (service, data_dir, scope, model, module, cancel, events) = (
|
||||
host.java_build.clone(),
|
||||
host.local_data_dir.clone(),
|
||||
scope.clone(),
|
||||
model.clone(),
|
||||
module.clone(),
|
||||
cancel.clone(),
|
||||
events.clone(),
|
||||
);
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let on_event = |event: BuildEvent| {
|
||||
if let Some(events) = &events {
|
||||
events(event);
|
||||
}
|
||||
};
|
||||
let kind = build.then_some(build_kind);
|
||||
build_with_service(&service, &data_dir, &scope, &model, &module, test, kind, &cancel, &on_event)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))??
|
||||
};
|
||||
if let Some(outputs) = built {
|
||||
progress("Resolving the classpath");
|
||||
let mut info = project.lsp.java_launch(&module, test, false, false, false, cancel).await?;
|
||||
let data_dir = host.local_data_dir.clone();
|
||||
let cancel = cancel.clone();
|
||||
return tokio::task::spawn_blocking(move || {
|
||||
// javac's verdict replaces JDT's, as a Maven build's does.
|
||||
if build {
|
||||
apply_external_build_result(&mut info, outputs.failure, true);
|
||||
}
|
||||
info.class_paths = outputs.class_paths.iter().map(|p| p.to_string_lossy().into_owned()).collect();
|
||||
apply_library_classpath(&mut info, &scope.root, &scope.settings.project_structure.libraries, test);
|
||||
finish_launch(&mut info, &scope.root, &module, &scope.settings, &model, &data_dir);
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
tracing::info!(
|
||||
total_ms = started.elapsed().as_millis(),
|
||||
"Java launch resolved with the IDE's Java build"
|
||||
);
|
||||
Ok(info)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
}
|
||||
}
|
||||
let waiting = launches.waiting.add(module.clone(), test, policy, events.clone());
|
||||
let mut external_build =
|
||||
if delegated { Some(project.lsp.java_external_build(&module, cancel).await?) } else { None };
|
||||
if build && !delegated {
|
||||
@@ -124,7 +185,6 @@ pub(crate) async fn resolve_launch(
|
||||
drop_processor_recreate_errors(&mut info);
|
||||
}
|
||||
}
|
||||
let model = std::sync::Arc::new(model);
|
||||
let members = if delegated {
|
||||
build_members(&project, &scope, &model, &module, test, &waiting, cancel).await?
|
||||
} else {
|
||||
@@ -217,6 +277,104 @@ pub(crate) async fn resolve_launch(
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
}
|
||||
|
||||
/// Builds the launch of a Maven module with the IDE's Java build (#4078): javac in a resident
|
||||
/// process with the configuration Maven gives the compiler, into outputs in the project cache
|
||||
/// that neither the language server nor a terminal `mvn` writes. `None` when the module needs
|
||||
/// Maven's own build (another compiler, a multi-release jar, a Java module…), which then runs.
|
||||
/// Without `kind` (no build before launch), the outputs of its last build, if any.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn build_with_service(
|
||||
service: &JavaBuildService,
|
||||
data_dir: &Path,
|
||||
scope: &workspace::Scope,
|
||||
model: &BuildModel,
|
||||
module: &Path,
|
||||
test: bool,
|
||||
kind: Option<compile::BuildKind>,
|
||||
cancel: &CancellationToken,
|
||||
on_event: &(dyn Fn(BuildEvent) + Sync),
|
||||
) -> IdeResult<Option<LaunchOutputs>> {
|
||||
let service =
|
||||
ServiceBuild { service, data_dir, root: &scope.root, cache: &scope.cache, settings: &scope.settings, model };
|
||||
match kind {
|
||||
Some(kind) => service.build(Target::Launch { module, test }, kind, cancel, on_event),
|
||||
// No build: the outputs of the last one, when there was one.
|
||||
None => Ok(service
|
||||
.with(module, |build| build.recorded_launch(module, test))
|
||||
.flatten()
|
||||
.map(|class_paths| LaunchOutputs { class_paths, ..Default::default() })),
|
||||
}
|
||||
}
|
||||
|
||||
/// A build of the IDE's Java build service in one project (or workspace member).
|
||||
pub(crate) struct ServiceBuild<'a> {
|
||||
pub service: &'a JavaBuildService,
|
||||
pub data_dir: &'a Path,
|
||||
pub root: &'a Path,
|
||||
pub cache: &'a Path,
|
||||
pub settings: &'a Settings,
|
||||
pub model: &'a BuildModel,
|
||||
}
|
||||
|
||||
impl ServiceBuild<'_> {
|
||||
/// Runs `f` with the build, its JDKs resolved for `module`; `None` when the build jar
|
||||
/// can't be installed.
|
||||
fn with<R>(&self, module: &Path, f: impl FnOnce(&JavaBuild) -> R) -> Option<R> {
|
||||
let jar = ide_sdk::java::java_build_jar(self.data_dir)?;
|
||||
let (root, settings) = (self.root, self.settings);
|
||||
let jdk = |release: Option<u32>| {
|
||||
ide_sdk::apply::module_jdk(root, module, settings)
|
||||
.or_else(|| ide_sdk::java::pick_jdk(&ide_sdk::java::installed_jdks(), release).cloned())
|
||||
.map(|jdk| jdk.home)
|
||||
};
|
||||
let version = ide_sdk::java::java_build_version();
|
||||
let build = JavaBuild {
|
||||
root,
|
||||
model: self.model,
|
||||
cache: self.cache,
|
||||
jar: &jar,
|
||||
jar_version: &version,
|
||||
local_repo: ide_sdk::apply::maven_local_repository(root, settings),
|
||||
service: self.service,
|
||||
jdk: &jdk,
|
||||
};
|
||||
Some(f(&build))
|
||||
}
|
||||
|
||||
/// Builds `target`; `None` when the build tool has to (the service doesn't build it, or failed).
|
||||
pub fn build(
|
||||
&self,
|
||||
target: Target,
|
||||
kind: compile::BuildKind,
|
||||
cancel: &CancellationToken,
|
||||
on_event: &(dyn Fn(BuildEvent) + Sync),
|
||||
) -> IdeResult<Option<LaunchOutputs>> {
|
||||
let module = match target {
|
||||
Target::Launch { module, .. } | Target::Module(module) | Target::File(module) => module,
|
||||
Target::Project => self.root,
|
||||
};
|
||||
let Some(built) = self.with(module, |build| build.build(target, kind, cancel, on_event)) else {
|
||||
return Ok(None);
|
||||
};
|
||||
match built {
|
||||
Ok(Built::Done(outputs)) => Ok(Some(outputs)),
|
||||
Ok(Built::Unsupported(reason)) => {
|
||||
tracing::info!(module = %module.display(), reason, "Building with the build tool");
|
||||
Ok(None)
|
||||
}
|
||||
Err(e) if e.kind == ErrorKind::Cancelled => Err(e),
|
||||
Err(e) => {
|
||||
tracing::warn!(module = %module.display(), "The IDE's Java build failed: {}", e.message);
|
||||
on_event(BuildEvent::Output {
|
||||
text: format!("The IDE's Java build failed, so the build tool builds it: {}\n", e.message),
|
||||
stderr: true,
|
||||
});
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn load_launch_model(scope: &workspace::Scope) -> BuildModel {
|
||||
with_profiles(load(&scope.root, &scope.cache, &scope.settings), &scope.cache)
|
||||
}
|
||||
@@ -225,6 +383,39 @@ fn is_maven_module(root: &Path, model: &BuildModel, module: &Path) -> bool {
|
||||
model.maven.as_ref().is_some_and(|m| m.projects.iter().any(|p| root.join(&p.dir) == module))
|
||||
}
|
||||
|
||||
/// Whether the IDE's Java build builds the module holding `path` (#4078): a Maven module unless
|
||||
/// Settings › Maven › Delegate IDE build/run actions to Maven asks for Maven; a Gradle module
|
||||
/// when Settings › Gradle › Build and run using asks for the IDE.
|
||||
pub(crate) fn served_by_service(root: &Path, model: &BuildModel, settings: &Settings, path: &Path) -> bool {
|
||||
let maven = model.maven.iter().flat_map(|m| m.projects.iter().map(|p| (root.join(&p.dir), true)));
|
||||
let gradle = model.gradle.iter().flat_map(|g| g.projects.iter().map(|p| (root.join(&p.dir), false)));
|
||||
// The deepest module holding it; Maven's when both build the folder.
|
||||
let module = maven
|
||||
.chain(gradle)
|
||||
.filter(|(dir, _)| path.starts_with(dir))
|
||||
.max_by_key(|(dir, maven)| (dir.components().count(), *maven));
|
||||
match module {
|
||||
Some((_, true)) => !settings.languages.java.maven.delegate_build,
|
||||
Some((_, false)) => gradle_served(settings),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the IDE's Java build builds the whole project: it has Maven or Gradle builds, and
|
||||
/// builds them all.
|
||||
pub(crate) fn project_served_by_service(model: &BuildModel, settings: &Settings) -> bool {
|
||||
let maven = model.maven.as_ref().map(|_| !settings.languages.java.maven.delegate_build);
|
||||
let gradle = (!model.gradle.is_empty()).then(|| gradle_served(settings));
|
||||
match (maven, gradle) {
|
||||
(None, None) => false,
|
||||
(maven, gradle) => maven.unwrap_or(true) && gradle.unwrap_or(true),
|
||||
}
|
||||
}
|
||||
|
||||
fn gradle_served(settings: &Settings) -> bool {
|
||||
settings.languages.java.gradle.run_using == ide_core::settings::GradleRunUsing::Ide
|
||||
}
|
||||
|
||||
/// A launch of a module jdtls doesn't serve (another Java language server, or none): the
|
||||
/// build tool compiles it, and the classpath comes from that server, else from Maven.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
@@ -241,8 +432,9 @@ async fn resolve_launch_without_jdtls(
|
||||
let started = std::time::Instant::now();
|
||||
let scope = std::sync::Arc::new(scope);
|
||||
let kind = if policy == BuildPolicy::Rebuild { compile::BuildKind::Rebuild } else { compile::BuildKind::Build };
|
||||
let (model, built) = {
|
||||
let (model, built, by_service) = {
|
||||
let (scope, module, cancel, events) = (scope.clone(), module.clone(), cancel.clone(), events.clone());
|
||||
let (service, data_dir) = (host.java_build.clone(), host.local_data_dir.clone());
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let model = load_launch_model(&scope);
|
||||
let on_event = |event: BuildEvent| {
|
||||
@@ -250,12 +442,33 @@ async fn resolve_launch_without_jdtls(
|
||||
events(event);
|
||||
}
|
||||
};
|
||||
let built = if policy == BuildPolicy::NoBuild {
|
||||
None
|
||||
} else {
|
||||
Some(compile::build_for_launch(&scope.root, &model, &module, test, kind, &cancel, &on_event))
|
||||
};
|
||||
(model, built)
|
||||
if policy == BuildPolicy::NoBuild {
|
||||
return (model, None, false);
|
||||
}
|
||||
if served_by_service(&scope.root, &model, &scope.settings, &module)
|
||||
&& !compile::launch_has_non_java_sources(&scope.root, &model, &module, test)
|
||||
{
|
||||
match build_with_service(
|
||||
&service,
|
||||
&data_dir,
|
||||
&scope,
|
||||
&model,
|
||||
&module,
|
||||
test,
|
||||
Some(kind),
|
||||
&cancel,
|
||||
&on_event,
|
||||
) {
|
||||
Ok(Some(outputs)) => {
|
||||
let built = compile::LaunchBuild { class_dirs: outputs.class_paths, failure: outputs.failure };
|
||||
return (model, Some(Ok(built)), true);
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(e) => return (model, Some(Err(e)), false),
|
||||
}
|
||||
}
|
||||
let built = compile::build_for_launch(&scope.root, &model, &module, test, kind, &cancel, &on_event);
|
||||
(model, Some(built), false)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?
|
||||
@@ -294,6 +507,12 @@ async fn resolve_launch_without_jdtls(
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let (root, cache, settings) = (&scope.root, &scope.cache, &scope.settings);
|
||||
match from_server {
|
||||
// The IDE's Java build gave the whole classpath; the server adds its JDK.
|
||||
Some(server) if by_service => {
|
||||
info.project_root = server.classpath.project_root;
|
||||
info.java_home = server.jdk_home.map(Into::into);
|
||||
}
|
||||
None if by_service => {}
|
||||
Some(server) => {
|
||||
info.project_root = server.classpath.project_root;
|
||||
info.module_paths = server.classpath.module_paths;
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
mod common;
|
||||
|
||||
use ide_build::compile::BuildEvent;
|
||||
use ide_core::RequestId;
|
||||
use ide_host::{Host, ops};
|
||||
use ide_run::BuildPolicy;
|
||||
use ide_workspace::{SettingsStore, settings::SettingsScope};
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
fn write(root: &Path, rel: &str, text: &str) {
|
||||
let path = root.join(rel);
|
||||
fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
fs::write(path, text).unwrap();
|
||||
}
|
||||
|
||||
/// A Maven launch compiles with the IDE's Java build (javac, outputs in the project cache)
|
||||
/// and runs from its outputs. Needs `mvn` and a JDK (`JAVA_HOME`), else it is skipped.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn maven_launch_compiles_with_the_ides_java_build() {
|
||||
let has_jdk = std::env::var_os("JAVA_HOME").is_some_and(|h| Path::new(&h).join("bin").is_dir());
|
||||
if !has_jdk || ide_core::process::find_executable("mvn", &ide_core::tool_path::search_path()).is_none() {
|
||||
eprintln!("skipped: needs JAVA_HOME and mvn");
|
||||
return;
|
||||
}
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
write(
|
||||
&root,
|
||||
"pom.xml",
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>root</artifactId><version>1</version><packaging>pom</packaging>
|
||||
<modules><module>lib</module><module>app</module></modules>
|
||||
<properties><maven.compiler.release>11</maven.compiler.release><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties></project>"#,
|
||||
);
|
||||
write(
|
||||
&root,
|
||||
"lib/pom.xml",
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>lib</artifactId></project>"#,
|
||||
);
|
||||
write(
|
||||
&root,
|
||||
"app/pom.xml",
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent><artifactId>app</artifactId>
|
||||
<dependencies><dependency><groupId>t</groupId><artifactId>lib</artifactId><version>1</version></dependency></dependencies></project>"#,
|
||||
);
|
||||
write(
|
||||
&root,
|
||||
"lib/src/main/java/l/L.java",
|
||||
"package l;\npublic class L { public static String name() { return \"lib\"; } }\n",
|
||||
);
|
||||
write(
|
||||
&root,
|
||||
"app/src/main/java/a/A.java",
|
||||
"package a;\npublic class A { public static void main(String[] args) { System.out.println(l.L.name()); } }\n",
|
||||
);
|
||||
// No language server: the build tool compiles the launch.
|
||||
let global = SettingsStore::load(&base.join("config"), None);
|
||||
for server in ["jdtls", "java-analyzer", "kmp-lsp"] {
|
||||
global
|
||||
.set(SettingsScope::Global, &format!("languageServers.{server}.enabled"), serde_json::json!(false))
|
||||
.unwrap();
|
||||
}
|
||||
let host = Host::new(common::host_config(&base));
|
||||
host.trust.decide(&root, true, false).unwrap();
|
||||
host.open_project("main", &root).unwrap();
|
||||
|
||||
let events = Arc::new(Mutex::new(Vec::new()));
|
||||
let sink = events.clone();
|
||||
let channel = ops::Channel::new(move |event: BuildEvent| sink.lock().unwrap().push(event));
|
||||
let info = ops::java::java_resolve_launch(
|
||||
&host,
|
||||
"main",
|
||||
root.join("app"),
|
||||
false,
|
||||
false,
|
||||
BuildPolicy::Make,
|
||||
RequestId::next(),
|
||||
channel,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let steps: Vec<String> = events
|
||||
.lock()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter_map(|e| match e {
|
||||
BuildEvent::Step { command, .. } => Some(command.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert!(steps.iter().any(|s| s.starts_with("javac lib")), "{steps:?}");
|
||||
assert!(steps.iter().any(|s| s.starts_with("javac app")), "{steps:?}");
|
||||
assert!(!steps.iter().any(|s| s.contains("-am")), "{steps:?}");
|
||||
let first = Path::new(&info.class_paths[0]);
|
||||
assert!(first.ends_with("out/t.app/classes"), "{:?}", info.class_paths);
|
||||
assert!(first.join("a/A.class").is_file());
|
||||
assert!(info.class_paths.iter().any(|p| Path::new(p).ends_with("out/t.lib/classes")), "{:?}", info.class_paths);
|
||||
assert!(!root.join("app/target/classes").exists());
|
||||
|
||||
// Build › Build Project compiles with it too, and reports javac's errors.
|
||||
write(&root, "lib/src/main/java/l/L.java", "package l;\npublic class L { }\n");
|
||||
let built = ops::build::build_run(
|
||||
&host,
|
||||
"main",
|
||||
ide_build::compile::BuildKind::Build,
|
||||
None,
|
||||
None,
|
||||
RequestId::next(),
|
||||
Vec::new(),
|
||||
ops::Channel::new(|_: BuildEvent| {}),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(built.system, ide_build::compile::BuildSystem::Javac);
|
||||
assert!(!built.success);
|
||||
assert_eq!(built.errors, 1, "{:?}", built.messages);
|
||||
assert!(built.messages[0].path.as_deref().is_some_and(|p| p.ends_with("a/A.java")), "{:?}", built.messages);
|
||||
assert!(!root.join("lib/target/classes").exists());
|
||||
host.shutdown().await;
|
||||
}
|
||||
|
||||
/// With Settings › Gradle › Build and run using: IDE, a Gradle launch and Build Project compile
|
||||
/// with the IDE's Java build too. Needs a JDK (`JAVA_HOME`) and Gradle (`OPENIDEA_TEST_GRADLE`).
|
||||
#[cfg(unix)]
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn gradle_launch_compiles_with_the_ides_java_build() {
|
||||
let has_jdk = std::env::var_os("JAVA_HOME").is_some_and(|h| Path::new(&h).join("bin").is_dir());
|
||||
let Some(gradle) = std::env::var_os("OPENIDEA_TEST_GRADLE").filter(|_| has_jdk) else {
|
||||
eprintln!("skipped: needs JAVA_HOME and OPENIDEA_TEST_GRADLE");
|
||||
return;
|
||||
};
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
write(&root, "settings.gradle", "rootProject.name = 'root'\ninclude 'lib', 'app'\n");
|
||||
write(&root, "build.gradle", "subprojects {\n apply plugin: 'java'\n group = 't'\n}\n");
|
||||
write(&root, "lib/build.gradle", "");
|
||||
write(&root, "app/build.gradle", "dependencies { implementation project(':lib') }\n");
|
||||
write(&root, "gradlew", &format!("#!/bin/sh\nexec '{}' \"$@\"\n", Path::new(&gradle).display()));
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
fs::set_permissions(root.join("gradlew"), fs::Permissions::from_mode(0o755)).unwrap();
|
||||
write(
|
||||
&root,
|
||||
"lib/src/main/java/l/L.java",
|
||||
"package l;\npublic class L { public static String name() { return \"lib\"; } }\n",
|
||||
);
|
||||
write(
|
||||
&root,
|
||||
"app/src/main/java/a/A.java",
|
||||
"package a;\npublic class A { public static void main(String[] args) { System.out.println(l.L.name()); } }\n",
|
||||
);
|
||||
let global = SettingsStore::load(&base.join("config"), None);
|
||||
for server in ["jdtls", "java-analyzer", "kmp-lsp"] {
|
||||
global
|
||||
.set(SettingsScope::Global, &format!("languageServers.{server}.enabled"), serde_json::json!(false))
|
||||
.unwrap();
|
||||
}
|
||||
global.set(SettingsScope::Global, "languages.java.gradle.runUsing", serde_json::json!("ide")).unwrap();
|
||||
let host = Host::new(common::host_config(&base));
|
||||
host.trust.decide(&root, true, false).unwrap();
|
||||
host.open_project("main", &root).unwrap();
|
||||
|
||||
let events = Arc::new(Mutex::new(Vec::new()));
|
||||
let sink = events.clone();
|
||||
let channel = ops::Channel::new(move |event: BuildEvent| sink.lock().unwrap().push(event));
|
||||
let info = ops::java::java_resolve_launch(
|
||||
&host,
|
||||
"main",
|
||||
root.join("app"),
|
||||
false,
|
||||
false,
|
||||
BuildPolicy::Make,
|
||||
RequestId::next(),
|
||||
channel,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let steps: Vec<String> = events
|
||||
.lock()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter_map(|e| match e {
|
||||
BuildEvent::Step { command, .. } => Some(command.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert!(steps.iter().any(|s| s.contains("openideaBuildModel")), "{steps:?}");
|
||||
assert!(steps.iter().any(|s| s.starts_with("javac lib")), "{steps:?}");
|
||||
assert!(steps.iter().any(|s| s.starts_with("javac app")), "{steps:?}");
|
||||
let first = Path::new(&info.class_paths[0]);
|
||||
assert!(first.ends_with("out/t.app/classes"), "{:?}", info.class_paths);
|
||||
assert!(first.join("a/A.class").is_file());
|
||||
assert!(info.class_paths.iter().any(|p| Path::new(p).ends_with("out/t.lib/classes")), "{:?}", info.class_paths);
|
||||
assert!(!root.join("app/build/classes").exists());
|
||||
|
||||
write(&root, "lib/src/main/java/l/L.java", "package l;\npublic class L { }\n");
|
||||
let built = ops::build::build_run(
|
||||
&host,
|
||||
"main",
|
||||
ide_build::compile::BuildKind::Build,
|
||||
None,
|
||||
None,
|
||||
RequestId::next(),
|
||||
Vec::new(),
|
||||
ops::Channel::new(|_: BuildEvent| {}),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(built.system, ide_build::compile::BuildSystem::Javac);
|
||||
assert_eq!(built.errors, 1, "{:?}", built.messages);
|
||||
assert!(built.messages[0].path.as_deref().is_some_and(|p| p.ends_with("a/A.java")), "{:?}", built.messages);
|
||||
host.shutdown().await;
|
||||
}
|
||||
@@ -88,10 +88,18 @@ done
|
||||
let events = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
|
||||
let sink = events.clone();
|
||||
let channel = ops::Channel::new(move |event: ide_build::compile::BuildEvent| sink.lock().unwrap().push(event));
|
||||
let info =
|
||||
ops::java::java_resolve_launch(&host, "main", module, test, BuildPolicy::Make, RequestId::next(), channel)
|
||||
.await
|
||||
.unwrap();
|
||||
let info = ops::java::java_resolve_launch(
|
||||
&host,
|
||||
"main",
|
||||
module,
|
||||
test,
|
||||
false,
|
||||
BuildPolicy::Make,
|
||||
RequestId::next(),
|
||||
channel,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
// The build streams its command and progress while it runs.
|
||||
use ide_build::compile::BuildEvent;
|
||||
let events = events.lock().unwrap();
|
||||
@@ -110,7 +118,9 @@ done
|
||||
assert!(info.class_paths.iter().any(|p| std::path::Path::new(p) == out));
|
||||
assert!(info.class_paths.iter().any(|p| std::path::Path::new(p) == jar));
|
||||
let calls = fs::read_to_string(root.join("calls")).unwrap();
|
||||
assert!(calls.lines().next().unwrap().contains("-pl app -am"), "{calls}");
|
||||
// This Maven records no build model for the IDE's Java build, so Maven builds the module.
|
||||
assert!(calls.lines().next().unwrap().contains("-Dopenidea.build.model="), "{calls}");
|
||||
assert!(calls.lines().nth(1).unwrap().contains("-pl app -am"), "{calls}");
|
||||
assert!(calls.lines().all(|line| line.contains(&format!("-P member-{index}"))), "{calls}");
|
||||
assert!(calls.contains(":build-classpath"), "{calls}");
|
||||
}
|
||||
|
||||
@@ -1188,3 +1188,107 @@ async fn phoxite_pulls_a_member_up_end_to_end() {
|
||||
assert!(!refused.message.is_empty() && !refused.message.starts_with("phoxite:"), "{refused:?}");
|
||||
mgr.shutdown_all().await;
|
||||
}
|
||||
|
||||
/// jdtls keeps building incrementally even though the IDE's Java build compiles what runs:
|
||||
/// its build is what reports an API change in one Maven module in the files of the modules
|
||||
/// that use it, open or not. With `java.autobuild.enabled: false` (and
|
||||
/// `validateAllOpenBuffersOnChanges`), neither updates.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "requires jdtls on PATH (or OPENIDEA_TEST_JDTLS) and a compatible JDK"]
|
||||
async fn jdtls_build_reports_cross_module_errors_in_open_and_closed_files() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(dir.path()).unwrap().join("project");
|
||||
let write = |rel: &str, text: &str| {
|
||||
let path = root.join(rel);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(&path, text).unwrap();
|
||||
path
|
||||
};
|
||||
let parent = r#"<parent><groupId>t</groupId><artifactId>root</artifactId><version>1</version></parent>"#;
|
||||
write(
|
||||
"pom.xml",
|
||||
r#"<project><modelVersion>4.0.0</modelVersion><groupId>t</groupId><artifactId>root</artifactId><version>1</version><packaging>pom</packaging><modules><module>lib</module><module>app</module></modules><properties><maven.compiler.release>11</maven.compiler.release></properties></project>"#,
|
||||
);
|
||||
write(
|
||||
"lib/pom.xml",
|
||||
&format!("<project><modelVersion>4.0.0</modelVersion>{parent}<artifactId>lib</artifactId></project>"),
|
||||
);
|
||||
write(
|
||||
"app/pom.xml",
|
||||
&format!(
|
||||
"<project><modelVersion>4.0.0</modelVersion>{parent}<artifactId>app</artifactId><dependencies><dependency><groupId>t</groupId><artifactId>lib</artifactId><version>1</version></dependency></dependencies></project>"
|
||||
),
|
||||
);
|
||||
let lib_source = "package l;\npublic class L { public static String name() { return \"lib\"; } }\n";
|
||||
let app_source = "package a;\npublic class A { String s = l.L.name(); }\n";
|
||||
let lib = write("lib/src/main/java/l/L.java", lib_source);
|
||||
let app = write("app/src/main/java/a/A.java", app_source);
|
||||
let closed = write("app/src/main/java/a/B.java", "package a;\nclass B { String s = l.L.name(); }\n");
|
||||
let mut java = LanguageRegistry::load(None).unwrap().get(&LanguageId::new("java")).unwrap();
|
||||
java.language_servers.retain(|s| s.name == "jdtls");
|
||||
let server = &mut java.language_servers[0];
|
||||
if let Ok(bin) = std::env::var("OPENIDEA_TEST_JDTLS") {
|
||||
server.command = bin;
|
||||
}
|
||||
server.args.extend(["-data".into(), dir.path().join("jdtls-data").to_string_lossy().into_owned()]);
|
||||
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![java]));
|
||||
let (lib_doc, app_doc) = (DocId::next(), DocId::next());
|
||||
mgr.did_open(lib_doc, &lib, &LanguageId::new("java"), 1, lib_source);
|
||||
mgr.did_open(app_doc, &app, &LanguageId::new("java"), 1, app_source);
|
||||
let errors = |path: &Path| {
|
||||
events.lock().iter().rev().find_map(|e| match e {
|
||||
IdeEvent::Diagnostics { path: p, items, .. } if p.0 == path => Some(
|
||||
items
|
||||
.iter()
|
||||
.filter(|d| d.severity == ide_core::Severity::Error)
|
||||
.map(|d| d.message.clone())
|
||||
.collect::<Vec<_>>(),
|
||||
),
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
// The import resolves `lib` from source: the open editor of `app` has no errors.
|
||||
retry("app imported", Duration::from_secs(300), || {
|
||||
let status = last_status(&events, "jdtls");
|
||||
if let Some((ServerStatus::Crashed | ServerStatus::Missing | ServerStatus::Misconfigured, message)) = &status {
|
||||
panic!("jdtls failed: {message:?}");
|
||||
}
|
||||
let clean = errors(&app).is_some_and(|e| e.is_empty());
|
||||
let mgr = mgr.clone();
|
||||
let app = app.clone();
|
||||
async move {
|
||||
let cp =
|
||||
tokio::time::timeout(Duration::from_secs(10), mgr.java_classpath(&app, false, &Default::default()))
|
||||
.await
|
||||
.ok()?
|
||||
.ok()?;
|
||||
(clean && cp.class_paths.iter().any(|p| p.contains("/lib/"))).then_some(())
|
||||
}
|
||||
})
|
||||
.await;
|
||||
// Rename the method in the editor of `lib`, and save.
|
||||
let renamed = lib_source.replace("name()", "title()");
|
||||
let line = lib_source.lines().nth(1).unwrap();
|
||||
mgr.did_change(
|
||||
lib_doc,
|
||||
2,
|
||||
&[AppliedChange {
|
||||
range: Range::new(Pos::new(1, 0), Pos::new(1, line.len() as u32)),
|
||||
text: renamed.lines().nth(1).unwrap().to_owned(),
|
||||
}],
|
||||
&|| renamed.clone(),
|
||||
);
|
||||
std::fs::write(&lib, &renamed).unwrap();
|
||||
mgr.did_save(lib_doc, &renamed);
|
||||
retry("the open editor of app reports the removed method", Duration::from_secs(120), || {
|
||||
let found = errors(&app).is_some_and(|e| e.iter().any(|m| m.contains("name()")));
|
||||
async move { found.then_some(()) }
|
||||
})
|
||||
.await;
|
||||
retry("the closed file of app reports it too", Duration::from_secs(60), || {
|
||||
let found = errors(&closed).is_some_and(|e| e.iter().any(|m| m.contains("name()")));
|
||||
async move { found.then_some(()) }
|
||||
})
|
||||
.await;
|
||||
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
|
||||
}
|
||||
@@ -1654,6 +1654,23 @@ pub fn junit_runner_jar(data_dir: &Path) -> Option<PathBuf> {
|
||||
)
|
||||
}
|
||||
|
||||
/// The IDE's Java build (`java/java-build`): the resident javac server and the Maven
|
||||
/// extension that records the build model.
|
||||
const JAVA_BUILD: &[u8] = include_bytes!("../../../java/java-build/openidea-java-build.jar");
|
||||
|
||||
/// Extracts the Java build jar into the application's data directory.
|
||||
pub fn java_build_jar(data_dir: &Path) -> Option<PathBuf> {
|
||||
install_bundle(data_dir, "java-build", "1.0.0", JAVA_BUILD)
|
||||
}
|
||||
|
||||
/// Changes whenever the embedded Java build jar does (FNV-1a of its bytes), so build models
|
||||
/// recorded by an older extension are prepared again.
|
||||
pub fn java_build_version() -> String {
|
||||
let hash =
|
||||
JAVA_BUILD.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x100_0000_01b3));
|
||||
format!("{hash:016x}")
|
||||
}
|
||||
|
||||
/// The JUnit Platform launcher a test classpath needs to start the runner.
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum JunitLauncher {
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
# Java build
|
||||
|
||||
The IDE's own build of Maven and Gradle modules (`ide_build::jbuild`). The jar holds two parts:
|
||||
|
||||
- `ai.openidea.javac.Server` (`src/`): a resident javac. OpenIDEA starts one per JDK (and
|
||||
`.mvn/jvm.config`) as `java -cp openidea-java-build.jar ai.openidea.javac.Server` and keeps it
|
||||
running between builds. It reads one JSON request per line on stdin and answers on stdout:
|
||||
|
||||
| Request | Meaning |
|
||||
| ------------------------------------------------------------------------ | ----------------------------------------------- |
|
||||
| `{"id":1,"op":"compile","options":[…],"sources":[…],"encoding":"UTF-8"}` | Compile with javac (`ToolProvider`), in process |
|
||||
| `{"op":"cancel","id":1}` | Stop that compilation at javac's next phase |
|
||||
| `{"op":"exit"}` | Finish the queued requests, then exit |
|
||||
|
||||
Replies carry the request's `id`: `diagnostic` (1-based line, 0-based UTF-16 column),
|
||||
`output` (a class file and the source it came from), `generated` (a source an annotation
|
||||
processor wrote), `output-text`, then `done`. `ready` and `fatal` concern the server.
|
||||
|
||||
- `ai.openidea.javac.maven.BuildModel` (`maven/`): a Maven core extension, loaded with
|
||||
`-Dmaven.ext.class.path`. With `-Dopenidea.build.output=<dir>` it redirects every project's
|
||||
output to `<dir>/<groupId>.<artifactId>/classes|test-classes`, and resolves reactor
|
||||
projects to those folders. With `-Dopenidea.build.model=<file>` it writes, after the build,
|
||||
each project's source roots, classpaths, resources and the configuration maven-compiler-plugin's
|
||||
mojos get (including the resolved `annotationProcessorPaths`), as JSON.
|
||||
|
||||
OpenIDEA runs `mvn process-resources resources:testResources` with the extension when the POMs,
|
||||
settings or generator inputs change, then compiles the launch's modules with the server.
|
||||
|
||||
Gradle builds get the same model from an init script instead
|
||||
(`crates/ide-build/src/jbuild/gradle-build.init.gradle`, task `openideaBuildModel`, with
|
||||
`-Popenidea.build.output` and `-Popenidea.build.model`), when Settings › Gradle › Build and run
|
||||
using is set to the IDE.
|
||||
|
||||
The jar is committed and embedded by `ide-sdk` (`java_build_jar`). It is built with `--release 8`
|
||||
against Maven 3.9.11, whose files `build-dependencies.sha256` pins. Rebuild it after changing
|
||||
the source:
|
||||
|
||||
```sh
|
||||
JAVA_HOME=<JDK 11+> python3 build.py <apache-maven-3.9.11 folder>
|
||||
```
|
||||
@@ -0,0 +1,52 @@
|
||||
0addec670fedcd3f113c5c8091d783280d23f75e3acb841b61a9cdb079376a08 maven/aopalliance-1.0.jar
|
||||
876eab6a83daecad5ca67eb9fcabb063c97b5aeb8cf1fca7a989ecde17522051 maven/asm-9.8.jar
|
||||
d3d530d0f28fd0fbbffe2b0b338f70e8cb96f1605579e2e3abd4db29cac24e69 maven/commons-cli-1.9.0.jar
|
||||
ba005f304cef92a3dede24a38ad5ac9b8afccf0d8f75839d6c1338634cf7f6e4 maven/commons-codec-1.18.0.jar
|
||||
6661d5335090a5fc61dd869d2095bc6c1e2156e3aa47a6e4ababdf64c99a7889 maven/error_prone_annotations-2.38.0.jar
|
||||
cbfc3906b19b8f55dd7cfd6dfe0aa4532e834250d7f080bd8d211a3e246b59cb maven/failureaccess-1.0.3.jar
|
||||
94855942d4992f112946d3de1c334e709237b8126d8130bf07807c018a4a2120 maven/gson-2.13.1.jar
|
||||
f3d7f57f67fd622f4d468dfdd692b3a5e3909246c28017ac3263405f0fe617ed maven/guava-33.4.8-jre.jar
|
||||
142ad4475e19524d2fe3ac995b3f7cbc962fc726f2edb9dbdccc61feab9b2bf9 maven/guice-5.1.0-classes.jar
|
||||
c8bc7e1c51a6d4ce72f40d2ebbabf1c4b68bfe76e732104b04381b493478e9d6 maven/httpclient-4.5.14.jar
|
||||
6c9b3dd142a09dc468e23ad39aad6f75a0f2b85125104469f026e52a474e464f maven/httpcore-4.4.16.jar
|
||||
0b7b8b003a90ea491579b62f5118828e45112914c65589b00faa49d6ec785839 maven/jansi-2.4.2.jar
|
||||
e04ba5195bcd555dc95650f7cc614d151e4bcd52d29a10b8aa2197f3ab89ab9b maven/javax.annotation-api-1.3.2.jar
|
||||
91c77044a50c481636c32d916fd89c9118a72195390452c81065080f957de7ff maven/javax.inject-1.jar
|
||||
ab57ca8fd223772c17365d121f59e94ecbf0ae59d08c03a3cb5b81071c019195 maven/jcl-over-slf4j-1.7.36.jar
|
||||
1fad6e6be7557781e4d33729d49ae1cdc8fdda6fe477bb0cc68ce351eafdfbab maven/jspecify-1.0.0.jar
|
||||
0bfd1c121f907642344311d81e4dfd93eba6c24dc712cc0aeae273eb22833022 maven/maven-artifact-3.9.11.jar
|
||||
5b1de1560ec19c4c69a655f986455888f3a0bcc3c160cac1f1edb87de3825f77 maven/maven-builder-support-3.9.11.jar
|
||||
b0e2865fc808fd9fb3bee95bf37c0609eeb20c59bf1e6b958b37b365ee11f52e maven/maven-compat-3.9.11.jar
|
||||
93d3c0523dda6c86c6620d9e692e7df39d0e2e4e4cd860061a8c0d274c2ad185 maven/maven-core-3.9.11.jar
|
||||
7e15e05035331d0a7e0fe56d7354b2b30e15c0a8c60863cbf28df25190e197db maven/maven-embedder-3.9.11.jar
|
||||
163aa596f976264384efeb50b4cb8a806086fd64a9b755ad1f69195fed3998ad maven/maven-model-3.9.11.jar
|
||||
c4c72accdcd848332c1a37995610a6a369d49fdaabc43e85f0022a5b77de3ba7 maven/maven-model-builder-3.9.11.jar
|
||||
8e985a56412564cf687040efed8bcd3a63eac2202a824bb01e1d5ece2b87458f maven/maven-plugin-api-3.9.11.jar
|
||||
f8655f5f0060e0032944f2a23688d186e140d2184749bcfa1927f83cd6a8b1a2 maven/maven-repository-metadata-3.9.11.jar
|
||||
c0ce14849298720dcf3b09fe9e263b3c576d2d6cd43c61f8aa9d6117e04e5e47 maven/maven-resolver-api-1.9.24.jar
|
||||
18b7d557c41379db8b157ba95263c676f52c293f5416b67bd1db083e99b30383 maven/maven-resolver-connector-basic-1.9.24.jar
|
||||
3cd88edda00c46242cdbe57aefb47703519d176d9e8a500333de15faf41b0e1d maven/maven-resolver-impl-1.9.24.jar
|
||||
a222b0a5ca4c145e8e0f45207a23bcce18bdbe1f1c980e4e9fb332591ee8c91a maven/maven-resolver-named-locks-1.9.24.jar
|
||||
b5d6e52ae1ecf1cb62ede2234234ba3093149524066488e84415187ce478c582 maven/maven-resolver-provider-3.9.11.jar
|
||||
e3153906e93333c106ee18babb72ba7984ccb15e9116ea08f88c71b8d9387e01 maven/maven-resolver-spi-1.9.24.jar
|
||||
b09268d41e1dfcae15a829d45a512ca29d62b727421d3bd6383ac6252e5e960f maven/maven-resolver-transport-file-1.9.24.jar
|
||||
a0de339a8dd3473d9abaa1cf974507f38783e26af31d36a90c1e59cc8714ded0 maven/maven-resolver-transport-http-1.9.24.jar
|
||||
78ed57fa2123a2d84fad7a0b15ca73b89df47c10294d02d6f8121c4d0e5050cb maven/maven-resolver-transport-wagon-1.9.24.jar
|
||||
aeb7e776a8c47b1c317a2581f299e2525b044cb8abde31164e970bbbefab12b1 maven/maven-resolver-util-1.9.24.jar
|
||||
026718d47d19e360d978857bc63d3dc065884fc2c801563d8a2a77b5ab74ccf8 maven/maven-settings-3.9.11.jar
|
||||
33c96e4ca5a15b7c93180f6b2f8deb15f511dfc15dda0d2b671c968b22108972 maven/maven-settings-builder-3.9.11.jar
|
||||
b613357e1bad4dfc1dead801691c9460f9585fe7c6b466bc25186212d7d18487 maven/maven-shared-utils-3.4.2.jar
|
||||
76d9fa894fa61d1492877ca599cb5ab28ca4573d5f389d6c12a8233b995335f9 maven/maven-slf4j-provider-3.9.11.jar
|
||||
1cbd7a965a5e2a9ea823bab311962a4e5aa5c240705bdbad5a52b40ffdfa1004 maven/org.eclipse.sisu.inject-0.9.0.M4.jar
|
||||
b90579bc652eac7331436e0a25533fce14130b9c6e015f2dd3a3d4bb07e942b7 maven/org.eclipse.sisu.plexus-0.9.0.M4.jar
|
||||
9a7f1b5c5a9effd61eadfd8731452a2f76a8e79111fac391ef75ea801bea203a maven/plexus-cipher-2.0.jar
|
||||
50edb93c73786e62822b4fe1336e22880fdf147191373cf5c911370e16748fcf maven/plexus-component-annotations-2.2.0.jar
|
||||
ab2a8715570438a2e4164d85ad3e8d489eabc38ea5093c2eb8ab7f58403535b5 maven/plexus-interpolation-1.28.jar
|
||||
873139960c4c780176dda580b003a2c4bf82188bdce5bb99234e224ef7acfceb maven/plexus-sec-dispatcher-2.0.jar
|
||||
27ef130e32c236090e408fb5498d94cb9ea26d14070fb1c8985d607b62d098d1 maven/plexus-utils-3.6.0.jar
|
||||
d3ef575e3e4979678dc01bf1dcce51021493b4d11fb7f1be8ad982877c16a1c0 maven/slf4j-api-1.7.36.jar
|
||||
afc9216fa97b78dad227b4a8d4d67b9897bf113a57f80598d62993841113e103 maven/wagon-file-3.5.3.jar
|
||||
d2b6e48c9fcbe579e1858c622d14464011ff265fa6e28e794004a6882154a509 maven/wagon-http-3.5.3.jar
|
||||
8e7da766f55164fde8779aaaa125832506c2848cab4876b5305138873e28037f maven/wagon-http-shared-3.5.3.jar
|
||||
5e72000338945ed3e96f8e4f578d1d0672e1af7e19c0e9014197ae5b31af3ef4 maven/wagon-provider-api-3.5.3.jar
|
||||
1ad3292cd563381e3fd632f3fded1988f9e9b2be7a9f3db63ff4c4cedba13fa5 maven/plexus-classworlds-2.9.0.jar
|
||||
@@ -0,0 +1,38 @@
|
||||
"""Build the committed jar: python3 build.py /path/to/apache-maven-3.9.11 [--record-dependencies].
|
||||
|
||||
One jar, two parts, Java 8 bytecode:
|
||||
- `src`: the resident javac server (`ai.openidea.javac.Server`), JDK classes only.
|
||||
- `maven`: the prepare run's Maven extension (`ai.openidea.javac.maven.BuildModel`), compiled
|
||||
against Maven 3.9.11's API jars, pinned by build-dependencies.sha256.
|
||||
Archive order and timestamps are deterministic. Use a JDK that still compiles `--release 8`."""
|
||||
import hashlib
|
||||
import os
|
||||
import pathlib
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import zipfile
|
||||
|
||||
root = pathlib.Path(__file__).resolve().parent
|
||||
maven = pathlib.Path(sys.argv[1]).resolve()
|
||||
jars = sorted((maven / 'lib').glob('*.jar')) + sorted((maven / 'boot').glob('*.jar'))
|
||||
actual = ''.join(f'{hashlib.sha256(p.read_bytes()).hexdigest()} maven/{p.name}\n' for p in jars)
|
||||
if '--record-dependencies' in sys.argv:
|
||||
(root / 'build-dependencies.sha256').write_text(actual)
|
||||
if (root / 'build-dependencies.sha256').read_text() != actual:
|
||||
sys.exit('Build dependencies differ from build-dependencies.sha256')
|
||||
java_home = os.environ.get('JAVA_HOME')
|
||||
javac = str(pathlib.Path(java_home) / 'bin' / 'javac') if java_home else 'javac'
|
||||
with tempfile.TemporaryDirectory() as output:
|
||||
for source, classpath in [('src', []), ('maven', jars)]:
|
||||
subprocess.run([javac, '--release', '8', '-Xlint:-options', '-proc:none', '-encoding', 'UTF-8', '-g',
|
||||
'-classpath', os.pathsep.join(map(str, classpath)), '-d', output,
|
||||
*map(str, sorted((root / source).rglob('*.java')))], check=True)
|
||||
files = {p.relative_to(output).as_posix(): p.read_bytes() for p in pathlib.Path(output).rglob('*.class')}
|
||||
files['META-INF/sisu/javax.inject.Named'] = b'ai.openidea.javac.maven.BuildModel\n'
|
||||
files['META-INF/MANIFEST.MF'] = b'Manifest-Version: 1.0\nMain-Class: ai.openidea.javac.Server\n\n'
|
||||
staged = root / 'openidea-java-build.jar.pending'
|
||||
with zipfile.ZipFile(staged, 'w', zipfile.ZIP_DEFLATED) as jar:
|
||||
for name, data in sorted(files.items()):
|
||||
jar.writestr(zipfile.ZipInfo(name, (2026, 1, 1, 0, 0, 0)), data)
|
||||
staged.replace(root / 'openidea-java-build.jar')
|
||||
@@ -0,0 +1,501 @@
|
||||
package ai.openidea.javac.maven;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStreamWriter;
|
||||
import java.io.Writer;
|
||||
import java.lang.reflect.Field;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import org.apache.maven.AbstractMavenLifecycleParticipant;
|
||||
import org.apache.maven.MavenExecutionException;
|
||||
import org.apache.maven.execution.MavenSession;
|
||||
import org.apache.maven.lifecycle.LifecycleExecutor;
|
||||
import org.apache.maven.lifecycle.MavenExecutionPlan;
|
||||
import org.apache.maven.model.Dependency;
|
||||
import org.apache.maven.model.Resource;
|
||||
import org.apache.maven.plugin.BuildPluginManager;
|
||||
import org.apache.maven.plugin.MavenPluginManager;
|
||||
import org.apache.maven.plugin.Mojo;
|
||||
import org.apache.maven.plugin.MojoExecution;
|
||||
import org.apache.maven.project.DefaultDependencyResolutionRequest;
|
||||
import org.apache.maven.project.DependencyResolutionResult;
|
||||
import org.apache.maven.project.MavenProject;
|
||||
import org.apache.maven.project.ProjectDependenciesResolver;
|
||||
import javax.inject.Inject;
|
||||
import javax.inject.Named;
|
||||
import javax.inject.Singleton;
|
||||
import org.eclipse.aether.DefaultRepositorySystemSession;
|
||||
import org.eclipse.aether.RepositorySystem;
|
||||
import org.eclipse.aether.RepositorySystemSession;
|
||||
import org.eclipse.aether.artifact.Artifact;
|
||||
import org.eclipse.aether.artifact.DefaultArtifact;
|
||||
import org.eclipse.aether.collection.CollectRequest;
|
||||
import org.eclipse.aether.graph.DependencyNode;
|
||||
import org.eclipse.aether.graph.Exclusion;
|
||||
import org.eclipse.aether.repository.WorkspaceReader;
|
||||
import org.eclipse.aether.repository.WorkspaceRepository;
|
||||
import org.eclipse.aether.resolution.ArtifactResult;
|
||||
import org.eclipse.aether.resolution.DependencyRequest;
|
||||
import org.eclipse.aether.resolution.DependencyResult;
|
||||
|
||||
/**
|
||||
* Records how each project of the session compiles, for the IDE's own Java build. Loaded only
|
||||
* by the IDE's prepare run ({@code -Dmaven.ext.class.path=<jar> -Dopenidea.build.model=<file>
|
||||
* process-resources resources:testResources}): generated sources exist and resources are
|
||||
* processed, and nothing is compiled. Test source generators run after {@code compile} in
|
||||
* Maven's lifecycle, so they don't run; the source roots build-helper adds are read from its
|
||||
* configuration, and any other generator is listed so the IDE leaves those tests to Maven.
|
||||
*
|
||||
* <p>Per project and source set (main, test): the source roots (including the ones generated
|
||||
* sources added), the output directory, the compile classpath with reactor projects as their
|
||||
* output directories (never their jars), the runtime classpath, the compiler plugin's resolved
|
||||
* configuration (release, encoding, arguments, annotation processor path) and the resources.
|
||||
* Executions bound to the compile phases that are not javac (Kotlin, AspectJ, bytecode
|
||||
* enhancers) are listed, so the IDE leaves such projects to Maven.
|
||||
*/
|
||||
@Named("openidea-build-model")
|
||||
@Singleton
|
||||
public final class BuildModel extends AbstractMavenLifecycleParticipant {
|
||||
private static final String COMPILER = "org.apache.maven.plugins:maven-compiler-plugin";
|
||||
/** Test phases before test-compile, which the prepare run doesn't reach. */
|
||||
private static final Set<String> TEST_GENERATE_PHASES = new HashSet<>(Arrays.asList(
|
||||
"generate-test-sources", "process-test-sources", "generate-test-resources", "process-test-resources"));
|
||||
/** Phases whose executions change what the compile phases produce. */
|
||||
private static final Set<String> COMPILE_PHASES =
|
||||
new HashSet<>(Arrays.asList("compile", "process-classes", "test-compile", "process-test-classes"));
|
||||
/** Executions in those phases that don't change the classes the IDE compiles. */
|
||||
private static final Set<String> HARMLESS = new HashSet<>(Arrays.asList(
|
||||
"org.jacoco:jacoco-maven-plugin", "org.apache.maven.plugins:maven-enforcer-plugin",
|
||||
"org.codehaus.mojo:animal-sniffer-maven-plugin", "org.apache.maven.plugins:maven-checkstyle-plugin",
|
||||
"com.github.spotbugs:spotbugs-maven-plugin", "org.apache.maven.plugins:maven-pmd-plugin",
|
||||
"com.diffplug.spotless:spotless-maven-plugin", "org.apache.maven.plugins:maven-dependency-plugin",
|
||||
"org.apache.maven.plugins:maven-resources-plugin", "org.codehaus.mojo:build-helper-maven-plugin",
|
||||
"pl.project13.maven:git-commit-id-plugin", "io.github.git-commit-id:git-commit-id-maven-plugin"));
|
||||
|
||||
private final LifecycleExecutor lifecycle;
|
||||
private final MavenPluginManager plugins;
|
||||
private final BuildPluginManager buildPlugins;
|
||||
private final ProjectDependenciesResolver dependencies;
|
||||
private final RepositorySystem repositories;
|
||||
|
||||
@Inject
|
||||
public BuildModel(LifecycleExecutor lifecycle, MavenPluginManager plugins, BuildPluginManager buildPlugins,
|
||||
ProjectDependenciesResolver dependencies, RepositorySystem repositories) {
|
||||
this.lifecycle = lifecycle;
|
||||
this.plugins = plugins;
|
||||
this.buildPlugins = buildPlugins;
|
||||
this.dependencies = dependencies;
|
||||
this.repositories = repositories;
|
||||
}
|
||||
|
||||
/**
|
||||
* With {@code -Dopenidea.build.output=<dir>}, every project's classes and resources go to
|
||||
* {@code <dir>/<groupId>.<artifactId>/classes} (and {@code test-classes}): the IDE's outputs,
|
||||
* apart from what a terminal build or the language server writes to {@code target}.
|
||||
*/
|
||||
@Override public void afterProjectsRead(MavenSession session) {
|
||||
String output = session.getUserProperties().getProperty("openidea.build.output");
|
||||
if (output == null) return;
|
||||
for (MavenProject project : session.getProjects()) {
|
||||
File dir = new File(output, project.getGroupId() + "." + project.getArtifactId());
|
||||
project.getBuild().setOutputDirectory(new File(dir, "classes").getAbsolutePath());
|
||||
project.getBuild().setTestOutputDirectory(new File(dir, "test-classes").getAbsolutePath());
|
||||
}
|
||||
}
|
||||
|
||||
@Override public void afterSessionEnd(MavenSession session) throws MavenExecutionException {
|
||||
String destination = session.getUserProperties().getProperty("openidea.build.model");
|
||||
if (destination == null) return;
|
||||
StringBuilder json = new StringBuilder("{\"version\":1,\"projects\":[");
|
||||
boolean first = true;
|
||||
MavenProject current = session.getCurrentProject();
|
||||
try {
|
||||
for (MavenProject project : session.getProjects()) {
|
||||
if (!first) json.append(',');
|
||||
first = false;
|
||||
project(json, session, project);
|
||||
}
|
||||
} finally {
|
||||
session.setCurrentProject(current);
|
||||
}
|
||||
json.append("]}");
|
||||
File target = new File(destination);
|
||||
try {
|
||||
File parent = target.getAbsoluteFile().getParentFile();
|
||||
parent.mkdirs();
|
||||
File temp = File.createTempFile("build-model", ".json", parent);
|
||||
try (Writer out = new OutputStreamWriter(Files.newOutputStream(temp.toPath()), StandardCharsets.UTF_8)) {
|
||||
out.write(json.toString());
|
||||
}
|
||||
Files.move(temp.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
|
||||
} catch (IOException e) {
|
||||
throw new MavenExecutionException("Cannot write the IDE build model: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
private void project(StringBuilder json, MavenSession session, MavenProject project) {
|
||||
session.setCurrentProject(project);
|
||||
json.append("{\"dir\":").append(q(project.getBasedir().getAbsolutePath()))
|
||||
.append(",\"groupId\":").append(q(project.getGroupId()))
|
||||
.append(",\"artifactId\":").append(q(project.getArtifactId()))
|
||||
.append(",\"version\":").append(q(project.getVersion()))
|
||||
.append(",\"packaging\":").append(q(project.getPackaging()));
|
||||
List<String> problems = new ArrayList<>();
|
||||
Map<String, Mojo> compilers = new HashMap<>();
|
||||
List<MojoExecution> configured = new ArrayList<>();
|
||||
List<String> others = new ArrayList<>();
|
||||
List<String> testGenerators = new ArrayList<>();
|
||||
List<String> testRoots = new ArrayList<>(project.getTestCompileSourceRoots());
|
||||
try {
|
||||
MavenExecutionPlan plan = lifecycle.calculateExecutionPlan(session, true, "test-compile");
|
||||
for (MojoExecution execution : plan.getMojoExecutions()) {
|
||||
String plugin = execution.getGroupId() + ":" + execution.getArtifactId();
|
||||
String phase = execution.getLifecyclePhase();
|
||||
if (COMPILER.equals(plugin) && ("compile".equals(execution.getGoal()) || "testCompile".equals(execution.getGoal()))) {
|
||||
if (compilers.containsKey(execution.getGoal())) {
|
||||
others.add(plugin + ":" + execution.getGoal() + "@" + execution.getExecutionId());
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
buildPlugins.getPluginRealm(session, execution.getMojoDescriptor().getPluginDescriptor());
|
||||
Mojo mojo = plugins.getConfiguredMojo(Mojo.class, session, execution);
|
||||
compilers.put(execution.getGoal(), mojo);
|
||||
configured.add(execution);
|
||||
} catch (Exception e) {
|
||||
problems.add("Cannot read the " + execution.getGoal() + " configuration: " + e);
|
||||
}
|
||||
} else if (phase != null && COMPILE_PHASES.contains(phase) && !HARMLESS.contains(plugin)) {
|
||||
others.add(plugin + ":" + execution.getGoal() + "@" + execution.getExecutionId());
|
||||
} else if (phase != null && TEST_GENERATE_PHASES.contains(phase)) {
|
||||
String goal = plugin + ":" + execution.getGoal();
|
||||
if (goal.equals("org.apache.maven.plugins:maven-resources-plugin:testResources")) continue;
|
||||
if (goal.equals("org.codehaus.mojo:build-helper-maven-plugin:add-test-source")) {
|
||||
try {
|
||||
buildPlugins.getPluginRealm(session, execution.getMojoDescriptor().getPluginDescriptor());
|
||||
Mojo mojo = plugins.getConfiguredMojo(Mojo.class, session, execution);
|
||||
Object sources = get(mojo, "sources");
|
||||
if (sources instanceof File[])
|
||||
for (File f : (File[]) sources) testRoots.add(f.getAbsolutePath());
|
||||
plugins.releaseMojo(mojo, execution);
|
||||
continue;
|
||||
} catch (Exception e) {
|
||||
problems.add("Cannot read build-helper's test sources: " + e);
|
||||
}
|
||||
}
|
||||
testGenerators.add(goal + "@" + execution.getExecutionId());
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
problems.add("Cannot plan the build: " + e);
|
||||
}
|
||||
Set<String> reactor = new HashSet<>();
|
||||
for (MavenProject p : session.getProjects()) reactor.add(p.getGroupId() + ":" + p.getArtifactId());
|
||||
RepositorySystemSession repo = reactorSession(session);
|
||||
List<String> compile = new ArrayList<>();
|
||||
List<String> runtime = new ArrayList<>();
|
||||
List<String> test = new ArrayList<>();
|
||||
try {
|
||||
DependencyResolutionResult result =
|
||||
dependencies.resolve(new DefaultDependencyResolutionRequest(project, repo));
|
||||
classpaths(result.getDependencyGraph(), compile, runtime, test);
|
||||
for (Exception e : result.getCollectionErrors()) problems.add(e.getMessage());
|
||||
} catch (Exception e) {
|
||||
problems.add("Cannot resolve the dependencies: " + rootMessage(e));
|
||||
org.apache.maven.project.DependencyResolutionException failure = cause(e);
|
||||
if (failure != null && failure.getResult() != null && failure.getResult().getDependencyGraph() != null)
|
||||
classpaths(failure.getResult().getDependencyGraph(), compile, runtime, test);
|
||||
}
|
||||
json.append(",\"main\":");
|
||||
sourceSet(json, session, project, compilers.get("compile"), null, compile, runtime, problems);
|
||||
json.append(",\"test\":");
|
||||
List<String> testClasspath = new ArrayList<>();
|
||||
testClasspath.add(project.getBuild().getOutputDirectory());
|
||||
testClasspath.addAll(test);
|
||||
sourceSet(json, session, project, compilers.get("testCompile"), testRoots, testClasspath, testClasspath, problems);
|
||||
json.append(",\"otherCompilers\":").append(strings(others));
|
||||
json.append(",\"testGenerators\":").append(strings(testGenerators));
|
||||
json.append(",\"problems\":").append(strings(problems)).append('}');
|
||||
for (int i = 0; i < configured.size(); i++) {
|
||||
Mojo mojo = compilers.get(configured.get(i).getGoal());
|
||||
if (mojo != null) plugins.releaseMojo(mojo, configured.get(i));
|
||||
}
|
||||
}
|
||||
|
||||
/** `testRoots`: the test source roots, `null` for the main source set. */
|
||||
private void sourceSet(StringBuilder json, MavenSession session, MavenProject project, Mojo compiler,
|
||||
List<String> testRoots, List<String> classpath, List<String> runtime, List<String> problems) {
|
||||
boolean test = testRoots != null;
|
||||
List<String> roots = test ? testRoots : project.getCompileSourceRoots();
|
||||
String output = test ? project.getBuild().getTestOutputDirectory() : project.getBuild().getOutputDirectory();
|
||||
json.append("{\"sourceRoots\":").append(strings(roots))
|
||||
.append(",\"output\":").append(q(output))
|
||||
.append(",\"classpath\":").append(strings(classpath))
|
||||
.append(",\"runtimeClasspath\":").append(strings(runtime))
|
||||
.append(",\"resources\":");
|
||||
List<Resource> resources = test ? project.getTestResources() : project.getResources();
|
||||
json.append('[');
|
||||
for (int i = 0; i < resources.size(); i++) {
|
||||
Resource r = resources.get(i);
|
||||
if (i > 0) json.append(',');
|
||||
json.append("{\"directory\":").append(q(new File(project.getBasedir(), r.getDirectory()).isAbsolute()
|
||||
? r.getDirectory() : new File(project.getBasedir(), r.getDirectory()).getAbsolutePath()))
|
||||
.append(",\"filtering\":").append(r.isFiltering())
|
||||
.append(",\"targetPath\":").append(q(r.getTargetPath()))
|
||||
.append(",\"includes\":").append(strings(r.getIncludes()))
|
||||
.append(",\"excludes\":").append(strings(r.getExcludes())).append('}');
|
||||
}
|
||||
json.append(']');
|
||||
json.append(",\"compiler\":");
|
||||
if (compiler == null) {
|
||||
json.append("null}");
|
||||
return;
|
||||
}
|
||||
json.append('{');
|
||||
String goal = test ? "testCompile" : "compile";
|
||||
field(json, "compilerId", get(compiler, "compilerId"));
|
||||
field(json, "source", get(compiler, test ? "testSource" : "source", "source"));
|
||||
field(json, "target", get(compiler, test ? "testTarget" : "target", "target"));
|
||||
field(json, "release", get(compiler, test ? "testRelease" : "release", "release"));
|
||||
field(json, "encoding", get(compiler, "encoding"));
|
||||
field(json, "parameters", get(compiler, "parameters"));
|
||||
field(json, "debug", get(compiler, "debug"));
|
||||
field(json, "debuglevel", get(compiler, "debuglevel"));
|
||||
field(json, "proc", get(compiler, "proc"));
|
||||
field(json, "enablePreview", get(compiler, "enablePreview"));
|
||||
field(json, "fork", get(compiler, "fork"));
|
||||
field(json, "executable", get(compiler, "executable"));
|
||||
field(json, "skip", get(compiler, test ? "skip" : "skipMain"));
|
||||
field(json, "showWarnings", get(compiler, "showWarnings"));
|
||||
field(json, "showDeprecation", get(compiler, "showDeprecation"));
|
||||
field(json, "generatedSourcesDirectory",
|
||||
get(compiler, test ? "generatedTestSourcesDirectory" : "generatedSourcesDirectory"));
|
||||
field(json, "includes", get(compiler, test ? "testIncludes" : "includes"));
|
||||
field(json, "excludes", get(compiler, test ? "testExcludes" : "excludes"));
|
||||
field(json, "annotationProcessors", get(compiler, "annotationProcessors"));
|
||||
field(json, "compilerArgs", get(compiler, "compilerArgs"));
|
||||
field(json, "compilerArgument", get(compiler, "compilerArgument"));
|
||||
field(json, "compilerArguments", get(compiler, "compilerArguments"));
|
||||
field(json, "multiReleaseOutput", get(compiler, "multiReleaseOutput"));
|
||||
Object paths = get(compiler, "annotationProcessorPaths");
|
||||
if (paths instanceof Collection && !((Collection<?>) paths).isEmpty()) {
|
||||
try {
|
||||
Object useDepMgmt = get(compiler, "annotationProcessorPathsUseDepMgmt");
|
||||
field(json, "processorPath", processorPath(session, project, (Collection<?>) paths,
|
||||
Boolean.TRUE.equals(useDepMgmt)));
|
||||
} catch (Exception e) {
|
||||
problems.add("Cannot resolve the annotation processor path of " + goal + ": " + rootMessage(e));
|
||||
field(json, "processorPathError", rootMessage(e));
|
||||
}
|
||||
}
|
||||
if (json.charAt(json.length() - 1) == ',') json.setLength(json.length() - 1);
|
||||
json.append("}}");
|
||||
}
|
||||
|
||||
/** The classpaths of the resolved graph, in Maven's order: compile, runtime, test scopes. */
|
||||
private static void classpaths(DependencyNode root, List<String> compile, List<String> runtime, List<String> test) {
|
||||
List<DependencyNode> nodes = new ArrayList<>();
|
||||
collect(root, nodes, new HashSet<>());
|
||||
for (DependencyNode node : nodes) {
|
||||
if (node.getDependency() == null || node.getArtifact() == null) continue;
|
||||
File file = node.getArtifact().getFile();
|
||||
if (file == null) continue;
|
||||
String scope = node.getDependency().getScope();
|
||||
String path = file.getAbsolutePath();
|
||||
if (!"test".equals(scope) && !"runtime".equals(scope)) compile.add(path);
|
||||
if (!"test".equals(scope) && !"provided".equals(scope) && !"system".equals(scope)) runtime.add(path);
|
||||
test.add(path);
|
||||
}
|
||||
}
|
||||
|
||||
/** Pre-order, as Maven lists `project.getArtifacts()` for classpaths. */
|
||||
private static void collect(DependencyNode node, List<DependencyNode> out, Set<String> seen) {
|
||||
for (DependencyNode child : node.getChildren()) {
|
||||
Artifact a = child.getArtifact();
|
||||
String key = a == null ? String.valueOf(System.identityHashCode(child))
|
||||
: a.getGroupId() + ":" + a.getArtifactId() + ":" + a.getExtension() + ":" + a.getClassifier();
|
||||
if (seen.add(key)) out.add(child);
|
||||
}
|
||||
for (DependencyNode child : node.getChildren()) collect(child, out, seen);
|
||||
}
|
||||
|
||||
/**
|
||||
* A repository session that resolves reactor projects to their output directories, as the
|
||||
* IDE compiles against them: before (and without) any packaging, and even before they exist.
|
||||
*/
|
||||
private static RepositorySystemSession reactorSession(MavenSession session) {
|
||||
final Map<String, MavenProject> byKey = new HashMap<>();
|
||||
for (MavenProject p : session.getProjects())
|
||||
byKey.put(p.getGroupId() + ":" + p.getArtifactId() + ":" + p.getVersion(), p);
|
||||
final WorkspaceReader fallback = session.getRepositorySession().getWorkspaceReader();
|
||||
final WorkspaceRepository repository = new WorkspaceRepository("openidea-reactor");
|
||||
WorkspaceReader reader = new WorkspaceReader() {
|
||||
@Override public WorkspaceRepository getRepository() {
|
||||
return repository;
|
||||
}
|
||||
|
||||
@Override public File findArtifact(Artifact artifact) {
|
||||
MavenProject p = byKey.get(artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + artifact.getBaseVersion());
|
||||
if (p == null) return fallback == null ? null : fallback.findArtifact(artifact);
|
||||
if ("pom".equals(artifact.getExtension())) return p.getFile();
|
||||
boolean tests = "tests".equals(artifact.getClassifier()) || "test-jar".equals(artifact.getProperty("type", ""));
|
||||
File dir = new File(tests ? p.getBuild().getTestOutputDirectory() : p.getBuild().getOutputDirectory());
|
||||
dir.mkdirs();
|
||||
return dir;
|
||||
}
|
||||
|
||||
@Override public List<String> findVersions(Artifact artifact) {
|
||||
MavenProject p = byKey.get(artifact.getGroupId() + ":" + artifact.getArtifactId() + ":" + artifact.getBaseVersion());
|
||||
if (p != null) return java.util.Collections.singletonList(p.getVersion());
|
||||
return fallback == null ? java.util.Collections.<String>emptyList() : fallback.findVersions(artifact);
|
||||
}
|
||||
};
|
||||
DefaultRepositorySystemSession copy = new DefaultRepositorySystemSession(session.getRepositorySession());
|
||||
copy.setWorkspaceReader(reader);
|
||||
return copy;
|
||||
}
|
||||
|
||||
/** maven-compiler-plugin's `annotationProcessorPaths`, resolved with their dependencies as the plugin does. */
|
||||
private List<String> processorPath(MavenSession session, MavenProject project, Collection<?> coordinates,
|
||||
boolean useDepMgmt) throws Exception {
|
||||
Map<String, String> managed = new HashMap<>();
|
||||
if (project.getDependencyManagement() != null)
|
||||
for (Dependency d : project.getDependencyManagement().getDependencies())
|
||||
managed.put(d.getGroupId() + ":" + d.getArtifactId(), d.getVersion());
|
||||
CollectRequest request = new CollectRequest();
|
||||
request.setRepositories(project.getRemoteProjectRepositories());
|
||||
for (Object c : coordinates) {
|
||||
String group = (String) get(c, "groupId");
|
||||
String artifact = (String) get(c, "artifactId");
|
||||
String version = (String) get(c, "version");
|
||||
if (version == null) version = managed.get(group + ":" + artifact);
|
||||
if (version == null) throw new IllegalStateException("No version for " + group + ":" + artifact);
|
||||
String classifier = (String) get(c, "classifier");
|
||||
String type = (String) get(c, "type");
|
||||
List<Exclusion> exclusions = new ArrayList<>();
|
||||
Object declared = get(c, "exclusions");
|
||||
if (declared instanceof Collection)
|
||||
for (Object e : (Collection<?>) declared)
|
||||
exclusions.add(new Exclusion((String) get(e, "groupId"), (String) get(e, "artifactId"), "*", "*"));
|
||||
DefaultArtifact a = new DefaultArtifact(group, artifact, classifier == null ? "" : classifier,
|
||||
type == null || "jar".equals(type) ? "jar" : type, version);
|
||||
request.addDependency(new org.eclipse.aether.graph.Dependency(a, "runtime", false, exclusions));
|
||||
}
|
||||
if (useDepMgmt && project.getDependencyManagement() != null) {
|
||||
for (Dependency d : project.getDependencyManagement().getDependencies()) {
|
||||
request.addManagedDependency(new org.eclipse.aether.graph.Dependency(new DefaultArtifact(d.getGroupId(),
|
||||
d.getArtifactId(), d.getClassifier() == null ? "" : d.getClassifier(),
|
||||
d.getType() == null ? "jar" : d.getType(), d.getVersion()), d.getScope()));
|
||||
}
|
||||
}
|
||||
DependencyResult result =
|
||||
repositories.resolveDependencies(reactorSession(session), new DependencyRequest(request, null));
|
||||
Set<String> out = new LinkedHashSet<>();
|
||||
for (ArtifactResult r : result.getArtifactResults())
|
||||
if (r.getArtifact() != null && r.getArtifact().getFile() != null) out.add(r.getArtifact().getFile().getAbsolutePath());
|
||||
return new ArrayList<>(out);
|
||||
}
|
||||
|
||||
private static org.apache.maven.project.DependencyResolutionException cause(Throwable e) {
|
||||
for (Throwable t = e; t != null; t = t.getCause())
|
||||
if (t instanceof org.apache.maven.project.DependencyResolutionException)
|
||||
return (org.apache.maven.project.DependencyResolutionException) t;
|
||||
return null;
|
||||
}
|
||||
|
||||
private static String rootMessage(Throwable e) {
|
||||
Throwable t = e;
|
||||
while (t.getCause() != null && t.getCause() != t) t = t.getCause();
|
||||
return t.getMessage() == null ? t.toString() : t.getMessage();
|
||||
}
|
||||
|
||||
/** The first of `names` that a field of the mojo (or its superclasses) has, read reflectively. */
|
||||
private static Object get(Object target, String... names) {
|
||||
for (String name : names) {
|
||||
for (Class<?> c = target.getClass(); c != null && c != Object.class; c = c.getSuperclass()) {
|
||||
try {
|
||||
Field f = c.getDeclaredField(name);
|
||||
f.setAccessible(true);
|
||||
Object value = f.get(target);
|
||||
if (value != null || names.length == 1) return value;
|
||||
break;
|
||||
} catch (NoSuchFieldException e) {
|
||||
// Try the superclass.
|
||||
} catch (IllegalAccessException | RuntimeException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static void field(StringBuilder json, String name, Object value) {
|
||||
if (value == null) return;
|
||||
json.append(q(name)).append(':').append(value(value)).append(',');
|
||||
}
|
||||
|
||||
private static String value(Object value) {
|
||||
if (value == null) return "null";
|
||||
if (value instanceof Boolean || value instanceof Number) return value.toString();
|
||||
if (value instanceof File) return q(((File) value).getAbsolutePath());
|
||||
if (value instanceof Collection) {
|
||||
StringBuilder b = new StringBuilder("[");
|
||||
for (Object o : (Collection<?>) value) {
|
||||
if (b.length() > 1) b.append(',');
|
||||
b.append(value(o));
|
||||
}
|
||||
return b.append(']').toString();
|
||||
}
|
||||
if (value instanceof Object[]) return value(Arrays.asList((Object[]) value));
|
||||
if (value instanceof Map) {
|
||||
StringBuilder b = new StringBuilder("{");
|
||||
for (Map.Entry<?, ?> e : new LinkedHashMap<>((Map<?, ?>) value).entrySet()) {
|
||||
if (b.length() > 1) b.append(',');
|
||||
b.append(q(String.valueOf(e.getKey()))).append(':').append(q(e.getValue() == null ? null : String.valueOf(e.getValue())));
|
||||
}
|
||||
return b.append('}').toString();
|
||||
}
|
||||
return q(value.toString());
|
||||
}
|
||||
|
||||
private static String strings(Collection<String> values) {
|
||||
StringBuilder b = new StringBuilder("[");
|
||||
if (values != null) {
|
||||
for (String s : values) {
|
||||
if (b.length() > 1) b.append(',');
|
||||
b.append(q(s));
|
||||
}
|
||||
}
|
||||
return b.append(']').toString();
|
||||
}
|
||||
|
||||
static String q(String s) {
|
||||
if (s == null) return "null";
|
||||
StringBuilder b = new StringBuilder(s.length() + 2).append('"');
|
||||
for (int i = 0; i < s.length(); i++) {
|
||||
char c = s.charAt(i);
|
||||
switch (c) {
|
||||
case '"': b.append("\\\""); break;
|
||||
case '\\': b.append("\\\\"); break;
|
||||
case '\n': b.append("\\n"); break;
|
||||
case '\r': b.append("\\r"); break;
|
||||
case '\t': b.append("\\t"); break;
|
||||
default:
|
||||
if (c < 0x20) b.append(String.format("\\u%04x", (int) c));
|
||||
else b.append(c);
|
||||
}
|
||||
}
|
||||
return b.append('"').toString();
|
||||
}
|
||||
}
|
||||
Бінарний файл не відображається.
@@ -0,0 +1,459 @@
|
||||
package ai.openidea.javac;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStreamWriter;
|
||||
import java.io.PrintWriter;
|
||||
import java.io.StringWriter;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import javax.tools.Diagnostic;
|
||||
import javax.tools.DiagnosticListener;
|
||||
import javax.tools.FileObject;
|
||||
import javax.tools.ForwardingJavaFileManager;
|
||||
import javax.tools.JavaCompiler;
|
||||
import javax.tools.JavaFileManager;
|
||||
import javax.tools.JavaFileObject;
|
||||
import javax.tools.StandardJavaFileManager;
|
||||
import javax.tools.StandardLocation;
|
||||
import javax.tools.ToolProvider;
|
||||
|
||||
/**
|
||||
* A resident javac for the IDE's Java build: one JVM per JDK, compiling requests one at a
|
||||
* time with the JDK's own compiler, in process, annotation processors included.
|
||||
*
|
||||
* <p>Protocol: one JSON object per line. Requests on stdin:
|
||||
* {@code {"id":1,"op":"compile","options":[...],"sources":[...],"encoding":"UTF-8"}},
|
||||
* {@code {"op":"cancel","id":1}}, {@code {"op":"exit"}}. Replies on stdout, all carrying the
|
||||
* request {@code id}: {@code diagnostic} (severity, path, 1-based line, UTF-16 column and end,
|
||||
* code, message), {@code output} (a class or resource file written, with the source it came
|
||||
* from), {@code generated} (a source an annotation processor wrote), {@code output-text}
|
||||
* (javac's own printed text), then one {@code done} (success, cancelled).
|
||||
*/
|
||||
public final class Server {
|
||||
private static final Object OUT_LOCK = new Object();
|
||||
private static PrintWriter out;
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
out = new PrintWriter(new OutputStreamWriter(System.out, StandardCharsets.UTF_8), false);
|
||||
// Anything else printing to stdout would break the protocol.
|
||||
System.setOut(System.err);
|
||||
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
|
||||
if (compiler == null) {
|
||||
send("{\"kind\":\"fatal\",\"message\":" + Json.quote("This Java runtime has no compiler (a JRE, not a JDK)") + "}");
|
||||
System.exit(2);
|
||||
}
|
||||
send("{\"kind\":\"ready\",\"version\":" + Json.quote(System.getProperty("java.version")) + "}");
|
||||
BufferedReader in = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8));
|
||||
final AtomicReference<Request> running = new AtomicReference<>();
|
||||
final java.util.concurrent.BlockingQueue<Request> queue = new java.util.concurrent.LinkedBlockingQueue<>();
|
||||
Thread worker = new Thread(() -> {
|
||||
while (true) {
|
||||
Request request;
|
||||
try {
|
||||
request = queue.take();
|
||||
} catch (InterruptedException e) {
|
||||
return;
|
||||
}
|
||||
if (request.exit) return;
|
||||
running.set(request);
|
||||
try {
|
||||
compile(compiler, request);
|
||||
} catch (Throwable t) {
|
||||
StringWriter trace = new StringWriter();
|
||||
t.printStackTrace(new PrintWriter(trace));
|
||||
send("{\"id\":" + request.id + ",\"kind\":\"diagnostic\",\"severity\":\"error\",\"message\":"
|
||||
+ Json.quote("javac crashed: " + trace) + "}");
|
||||
send("{\"id\":" + request.id + ",\"kind\":\"done\",\"success\":false,\"cancelled\":false}");
|
||||
} finally {
|
||||
running.set(null);
|
||||
}
|
||||
}
|
||||
}, "javac");
|
||||
worker.start();
|
||||
String line;
|
||||
while ((line = in.readLine()) != null) {
|
||||
if (line.trim().isEmpty()) continue;
|
||||
Map<String, Object> message;
|
||||
try {
|
||||
message = Json.parseObject(line);
|
||||
} catch (RuntimeException e) {
|
||||
send("{\"kind\":\"fatal\",\"message\":" + Json.quote("Bad request: " + e.getMessage()) + "}");
|
||||
continue;
|
||||
}
|
||||
String op = (String) message.get("op");
|
||||
if ("cancel".equals(op)) {
|
||||
Request current = running.get();
|
||||
long id = ((Number) message.get("id")).longValue();
|
||||
if (current != null && current.id == id) current.cancelled = true;
|
||||
for (Request queued : queue) if (queued.id == id) queued.cancelled = true;
|
||||
} else if ("exit".equals(op)) {
|
||||
break;
|
||||
} else if ("compile".equals(op)) {
|
||||
queue.add(Request.of(message));
|
||||
}
|
||||
}
|
||||
Request exit = new Request();
|
||||
exit.exit = true;
|
||||
// Requests already sent finish first; the host cancels the ones it no longer wants.
|
||||
queue.add(exit);
|
||||
try {
|
||||
worker.join();
|
||||
} catch (InterruptedException ignored) {
|
||||
}
|
||||
System.exit(0);
|
||||
}
|
||||
|
||||
static void send(String json) {
|
||||
synchronized (OUT_LOCK) {
|
||||
out.print(json);
|
||||
out.print('\n');
|
||||
out.flush();
|
||||
}
|
||||
}
|
||||
|
||||
static final class Request {
|
||||
long id;
|
||||
List<String> options = new ArrayList<>();
|
||||
List<String> sources = new ArrayList<>();
|
||||
String encoding;
|
||||
volatile boolean cancelled;
|
||||
boolean exit;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
static Request of(Map<String, Object> message) {
|
||||
Request r = new Request();
|
||||
r.id = ((Number) message.get("id")).longValue();
|
||||
Object options = message.get("options");
|
||||
if (options != null) for (Object o : (List<Object>) options) r.options.add((String) o);
|
||||
Object sources = message.get("sources");
|
||||
if (sources != null) for (Object o : (List<Object>) sources) r.sources.add((String) o);
|
||||
r.encoding = (String) message.get("encoding");
|
||||
return r;
|
||||
}
|
||||
}
|
||||
|
||||
/** Thrown from the task listener to stop a cancelled compilation. */
|
||||
static final class Cancelled extends RuntimeException {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
Cancelled() {
|
||||
super("cancelled", null, false, false);
|
||||
}
|
||||
}
|
||||
|
||||
private static void compile(JavaCompiler compiler, final Request request) throws IOException {
|
||||
final long id = request.id;
|
||||
if (request.cancelled) {
|
||||
send("{\"id\":" + id + ",\"kind\":\"done\",\"success\":false,\"cancelled\":true}");
|
||||
return;
|
||||
}
|
||||
Charset charset = request.encoding == null ? StandardCharsets.UTF_8 : Charset.forName(request.encoding);
|
||||
final int[] errors = {0};
|
||||
DiagnosticListener<JavaFileObject> diagnostics = d -> {
|
||||
if (d.getKind() == Diagnostic.Kind.ERROR) errors[0]++;
|
||||
send(diagnostic(id, d));
|
||||
};
|
||||
StandardJavaFileManager standard = compiler.getStandardFileManager(diagnostics, Locale.ROOT, charset);
|
||||
JavaFileManager manager = new Recording(standard, id);
|
||||
List<File> files = new ArrayList<>();
|
||||
for (String source : request.sources) files.add(new File(source));
|
||||
Iterable<? extends JavaFileObject> units = standard.getJavaFileObjectsFromFiles(files);
|
||||
StringWriter printed = new StringWriter();
|
||||
boolean success = false;
|
||||
boolean cancelled = false;
|
||||
try {
|
||||
JavaCompiler.CompilationTask task =
|
||||
compiler.getTask(printed, manager, diagnostics, request.options, null, units);
|
||||
stopWhenCancelled(task, request);
|
||||
success = Boolean.TRUE.equals(task.call()) && errors[0] == 0;
|
||||
} catch (RuntimeException e) {
|
||||
if (isCancelled(e)) {
|
||||
cancelled = true;
|
||||
} else if (e instanceof IllegalArgumentException) {
|
||||
// An option javac doesn't know (a newer --release than this JDK has).
|
||||
send("{\"id\":" + id + ",\"kind\":\"diagnostic\",\"severity\":\"error\",\"message\":"
|
||||
+ Json.quote(e.getMessage()) + "}");
|
||||
} else {
|
||||
throw e;
|
||||
}
|
||||
} finally {
|
||||
try {
|
||||
manager.close();
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
}
|
||||
String text = printed.toString();
|
||||
if (!text.isEmpty()) send("{\"id\":" + id + ",\"kind\":\"output-text\",\"text\":" + Json.quote(text) + "}");
|
||||
send("{\"id\":" + id + ",\"kind\":\"done\",\"success\":" + success + ",\"cancelled\":" + cancelled + "}");
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops the compilation at its next phase once {@code request} is cancelled, through
|
||||
* {@code com.sun.source.util.TaskListener} (reflectively: Java 8's {@code --release} API has no
|
||||
* {@code jdk.compiler}).
|
||||
*/
|
||||
private static void stopWhenCancelled(JavaCompiler.CompilationTask task, final Request request) {
|
||||
try {
|
||||
Class<?> listener = Class.forName("com.sun.source.util.TaskListener", false, task.getClass().getClassLoader());
|
||||
Object proxy = java.lang.reflect.Proxy.newProxyInstance(listener.getClassLoader(), new Class<?>[] {listener},
|
||||
(self, method, args) -> {
|
||||
if (method.getDeclaringClass() == Object.class) {
|
||||
switch (method.getName()) {
|
||||
case "hashCode": return System.identityHashCode(self);
|
||||
case "equals": return self == args[0];
|
||||
default: return "cancellation listener";
|
||||
}
|
||||
}
|
||||
if (request.cancelled) throw new Cancelled();
|
||||
return null;
|
||||
});
|
||||
task.getClass().getMethod("addTaskListener", listener).invoke(task, proxy);
|
||||
} catch (ReflectiveOperationException | RuntimeException e) {
|
||||
// Not javac's task: cancellation then waits for the compilation to end.
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isCancelled(Throwable e) {
|
||||
for (Throwable t = e; t != null; t = t.getCause()) if (t instanceof Cancelled) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
private static String diagnostic(long id, Diagnostic<? extends JavaFileObject> d) {
|
||||
StringBuilder json = new StringBuilder("{\"id\":").append(id).append(",\"kind\":\"diagnostic\",\"severity\":");
|
||||
String severity;
|
||||
switch (d.getKind()) {
|
||||
case ERROR: severity = "error"; break;
|
||||
case WARNING:
|
||||
case MANDATORY_WARNING: severity = "warning"; break;
|
||||
default: severity = "info";
|
||||
}
|
||||
json.append(Json.quote(severity));
|
||||
JavaFileObject source = d.getSource();
|
||||
if (source != null) {
|
||||
json.append(",\"path\":").append(Json.quote(path(source.toUri())));
|
||||
long start = d.getStartPosition();
|
||||
long end = d.getEndPosition();
|
||||
int[] startCol = start >= 0 ? lineColumn(source, start) : null;
|
||||
int[] endCol = end >= 0 ? lineColumn(source, end) : null;
|
||||
if (startCol != null) json.append(",\"line\":").append(startCol[0]).append(",\"column\":").append(startCol[1]);
|
||||
else if (d.getLineNumber() > 0) json.append(",\"line\":").append(d.getLineNumber());
|
||||
if (endCol != null) json.append(",\"endLine\":").append(endCol[0]).append(",\"endColumn\":").append(endCol[1]);
|
||||
}
|
||||
if (d.getCode() != null) json.append(",\"code\":").append(Json.quote(d.getCode()));
|
||||
json.append(",\"message\":").append(Json.quote(d.getMessage(Locale.ROOT)));
|
||||
return json.append('}').toString();
|
||||
}
|
||||
|
||||
/** 1-based line and 0-based UTF-16 column of a char offset (Java chars are UTF-16 units). */
|
||||
private static int[] lineColumn(JavaFileObject source, long offset) {
|
||||
CharSequence text;
|
||||
try {
|
||||
text = source.getCharContent(true);
|
||||
} catch (IOException | RuntimeException e) {
|
||||
return null;
|
||||
}
|
||||
if (offset > text.length()) return null;
|
||||
int line = 1;
|
||||
int lineStart = 0;
|
||||
for (int i = 0; i < offset; i++) {
|
||||
char c = text.charAt(i);
|
||||
if (c == '\n' || (c == '\r' && (i + 1 >= text.length() || text.charAt(i + 1) != '\n'))) {
|
||||
line++;
|
||||
lineStart = i + 1;
|
||||
}
|
||||
}
|
||||
return new int[] {line, (int) offset - lineStart};
|
||||
}
|
||||
|
||||
static String path(URI uri) {
|
||||
if ("file".equals(uri.getScheme())) return new File(uri).getPath();
|
||||
return uri.toString();
|
||||
}
|
||||
|
||||
/** Reports every file the compiler writes and the source it came from. */
|
||||
static final class Recording extends ForwardingJavaFileManager<JavaFileManager> {
|
||||
private final long id;
|
||||
|
||||
Recording(JavaFileManager manager, long id) {
|
||||
super(manager);
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind,
|
||||
FileObject sibling) throws IOException {
|
||||
JavaFileObject file = super.getJavaFileForOutput(location, className, kind, sibling);
|
||||
report(location, file, sibling, kind == JavaFileObject.Kind.SOURCE);
|
||||
return file;
|
||||
}
|
||||
|
||||
@Override
|
||||
public FileObject getFileForOutput(Location location, String packageName, String relativeName,
|
||||
FileObject sibling) throws IOException {
|
||||
FileObject file = super.getFileForOutput(location, packageName, relativeName, sibling);
|
||||
report(location, file, sibling, location == StandardLocation.SOURCE_OUTPUT);
|
||||
return file;
|
||||
}
|
||||
|
||||
private void report(Location location, FileObject file, FileObject sibling, boolean generatedSource) {
|
||||
StringBuilder json = new StringBuilder("{\"id\":").append(id).append(",\"kind\":")
|
||||
.append(Json.quote(generatedSource ? "generated" : "output"))
|
||||
.append(",\"path\":").append(Json.quote(path(file.toUri())));
|
||||
if (sibling != null && sibling.toUri().getScheme() != null)
|
||||
json.append(",\"source\":").append(Json.quote(path(sibling.toUri())));
|
||||
json.append(",\"location\":").append(Json.quote(location.getName()));
|
||||
send(json.append('}').toString());
|
||||
}
|
||||
}
|
||||
|
||||
/** Just enough JSON for the protocol: objects, arrays, strings, numbers, booleans, null. */
|
||||
static final class Json {
|
||||
private final String text;
|
||||
private int at;
|
||||
|
||||
private Json(String text) {
|
||||
this.text = text;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
static Map<String, Object> parseObject(String text) {
|
||||
Json json = new Json(text);
|
||||
Object value = json.value();
|
||||
json.space();
|
||||
if (!(value instanceof Map) || json.at != text.length()) throw new IllegalArgumentException("not one JSON object");
|
||||
return (Map<String, Object>) value;
|
||||
}
|
||||
|
||||
static String quote(String s) {
|
||||
if (s == null) return "null";
|
||||
StringBuilder b = new StringBuilder(s.length() + 2).append('"');
|
||||
for (int i = 0; i < s.length(); i++) {
|
||||
char c = s.charAt(i);
|
||||
switch (c) {
|
||||
case '"': b.append("\\\""); break;
|
||||
case '\\': b.append("\\\\"); break;
|
||||
case '\n': b.append("\\n"); break;
|
||||
case '\r': b.append("\\r"); break;
|
||||
case '\t': b.append("\\t"); break;
|
||||
default:
|
||||
if (c < 0x20) b.append(String.format("\\u%04x", (int) c));
|
||||
else b.append(c);
|
||||
}
|
||||
}
|
||||
return b.append('"').toString();
|
||||
}
|
||||
|
||||
private void space() {
|
||||
while (at < text.length() && Character.isWhitespace(text.charAt(at))) at++;
|
||||
}
|
||||
|
||||
private char peek() {
|
||||
space();
|
||||
if (at >= text.length()) throw new IllegalArgumentException("unexpected end");
|
||||
return text.charAt(at);
|
||||
}
|
||||
|
||||
private void expect(char c) {
|
||||
if (peek() != c) throw new IllegalArgumentException("expected '" + c + "' at " + at);
|
||||
at++;
|
||||
}
|
||||
|
||||
private Object value() {
|
||||
char c = peek();
|
||||
if (c == '{') {
|
||||
at++;
|
||||
Map<String, Object> map = new java.util.LinkedHashMap<>();
|
||||
if (peek() == '}') {
|
||||
at++;
|
||||
return map;
|
||||
}
|
||||
while (true) {
|
||||
String key = string();
|
||||
expect(':');
|
||||
map.put(key, value());
|
||||
if (peek() == ',') {
|
||||
at++;
|
||||
continue;
|
||||
}
|
||||
expect('}');
|
||||
return map;
|
||||
}
|
||||
}
|
||||
if (c == '[') {
|
||||
at++;
|
||||
List<Object> list = new ArrayList<>();
|
||||
if (peek() == ']') {
|
||||
at++;
|
||||
return list;
|
||||
}
|
||||
while (true) {
|
||||
list.add(value());
|
||||
if (peek() == ',') {
|
||||
at++;
|
||||
continue;
|
||||
}
|
||||
expect(']');
|
||||
return list;
|
||||
}
|
||||
}
|
||||
if (c == '"') return string();
|
||||
if (text.startsWith("true", at)) {
|
||||
at += 4;
|
||||
return Boolean.TRUE;
|
||||
}
|
||||
if (text.startsWith("false", at)) {
|
||||
at += 5;
|
||||
return Boolean.FALSE;
|
||||
}
|
||||
if (text.startsWith("null", at)) {
|
||||
at += 4;
|
||||
return null;
|
||||
}
|
||||
int start = at;
|
||||
while (at < text.length() && "+-0123456789.eE".indexOf(text.charAt(at)) >= 0) at++;
|
||||
if (start == at) throw new IllegalArgumentException("unexpected '" + c + "' at " + at);
|
||||
String number = text.substring(start, at);
|
||||
return number.contains(".") || number.contains("e") || number.contains("E")
|
||||
? (Object) Double.parseDouble(number) : (Object) Long.parseLong(number);
|
||||
}
|
||||
|
||||
private String string() {
|
||||
expect('"');
|
||||
StringBuilder b = new StringBuilder();
|
||||
while (true) {
|
||||
if (at >= text.length()) throw new IllegalArgumentException("unterminated string");
|
||||
char c = text.charAt(at++);
|
||||
if (c == '"') return b.toString();
|
||||
if (c != '\\') {
|
||||
b.append(c);
|
||||
continue;
|
||||
}
|
||||
char e = text.charAt(at++);
|
||||
switch (e) {
|
||||
case 'n': b.append('\n'); break;
|
||||
case 'r': b.append('\r'); break;
|
||||
case 't': b.append('\t'); break;
|
||||
case 'b': b.append('\b'); break;
|
||||
case 'f': b.append('\f'); break;
|
||||
case 'u':
|
||||
b.append((char) Integer.parseInt(text.substring(at, at + 4), 16));
|
||||
at += 4;
|
||||
break;
|
||||
default: b.append(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Server() {
|
||||
}
|
||||
}
|
||||
@@ -858,8 +858,10 @@ export const commands = {
|
||||
* A module with Kotlin / Groovy / Scala sources is built by its build system, whose class directories come first.
|
||||
* The build streams its console, messages and progress on `on_event` while it runs; a launch
|
||||
* whose build another launch's build joins receives that build's events.
|
||||
* A Maven module is built by the IDE's Java build, except for a `debug` launch the language
|
||||
* server serves: java-debug's HotSwap reloads the classes the language server compiles.
|
||||
*/
|
||||
javaResolveLaunch: (module: string, test: boolean, policy: BuildPolicy, request: RequestId, onEvent: Channel<BuildEvent>) => typedError<JavaLaunchInfo, IdeError>(__TAURI_INVOKE("java_resolve_launch", { module, test, policy, request, onEvent })),
|
||||
javaResolveLaunch: (module: string, test: boolean, debug: boolean, policy: BuildPolicy, request: RequestId, onEvent: Channel<BuildEvent>) => typedError<JavaLaunchInfo, IdeError>(__TAURI_INVOKE("java_resolve_launch", { module, test, debug, policy, request, onEvent })),
|
||||
/**
|
||||
* Downloads the latest `vendor` JDK of Java `version` into `location` (default:
|
||||
* [`jdk_download_location`]), streaming progress through `on_event`; cancellable
|
||||
|
||||
@@ -99,7 +99,7 @@ describe("Java debugging (java-debug through jdtls)", () => {
|
||||
expect(isJavaDebuggable({ ...app, kind: "maven" })).toBe(false);
|
||||
const l = await javaLaunchConfig(app, "/p");
|
||||
expect(invoked).toEqual([
|
||||
["javaResolveLaunch", ["api", false, "automatic", expect.any(Number), expect.anything()]],
|
||||
["javaResolveLaunch", ["api", false, true, "automatic", expect.any(Number), expect.anything()]],
|
||||
["javaDebugAdapter", ["api"]],
|
||||
["javaDebugServer", ["api"]],
|
||||
]);
|
||||
@@ -240,7 +240,7 @@ it.each(["sibling", "/outside/modules"])("debugs from %s with the main class mod
|
||||
const launch = await javaLaunchConfig({ ...app, module, cwd }, "/p");
|
||||
expect(invoked).toContainEqual([
|
||||
"javaResolveLaunch",
|
||||
["api", false, "automatic", expect.any(Number), expect.anything()],
|
||||
["api", false, true, "automatic", expect.any(Number), expect.anything()],
|
||||
]);
|
||||
expect(invoked).toContainEqual(["javaDebugServer", ["api"]]);
|
||||
expect(launch.cwd).toBe(cwd.startsWith("/") ? cwd : `/p/${cwd}`);
|
||||
|
||||
@@ -70,7 +70,7 @@ async function startAndStop() {
|
||||
).toContain("Building and resolving the classpath of Main…");
|
||||
expect(useDebugRunSessions.getState().sessions[0]?.configId).toBe(config.id);
|
||||
await executeAction("debug.stop");
|
||||
expect(ipc.cancelRequest).toHaveBeenCalledWith(ipc.javaResolveLaunch.mock.calls[0]![3]);
|
||||
expect(ipc.cancelRequest).toHaveBeenCalledWith(ipc.javaResolveLaunch.mock.calls[0]![4]);
|
||||
expect(useDebug.getState().sessions[session.id]?.status).toBe("terminated");
|
||||
expect(useDebugRunSessions.getState().sessions).toEqual([]);
|
||||
return { starting };
|
||||
|
||||
@@ -145,16 +145,16 @@ export async function javaLaunchConfig(
|
||||
const parsed = parseJavaArgs(rc.args);
|
||||
if (!parsed.mainClass) throw new Error(`No main class in '${rc.name}'`);
|
||||
preparation?.signal.throwIfAborted();
|
||||
const { module, info, resolved } = await prepareJavaLaunch(
|
||||
rc,
|
||||
preparation ?? {
|
||||
const { module, info, resolved } = await prepareJavaLaunch(rc, {
|
||||
...(preparation ?? {
|
||||
request: nextRequestId(),
|
||||
signal: new AbortController().signal,
|
||||
saveAll: async () => {
|
||||
await maybeEditorService()?.saveAll();
|
||||
},
|
||||
},
|
||||
);
|
||||
}),
|
||||
debug: true,
|
||||
});
|
||||
const cwd = resolved.cwd ? join(root, resolved.cwd) : root;
|
||||
if (info.errorCount > 0 && !preparation?.report)
|
||||
notifications().notify({
|
||||
|
||||
@@ -147,7 +147,7 @@ const boot = {
|
||||
describe("Spring Boot application updates", () => {
|
||||
it("processes resources and publishes them to the resolved runtime output", async () => {
|
||||
await updateTomcat(boot, "resources");
|
||||
expect(mocks.resolve).toHaveBeenCalledWith("app", false, "noBuild", 1, expect.anything());
|
||||
expect(mocks.resolve).toHaveBeenCalledWith("app", false, true, "noBuild", 1, expect.anything());
|
||||
expect(mocks.runBuild).toHaveBeenCalledWith({ id: "build" });
|
||||
expect(mocks.publish).toHaveBeenCalledWith(boot.config, ["/p/app/bin/main"], "a.Main");
|
||||
expect(mocks.update).not.toHaveBeenCalled();
|
||||
@@ -155,7 +155,7 @@ describe("Spring Boot application updates", () => {
|
||||
});
|
||||
it("compiles and invokes the existing scoped HotSwap action in debug", async () => {
|
||||
await updateTomcat(boot, "classes");
|
||||
expect(mocks.resolve).toHaveBeenCalledWith("app", false, "make", 1, expect.anything());
|
||||
expect(mocks.resolve).toHaveBeenCalledWith("app", false, true, "make", 1, expect.anything());
|
||||
expect(mocks.action).toHaveBeenCalledWith("debug.reloadChangedClasses", { configId: "boot" });
|
||||
});
|
||||
it("explains compiled classes require restart without a debugger", async () => {
|
||||
|
||||
@@ -54,6 +54,8 @@ async function updateSpringBoot(config: RunConfig, mode: UpdateMode, debugging:
|
||||
mode === "classes" ? "make" : "noBuild",
|
||||
request,
|
||||
followLaunchBuild(request, tx`Build before launch: ${config.name}`),
|
||||
// HotSwap reloads what the Java language server compiles.
|
||||
debugging,
|
||||
);
|
||||
if (info.build === "failed" || info.build === "withErrors" || info.build === "cancelled")
|
||||
throw updateBuildError(info);
|
||||
|
||||
@@ -84,7 +84,14 @@ afterEach(() => {
|
||||
it.each(["sibling", "/outside/modules"])("runs from %s using the stored module's classpath", async (cwd) => {
|
||||
const session = await startRun({ ...config, module: "app", cwd });
|
||||
expect(session?.status).toBe("running");
|
||||
expect(ipc.javaResolveLaunch).toHaveBeenCalledWith("app", false, "automatic", expect.any(Number), expect.anything());
|
||||
expect(ipc.javaResolveLaunch).toHaveBeenCalledWith(
|
||||
"app",
|
||||
false,
|
||||
false,
|
||||
"automatic",
|
||||
expect.any(Number),
|
||||
expect.anything(),
|
||||
);
|
||||
expect(ipc.runStart).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ cwd, args: ["-cp", "/p/app/target/classes", "a.Main"] }),
|
||||
expect.anything(),
|
||||
@@ -108,13 +115,27 @@ const launchInfo = (build: "succeeded" | "failed" | "withErrors") => ({
|
||||
|
||||
it.each(["noBuild", "rebuild"] as const)("passes the %s build policy to the resolver", async (buildPolicy) => {
|
||||
await startRun({ ...config, module: "app", buildPolicy });
|
||||
expect(ipc.javaResolveLaunch).toHaveBeenCalledWith("app", false, buildPolicy, expect.any(Number), expect.anything());
|
||||
expect(ipc.javaResolveLaunch).toHaveBeenCalledWith(
|
||||
"app",
|
||||
false,
|
||||
false,
|
||||
buildPolicy,
|
||||
expect.any(Number),
|
||||
expect.anything(),
|
||||
);
|
||||
});
|
||||
|
||||
it("always applies the launch policy after a Before launch Build Project", async () => {
|
||||
useProject.setState({ project: { root: "/p" } as never });
|
||||
await startRun({ ...config, module: "app" });
|
||||
expect(ipc.javaResolveLaunch).toHaveBeenCalledWith("app", false, "automatic", expect.any(Number), expect.anything());
|
||||
expect(ipc.javaResolveLaunch).toHaveBeenCalledWith(
|
||||
"app",
|
||||
false,
|
||||
false,
|
||||
"automatic",
|
||||
expect.any(Number),
|
||||
expect.anything(),
|
||||
);
|
||||
useProject.setState({ project: null });
|
||||
});
|
||||
|
||||
@@ -145,7 +166,14 @@ it.each([undefined, "automatic", "make", "rebuild"] as const)(
|
||||
it("finds the source module for an old saved configuration without a module", async () => {
|
||||
await startRun({ ...config, cwd: "/outside/modules" });
|
||||
expect(ipc.findFiles).toHaveBeenCalledWith("Main.java", 1000);
|
||||
expect(ipc.javaResolveLaunch).toHaveBeenCalledWith("app", false, "automatic", expect.any(Number), expect.anything());
|
||||
expect(ipc.javaResolveLaunch).toHaveBeenCalledWith(
|
||||
"app",
|
||||
false,
|
||||
false,
|
||||
"automatic",
|
||||
expect.any(Number),
|
||||
expect.anything(),
|
||||
);
|
||||
expect(ipc.runStart).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ cwd: "/outside/modules" }),
|
||||
expect.anything(),
|
||||
@@ -166,7 +194,14 @@ it.each([null, "/elsewhere"])("recovers an attached module from its indexed path
|
||||
});
|
||||
const session = await startRun({ ...config, cwd });
|
||||
expect(session?.status).toBe("running");
|
||||
expect(ipc.javaResolveLaunch).toHaveBeenCalledWith(module, false, "automatic", expect.any(Number), expect.anything());
|
||||
expect(ipc.javaResolveLaunch).toHaveBeenCalledWith(
|
||||
module,
|
||||
false,
|
||||
false,
|
||||
"automatic",
|
||||
expect.any(Number),
|
||||
expect.anything(),
|
||||
);
|
||||
expect(ipc.runStart).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ cwd: cwd ?? module, module }),
|
||||
expect.anything(),
|
||||
@@ -184,7 +219,14 @@ it.each([["-cp", "lib/*"], []])("colours Spring Boot runs without classpath reso
|
||||
expect.anything(),
|
||||
expect.any(Number),
|
||||
);
|
||||
expect(ipc.javaResolveLaunch).toHaveBeenCalledWith("app", false, "automatic", expect.any(Number), expect.anything());
|
||||
expect(ipc.javaResolveLaunch).toHaveBeenCalledWith(
|
||||
"app",
|
||||
false,
|
||||
false,
|
||||
"automatic",
|
||||
expect.any(Number),
|
||||
expect.anything(),
|
||||
);
|
||||
expect(boot.args).toBe(args);
|
||||
expect(args).not.toContain("-Dspring.output.ansi.enabled=always");
|
||||
});
|
||||
@@ -193,14 +235,28 @@ it.each(["never", "detect", "always"])("preserves an explicit Spring Boot consol
|
||||
const args = [`-Dspring.output.ansi.enabled=${value}`, "-cp", "lib/*", "a.Main"];
|
||||
await startRun({ ...config, kind: "spring-boot", args });
|
||||
expect(ipc.runStart).toHaveBeenCalledWith(expect.objectContaining({ args }), expect.anything(), expect.any(Number));
|
||||
expect(ipc.javaResolveLaunch).toHaveBeenCalledWith("app", false, "automatic", expect.any(Number), expect.anything());
|
||||
expect(ipc.javaResolveLaunch).toHaveBeenCalledWith(
|
||||
"app",
|
||||
false,
|
||||
false,
|
||||
"automatic",
|
||||
expect.any(Number),
|
||||
expect.anything(),
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps plain Java runs with an explicit classpath free of Spring Boot options", async () => {
|
||||
const args = ["-cp", "lib/*", "a.Main"];
|
||||
await startRun({ ...config, args });
|
||||
expect(ipc.runStart).toHaveBeenCalledWith(expect.objectContaining({ args }), expect.anything(), expect.any(Number));
|
||||
expect(ipc.javaResolveLaunch).toHaveBeenCalledWith("app", false, "automatic", expect.any(Number), expect.anything());
|
||||
expect(ipc.javaResolveLaunch).toHaveBeenCalledWith(
|
||||
"app",
|
||||
false,
|
||||
false,
|
||||
"automatic",
|
||||
expect.any(Number),
|
||||
expect.anything(),
|
||||
);
|
||||
});
|
||||
|
||||
it("adds the Spring Boot console option once when resolving the module classpath", async () => {
|
||||
|
||||
@@ -69,7 +69,7 @@ describe("Stop during Java launch resolution", () => {
|
||||
await vi.waitFor(() => expect(ipc.javaResolveLaunch).toHaveBeenCalledOnce());
|
||||
const session = useRun.getState().sessions[0]!;
|
||||
expect(session.status).toBe("starting");
|
||||
const request = ipc.javaResolveLaunch.mock.calls[0]![3];
|
||||
const request = ipc.javaResolveLaunch.mock.calls[0]![4];
|
||||
expect(request).toEqual(expect.any(Number));
|
||||
await stopSession(session.id);
|
||||
expect(ipc.cancelRequest).toHaveBeenCalledExactlyOnceWith(request);
|
||||
|
||||
@@ -292,7 +292,14 @@ describe("updating a running Tomcat deployment", () => {
|
||||
it("compiles the selected WAR module and copies its outputs instead of rebuilding the WAR", async () => {
|
||||
const c = config({ deployment: "artifact", artifact: "maven:web/pom.xml" });
|
||||
expect(await syncTomcatOutputs(c, false)).toBe(true);
|
||||
expect(commands.javaResolveLaunch).toHaveBeenCalledWith("web", false, "make", expect.anything(), expect.anything());
|
||||
expect(commands.javaResolveLaunch).toHaveBeenCalledWith(
|
||||
"web",
|
||||
false,
|
||||
false,
|
||||
"make",
|
||||
expect.anything(),
|
||||
expect.anything(),
|
||||
);
|
||||
expect(commands.runTomcatSync).toHaveBeenCalledWith(c, "web", ["/p/web/target/classes", "/m2/lib.jar"], false);
|
||||
});
|
||||
|
||||
|
||||
@@ -252,6 +252,11 @@ export interface JavaPreparation {
|
||||
saveAll?: () => Promise<void>;
|
||||
/** Follows the build while it runs (status bar, Build tool window); see `followLaunchBuild`. */
|
||||
build?: JavaBuildFollower;
|
||||
/**
|
||||
* A debug launch: a module the Java language server serves is compiled by it, whose classes
|
||||
* java-debug's HotSwap reloads, instead of the IDE's Java build.
|
||||
*/
|
||||
debug?: boolean;
|
||||
}
|
||||
|
||||
/** Receives the events of a launch's build as it runs, then its outcome. */
|
||||
@@ -267,11 +272,12 @@ export async function resolveJavaLaunch(
|
||||
policy: BuildPolicy,
|
||||
request: RequestId,
|
||||
build?: JavaBuildFollower,
|
||||
debug = false,
|
||||
): Promise<JavaLaunchInfo> {
|
||||
const channel = new Channel<BuildEvent>();
|
||||
channel.onmessage = (e) => build?.onEvent(e);
|
||||
try {
|
||||
const info = await call(commands.javaResolveLaunch(module, test, policy, request, channel));
|
||||
const info = await call(commands.javaResolveLaunch(module, test, debug, policy, request, channel));
|
||||
build?.finish(info.build === "failed" ? "failed" : info.build === "cancelled" ? "cancelled" : "success");
|
||||
return info;
|
||||
} catch (e) {
|
||||
@@ -305,6 +311,7 @@ export async function prepareJavaLaunch(config: RunConfig, preparation: JavaPrep
|
||||
policy,
|
||||
preparation.request,
|
||||
preparation.build,
|
||||
preparation.debug,
|
||||
).catch((error: unknown) => {
|
||||
if (error instanceof IpcError && error.data?.type === "javaBuildProblems") {
|
||||
const problems = error.data.problems.join("; ");
|
||||
|
||||
Reference in new issue
Заблокувати користувача