This is an automated email from the ASF dual-hosted git repository.
gnodet pushed a commit to branch maven-4.0.x
in repository https://gitbox.apache.org/repos/asf/maven.git
The following commit(s) were added to refs/heads/maven-4.0.x by this push:
new 1030196d94 [Backport maven-4.0.x] perf: replace FastTerminal with
JLine's DeferredTerminal (#13955)
1030196d94 is described below
commit 1030196d9487496bb91c41a206f272834da59b8c
Author: Guillaume Nodet <[email protected]>
AuthorDate: Mon Nov 16 15:33:48 2026 +0100
[Backport maven-4.0.x] perf: replace FastTerminal with JLine's
DeferredTerminal (#13955)
Backport of #13955 to maven-4.0.x.
- Delete FastTerminal.java — replaced by JLine 4.7.0's built-in
DeferredTerminal
- Simplify MessageUtils.systemInstall() using buildDeferred() and
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 to avoid StackOverflowError;
doConfigureWithTerminal moved to main thread after configureLogging
- Fix awaitTerminalInitialization to wait for the onComplete callback to
fire
- Fix ANSI output for dumb terminals and IT stdout verification; guard
stdout fallback on size > 0
- Skip waiting on shutdown — if terminal is not 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
---
.../main/java/org/apache/maven/api/Constants.java | 13 +
.../main/java/org/apache/maven/cli/MavenCli.java | 12 -
.../org/apache/maven/cli/MavenCliLoggingTest.java | 316 -----------------
.../apache/maven/cling/invoker/LookupInvoker.java | 64 ++--
.../org/apache/maven/jline/DefaultPrompter.java | 10 +-
.../java/org/apache/maven/jline/FastTerminal.java | 386 ---------------------
.../maven/jline/JLineMessageBuilderFactory.java | 7 +-
.../java/org/apache/maven/jline/MessageUtils.java | 112 +++---
.../maven/jline/FastTerminalReentrancyTest.java | 140 ++------
.../main/java/org/apache/maven/it/Verifier.java | 10 +
pom.xml | 2 +-
11 files changed, 159 insertions(+), 913 deletions(-)
diff --git
a/api/maven-api-core/src/main/java/org/apache/maven/api/Constants.java
b/api/maven-api-core/src/main/java/org/apache/maven/api/Constants.java
index ea3c1f0af5..640a923001 100644
--- a/api/maven-api-core/src/main/java/org/apache/maven/api/Constants.java
+++ b/api/maven-api-core/src/main/java/org/apache/maven/api/Constants.java
@@ -815,5 +815,18 @@ public final class Constants {
readOnly = true)
public static final String MAVEN_SITE_LIFECYCLE_DISABLED =
"maven.site.lifecycle.disabled";
+ /**
+ * Whether to build the terminal on a background thread. When {@code
false},
+ * the terminal is built synchronously during startup.
+ *
+ * @since 4.0.0
+ */
+ @Config(
+ type = "java.lang.Boolean",
+ defaultValue = "true",
+ source = Config.Source.SYSTEM_PROPERTIES,
+ readOnly = true)
+ public static final String MAVEN_TERMINAL_DEFERRED =
"maven.terminal.deferred";
+
private Constants() {}
}
diff --git
a/compat/maven-embedder/src/main/java/org/apache/maven/cli/MavenCli.java
b/compat/maven-embedder/src/main/java/org/apache/maven/cli/MavenCli.java
index 3e3d3a4e84..fb8842b0c6 100644
--- a/compat/maven-embedder/src/main/java/org/apache/maven/cli/MavenCli.java
+++ b/compat/maven-embedder/src/main/java/org/apache/maven/cli/MavenCli.java
@@ -557,11 +557,6 @@ void logging(CliRequest cliRequest) throws ExitException {
File logFile = new
File(commandLine.getOptionValue(CLIManager.LOG_FILE));
logFile = ResolveFile.resolveFile(logFile,
cliRequest.workingDirectory);
- // make sure the terminal has finished installing before we grab
the streams, otherwise it
- // could later overwrite our redirection and logs would leak back
to the console
- // (see https://github.com/apache/maven/issues/12188)
- MessageUtils.awaitTerminalInitialization();
-
// redirect stdout and stderr to file
try {
PrintStream ps = new PrintStream(new
FileOutputStream(logFile));
@@ -575,13 +570,6 @@ void logging(CliRequest cliRequest) throws ExitException {
slf4jConfiguration.activate();
} else {
- // Logging caches System.out, so wait for terminal installation to
complete before
- // activating, except when color is explicitly forced. With forced
color the user expects
- // raw ANSI to flow through the original stdout; waiting causes
AnsiConsole to wrap that
- // stream before the logger caches it, which may strip the escape
codes.
- if (!"always".equals(styleColor) && !"yes".equals(styleColor) &&
!"force".equals(styleColor)) {
- MessageUtils.awaitTerminalInitialization();
- }
slf4jConfiguration.activate();
}
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
deleted file mode 100644
index d23866ec46..0000000000
---
a/compat/maven-embedder/src/test/java/org/apache/maven/cli/MavenCliLoggingTest.java
+++ /dev/null
@@ -1,316 +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.cli;
-
-import java.io.ByteArrayOutputStream;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.PrintStream;
-import java.lang.reflect.Field;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.FutureTask;
-import java.util.concurrent.TimeUnit;
-
-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.apache.maven.slf4j.MavenLoggerFactory;
-import org.jline.terminal.Terminal;
-import org.jline.terminal.impl.DumbTerminal;
-import org.jline.terminal.spi.TerminalExt;
-import org.junit.jupiter.api.AfterEach;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.parallel.Isolated;
-import org.slf4j.LoggerFactory;
-
-import static java.nio.charset.StandardCharsets.UTF_8;
-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.junit.jupiter.api.Assumptions.assumeTrue;
-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 {
-
- private static final String[] SAVED_PROPERTIES = {
- MavenBaseLogger.LEGACY_PREFIX + "logFile",
- MavenBaseLogger.LEGACY_PREFIX + "cacheOutputStream",
- MavenBaseLogger.LEGACY_PREFIX + "defaultLogLevel",
- Constants.MAVEN_LOGGER_LOG_FILE,
- Constants.MAVEN_LOGGER_CACHE_OUTPUT_STREAM,
- Constants.MAVEN_LOGGER_DEFAULT_LOG_LEVEL,
- };
-
- private PrintStream savedOut;
- private Terminal savedTerminal;
- private boolean savedColor;
- private final String[] savedPropertyValues = new
String[SAVED_PROPERTIES.length];
-
- @BeforeEach
- void setUp() throws Exception {
- // These tests require MavenLoggerFactory as the active SLF4J provider
because they
- // rely on stream caching behaviour specific to
MavenSimpleConfiguration.activate().
- // When another binding (e.g. Logback) is on the classpath and wins
the ServiceLoader
- // race (platform-dependent), the assertions cannot hold and the test
must be skipped
- // rather than fail.
- assumeTrue(
- LoggerFactory.getILoggerFactory() instanceof
MavenLoggerFactory,
- "MavenLoggerFactory must be the active SLF4J provider");
- savedOut = System.out;
- savedTerminal = getTerminalField();
- savedColor = getColorEnabled();
- // Null out the terminal so leftover FastTerminal threads from other
tests cannot
- // race with this test's stream setup via their consumer callbacks.
- injectTerminal(null);
- 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. The re-init is
needed because
- // SimpleLoggerConfiguration.init() only updates defaultLogLevel when
the property IS set;
- // clearing the property alone leaves the stale value in the config
object.
- for (String prop : SAVED_PROPERTIES) {
- System.clearProperty(prop);
- }
- activateSlf4j();
- }
-
- @AfterEach
- void tearDown() throws Exception {
- System.setOut(savedOut);
- injectTerminal(savedTerminal);
- setColorEnabled(savedColor);
- for (int i = 0; i < SAVED_PROPERTIES.length; i++) {
- restoreProperty(SAVED_PROPERTIES[i], savedPropertyValues[i]);
- }
- activateSlf4j();
- }
-
- /**
- * 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>
- * 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 {
- ByteArrayOutputStream earlyOutput = new ByteArrayOutputStream();
- ByteArrayOutputStream lateOutput = new ByteArrayOutputStream();
- try (PrintStream earlyStream = new PrintStream(earlyOutput, 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();
-
- // 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);
- cli.logging(request);
-
- // 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");
- assertTrue(
-
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(
-
lateOutput.toString(UTF_8.name()).contains("terminal-output-marker"),
- "Logger must not switch to the stream installed after
logging() completed");
- }
- }
-
- /**
- * When color is set to {@code never} or {@code auto} (batch mode), {@code
logging()} must call
- * {@code awaitTerminalInitialization()} before activating the logging
configuration, so that
- * the terminal consumer has already swapped {@code System.out} before the
logger caches it.
- * This prevents logs from going to a stale stream instead of the
terminal-wrapped one.
- */
- @Test
- void cachesOutputAfterTerminalInstallationWithColorDisabled() throws
Exception {
- cachesOutputAfterTerminalInstallation("never");
- }
-
- @Test
- void cachesOutputAfterTerminalInstallationInBatchMode() throws Exception {
- cachesOutputAfterTerminalInstallation("batch");
- }
-
- private void cachesOutputAfterTerminalInstallation(String color) throws
Exception {
- CountDownLatch buildingTerminal = new CountDownLatch(1);
- CountDownLatch releaseTerminal = new CountDownLatch(1);
- ByteArrayOutputStream earlyOutput = new ByteArrayOutputStream();
- 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())) {
- 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));
- // 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();
- assertTrue(buildingTerminal.await(10, SECONDS));
-
- MavenCli cli = new MavenCli();
- CliRequest request = new CliRequest(
- "batch".equals(color) ? new String[] {"-B"} : new String[]
{"-Dstyle.color=" + color}, 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();
-
- // 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()).
- awaitThreadState(loggingThread, Thread.State.WAITING, 10_000);
-
- // Release the terminal — the consumer sets
System.out=terminalStream.
- // awaitTerminalInitialization() returns, then config.init()
captures terminalStream.
- releaseTerminal.countDown();
- logging.get(10, SECONDS);
-
-
LoggerFactory.getLogger(MavenCliLoggingTest.class).warn("terminal-output-marker");
-
assertTrue(terminalOutput.toString(UTF_8.name()).contains("terminal-output-marker"));
-
assertFalse(earlyOutput.toString(UTF_8.name()).contains("terminal-output-marker"));
- } finally {
- releaseTerminal.countDown();
- if (loggingThread != null) {
- loggingThread.join(10000);
- }
- }
- }
-
- /**
- * 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 behaviour.
- *
- * @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
- */
- private static void awaitThreadState(Thread thread, Thread.State expected,
long timeoutMs)
- throws InterruptedException {
- long deadline = System.nanoTime() +
TimeUnit.MILLISECONDS.toNanos(timeoutMs);
- while (thread.getState() != expected) {
- if (System.nanoTime() > deadline) {
- throw new AssertionError("Thread " + thread.getName() + " did
not reach state " + expected + " within "
- + timeoutMs + "ms; actual state: " +
thread.getState());
- }
- Thread.sleep(10);
- }
- }
-
- /**
- * 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.
- */
- private static void injectTerminal(Terminal terminal) throws Exception {
- Field field = MessageUtils.class.getDeclaredField("terminal");
- field.setAccessible(true);
- field.set(null, terminal);
- }
-
- /**
- * 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}).
- */
- private static boolean getColorEnabled() throws Exception {
- Field field = MessageUtils.class.getDeclaredField("colorEnabled");
- field.setAccessible(true);
- return (boolean) field.get(null);
- }
-
- private static void setColorEnabled(boolean value) throws Exception {
- Field field = MessageUtils.class.getDeclaredField("colorEnabled");
- field.setAccessible(true);
- field.set(null, value);
- }
-
- private static Terminal getTerminalField() throws Exception {
- Field field = MessageUtils.class.getDeclaredField("terminal");
- field.setAccessible(true);
- return (Terminal) field.get(null);
- }
-
- private static void activateSlf4j() {
- Slf4jConfiguration config =
Slf4jConfigurationFactory.getConfiguration(LoggerFactory.getILoggerFactory());
- config.activate();
- }
-
- private static void restoreProperty(String name, String value) {
- if (value == null) {
- System.clearProperty(name);
- } else {
- System.setProperty(name, value);
- }
- }
-}
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 52eb14ea44..a69dfb64dd 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,8 +89,8 @@
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;
import org.slf4j.bridge.SLF4JBridgeHandler;
import org.slf4j.spi.LocationAwareLogger;
@@ -106,7 +105,6 @@
* @param <C> The context type.
*/
public abstract class LookupInvoker<C extends LookupContext> implements
Invoker {
- private static final int SIGINT_EXIT_CODE = 130;
protected final Lookup protoLookup;
@@ -170,14 +168,15 @@ 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);
helpOrVersionAndMayExit(context);
+ doConfigureWithTerminal(context);
preCommands(context);
container(context);
postContainer(context);
@@ -305,6 +304,14 @@ protected void configureLogging(C context) throws
Exception {
}
}
+ // Propagate color setting immediately so that the first log message
+ // (written during activateLogging()) already uses the correct color
mode.
+ // Without this, DeferredTerminal.getType() may return "ansi"
heuristically
+ // and cause isColorEnabled() to cache true before
setColorEnabled(false) is called.
+ if (context.coloredOutput != null) {
+ MessageUtils.setColorEnabled(context.coloredOutput);
+ }
+
context.loggerFactory = LoggerFactory.getILoggerFactory();
context.slf4jConfiguration =
Slf4jConfigurationFactory.getConfiguration(context.loggerFactory);
@@ -335,24 +342,20 @@ protected BuildEventListener
doDetermineBuildEventListener(C context) {
protected final void createTerminal(C context) {
if (context.terminal == null) {
- // Create the build log appender; also sets MavenSimpleLogger sink
- ProjectBuildLogAppender projectBuildLogAppender =
- new
ProjectBuildLogAppender(determineBuildEventListener(context));
- context.closeables.add(projectBuildLogAppender);
-
- 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));
- }
- doConfigureWithTerminal(context, terminal);
- });
+ MessageUtils.systemInstall(
+ builder -> doCreateTerminal(context, builder),
context.invokerRequest.embedded());
context.terminal = MessageUtils.getTerminal();
context.closeables.add(MessageUtils::systemUninstall);
MessageUtils.registerShutdownHook(); // safety belt
+
+ // Create the build log appender; also sets MavenSimpleLogger sink
+ ProjectBuildLogAppender projectBuildLogAppender =
+ 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).
}
}
@@ -367,7 +370,7 @@ protected void doCreateTerminal(C context, TerminalBuilder
builder) {
OutputStream out =
context.invokerRequest.stdOut().orElse(OutputStream.nullOutputStream());
builder.streams(in, out);
builder.provider(TerminalBuilder.PROP_PROVIDER_EXEC);
- context.coloredOutput = context.coloredOutput != null ?
context.coloredOutput : false;
+ context.coloredOutput = context.coloredOutput != null &&
context.coloredOutput;
context.closeables.add(out::flush);
} else {
builder.systemOutput(TerminalBuilder.SystemOutput.SysOut);
@@ -380,20 +383,23 @@ protected void doCreateTerminal(C context,
TerminalBuilder builder) {
/**
* Called from {@link #createTerminal(LookupContext)} when Terminal was
built.
*/
- protected final void doConfigureWithTerminal(C context, Terminal terminal)
{
- context.terminal = terminal;
- // Align Maven's color setting with JLine's terminal detection:
- // if embedded, we default to context.coloredOutput=false unless
overridden (see above)
- // if not embedded, JLine detects redirection via SysOut and will
create dumb terminal.
- // To align Maven with outcomes, we set here color enabled based on
these premises.
- MessageUtils.setColorEnabled(
- context.coloredOutput != null ? context.coloredOutput :
!Terminal.TYPE_DUMB.equals(terminal.getType()));
+ protected final void doConfigureWithTerminal(C context) {
+ // Set color if explicitly configured (--color=always/never, batch
mode, etc.).
+ // When null (auto), MessageUtils.isColorEnabled() will lazily resolve
from
+ // the terminal type on first access, avoiding a block on the
DeferredTerminal.
+ if (context.coloredOutput != null) {
+ MessageUtils.setColorEnabled(context.coloredOutput);
+ }
// handle rawStreams: some would like to act on true, some on false
// 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 {
@@ -529,8 +535,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/DefaultPrompter.java
b/impl/maven-jline/src/main/java/org/apache/maven/jline/DefaultPrompter.java
index 565419a3cc..e6853bdb50 100644
--- a/impl/maven-jline/src/main/java/org/apache/maven/jline/DefaultPrompter.java
+++ b/impl/maven-jline/src/main/java/org/apache/maven/jline/DefaultPrompter.java
@@ -60,10 +60,10 @@ private String doPrompt(String message, boolean password) {
int lastNl = message.lastIndexOf('\n');
String begin = message.substring(0, lastNl + 1);
message = message.substring(lastNl + 1);
- MessageUtils.terminal.writer().print(begin);
- MessageUtils.terminal.flush();
+ MessageUtils.getTerminal().writer().print(begin);
+ MessageUtils.getTerminal().flush();
}
- return MessageUtils.reader.readLine(message, password ? '*' :
null);
+ return MessageUtils.getReader().readLine(message, password ? '*' :
null);
} catch (Exception e) {
throw new PrompterException("Unable to prompt user", e);
}
@@ -71,8 +71,8 @@ private String doPrompt(String message, boolean password) {
private void doDisplay(String message) {
try {
- MessageUtils.terminal.writer().print(message);
- MessageUtils.terminal.flush();
+ MessageUtils.getTerminal().writer().print(message);
+ MessageUtils.getTerminal().flush();
} catch (Exception e) {
throw new PrompterException("Unable to display message", e);
}
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..b9fa2f53cb 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.getTerminal();
+ 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 a32b25c4fc..a506ec3690 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,8 +18,11 @@
*/
package org.apache.maven.jline;
+import java.io.IOException;
+import java.io.UncheckedIOException;
import java.util.function.Consumer;
+import org.apache.maven.api.Constants;
import org.apache.maven.api.services.MessageBuilder;
import org.apache.maven.api.services.MessageBuilderFactory;
import org.jline.jansi.AnsiConsole;
@@ -27,53 +30,64 @@
import org.jline.reader.LineReaderBuilder;
import org.jline.terminal.Terminal;
import org.jline.terminal.TerminalBuilder;
+import org.jline.terminal.impl.DeferredTerminal;
+import org.jline.utils.OSUtils;
public class MessageUtils {
- static Terminal terminal;
- static LineReader reader;
+ private static final int SIGINT_EXIT_CODE = 130;
+
+ static volatile Terminal terminal;
+ static volatile LineReader reader;
static MessageBuilderFactory messageBuilderFactory = new
JLineMessageBuilderFactory();
- static boolean colorEnabled = true;
+ static volatile Boolean colorEnabled;
static Thread shutdownHook;
static final Object STARTUP_SHUTDOWN_MONITOR = new Object();
- public static void systemInstall(Terminal terminal) {
- MessageUtils.terminal = terminal;
- MessageUtils.reader = createReader(terminal);
+ public static void systemInstall() {
+ systemInstall(null);
}
- public static void systemInstall() {
- systemInstall(null, null);
+ public static void systemInstall(Consumer<TerminalBuilder>
builderConsumer) {
+ systemInstall(builderConsumer, false);
}
- 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();
+ public static void systemInstall(Consumer<TerminalBuilder>
builderConsumer, boolean embedded) {
+ TerminalBuilder builder =
TerminalBuilder.builder().name("Maven").dumb(true);
+ if (builderConsumer != null) {
+ builderConsumer.accept(builder);
+ }
+ boolean deferred =
+ !embedded &&
Boolean.parseBoolean(System.getProperty(Constants.MAVEN_TERMINAL_DEFERRED,
"true"));
+ if (!deferred) {
+ try {
+ MessageUtils.terminal = builder.build();
+ AnsiConsole.setTerminal(MessageUtils.terminal);
+ if (OSUtils.IS_WINDOWS) {
+ MessageUtils.terminal.handle(Terminal.Signal.INT, signal
-> System.exit(SIGINT_EXIT_CODE));
+ }
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ } else {
+ DeferredTerminal deferredTerminal = (DeferredTerminal)
builder.buildDeferred();
+ deferredTerminal.onComplete(terminal -> {
+ if (OSUtils.IS_WINDOWS) {
+ terminal.handle(Terminal.Signal.INT, signal ->
System.exit(SIGINT_EXIT_CODE));
+ }
+ AnsiConsole.setTerminal(terminal);
+ });
+ MessageUtils.terminal = deferredTerminal;
+ }
}
- private static LineReader createReader(Terminal terminal) {
- return LineReaderBuilder.builder().terminal(terminal).build();
+ static LineReader getReader() {
+ LineReader r = reader;
+ if (r == null) {
+ r = LineReaderBuilder.builder().terminal(terminal).build();
+ reader = r;
+ }
+ return r;
}
public static void registerShutdownHook() {
@@ -100,27 +114,15 @@ 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 != null) {
+ terminal.close();
}
- AnsiConsole.systemUninstall();
+ } catch (IOException e) {
+ // best-effort cleanup
} finally {
terminal = 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.
- *
- * @see <a href="https://github.com/apache/maven/issues/12188">#12188</a>
- */
- public static void awaitTerminalInitialization() {
- if (terminal instanceof FastTerminal fastTerminal) {
- fastTerminal.getTerminal();
+ colorEnabled = null;
+ reader = null;
}
}
@@ -129,7 +131,11 @@ public static void setColorEnabled(boolean enabled) {
}
public static boolean isColorEnabled() {
- return colorEnabled && terminal != null;
+ if (terminal == null) {
+ return false;
+ }
+ Boolean c = colorEnabled;
+ return c == null || c;
}
public static int getTerminalWidth() {
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..cfad65f00d 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,10 @@
*/
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 +31,58 @@
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 terminalMethodsWorkAfterInitialization() {
assertTimeoutPreemptively(Duration.ofSeconds(30), () -> {
- CompletableFuture<String[]> probed = new CompletableFuture<>();
- installAndAwait(builder -> probed.complete(probe()), terminal ->
{});
- assertProbe(probed.get());
+ installAndAwait();
+ assertProbe(probe());
});
}
@Test
- void usingTheTerminalFromTheConsumerDoesNotDeadlock() {
+ void terminalAssignmentIsVisibleImmediately() {
assertTimeoutPreemptively(Duration.ofSeconds(30), () -> {
- CompletableFuture<String[]> probed = new CompletableFuture<>();
- installAndAwait(builder -> {}, terminal ->
probed.complete(probe()));
- assertProbe(probed.get());
+ installAndAwait();
+ 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()} 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 writerWorksBeforeTerminalIsReady() {
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 t = MessageUtils.getTerminal();
+ assertNotNull(t.writer(), "writer() must not return null");
+ t.writer().print("test");
+ t.writer().flush();
});
}
- /**
- * 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 getTypeReturnsNonNullBeforeReady() {
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 t = MessageUtils.getTerminal();
+ assertNotNull(t.getType(), "getType() must not return null");
});
}
- /**
- * 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() {
- 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");
- });
- }
-
- /**
- * 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 +90,12 @@ 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() {
+ MessageUtils.systemInstall(builder -> {});
}
}
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 20b784a617..df010c5275 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
@@ -647,6 +647,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 11986ade95..3af0191a3b 100644
--- a/pom.xml
+++ b/pom.xml
@@ -154,7 +154,7 @@ under the License.
<hamcrestVersion>3.0</hamcrestVersion>
<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>