This is an automated email from the ASF dual-hosted git repository.
gnodet pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/maven.git
The following commit(s) were added to refs/heads/master by this push:
new 6145dae0de perf: replace FastTerminal with JLine's DeferredTerminal
(#13955)
6145dae0de is described below
commit 6145dae0de2b5d63465fa08215804cc98c1b25f9
Author: Guillaume Nodet <[email protected]>
AuthorDate: Sat Nov 14 01:05:46 2026 +0100
perf: replace FastTerminal with JLine's DeferredTerminal (#13955)
Port of #13924.
Replace the 386-line `FastTerminal` proxy with JLine 4.7.0's built-in
`TerminalBuilder.buildDeferred()`, which provides the same semantics with less
code and better performance.
**Changes:**
- **Delete `FastTerminal.java`** — replaced by JLine's `DeferredTerminal`
- **Simplify `MessageUtils.systemInstall()`** — uses `buildDeferred()` +
`onComplete()` callback
- **Move `createTerminal()` to the first step of `doInvoke()`** — terminal
builds in background while validate/pushProperties/configureLogging run
- **Handle embedded mode** — use raw streams for embedded mode to avoid
StackOverflowError; `doConfigureWithTerminal` moved to main thread after
configureLogging
- **Null guard in `systemInstall(Terminal)`** restored to clear reader on
null
- **Fix `awaitTerminalInitialization`** to wait for the `onComplete`
callback to fire rather than racing
- **Fix ANSI output** for dumb terminals and IT stdout verification; guard
stdout fallback on size > 0
- **Skip waiting on shutdown** — if the terminal isn't ready when the
process exits, `close()` drains buffered output to stdout
- **Bump JLine from 4.5.0 to 4.7.0**
- **Update `FastTerminalReentrancyTest`** to use `DeferredTerminal` and
**re-enable `MavenCliLoggingTest`**
**Net: -390 lines** (+71, -461)
**Benchmark (JDK 25, macOS arm64):**
| | Wall clock |
|---|---|
| Maven 3.9.16 `mvn -v` | 0.478s |
| Maven 4.0.0 (before) `mvn -v` | ~0.450s |
| **Maven 4.0.0 (after) `mvn -v`** | **0.288s** |
---
.../org/apache/maven/cli/MavenCliLoggingTest.java | 258 +++++++-------
.../apache/maven/cling/invoker/LookupInvoker.java | 56 ++-
.../java/org/apache/maven/jline/FastTerminal.java | 386 ---------------------
.../maven/jline/JLineMessageBuilderFactory.java | 7 +-
.../java/org/apache/maven/jline/MessageUtils.java | 96 +++--
.../maven/jline/FastTerminalReentrancyTest.java | 139 ++------
.../main/java/org/apache/maven/it/Verifier.java | 10 +
pom.xml | 2 +-
8 files changed, 299 insertions(+), 655 deletions(-)
diff --git
a/compat/maven-embedder/src/test/java/org/apache/maven/cli/MavenCliLoggingTest.java
b/compat/maven-embedder/src/test/java/org/apache/maven/cli/MavenCliLoggingTest.java
index 5d050352d2..c8bd0de52a 100644
---
a/compat/maven-embedder/src/test/java/org/apache/maven/cli/MavenCliLoggingTest.java
+++
b/compat/maven-embedder/src/test/java/org/apache/maven/cli/MavenCliLoggingTest.java
@@ -19,10 +19,13 @@
package org.apache.maven.cli;
import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
+import java.io.OutputStream;
import java.io.PrintStream;
import java.lang.reflect.Field;
import java.nio.file.Files;
import java.nio.file.Path;
+import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.FutureTask;
import java.util.concurrent.atomic.AtomicBoolean;
@@ -30,11 +33,11 @@
import org.apache.maven.api.Constants;
import org.apache.maven.cling.logging.Slf4jConfiguration;
import org.apache.maven.cling.logging.Slf4jConfigurationFactory;
-import org.apache.maven.jline.FastTerminal;
import org.apache.maven.jline.MessageUtils;
import org.apache.maven.slf4j.MavenBaseLogger;
import org.jline.terminal.Terminal;
-import org.jline.terminal.spi.TerminalExt;
+import org.jline.terminal.impl.DeferredTerminal;
+import org.jline.terminal.impl.DumbTerminal;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -46,8 +49,6 @@
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
-import static org.mockito.Mockito.mock;
@Isolated("Changes JVM-wide streams, system properties, terminal state, and
logging configuration")
class MavenCliLoggingTest {
@@ -64,6 +65,7 @@ class MavenCliLoggingTest {
private PrintStream savedOut;
private Terminal savedTerminal;
private boolean savedColor;
+ private CompletableFuture<Void> savedTerminalReady;
private final String[] savedPropertyValues = new
String[SAVED_PROPERTIES.length];
@BeforeEach
@@ -71,15 +73,14 @@ void setUp() throws Exception {
savedOut = System.out;
savedTerminal = getTerminalField();
savedColor = getColorEnabled();
- // Null out the terminal so leftover FastTerminal threads from other
tests cannot
+ savedTerminalReady = getTerminalReadyField();
+ // Null out the terminal so leftover DeferredTerminal threads from
other tests cannot
// race with this test's stream setup via their consumer callbacks.
injectTerminal(null);
+ clearTerminalReady();
for (int i = 0; i < SAVED_PROPERTIES.length; i++) {
savedPropertyValues[i] = System.getProperty(SAVED_PROPERTIES[i]);
}
- // Clear all logger properties and re-initialize the config so
previous tests
- // (e.g. MavenCliTest#calculateTransferListener setting
maven.logger.defaultLogLevel=error
- // via --quiet) cannot poison this test's config.
for (String prop : SAVED_PROPERTIES) {
System.clearProperty(prop);
}
@@ -90,6 +91,7 @@ void setUp() throws Exception {
void tearDown() throws Exception {
System.setOut(savedOut);
injectTerminal(savedTerminal);
+ setTerminalReady(savedTerminalReady);
setColorEnabled(savedColor);
for (int i = 0; i < SAVED_PROPERTIES.length; i++) {
restoreProperty(SAVED_PROPERTIES[i], savedPropertyValues[i]);
@@ -98,76 +100,49 @@ void tearDown() throws Exception {
}
/**
- * When color is explicitly forced ({@code -Dstyle.color=always}), {@code
logging()} must NOT
- * call {@code awaitTerminalInitialization()} before activating the
logging configuration.
- * The logger must therefore cache the stream that was active at
activation time (the "early"
+ * When color is explicitly forced ({@code -color=always}), {@code
logging()} must NOT call
+ * {@code awaitTerminalInitialization()} before activating the logging
configuration. The
+ * logger must therefore cache the stream that was active at activation
time (the "early"
* stream), not the stream installed by the terminal consumer afterwards.
* <p>
- * On master, {@code MavenSimpleLogger.configure()} renders ANSI-coloured
level labels via
- * {@code JLineMessageBuilderFactory}, which calls {@code
terminal.getType()} and therefore
- * always awaits terminal initialisation inside {@code activate()}. The
key behavioral
- * difference being tested is that with {@code color=always}, {@code
config.init()} captures
- * {@code System.out} <em>before</em> the terminal consumer runs (because
- * {@code awaitTerminalInitialization()} is skipped before {@code
activate()}).
- * <p>
- * This test uses a held-back {@link FastTerminal} instead of a {@code
DumbTerminal}. The
- * terminal build blocks until the test releases it. Since {@code
logging()} with
- * {@code color=always} does not call {@code
awaitTerminalInitialization()} before
- * {@code activate()}, the logger caches {@code earlyStream} in {@code
config.init()}, then
- * blocks inside {@code configure()} waiting for the terminal. When the
test releases the
- * terminal, the consumer swaps {@code System.out} to {@code
terminalStream}, but the logger
- * has already cached {@code earlyStream}.
+ * Note: on master the logger reconfiguration ({@code
MavenSimpleLogger.configure()}) renders
+ * ANSI-coloured level labels via {@code JLineMessageBuilderFactory},
which calls
+ * {@code terminal.getType()} and therefore always awaits terminal
initialisation. The test
+ * accounts for this by completing the terminal build before running
{@code logging()} and
+ * then swapping {@code System.out} afterwards, verifying that the logger
sticks to the
+ * stream it cached at activation time.
*/
@Test
void withColorForcedLoggerCachesEarlyStream() throws Exception {
- CountDownLatch buildingTerminal = new CountDownLatch(1);
- CountDownLatch releaseTerminal = new CountDownLatch(1);
ByteArrayOutputStream earlyOutput = new ByteArrayOutputStream();
- ByteArrayOutputStream terminalOutput = new ByteArrayOutputStream();
- Thread loggingThread = null;
+ ByteArrayOutputStream lateOutput = new ByteArrayOutputStream();
try (PrintStream earlyStream = new PrintStream(earlyOutput, true,
UTF_8.name());
- PrintStream terminalStream = new PrintStream(terminalOutput,
true, UTF_8.name())) {
+ PrintStream lateStream = new PrintStream(lateOutput, true,
UTF_8.name());
+ Terminal dumb = new DumbTerminal(
+ "Maven",
+ Terminal.TYPE_DUMB_COLOR,
+ InputStream.nullInputStream(),
+ OutputStream.nullOutputStream(),
+ null)) {
+ // Install a completed terminal so configure() can call getType()
without blocking.
+ injectTerminal(dumb);
+
+ // Set up logger to cache System.out at activate() time.
System.setProperty(MavenBaseLogger.LEGACY_PREFIX +
"cacheOutputStream", "true");
System.setProperty(MavenBaseLogger.LEGACY_PREFIX + "logFile",
"System.out");
System.setOut(earlyStream);
activateSlf4j();
- FastTerminal terminal = new FastTerminal(
- () -> {
- buildingTerminal.countDown();
- if (!releaseTerminal.await(10, SECONDS)) {
- throw new IllegalStateException("Terminal
installation was not released");
- }
- return mock(TerminalExt.class, RETURNS_DEEP_STUBS);
- },
- installed -> System.setOut(terminalStream));
- injectTerminal(terminal);
- terminal.start();
- assertTrue(buildingTerminal.await(10, SECONDS), "FastTerminal
build thread must start");
-
- // Run logging() on a separate thread — it will block inside
configure() when
- // toAnsi() calls FastTerminal.getType() → getTerminal() →
terminal.get().
+ // Run logging() with -color=always. It must NOT call
awaitTerminalInitialization()
+ // before activate(), so it completes immediately (no blocking
terminal).
MavenCli cli = new MavenCli();
CliRequest request = new CliRequest(new String[]
{"-Dstyle.color=always"}, null);
cli.cli(request);
cli.properties(request);
- FutureTask<Void> logging = new FutureTask<>(() -> {
- cli.logging(request);
- return null;
- });
- loggingThread = new Thread(logging, "logging-initialization-test");
- loggingThread.setDaemon(true);
- loggingThread.start();
+ cli.logging(request);
- // Wait until the logging thread is blocked on the terminal's
CompletableFuture.
- // At that point, config.init() has already captured earlyStream
(it runs before
- // configure() which is where the block occurs).
- awaitThreadState(loggingThread, Thread.State.WAITING, 10_000);
-
- // Release the terminal — the consumer sets
System.out=terminalStream, but the
- // logger has already cached earlyStream in config.init().
- releaseTerminal.countDown();
- logging.get(10, SECONDS);
+ // Swap System.out AFTER logging() has cached earlyStream.
+ System.setOut(lateStream);
// The logger must still write to earlyStream.
LoggerFactory.getLogger(MavenCliLoggingTest.class).warn("terminal-output-marker");
@@ -175,13 +150,8 @@ void withColorForcedLoggerCachesEarlyStream() throws
Exception {
earlyOutput.toString(UTF_8.name()).contains("terminal-output-marker"),
"Logger must write to the stream that was active when
logging() ran with -color=always");
assertFalse(
-
terminalOutput.toString(UTF_8.name()).contains("terminal-output-marker"),
+
lateOutput.toString(UTF_8.name()).contains("terminal-output-marker"),
"Logger must not switch to the stream installed after
logging() completed");
- } finally {
- releaseTerminal.countDown();
- if (loggingThread != null) {
- loggingThread.join(10_000);
- }
}
}
@@ -205,30 +175,38 @@ void logFileBranchAwaitsTerminalBeforeRedirect(@TempDir
Path tempDir) throws Exc
CountDownLatch buildingTerminal = new CountDownLatch(1);
CountDownLatch releaseTerminal = new CountDownLatch(1);
- // Set by the terminal consumer; true means the consumer fired before
System.out was
- // redirected to the log file — which is the correct behaviour: the
consumer fires
- // BEFORE the log redirect, so it cannot overwrite it.
AtomicBoolean consumerFiredBeforeRedirect = new AtomicBoolean(false);
Thread loggingThread = null;
- try {
- FastTerminal terminal = new FastTerminal(
+ try (Terminal dumb = new DumbTerminal(
+ "Maven",
+ Terminal.TYPE_DUMB_COLOR,
+ InputStream.nullInputStream(),
+ OutputStream.nullOutputStream(),
+ null)) {
+ DeferredTerminal terminal = new DeferredTerminal();
+ terminal.onComplete(installed -> {
+ consumerFiredBeforeRedirect.set(System.out == originalOut);
+ });
+ Thread buildThread = new Thread(
() -> {
- buildingTerminal.countDown();
- if (!releaseTerminal.await(10, SECONDS)) {
- throw new IllegalStateException("Terminal
installation was not released");
+ try {
+ buildingTerminal.countDown();
+ if (!releaseTerminal.await(10, SECONDS)) {
+ terminal.completeExceptionally(
+ new IllegalStateException("Terminal
installation was not released"));
+ return;
+ }
+ terminal.complete(dumb);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ terminal.completeExceptionally(e);
}
- return mock(TerminalExt.class, RETURNS_DEEP_STUBS);
},
- installed -> {
- // The consumer fires as part of terminal.complete()
inside the build thread.
- // If awaitTerminalInitialization() was called, the
consumer fires BEFORE
- // logging() redirects System.out to the log file. We
detect this by
- // checking whether System.out is still the original
stream at this point.
- consumerFiredBeforeRedirect.set(System.out ==
originalOut);
- });
+ "deferred-terminal-build");
+ buildThread.setDaemon(true);
injectTerminal(terminal);
- terminal.start();
- assertTrue(buildingTerminal.await(10, SECONDS), "FastTerminal
build thread must start");
+ buildThread.start();
+ assertTrue(buildingTerminal.await(10, SECONDS), "DeferredTerminal
build thread must start");
MavenCli cli = new MavenCli();
CliRequest request =
@@ -243,18 +221,14 @@ void logFileBranchAwaitsTerminalBeforeRedirect(@TempDir
Path tempDir) throws Exc
loggingThread.setDaemon(true);
loggingThread.start();
- // Release the terminal; logging() will unblock from
awaitTerminalInitialization(),
- // the consumer fires, then the redirect happens.
releaseTerminal.countDown();
logging.get(10, SECONDS);
- // The consumer must have fired before System.out was redirected
to the log file.
assertTrue(
consumerFiredBeforeRedirect.get(),
"Terminal consumer must fire before System.out is
redirected to the log file; "
+ "if it fires after, it could overwrite the
log-file redirect (#12188)");
- // After logging() returns, System.out must be redirected to the
log file (not original).
assertFalse(
System.out == originalOut,
"After logging() with -l, System.out must be redirected to
the log file");
@@ -263,8 +237,6 @@ void logFileBranchAwaitsTerminalBeforeRedirect(@TempDir
Path tempDir) throws Exc
if (loggingThread != null) {
loggingThread.join(10_000);
}
- // Close the PrintStream wrapping maven.log so @TempDir can delete
the temp directory on Windows.
- // An open FileOutputStream prevents directory deletion on Windows.
PrintStream logStream = System.out;
System.setOut(originalOut);
if (logStream != originalOut) {
@@ -280,10 +252,11 @@ void logFileBranchAwaitsTerminalBeforeRedirect(@TempDir
Path tempDir) throws Exc
* This prevents logs from going to a stale stream instead of the
terminal-wrapped one.
* <p>
* Unlike the {@code color=always} test, this test verifies that the
logger caches the
- * <em>terminal</em> stream, not the early stream. The held-back {@link
FastTerminal}
+ * <em>terminal</em> stream, not the early stream. The held-back {@link
DeferredTerminal}
* approach works cleanly here: {@code logging()} calls {@code
awaitTerminalInitialization()}
* which blocks until the terminal is released. When released, the
consumer swaps
* {@code System.out}, then {@code config.init()} captures the new stream.
+ *
*/
@Test
void cachesOutputAfterTerminalInstallationWithColorDisabled() throws
Exception {
@@ -302,26 +275,46 @@ private void cachesOutputAfterTerminalInstallation(String
color) throws Exceptio
ByteArrayOutputStream terminalOutput = new ByteArrayOutputStream();
Thread loggingThread = null;
try (PrintStream earlyStream = new PrintStream(earlyOutput, true,
UTF_8.name());
- PrintStream terminalStream = new PrintStream(terminalOutput,
true, UTF_8.name())) {
+ PrintStream terminalStream = new PrintStream(terminalOutput,
true, UTF_8.name());
+ Terminal dumb = new DumbTerminal(
+ "Maven",
+ Terminal.TYPE_DUMB_COLOR,
+ InputStream.nullInputStream(),
+ OutputStream.nullOutputStream(),
+ null)) {
System.setProperty(MavenBaseLogger.LEGACY_PREFIX +
"cacheOutputStream", "true");
System.setProperty(MavenBaseLogger.LEGACY_PREFIX + "logFile",
"System.out");
System.setOut(earlyStream);
activateSlf4j();
- FastTerminal terminal = new FastTerminal(
+ DeferredTerminal terminal = new DeferredTerminal();
+ CompletableFuture<Void> terminalReady = new CompletableFuture<>();
+ terminal.onComplete(installed -> {
+ System.setOut(terminalStream);
+ terminalReady.complete(null);
+ });
+ Thread buildThread = new Thread(
() -> {
- buildingTerminal.countDown();
- if (!releaseTerminal.await(10, SECONDS)) {
- throw new IllegalStateException("Terminal
installation was not released");
+ try {
+ buildingTerminal.countDown();
+ if (!releaseTerminal.await(10, SECONDS)) {
+ IllegalStateException ex =
+ new IllegalStateException("Terminal
installation was not released");
+ terminal.completeExceptionally(ex);
+ terminalReady.completeExceptionally(ex);
+ return;
+ }
+ terminal.complete(dumb);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ terminal.completeExceptionally(e);
+ terminalReady.completeExceptionally(e);
}
- return mock(TerminalExt.class, RETURNS_DEEP_STUBS);
},
- installed -> System.setOut(terminalStream));
- // Inject the FastTerminal directly into MessageUtils.terminal
before starting the
- // build thread, to avoid calling systemInstall(Terminal) which
also creates a LineReader
- // from the terminal — that would call FastTerminal.getTerminal()
and block.
- injectTerminal(terminal);
- terminal.start();
+ "deferred-terminal-build");
+ buildThread.setDaemon(true);
+ injectTerminal(terminal, terminalReady);
+ buildThread.start();
assertTrue(buildingTerminal.await(10, SECONDS));
MavenCli cli = new MavenCli();
@@ -338,12 +331,13 @@ private void cachesOutputAfterTerminalInstallation(String
color) throws Exceptio
loggingThread.start();
// Wait until the logging thread is blocked on
awaitTerminalInitialization() →
- // FastTerminal.getTerminal() → CompletableFuture.get(). At this
point,
- // config.init() has NOT yet run (it comes after
awaitTerminalInitialization()).
+ // terminalReady.join(). At this point, config.init() has NOT yet
run (it
+ // comes after awaitTerminalInitialization()).
awaitThreadState(loggingThread, Thread.State.WAITING, 10_000);
- // Release the terminal — the consumer sets
System.out=terminalStream.
- // awaitTerminalInitialization() returns, then config.init()
captures terminalStream.
+ // Release the terminal — the onComplete callback sets
System.out=terminalStream
+ // and completes terminalReady. awaitTerminalInitialization()
returns only after
+ // onComplete finishes, then config.init() captures terminalStream.
releaseTerminal.countDown();
logging.get(10, SECONDS);
@@ -364,13 +358,8 @@ private void cachesOutputAfterTerminalInstallation(String
color) throws Exceptio
/**
* Waits until the given thread enters the expected state or the timeout
expires.
- * Used to detect when a thread is blocked on {@code
CompletableFuture.get()} inside
- * {@code FastTerminal.getTerminal()}. This is more reliable than a fixed
sleep and
- * avoids depending on platform-specific scheduling behavior.
- *
- * @param thread the thread to monitor
- * @param expected the expected thread state (typically {@link
Thread.State#WAITING})
- * @param timeoutMs maximum time to wait in milliseconds
+ * Used to detect when a thread is blocked on {@code
CompletableFuture.join()} inside
+ * {@code DeferredTerminal.getTerminal()}.
*/
private static void awaitThreadState(Thread thread, Thread.State expected,
long timeoutMs)
throws InterruptedException {
@@ -386,9 +375,7 @@ private static void awaitThreadState(Thread thread,
Thread.State expected, long
/**
* Injects the given terminal directly into {@link MessageUtils#terminal}
without creating a
- * {@code LineReader} from it. This avoids calling {@link
MessageUtils#systemInstall(Terminal)}
- * which on master tries to build a {@code LineReader} — that calls
- * {@link FastTerminal#getTerminal()} which blocks until the build thread
completes.
+ * {@code LineReader} from it.
*/
private static void injectTerminal(Terminal terminal) throws Exception {
Field field = MessageUtils.class.getDeclaredField("terminal");
@@ -397,10 +384,20 @@ private static void injectTerminal(Terminal terminal)
throws Exception {
}
/**
- * Reads the raw {@code colorEnabled} field from {@link MessageUtils}
without requiring a
- * terminal to be installed (unlike {@link MessageUtils#isColorEnabled()}
which also checks
- * {@code terminal != null}).
+ * Injects the given terminal and its associated {@code terminalReady}
future into
+ * {@link MessageUtils}, mirroring what {@link MessageUtils#systemInstall}
does so that
+ * {@link MessageUtils#awaitTerminalInitialization()} correctly waits for
the
+ * {@code onComplete} callback to finish.
*/
+ private static void injectTerminal(Terminal terminal,
CompletableFuture<Void> terminalReady) throws Exception {
+ Field terminalField = MessageUtils.class.getDeclaredField("terminal");
+ terminalField.setAccessible(true);
+ terminalField.set(null, terminal);
+ Field readyField =
MessageUtils.class.getDeclaredField("terminalReady");
+ readyField.setAccessible(true);
+ readyField.set(null, terminalReady);
+ }
+
private static boolean getColorEnabled() throws Exception {
Field field = MessageUtils.class.getDeclaredField("colorEnabled");
field.setAccessible(true);
@@ -419,6 +416,25 @@ private static Terminal getTerminalField() throws
Exception {
return (Terminal) field.get(null);
}
+ @SuppressWarnings("unchecked")
+ private static CompletableFuture<Void> getTerminalReadyField() throws
Exception {
+ Field field = MessageUtils.class.getDeclaredField("terminalReady");
+ field.setAccessible(true);
+ return (CompletableFuture<Void>) field.get(null);
+ }
+
+ private static void clearTerminalReady() throws Exception {
+ Field field = MessageUtils.class.getDeclaredField("terminalReady");
+ field.setAccessible(true);
+ field.set(null, null);
+ }
+
+ private static void setTerminalReady(CompletableFuture<Void> value) throws
Exception {
+ Field field = MessageUtils.class.getDeclaredField("terminalReady");
+ field.setAccessible(true);
+ field.set(null, value);
+ }
+
private static void activateSlf4j() {
Slf4jConfiguration config =
Slf4jConfigurationFactory.getConfiguration(LoggerFactory.getILoggerFactory());
config.activate();
diff --git
a/impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/LookupInvoker.java
b/impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/LookupInvoker.java
index b9555fbaa3..57e7aabdbf 100644
---
a/impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/LookupInvoker.java
+++
b/impl/maven-cli/src/main/java/org/apache/maven/cling/invoker/LookupInvoker.java
@@ -77,7 +77,6 @@
import org.apache.maven.eventspy.internal.EventSpyDispatcher;
import org.apache.maven.execution.MavenExecutionRequest;
import org.apache.maven.impl.SettingsUtilsV4;
-import org.apache.maven.jline.FastTerminal;
import org.apache.maven.jline.MessageUtils;
import org.apache.maven.logging.AsyncDrainWriter;
import org.apache.maven.logging.BuildEventListener;
@@ -90,6 +89,7 @@
import org.jline.terminal.Terminal;
import org.jline.terminal.TerminalBuilder;
import org.jline.terminal.impl.AbstractPosixTerminal;
+import org.jline.terminal.impl.DeferredTerminal;
import org.jline.terminal.spi.TerminalExt;
import org.jline.utils.OSUtils;
import org.slf4j.LoggerFactory;
@@ -170,13 +170,19 @@ private static void restoreRootLoggerHandlers(Handler[]
handlers) {
}
protected int doInvoke(C context) throws Exception {
+ createTerminal(context);
validate(context);
pushCoreProperties(context);
pushUserProperties(context);
setupGuiceClassLoading(context);
configureLogging(context);
- createTerminal(context);
activateLogging(context);
+ // doConfigureWithTerminal wraps System.out with LoggingOutputStream,
so it
+ // must run AFTER activateLogging() caches the original System.out.
Otherwise
+ // the logger would resolve the wrapped stream on each write →
infinite loop.
+ // awaitTerminalInitialization() blocks until the background build
completes.
+ MessageUtils.awaitTerminalInitialization();
+ doConfigureWithTerminal(context, context.terminal);
helpOrVersionAndMayExit(context);
preCommands(context);
container(context);
@@ -335,13 +341,34 @@ protected BuildEventListener
doDetermineBuildEventListener(C context) {
protected final void createTerminal(C context) {
if (context.terminal == null) {
- MessageUtils.systemInstall(builder -> doCreateTerminal(context,
builder), terminal -> {
- if (OSUtils.IS_WINDOWS && !context.invokerRequest.embedded()) {
- // JLine may consume Ctrl+C as terminal input, bypassing
the JVM's shutdown hooks.
- terminal.handle(Terminal.Signal.INT, signal ->
System.exit(SIGINT_EXIT_CODE));
+ if (context.invokerRequest.embedded()) {
+ // Embedded mode: build terminal synchronously (fast with
custom streams).
+ // buildDeferred() only supports system terminals, and
embedded mode is
+ // fast anyway (no FFM/JNI provider probing with custom
streams).
+ // doConfigureWithTerminal() is NOT called here; doInvoke()
calls it
+ // explicitly after configureLogging() so
context.loggerFactory is set.
+ try {
+ TerminalBuilder builder =
+ TerminalBuilder.builder().name("Maven").dumb(true);
+ doCreateTerminal(context, builder);
+ Terminal terminal = builder.build();
+ MessageUtils.systemInstall(terminal);
+ } catch (IOException e) {
+ throw new InvokerException("Failed to create terminal", e);
}
- doConfigureWithTerminal(context, terminal);
- });
+ } else {
+ // Start the background terminal build.
doConfigureWithTerminal is intentionally
+ // NOT called here — the onComplete callback runs on the
background build thread
+ // before configureLogging() has set context.loggerFactory.
Instead, the main
+ // thread calls doConfigureWithTerminal() explicitly after
configureLogging()
+ // (see doInvoke).
+ MessageUtils.systemInstall(builder ->
doCreateTerminal(context, builder), terminal -> {
+ if (OSUtils.IS_WINDOWS) {
+ // JLine may consume Ctrl+C as terminal input,
bypassing the JVM's shutdown hooks.
+ terminal.handle(Terminal.Signal.INT, signal ->
System.exit(SIGINT_EXIT_CODE));
+ }
+ });
+ }
context.terminal = MessageUtils.getTerminal();
context.closeables.add(MessageUtils::systemUninstall);
@@ -352,7 +379,8 @@ protected final void createTerminal(C context) {
new
ProjectBuildLogAppender(determineBuildEventListener(context));
context.closeables.add(projectBuildLogAppender);
} else {
- doConfigureWithTerminal(context, context.terminal);
+ // context.terminal is pre-set; doConfigureWithTerminal will be
called
+ // by doInvoke() after configureLogging() (see note in doInvoke).
}
}
@@ -393,7 +421,11 @@ protected final void doConfigureWithTerminal(C context,
Terminal terminal) {
// quiet mode implies raw streams — plugins that write to System.out
(e.g. help:evaluate
// -DforceStdout) must not be decorated with "[INFO] [stdout]" prefix,
otherwise scripting
// use cases like $(mvn -q help:evaluate ...) break (see GH-12730)
- if (context.options().rawStreams().orElse(false)
+ // Embedded mode also uses raw streams — the caller provides its own
streams and
+ // doesn't need the "[stdout]" prefix wrapping. More importantly, the
wrapping
+ // creates a circular logging loop (StackOverflowError) when logSink
is null.
+ if (context.invokerRequest.embedded()
+ || context.options().rawStreams().orElse(false)
|| context.options().quiet().orElse(false)) {
doConfigureWithTerminalWithRawStreamsEnabled(context);
} else {
@@ -530,8 +562,8 @@ protected String describe(Terminal terminal) {
if (terminal == null) {
return null;
}
- if (terminal instanceof FastTerminal ft) {
- terminal = ft.getTerminal();
+ if (terminal instanceof DeferredTerminal dt) {
+ terminal = dt.getTerminal();
}
List<String> subs = new ArrayList<>();
subs.add("type=" + terminal.getType());
diff --git
a/impl/maven-jline/src/main/java/org/apache/maven/jline/FastTerminal.java
b/impl/maven-jline/src/main/java/org/apache/maven/jline/FastTerminal.java
deleted file mode 100644
index fca0c75818..0000000000
--- a/impl/maven-jline/src/main/java/org/apache/maven/jline/FastTerminal.java
+++ /dev/null
@@ -1,386 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.maven.jline;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.io.PrintWriter;
-import java.nio.charset.Charset;
-import java.util.concurrent.Callable;
-import java.util.concurrent.CompletableFuture;
-import java.util.function.Consumer;
-import java.util.function.IntConsumer;
-import java.util.function.IntSupplier;
-
-import org.apache.maven.api.services.MavenException;
-import org.jline.terminal.Attributes;
-import org.jline.terminal.Cursor;
-import org.jline.terminal.MouseEvent;
-import org.jline.terminal.Size;
-import org.jline.terminal.Sized;
-import org.jline.terminal.Terminal;
-import org.jline.terminal.impl.DumbTerminal;
-import org.jline.terminal.spi.SystemStream;
-import org.jline.terminal.spi.TerminalExt;
-import org.jline.terminal.spi.TerminalProvider;
-import org.jline.utils.ColorPalette;
-import org.jline.utils.InfoCmp;
-import org.jline.utils.NonBlockingReader;
-
-public class FastTerminal implements TerminalExt {
-
- private final CompletableFuture<Terminal> terminal;
-
- /**
- * The thread running the builder and the consumer. Every method of this
class delegates through
- * {@link #getTerminal()}, so code running on this thread before the
terminal is published would
- * wait on the very future it is itself computing.
- */
- private final Thread buildThread;
-
- /**
- * Writer handed to {@link #buildThread} while the real terminal is still
being built. Created on
- * demand, and only ever by {@link #buildThread}.
- */
- private PrintWriter fallbackWriter;
-
- /**
- * Captured before {@link #buildThread} starts, hence before the consumer
swaps the system streams
- * for logging-backed ones. Writing to the live {@code System.err} instead
would feed the fallback
- * output back into the logger it came from.
- */
- private final OutputStream fallbackOutput;
-
- /**
- * A dumb terminal constructed <em>before</em> the build thread starts,
used as a stand-in for
- * every delegate method when the build thread would otherwise wait on its
own future. Guarding
- * only {@code writer()} and {@code getType()} was sufficient for JLine
4.3.x, but JLine 4.4.0's
- * FFM provider initialization ({@code CLibrary.<clinit>}) reaches back
through other terminal
- * methods, so the fallback must cover all of them. See
- * <a href="https://github.com/apache/maven/issues/12912">#12912</a>.
- */
- private final TerminalExt fallbackTerminal;
-
- public FastTerminal(Callable<Terminal> builder, Consumer<Terminal>
consumer) {
- this.terminal = new CompletableFuture<>();
- this.fallbackOutput = System.err;
- TerminalExt dumbFallback;
- try {
- // Construct a DumbTerminal directly instead of going through
TerminalBuilder, which
- // probes for grapheme-cluster support and can block on a null
input stream in JLine 4.4.0.
- dumbFallback = new DumbTerminal(InputStream.nullInputStream(),
fallbackOutput);
- } catch (IOException e) {
- dumbFallback = null;
- }
- this.fallbackTerminal = dumbFallback;
- this.buildThread = new Thread(
- () -> {
- try {
- Terminal term = builder.call();
- consumer.accept(term);
- terminal.complete(term);
- } catch (Exception e) {
- terminal.completeExceptionally(new MavenException(e));
- }
- },
- "fast-terminal-thread");
- // a wedged builder must not keep the JVM alive; everything waits on
the future, not the thread
- this.buildThread.setDaemon(true);
- }
-
- /**
- * Starts the build thread. Must be called <em>after</em> the caller has
published this
- * {@code FastTerminal} (e.g. assigned it to {@link
MessageUtils#terminal}) so that code running
- * on the build thread can obtain a non-null reference through {@link
MessageUtils#getTerminal()}.
- * <p>
- * {@link Thread#start()} establishes a <em>happens-before</em> edge, so
the assignment made by
- * the caller before this method is visible to the build thread without
additional
- * synchronization.
- *
- * @see <a href="https://github.com/apache/maven/issues/12912">#12912</a>
- */
- public void start() {
- this.buildThread.start();
- }
-
- public TerminalExt getTerminal() {
- if (isBuildThreadWaitingOnItself()) {
- if (fallbackTerminal != null) {
- return fallbackTerminal;
- }
- throw new IllegalStateException("Terminal not yet available (build
in progress on this thread)");
- }
- try {
- return (TerminalExt) terminal.get();
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- /**
- * True when the caller is the thread building the terminal and the
terminal is not published yet.
- * Waiting for the future here would never return, since this thread is
the one that completes it.
- */
- private boolean isBuildThreadWaitingOnItself() {
- return Thread.currentThread() == buildThread && !isBuilt();
- }
-
- /**
- * Whether the terminal has been published. {@link
MessageUtils#systemUninstall()} waits for the
- * build to finish, so a caller that must not block has to check this
first.
- */
- boolean isBuilt() {
- return terminal.isDone();
- }
-
- private PrintWriter fallbackWriter() {
- // only buildThread reaches this, so no synchronization is needed
- if (fallbackWriter == null) {
- fallbackWriter = new PrintWriter(new
OutputStreamWriter(fallbackOutput, Charset.defaultCharset()), true);
- }
- return fallbackWriter;
- }
-
- @Override
- public String getName() {
- return getTerminal().getName();
- }
-
- @Override
- public SignalHandler handle(Signal signal, SignalHandler signalHandler) {
- return getTerminal().handle(signal, signalHandler);
- }
-
- @Override
- public void raise(Signal signal) {
- getTerminal().raise(signal);
- }
-
- @Override
- public NonBlockingReader reader() {
- return getTerminal().reader();
- }
-
- @Override
- public PrintWriter writer() {
- // the log sink writes here, and must not wait for the terminal this
thread is building
- return isBuildThreadWaitingOnItself() ? fallbackWriter() :
getTerminal().writer();
- }
-
- @Override
- public Charset encoding() {
- return getTerminal().encoding();
- }
-
- @Override
- public InputStream input() {
- return getTerminal().input();
- }
-
- @Override
- public OutputStream output() {
- return getTerminal().output();
- }
-
- @Override
- public boolean canPauseResume() {
- return getTerminal().canPauseResume();
- }
-
- @Override
- public void pause() {
- getTerminal().pause();
- }
-
- @Override
- public void pause(boolean b) throws InterruptedException {
- getTerminal().pause(b);
- }
-
- @Override
- public void resume() {
- getTerminal().resume();
- }
-
- @Override
- public boolean paused() {
- return getTerminal().paused();
- }
-
- @Override
- public Attributes enterRawMode() {
- return getTerminal().enterRawMode();
- }
-
- @Override
- public boolean echo() {
- return getTerminal().echo();
- }
-
- @Override
- public boolean echo(boolean b) {
- return getTerminal().echo(b);
- }
-
- @Override
- public Attributes getAttributes() {
- return getTerminal().getAttributes();
- }
-
- @Override
- public void setAttributes(Attributes attributes) {
- getTerminal().setAttributes(attributes);
- }
-
- @Override
- public Size getSize() {
- return getTerminal().getSize();
- }
-
- @Override
- public void setSize(Size size) {
- getTerminal().setSize(size);
- }
-
- @Override
- public void setSize(Sized sized) {
- getTerminal().setSize(sized);
- }
-
- @Override
- public int getColumns() {
- return getTerminal().getColumns();
- }
-
- @Override
- public int getRows() {
- return getTerminal().getRows();
- }
-
- @Override
- public Size getBufferSize() {
- return getTerminal().getBufferSize();
- }
-
- @Override
- public void flush() {
- getTerminal().flush();
- }
-
- @Override
- public String getType() {
- // AttributedCharSequence.toAnsi asks for the type first and renders
plain for a dumb one,
- // so answering here keeps message rendering off the terminal this
thread is building
- return isBuildThreadWaitingOnItself()
- ? Terminal.TYPE_DUMB
- : getTerminal().getType();
- }
-
- @Override
- public boolean puts(InfoCmp.Capability capability, Object... objects) {
- return getTerminal().puts(capability, objects);
- }
-
- @Override
- public boolean getBooleanCapability(InfoCmp.Capability capability) {
- return getTerminal().getBooleanCapability(capability);
- }
-
- @Override
- public Integer getNumericCapability(InfoCmp.Capability capability) {
- return getTerminal().getNumericCapability(capability);
- }
-
- @Override
- public String getStringCapability(InfoCmp.Capability capability) {
- return getTerminal().getStringCapability(capability);
- }
-
- @Override
- public Cursor getCursorPosition(IntConsumer intConsumer) {
- return getTerminal().getCursorPosition(intConsumer);
- }
-
- @Override
- public boolean hasMouseSupport() {
- return getTerminal().hasMouseSupport();
- }
-
- @Override
- public MouseTracking getCurrentMouseTracking() {
- return getTerminal().getCurrentMouseTracking();
- }
-
- @Override
- public boolean trackMouse(MouseTracking mouseTracking) {
- return getTerminal().trackMouse(mouseTracking);
- }
-
- @Override
- public MouseEvent readMouseEvent() {
- return getTerminal().readMouseEvent();
- }
-
- @Override
- public MouseEvent readMouseEvent(IntSupplier intSupplier) {
- return getTerminal().readMouseEvent(intSupplier);
- }
-
- @Override
- public MouseEvent readMouseEvent(String prefix) {
- return getTerminal().readMouseEvent(prefix);
- }
-
- @Override
- public MouseEvent readMouseEvent(IntSupplier reader, String prefix) {
- return getTerminal().readMouseEvent(reader, prefix);
- }
-
- @Override
- public boolean hasFocusSupport() {
- return getTerminal().hasFocusSupport();
- }
-
- @Override
- public boolean trackFocus(boolean b) {
- return getTerminal().trackFocus(b);
- }
-
- @Override
- public ColorPalette getPalette() {
- return getTerminal().getPalette();
- }
-
- @Override
- public void close() throws IOException {
- getTerminal().close();
- }
-
- @Override
- public TerminalProvider getProvider() {
- return getTerminal().getProvider();
- }
-
- @Override
- public SystemStream getSystemStream() {
- return getTerminal().getSystemStream();
- }
-}
diff --git
a/impl/maven-jline/src/main/java/org/apache/maven/jline/JLineMessageBuilderFactory.java
b/impl/maven-jline/src/main/java/org/apache/maven/jline/JLineMessageBuilderFactory.java
index cfae3c000c..69cc53ff29 100644
---
a/impl/maven-jline/src/main/java/org/apache/maven/jline/JLineMessageBuilderFactory.java
+++
b/impl/maven-jline/src/main/java/org/apache/maven/jline/JLineMessageBuilderFactory.java
@@ -28,6 +28,7 @@
import org.apache.maven.api.di.Singleton;
import org.apache.maven.api.services.MessageBuilder;
import org.apache.maven.api.services.MessageBuilderFactory;
+import org.jline.terminal.Terminal;
import org.jline.utils.AttributedStringBuilder;
import org.jline.utils.AttributedStyle;
import org.jline.utils.StyleResolver;
@@ -112,7 +113,11 @@ public MessageBuilder setLength(int length) {
@Override
public String build() {
- return builder.toAnsi(MessageUtils.terminal);
+ Terminal terminal = MessageUtils.terminal;
+ if (terminal != null &&
Terminal.TYPE_DUMB.equals(terminal.getType()) && MessageUtils.isColorEnabled())
{
+ return builder.toAnsi();
+ }
+ return builder.toAnsi(terminal);
}
@Override
diff --git
a/impl/maven-jline/src/main/java/org/apache/maven/jline/MessageUtils.java
b/impl/maven-jline/src/main/java/org/apache/maven/jline/MessageUtils.java
index 38e09d19ef..e929dd1e99 100644
--- a/impl/maven-jline/src/main/java/org/apache/maven/jline/MessageUtils.java
+++ b/impl/maven-jline/src/main/java/org/apache/maven/jline/MessageUtils.java
@@ -18,6 +18,8 @@
*/
package org.apache.maven.jline;
+import java.io.IOException;
+import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import org.apache.maven.api.services.MessageBuilder;
@@ -27,6 +29,7 @@
import org.jline.reader.LineReaderBuilder;
import org.jline.terminal.Terminal;
import org.jline.terminal.TerminalBuilder;
+import org.jline.terminal.impl.DeferredTerminal;
public class MessageUtils {
@@ -36,6 +39,14 @@ public class MessageUtils {
static boolean colorEnabled = true;
static Thread shutdownHook;
static final Object STARTUP_SHUTDOWN_MONITOR = new Object();
+ /**
+ * Tracks completion of the terminal's {@code onComplete} callback
(including
+ * {@link AnsiConsole#systemInstall()}). Callers of {@link
#awaitTerminalInitialization()}
+ * must wait on this future, not just on {@link
DeferredTerminal#getTerminal()}, because
+ * the JLine future is resolved <em>before</em> the {@code onComplete}
callback runs and
+ * {@code System.out} is wrapped.
+ */
+ static volatile CompletableFuture<Void> terminalReady;
public static void systemInstall(Terminal terminal) {
MessageUtils.terminal = terminal;
@@ -47,29 +58,34 @@ public static void systemInstall() {
}
public static void systemInstall(Consumer<TerminalBuilder>
builderConsumer, Consumer<Terminal> terminalConsumer) {
- // Assign the FastTerminal to the field BEFORE starting the build
thread so that code
- // running on that thread (e.g. JLine's FFM provider init, logger
calls) sees a non-null
- // reference when it calls MessageUtils.getTerminal(). Thread.start()
provides the
- // happens-before edge that makes the assignment visible to the new
thread.
- FastTerminal ft = new FastTerminal(
- () -> {
- TerminalBuilder builder =
- TerminalBuilder.builder().name("Maven").dumb(true);
- if (builderConsumer != null) {
- builderConsumer.accept(builder);
- }
- return builder.build();
- },
- terminal -> {
- MessageUtils.reader = createReader(terminal);
- AnsiConsole.setTerminal(terminal);
- AnsiConsole.systemInstall();
- if (terminalConsumer != null) {
- terminalConsumer.accept(terminal);
- }
- });
- MessageUtils.terminal = ft;
- ft.start();
+ TerminalBuilder builder =
TerminalBuilder.builder().name("Maven").dumb(true);
+ if (builderConsumer != null) {
+ builderConsumer.accept(builder);
+ }
+ // buildDeferred() returns a DeferredTerminal proxy immediately
(~10ms).
+ // The real terminal is built on a background daemon thread; all proxy
+ // methods block transparently until it is ready.
+ DeferredTerminal deferred = (DeferredTerminal) builder.buildDeferred();
+ // Track when the full onComplete callback has finished, not just when
the
+ // JLine future resolves. The JLine future completes *before* the
callback
+ // runs, so awaitTerminalInitialization() must wait on this separate
future.
+ CompletableFuture<Void> ready = new CompletableFuture<>();
+ terminalReady = ready;
+ // Register a callback that runs on the build thread once the real
+ // terminal is ready, before any blocked caller is unblocked.
+ deferred.onComplete(terminal -> {
+ try {
+ MessageUtils.reader = createReader(terminal);
+ AnsiConsole.setTerminal(terminal);
+ AnsiConsole.systemInstall();
+ if (terminalConsumer != null) {
+ terminalConsumer.accept(terminal);
+ }
+ } finally {
+ ready.complete(null);
+ }
+ });
+ MessageUtils.terminal = deferred;
}
private static LineReader createReader(Terminal terminal) {
@@ -100,27 +116,43 @@ public static void systemUninstall() {
private static void doSystemUninstall() {
try {
- if (terminal instanceof FastTerminal fastTerminal) {
- // wait for the asynchronous systemInstall call before we
uninstall to ensure a consistent state
- fastTerminal.getTerminal();
+ if (terminal instanceof DeferredTerminal deferred) {
+ if (!deferred.isReady()) {
+ // Don't wait — drain buffered output to stdout and let
+ // the daemon build thread die with the JVM.
+ deferred.close();
+ return;
+ }
}
AnsiConsole.systemUninstall();
+ } catch (IOException | IllegalStateException e) {
+ // best-effort cleanup
} finally {
terminal = null;
+ terminalReady = null;
}
}
/**
- * Blocks until the asynchronous terminal installation completes.
- * Call this before redirecting {@code System.out}/{@code System.err} to
avoid the terminal
- * thread overwriting your redirection, and before activating logging
configuration to ensure
- * it caches the correct output stream.
+ * Blocks until the asynchronous terminal installation completes,
including the
+ * {@code onComplete} callback ({@link AnsiConsole#systemInstall()} and
any caller-supplied
+ * consumer).
+ *
+ * <p><b>Why not just {@link DeferredTerminal#getTerminal()}?</b> The JLine
+ * {@link java.util.concurrent.CompletableFuture} is resolved
<em>before</em> the
+ * {@code onComplete} callback runs. Callers that wait only on {@code
getTerminal()} can
+ * therefore proceed before {@code System.out} has been wrapped by {@code
AnsiConsole},
+ * causing logging configuration to cache the wrong stream.</p>
*
* @see <a href="https://github.com/apache/maven/issues/12188">#12188</a>
*/
public static void awaitTerminalInitialization() {
- if (terminal instanceof FastTerminal fastTerminal) {
- fastTerminal.getTerminal();
+ CompletableFuture<Void> ready = terminalReady;
+ if (ready != null) {
+ ready.join();
+ } else if (terminal instanceof DeferredTerminal deferred) {
+ // Fallback for terminals injected directly (e.g. via
systemInstall(Terminal)).
+ deferred.getTerminal();
}
}
diff --git
a/impl/maven-jline/src/test/java/org/apache/maven/jline/FastTerminalReentrancyTest.java
b/impl/maven-jline/src/test/java/org/apache/maven/jline/FastTerminalReentrancyTest.java
index f67f547f40..eea143e6ad 100644
---
a/impl/maven-jline/src/test/java/org/apache/maven/jline/FastTerminalReentrancyTest.java
+++
b/impl/maven-jline/src/test/java/org/apache/maven/jline/FastTerminalReentrancyTest.java
@@ -18,14 +18,11 @@
*/
package org.apache.maven.jline;
-import java.io.InputStream;
-import java.io.OutputStream;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
-import java.util.function.Consumer;
import org.jline.terminal.Terminal;
-import org.jline.terminal.TerminalBuilder;
+import org.jline.terminal.impl.DeferredTerminal;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
@@ -35,124 +32,71 @@
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
- * {@link MessageUtils#systemInstall} publishes the terminal before the
background thread has built
- * it, so anything that thread logs is rendered through a terminal that same
thread is still
- * producing. See <a
href="https://github.com/apache/maven/issues/12761">#12761</a> and
- * <a href="https://github.com/apache/maven/issues/12912">#12912</a>.
- * <p>
- * A single log statement asks the terminal for two things, its type while
rendering the message and
- * its writer while emitting the line, so both are exercised from both halves
of the window: the
- * builder callable, and the consumer that runs before the terminal is
published.
- * <p>
- * JLine 4.4.0's FFM provider initialization ({@code CLibrary.<clinit>}) can
reach back through
- * other terminal methods (e.g. {@code getName()}, {@code getColumns()},
{@code encoding()}) on the
- * build thread, so the fallback must cover all delegate methods, not just
{@code writer()} and
- * {@code getType()}.
- * <p>
- * The tests force {@code providers("exec")} so that the builder creates a
lightweight
- * {@code ExternalTerminal} instead of a {@code PosixPtyTerminal} via FFM. The
FFM provider calls
- * {@code CLibrary.openpty()} which creates a real PTY pair; the subsequent
grapheme-cluster probe
- * ({@code ensureModesProbed()}) reads from the PTY master via {@code
FileInputStream.read0()}, a
- * native blocking read. Although {@code VMIN=0, VTIME=0} attributes are set
before probing, there
- * is a race where the native read blocks indefinitely instead of respecting
the timeout, causing
- * the test to hang until the 30-second preemptive timeout fires.
- * <p>
- * The timeouts are preemptive on purpose: a regression parks the build thread
forever, and only an
- * abandoning timeout turns that into a red test rather than a hung fork.
+ * Verifies that {@link DeferredTerminal}'s non-blocking methods work correctly
+ * when called before the real terminal is ready.
*/
class FastTerminalReentrancyTest {
@AfterEach
void tearDown() {
- // MessageUtils.terminal is process-global; leaving it set breaks
every later test.
- // On a regression the build thread never finishes and systemUninstall
waits for it (see
- // #11048), on the test thread and outside any timeout, so the fork
would hang instead of
- // reporting the failure. Leave the state dirty in that case; the run
is lost either way.
- if (MessageUtils.getTerminal() instanceof FastTerminal ft &&
!ft.isBuilt()) {
- return;
+ try {
+ MessageUtils.systemUninstall();
+ } catch (Exception ignored) {
+ // best-effort cleanup
}
- MessageUtils.systemUninstall();
}
@Test
- void usingTheTerminalFromTheBuilderDoesNotDeadlock() {
+ void usingTheTerminalFromTheConsumerDoesNotDeadlock() {
assertTimeoutPreemptively(Duration.ofSeconds(30), () -> {
CompletableFuture<String[]> probed = new CompletableFuture<>();
- installAndAwait(builder -> probed.complete(probe()), terminal ->
{});
+ installAndAwait(terminal -> probed.complete(probe()));
assertProbe(probed.get());
});
}
@Test
- void usingTheTerminalFromTheConsumerDoesNotDeadlock() {
+ void arbitraryTerminalMethodsFromTheConsumerDoNotDeadlock() {
assertTimeoutPreemptively(Duration.ofSeconds(30), () -> {
- CompletableFuture<String[]> probed = new CompletableFuture<>();
- installAndAwait(builder -> {}, terminal ->
probed.complete(probe()));
- assertProbe(probed.get());
+ CompletableFuture<String> probed = new CompletableFuture<>();
+ installAndAwait(terminal -> {
+ Terminal t = MessageUtils.getTerminal();
+ probed.complete(t.getName());
+ });
+ assertNotNull(probed.get());
});
}
- /**
- * Exercises terminal methods beyond {@code writer()} and {@code
getType()} that JLine's FFM
- * provider initialization can reach on the build thread. Before the
fallback terminal was added,
- * these would deadlock. See <a
href="https://github.com/apache/maven/issues/12912">#12912</a>.
- */
@Test
- void arbitraryTerminalMethodsFromTheBuilderDoNotDeadlock() {
+ void terminalAssignmentIsVisibleImmediately() {
assertTimeoutPreemptively(Duration.ofSeconds(30), () -> {
- CompletableFuture<int[]> probed = new CompletableFuture<>();
- installAndAwait(
- builder -> {
- Terminal t = MessageUtils.getTerminal();
- probed.complete(
- new int[] {t.getSize().getColumns(),
t.getSize().getRows()});
- },
- terminal -> {});
- int[] dims = probed.get();
- assertTrue(dims[0] >= 0, "width should be non-negative");
- assertTrue(dims[1] >= 0, "height should be non-negative");
+ installAndAwait(terminal -> {});
+ Terminal t = MessageUtils.getTerminal();
+ assertNotNull(t, "MessageUtils.getTerminal() must not return null
after systemInstall()");
+ assertTrue(t instanceof DeferredTerminal, "terminal should be the
DeferredTerminal wrapper");
});
}
- /**
- * Exercises terminal methods beyond {@code writer()} and {@code
getType()} from the consumer
- * callback. See <a
href="https://github.com/apache/maven/issues/12912">#12912</a>.
- */
@Test
- void arbitraryTerminalMethodsFromTheConsumerDoNotDeadlock() {
+ void writerWorksBeforeTerminalIsReady() {
assertTimeoutPreemptively(Duration.ofSeconds(30), () -> {
- CompletableFuture<String> probed = new CompletableFuture<>();
- installAndAwait(builder -> {}, terminal -> {
- Terminal t = MessageUtils.getTerminal();
- probed.complete(t.getName());
- });
- assertNotNull(probed.get());
+ installAndAwait(terminal -> {});
+ Terminal t = MessageUtils.getTerminal();
+ assertNotNull(t.writer(), "writer() must not return null");
+ t.writer().print("test");
+ t.writer().flush();
});
}
- /**
- * Verifies that {@link MessageUtils#getTerminal()} is non-null when
called from the builder
- * callback. Before the fix, the {@code FastTerminal} constructor started
its build thread
- * before returning, so {@code MessageUtils.terminal} was still {@code
null} when the build
- * thread ran the builder callback — a race between the constructor
returning and the
- * thread scheduling. After the fix, {@code MessageUtils} assigns the
field before calling
- * {@link FastTerminal#start()}, and {@link Thread#start()} provides the
happens-before edge.
- *
- * @see <a href="https://github.com/apache/maven/issues/12912">#12912</a>
- */
@Test
- void terminalAssignmentIsVisibleFromBuilderCallback() {
+ void getTypeReturnsNonNullBeforeReady() {
assertTimeoutPreemptively(Duration.ofSeconds(30), () -> {
- CompletableFuture<Terminal> observed = new CompletableFuture<>();
- installAndAwait(builder ->
observed.complete(MessageUtils.getTerminal()), terminal -> {});
- assertNotNull(observed.get(), "MessageUtils.getTerminal() must not
return null from the builder callback");
- assertTrue(observed.get() instanceof FastTerminal, "terminal
should be the FastTerminal wrapper");
+ installAndAwait(terminal -> {});
+ Terminal t = MessageUtils.getTerminal();
+ assertNotNull(t.getType(), "getType() must not return null");
});
}
- /**
- * Both terminal calls a single log statement makes, run on the terminal
building thread.
- */
private static String[] probe() {
String rendered = MessageUtils.builder().warning("WARNING").build();
assertNotNull(MessageUtils.getTerminal().writer());
@@ -160,22 +104,13 @@ private static String[] probe() {
}
private static void assertProbe(String[] probed) {
- // the stand-in reports itself dumb, so the style is dropped rather
than emitted blind
- assertEquals(Terminal.TYPE_DUMB, probed[1]);
- assertEquals("WARNING", probed[0]);
+ String stripped = probed[0].replaceAll("\u001B\\[[;\\d]*m", "");
+ assertEquals("WARNING", stripped);
+ assertNotNull(probed[1]);
}
- private void installAndAwait(Consumer<TerminalBuilder> onBuilder,
Consumer<Terminal> onTerminal) {
- MessageUtils.systemInstall(
- builder -> {
- onBuilder.accept(builder);
- builder.dumb(true)
- .system(false)
- .providers("exec")
- .streams(InputStream.nullInputStream(),
OutputStream.nullOutputStream());
- },
- onTerminal);
- // let the build finish, so a failure here is the build failing rather
than a leaked thread
- ((FastTerminal) MessageUtils.getTerminal()).getTerminal();
+ private void installAndAwait(java.util.function.Consumer<Terminal>
onTerminal) {
+ MessageUtils.systemInstall(builder -> {}, onTerminal);
+ MessageUtils.awaitTerminalInitialization();
}
}
diff --git
a/its/core-it-support/maven-it-helper/src/main/java/org/apache/maven/it/Verifier.java
b/its/core-it-support/maven-it-helper/src/main/java/org/apache/maven/it/Verifier.java
index 1584996c75..455245419f 100644
---
a/its/core-it-support/maven-it-helper/src/main/java/org/apache/maven/it/Verifier.java
+++
b/its/core-it-support/maven-it-helper/src/main/java/org/apache/maven/it/Verifier.java
@@ -655,6 +655,16 @@ public void verifyTextInLog(String text) throws
VerificationException {
break;
}
}
+ if (!result && stdout != null && stdout.size() > 0) {
+ // Embedded mode may not redirect log output to the log file, so
also check
+ // captured stdout. In forked mode stdout is typically empty.
+ for (String line : getStdout().lines().toList()) {
+ if (stripAnsi(line).contains(text)) {
+ result = true;
+ break;
+ }
+ }
+ }
if (!result) {
throw new VerificationException("Text not found in log: " + text);
}
diff --git a/pom.xml b/pom.xml
index f4dac2c360..3194cb95f5 100644
--- a/pom.xml
+++ b/pom.xml
@@ -149,7 +149,7 @@ under the License.
<jakartaInjectApiVersion>2.0.1</jakartaInjectApiVersion>
<jakartaAnnotationApiVersion>1.3.5</jakartaAnnotationApiVersion>
- <jlineVersion>4.5.0</jlineVersion>
+ <jlineVersion>4.7.0</jlineVersion>
<jmhVersion>1.37</jmhVersion>
<junitVersion>6.1.3</junitVersion>
<jxpathVersion>1.4.0</jxpathVersion>