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 9d8dd4699d refactor: simplify terminal creation and defer
initialization
9d8dd4699d is described below
commit 9d8dd4699d410cad957fac90a0120c790ce52d76
Author: Guillaume Nodet <[email protected]>
AuthorDate: Mon Nov 16 15:33:34 2026 +0100
refactor: simplify terminal creation and defer initialization
- Defer LineReader creation until first prompt — most builds never prompt,
so the reader is never needed
- Lazy color auto-detection: isColorEnabled() resolves from
terminal.getType() on first access instead of blocking on DeferredTerminal
during startup
- Remove AnsiConsole.systemInstall() wrapping of System.out — the terminal
writer handles ANSI natively; AnsiConsole.setTerminal() is still called in
onComplete so plugins calling AnsiConsole.out() reuse Maven's terminal
- Remove awaitTerminalInitialization() and terminalReady future — no longer
needed without AnsiConsole synchronization
- Unify terminal creation into systemInstall(Consumer<TerminalBuilder>,
boolean) — embedded builds synchronously, non-embedded uses buildDeferred()
- Move Windows Ctrl+C handler into MessageUtils (was in LookupInvoker)
- Move helpOrVersionAndMayExit() before doConfigureWithTerminal() so mvn -v
output is not wrapped with [INFO] [stdout] prefix
- Add maven.terminal.deferred system property (default true) as escape
hatch to disable deferred terminal build; @since 4.2.0
- Collapse LookupInvoker.createTerminal() from two branches to one
- Double-checked locking in getReader() using STARTUP_SHUTDOWN_MONITOR for
thread-safety
---
.../main/java/org/apache/maven/api/Constants.java | 13 +
.../main/java/org/apache/maven/cli/MavenCli.java | 13 -
.../org/apache/maven/cli/MavenCliLoggingTest.java | 450 ---------------------
.../apache/maven/cling/invoker/LookupInvoker.java | 62 +--
.../org/apache/maven/jline/DefaultPrompter.java | 10 +-
.../maven/jline/JLineMessageBuilderFactory.java | 2 +-
.../java/org/apache/maven/jline/MessageUtils.java | 127 +++---
.../maven/jline/FastTerminalReentrancyTest.java | 31 +-
8 files changed, 99 insertions(+), 609 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 add8daa798..75abe89a17 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
@@ -935,5 +935,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.2.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 a33794173f..e89a846531 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
@@ -605,11 +605,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));
@@ -621,16 +616,8 @@ void logging(CliRequest cliRequest) throws ExitException {
//
}
- // Logging caches System.out; with -l the wait above already ran,
so activate now.
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 c8bd0de52a..0000000000
---
a/compat/maven-embedder/src/test/java/org/apache/maven/cli/MavenCliLoggingTest.java
+++ /dev/null
@@ -1,450 +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.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;
-
-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.MessageUtils;
-import org.apache.maven.slf4j.MavenBaseLogger;
-import org.jline.terminal.Terminal;
-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;
-import org.junit.jupiter.api.io.TempDir;
-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;
-
-@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 CompletableFuture<Void> savedTerminalReady;
- private final String[] savedPropertyValues = new
String[SAVED_PROPERTIES.length];
-
- @BeforeEach
- void setUp() throws Exception {
- savedOut = System.out;
- savedTerminal = getTerminalField();
- savedColor = getColorEnabled();
- 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]);
- }
- for (String prop : SAVED_PROPERTIES) {
- System.clearProperty(prop);
- }
- activateSlf4j();
- }
-
- @AfterEach
- 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]);
- }
- 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 {@code -l <logfile>} is used, {@code logging()} must call
- * {@link MessageUtils#awaitTerminalInitialization()} before redirecting
{@code System.out}
- * to the log file. Without the await, the terminal's installed consumer
(which may call
- * {@code System.setOut}) could race with the log-file redirect, causing
logs to leak to
- * the console instead of the log file (see
- * <a href="https://github.com/apache/maven/issues/12188">#12188</a>).
- * <p>
- * This test verifies that the terminal consumer fires <em>before</em>
{@code System.out} is
- * redirected to the log file, so the consumer cannot overwrite the
log-file redirect.
- */
- @Test
- void logFileBranchAwaitsTerminalBeforeRedirect(@TempDir Path tempDir)
throws Exception {
- PrintStream originalOut = System.out;
-
- Path logFile = tempDir.resolve("maven.log");
- Files.writeString(logFile, "");
-
- CountDownLatch buildingTerminal = new CountDownLatch(1);
- CountDownLatch releaseTerminal = new CountDownLatch(1);
- AtomicBoolean consumerFiredBeforeRedirect = new AtomicBoolean(false);
- Thread loggingThread = null;
- 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(
- () -> {
- 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);
- }
- },
- "deferred-terminal-build");
- buildThread.setDaemon(true);
- injectTerminal(terminal);
- buildThread.start();
- assertTrue(buildingTerminal.await(10, SECONDS), "DeferredTerminal
build thread must start");
-
- MavenCli cli = new MavenCli();
- CliRequest request =
- new CliRequest(new String[] {"-l",
logFile.toAbsolutePath().toString()}, 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();
-
- releaseTerminal.countDown();
- logging.get(10, SECONDS);
-
- 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)");
-
- assertFalse(
- System.out == originalOut,
- "After logging() with -l, System.out must be redirected to
the log file");
- } finally {
- releaseTerminal.countDown();
- if (loggingThread != null) {
- loggingThread.join(10_000);
- }
- PrintStream logStream = System.out;
- System.setOut(originalOut);
- if (logStream != originalOut) {
- logStream.close();
- }
- }
- }
-
- /**
- * 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.
- * <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
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 {
- 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());
- 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();
-
- DeferredTerminal terminal = new DeferredTerminal();
- CompletableFuture<Void> terminalReady = new CompletableFuture<>();
- terminal.onComplete(installed -> {
- System.setOut(terminalStream);
- terminalReady.complete(null);
- });
- Thread buildThread = new Thread(
- () -> {
- 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);
- }
- },
- "deferred-terminal-build");
- buildThread.setDaemon(true);
- injectTerminal(terminal, terminalReady);
- buildThread.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() →
- // 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 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);
-
-
LoggerFactory.getLogger(MavenCliLoggingTest.class).warn("terminal-output-marker");
- assertTrue(
-
terminalOutput.toString(UTF_8.name()).contains("terminal-output-marker"),
- "Logger must write to the stream installed by the terminal
consumer");
- assertFalse(
-
earlyOutput.toString(UTF_8.name()).contains("terminal-output-marker"),
- "Logger must not write to the early stream that was active
before terminal installation");
- } finally {
- releaseTerminal.countDown();
- if (loggingThread != null) {
- loggingThread.join(10_000);
- }
- }
- }
-
- /**
- * Waits until the given thread enters the expected state or the timeout
expires.
- * 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 {
- long deadline = System.nanoTime() + timeoutMs * 1_000_000L;
- 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.
- */
- private static void injectTerminal(Terminal terminal) throws Exception {
- Field field = MessageUtils.class.getDeclaredField("terminal");
- field.setAccessible(true);
- field.set(null, terminal);
- }
-
- /**
- * 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);
- 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);
- }
-
- @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();
- }
-
- 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 57e7aabdbf..02ce3ec0ff 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
@@ -91,7 +91,6 @@
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;
@@ -177,13 +175,8 @@ protected int doInvoke(C context) throws Exception {
setupGuiceClassLoading(context);
configureLogging(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);
+ doConfigureWithTerminal(context);
preCommands(context);
container(context);
postContainer(context);
@@ -311,6 +304,12 @@ protected void configureLogging(C context) throws
Exception {
}
}
+ // Propagate color setting immediately so that the first log message
+ // (written during activateLogging()) uses the correct color mode.
+ if (context.coloredOutput != null) {
+ MessageUtils.setColorEnabled(context.coloredOutput);
+ }
+
context.loggerFactory = LoggerFactory.getILoggerFactory();
context.slf4jConfiguration =
Slf4jConfigurationFactory.getConfiguration(context.loggerFactory);
@@ -341,34 +340,8 @@ protected BuildEventListener
doDetermineBuildEventListener(C context) {
protected final void createTerminal(C context) {
if (context.terminal == null) {
- 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);
- }
- } 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));
- }
- });
- }
+ MessageUtils.systemInstall(
+ builder -> doCreateTerminal(context, builder),
context.invokerRequest.embedded());
context.terminal = MessageUtils.getTerminal();
context.closeables.add(MessageUtils::systemUninstall);
@@ -395,7 +368,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);
@@ -408,14 +381,13 @@ 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
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/JLineMessageBuilderFactory.java
b/impl/maven-jline/src/main/java/org/apache/maven/jline/JLineMessageBuilderFactory.java
index 69cc53ff29..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
@@ -113,7 +113,7 @@ public MessageBuilder setLength(int length) {
@Override
public String build() {
- Terminal terminal = MessageUtils.terminal;
+ Terminal terminal = MessageUtils.getTerminal();
if (terminal != null &&
Terminal.TYPE_DUMB.equals(terminal.getType()) && MessageUtils.isColorEnabled())
{
return builder.toAnsi();
}
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 e929dd1e99..6c3673d447 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
@@ -19,9 +19,10 @@
package org.apache.maven.jline;
import java.io.IOException;
-import java.util.concurrent.CompletableFuture;
+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;
@@ -30,66 +31,72 @@
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();
- /**
- * 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;
- MessageUtils.reader = terminal != null ? createReader(terminal) : null;
}
public static void systemInstall() {
- systemInstall(null, null);
+ systemInstall((Consumer<TerminalBuilder>) null);
+ }
+
+ public static void systemInstall(Consumer<TerminalBuilder>
builderConsumer) {
+ systemInstall(builderConsumer, false);
}
- public static void systemInstall(Consumer<TerminalBuilder>
builderConsumer, Consumer<Terminal> terminalConsumer) {
+ public static void systemInstall(Consumer<TerminalBuilder>
builderConsumer, boolean embedded) {
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 -> {
+ boolean deferred =
+ !embedded &&
Boolean.parseBoolean(System.getProperty(Constants.MAVEN_TERMINAL_DEFERRED,
"true"));
+ if (!deferred) {
try {
- MessageUtils.reader = createReader(terminal);
- AnsiConsole.setTerminal(terminal);
- AnsiConsole.systemInstall();
- if (terminalConsumer != null) {
- terminalConsumer.accept(terminal);
+ MessageUtils.terminal = builder.build();
+ AnsiConsole.setTerminal(MessageUtils.terminal);
+ if (OSUtils.IS_WINDOWS) {
+ MessageUtils.terminal.handle(Terminal.Signal.INT, signal
-> System.exit(SIGINT_EXIT_CODE));
}
- } finally {
- ready.complete(null);
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
}
- });
- MessageUtils.terminal = deferred;
+ } 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) {
+ synchronized (STARTUP_SHUTDOWN_MONITOR) {
+ r = reader;
+ if (r == null) {
+ r = LineReaderBuilder.builder().terminal(terminal).build();
+ reader = r;
+ }
+ }
+ }
+ return r;
}
public static void registerShutdownHook() {
@@ -116,43 +123,15 @@ public static void systemUninstall() {
private static void doSystemUninstall() {
try {
- 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;
- }
+ if (terminal != null) {
+ terminal.close();
}
- AnsiConsole.systemUninstall();
- } catch (IOException | IllegalStateException e) {
+ } catch (IOException e) {
// best-effort cleanup
} finally {
terminal = null;
- terminalReady = null;
- }
- }
-
- /**
- * 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() {
- 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();
+ colorEnabled = null;
+ reader = null;
}
}
@@ -161,7 +140,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 eea143e6ad..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
@@ -19,7 +19,6 @@
package org.apache.maven.jline;
import java.time.Duration;
-import java.util.concurrent.CompletableFuture;
import org.jline.terminal.Terminal;
import org.jline.terminal.impl.DeferredTerminal;
@@ -47,30 +46,17 @@ void tearDown() {
}
@Test
- void usingTheTerminalFromTheConsumerDoesNotDeadlock() {
+ void terminalMethodsWorkAfterInitialization() {
assertTimeoutPreemptively(Duration.ofSeconds(30), () -> {
- CompletableFuture<String[]> probed = new CompletableFuture<>();
- installAndAwait(terminal -> probed.complete(probe()));
- assertProbe(probed.get());
- });
- }
-
- @Test
- void arbitraryTerminalMethodsFromTheConsumerDoNotDeadlock() {
- assertTimeoutPreemptively(Duration.ofSeconds(30), () -> {
- CompletableFuture<String> probed = new CompletableFuture<>();
- installAndAwait(terminal -> {
- Terminal t = MessageUtils.getTerminal();
- probed.complete(t.getName());
- });
- assertNotNull(probed.get());
+ installAndAwait();
+ assertProbe(probe());
});
}
@Test
void terminalAssignmentIsVisibleImmediately() {
assertTimeoutPreemptively(Duration.ofSeconds(30), () -> {
- installAndAwait(terminal -> {});
+ 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");
@@ -80,7 +66,7 @@ void terminalAssignmentIsVisibleImmediately() {
@Test
void writerWorksBeforeTerminalIsReady() {
assertTimeoutPreemptively(Duration.ofSeconds(30), () -> {
- installAndAwait(terminal -> {});
+ installAndAwait();
Terminal t = MessageUtils.getTerminal();
assertNotNull(t.writer(), "writer() must not return null");
t.writer().print("test");
@@ -91,7 +77,7 @@ void writerWorksBeforeTerminalIsReady() {
@Test
void getTypeReturnsNonNullBeforeReady() {
assertTimeoutPreemptively(Duration.ofSeconds(30), () -> {
- installAndAwait(terminal -> {});
+ installAndAwait();
Terminal t = MessageUtils.getTerminal();
assertNotNull(t.getType(), "getType() must not return null");
});
@@ -109,8 +95,7 @@ private static void assertProbe(String[] probed) {
assertNotNull(probed[1]);
}
- private void installAndAwait(java.util.function.Consumer<Terminal>
onTerminal) {
- MessageUtils.systemInstall(builder -> {}, onTerminal);
- MessageUtils.awaitTerminalInitialization();
+ private void installAndAwait() {
+ MessageUtils.systemInstall(builder -> {});
}
}