This is an automated email from the ASF dual-hosted git repository.
cstamas pushed a commit to branch maven-3.10.x
in repository https://gitbox.apache.org/repos/asf/maven.git
The following commit(s) were added to refs/heads/maven-3.10.x by this push:
new 6530a35fd9 Drop JLine, emit ANSI colors directly (#13888)
6530a35fd9 is described below
commit 6530a35fd9adee078a5e9d5165bdc13521d8a504
Author: Tamas Cservenak <[email protected]>
AuthorDate: Mon Nov 9 12:17:58 2026 +0100
Drop JLine, emit ANSI colors directly (#13888)
Maven only needs colored log output. JLine brought a full terminal stack
(native libraries, a background setup thread, System.out/err replacement) for
what is a handful of escape codes.
- maven-jline: MessageUtils now only detects whether stdout is an
ANSI-capable terminal (System.console(), Console.isTerminal() on Java 22+,
TERM=dumb). JLineMessageBuilderFactory turns style specs such as "bold,f:red"
into escape codes itself, and still honours maven.style.* / style.* overrides.
- JAnsi compatibility classes (org.fusesource.jansi.*) no longer forward to
JLine. AnsiConsole.systemInstall() only counts calls and never replaces
System.out. Ansi.render() is reimplemented.
- MavenCli: color is on in "auto" mode only when a terminal was detected,
so embedded runs (#13357) stay plain without the dumb terminal workaround. The
waits on terminal setup are removed; with no terminal installed later, the -l
race (#12188) can't happen.
- Distribution: drop jline-native libs and the -Dlibrary.jline.path and
-Dorg.jline.* flags from mvn/mvn.cmd.
- Remove FastTerminal, its test, and MavenCliLoggingTest.
Behaviour changes:
- On Windows, "auto" colors only in consoles known to handle ANSI (Windows
Terminal, ConEmu, ANSICON, VS Code, or TERM set). In the old Windows console
(conhost), use --color=always.
- Git Bash/mintty is usually not detected as a terminal, so output is plain
unless --color=always is given.
- getTerminalWidth() uses lazily COLUMNS environment variable, or stty size
on Unix terminals; otherwise -1.
---
apache-maven/pom.xml | 23 --
apache-maven/src/bin/mvn | 6 -
apache-maven/src/bin/mvn.cmd | 2 -
apache-maven/src/lib/jline-native/README.txt | 8 -
apache-maven/src/main/assembly/component.xml | 9 -
.../src/test/scripts/test-mvn-path-conversion.sh | 4 +-
.../main/resources/META-INF/maven/extension.xml | 8 +-
.../project/ExtensionDescriptorBuilderTest.java | 2 +-
.../main/java/org/apache/maven/cli/MavenCli.java | 85 +-----
.../org/apache/maven/cli/MavenCliLoggingTest.java | 235 -----------------
.../java/org/apache/maven/cli/MavenCliTest.java | 34 +--
maven-jline/pom.xml | 21 +-
.../java/org/apache/maven/jline/FastTerminal.java | 291 ---------------------
.../maven/jline/JLineMessageBuilderFactory.java | 193 ++++++++++----
.../java/org/apache/maven/jline/MessageUtils.java | 179 +++++++------
.../src/main/java/org/fusesource/jansi/Ansi.java | 62 ++++-
.../java/org/fusesource/jansi/AnsiConsole.java | 23 +-
.../main/java/org/fusesource/jansi/AnsiMode.java | 4 +-
.../java/org/fusesource/jansi/AnsiPrintStream.java | 12 +-
.../org/apache/maven/jline/FastTerminalTest.java | 94 -------
.../org/apache/maven/jline/MessageUtilsTest.java | 60 ++++-
.../java/org/fusesource/jansi/AnsiConsoleTest.java | 29 +-
pom.xml | 27 +-
23 files changed, 394 insertions(+), 1017 deletions(-)
diff --git a/apache-maven/pom.xml b/apache-maven/pom.xml
index 3754742442..00a51dde76 100644
--- a/apache-maven/pom.xml
+++ b/apache-maven/pom.xml
@@ -92,10 +92,6 @@ under the License.
<groupId>org.apache.maven</groupId>
<artifactId>maven-slf4j-provider</artifactId>
</dependency>
- <dependency>
- <groupId>org.jline</groupId>
- <artifactId>jline-terminal-ffm</artifactId>
- </dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
@@ -139,25 +135,6 @@ under the License.
</plugins>
</pluginManagement>
<plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-dependency-plugin</artifactId>
- <executions>
- <execution>
- <id>unpack-jline-native</id>
- <goals>
- <goal>unpack-dependencies</goal>
- </goals>
- <configuration>
- <includeArtifactIds>jline-native</includeArtifactIds>
- <includes>org/jline/nativ/**</includes>
- <!-- exclude Mac OS binaries to prevent them from being marked
with quarantine flag (https://github.com/apache/maven/issues/10747) and
therefore being protected via Gatekeeper
- see also
https://www.cisa.gov/eviction-strategies-tool/info-attack/T1144 -->
- <excludes>org/jline/nativ/Mac/**</excludes>
- </configuration>
- </execution>
- </executions>
- </plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
diff --git a/apache-maven/src/bin/mvn b/apache-maven/src/bin/mvn
index a7c6f69e9b..aaa953b063 100755
--- a/apache-maven/src/bin/mvn
+++ b/apache-maven/src/bin/mvn
@@ -154,7 +154,6 @@ CLASSWORLDS_JAR=`echo
"${MAVEN_HOME}"/boot/plexus-classworlds-*.jar`
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# For Cygwin and MinGW, switch paths to Windows format before running java(1)
-JLINE_NATIVE_PATH="$MAVEN_HOME/lib/jline-native"
if $cygwin || $mingw ; then
[ -n "$MAVEN_HOME" ] &&
MAVEN_HOME=`cygpath --windows "$MAVEN_HOME"`
@@ -164,9 +163,6 @@ if $cygwin || $mingw ; then
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
[ -n "$CLASSWORLDS_JAR" ] &&
CLASSWORLDS_JAR=`cygpath --windows "$CLASSWORLDS_JAR"`
- # converted separately, appending to the already converted MAVEN_HOME would
- # produce a path mixing both separators, e.g. C:\maven/lib/jline-native
- JLINE_NATIVE_PATH=`cygpath --windows "$JLINE_NATIVE_PATH"`
fi
# traverses directory structure from process work directory to filesystem root
@@ -356,7 +352,5 @@ exec "$JAVACMD" \
-classpath "${CLASSWORLDS_JAR}" \
"-Dclassworlds.conf=${MAVEN_HOME}/bin/m2.conf" \
"-Dmaven.home=${MAVEN_HOME}" \
- "-Dlibrary.jline.path=$JLINE_NATIVE_PATH" \
- "-Dorg.jline.terminal.exec.redirectPipeCreationMode=native,reflection" \
"-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${CLASSWORLDS_LAUNCHER} "$@"
diff --git a/apache-maven/src/bin/mvn.cmd b/apache-maven/src/bin/mvn.cmd
index 22a2e1a92c..ef30431307 100644
--- a/apache-maven/src/bin/mvn.cmd
+++ b/apache-maven/src/bin/mvn.cmd
@@ -204,8 +204,6 @@ set "INTERNAL_MAVEN_OPTS=--enable-native-access=ALL-UNNAMED
%INTERNAL_MAVEN_OPTS
-classpath %CLASSWORLDS_JAR% ^
"-Dclassworlds.conf=%MAVEN_HOME%\bin\m2.conf" ^
"-Dmaven.home=%MAVEN_HOME%" ^
- "-Dlibrary.jline.path=%MAVEN_HOME%\lib\jline-native" ^
- "-Dorg.jline.terminal.exec.redirectPipeCreationMode=native,reflection" ^
"-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^
%CLASSWORLDS_LAUNCHER% %MAVEN_ARGS% %MAVEN_CMD_LINE_ARGS%
if ERRORLEVEL 1 goto error
diff --git a/apache-maven/src/lib/jline-native/README.txt
b/apache-maven/src/lib/jline-native/README.txt
deleted file mode 100644
index ed74b45f7e..0000000000
--- a/apache-maven/src/lib/jline-native/README.txt
+++ /dev/null
@@ -1,8 +0,0 @@
-This directory contains JLine native libraries extracted from JLine JAR.
-
-You can add your own build for platforms not natively supported by JLine.
-See here [1] on how to compile for your platform and here [2] how libraries
-follow JLine's directory and filename conventions.
-
-[1] https://github.com/jline/jline3/tree/master/native
-[2]
https://github.com/jline/jline3/blob/master/native/src/main/java/org/jline/nativ/OSInfo.java
diff --git a/apache-maven/src/main/assembly/component.xml
b/apache-maven/src/main/assembly/component.xml
index f63ce88a97..6e31060e45 100644
--- a/apache-maven/src/main/assembly/component.xml
+++ b/apache-maven/src/main/assembly/component.xml
@@ -62,15 +62,6 @@ under the License.
<include>**</include>
</includes>
</fileSet>
- <fileSet>
- <directory>target/dependency/org/jline/nativ</directory>
- <outputDirectory>lib/jline-native</outputDirectory>
- <includes>
- <include>**/*.so</include>
- <include>**/*.jnilib</include>
- <include>**/*.dll</include>
- </includes>
- </fileSet>
<fileSet>
<directory>src/bin</directory>
<outputDirectory>bin</outputDirectory>
diff --git a/apache-maven/src/test/scripts/test-mvn-path-conversion.sh
b/apache-maven/src/test/scripts/test-mvn-path-conversion.sh
index 66a86251d8..cab123e3ff 100644
--- a/apache-maven/src/test/scripts/test-mvn-path-conversion.sh
+++ b/apache-maven/src/test/scripts/test-mvn-path-conversion.sh
@@ -62,7 +62,7 @@ stub_dir="$work_dir/stubs"
maven_home="$work_dir/maven-home"
project_dir="$work_dir/project"
-mkdir -p "$stub_dir" "$maven_home/bin" "$maven_home/boot"
"$maven_home/lib/jline-native" \
+mkdir -p "$stub_dir" "$maven_home/bin" "$maven_home/boot" \
"$project_dir/.mvn" "$project_dir/module"
cp "$mvn_script" "$maven_home/bin/mvn"
@@ -306,8 +306,6 @@ for os in CYGWIN_NT-10.0 MINGW32_NT-6.2 MINGW64_NT-10.0
MSYS_NT-10.0; do
"[-Dmaven.multiModuleProjectDirectory=`to_windows "$project_dir"`]"
assert_contains "$os: maven.home is a native Windows path" "$output" \
"[-Dmaven.home=`to_windows "$maven_home"`]"
- assert_contains "$os: library.jline.path is a native Windows path" "$output"
\
- "[-Dlibrary.jline.path=`to_windows "$maven_home/lib/jline-native"`]"
assert_not_contains "$os: no path mixes both separators" "$output" "\\/"
done
diff --git a/maven-core/src/main/resources/META-INF/maven/extension.xml
b/maven-core/src/main/resources/META-INF/maven/extension.xml
index bb6f52745a..c329b5e22a 100644
--- a/maven-core/src/main/resources/META-INF/maven/extension.xml
+++ b/maven-core/src/main/resources/META-INF/maven/extension.xml
@@ -127,8 +127,8 @@ under the License.
<exportedPackage>org.slf4j.helpers.*</exportedPackage>
<exportedPackage>org.slf4j.event.*</exportedPackage>
- <!-- JAnsi: maven-jline ships Ansi, AnsiConsole, AnsiPrintStream and
AnsiMode, forwarding to the
- already-installed JLine terminal, for backward compatibility with
code (e.g. maven-shared-utils)
+ <!-- JAnsi: maven-jline ships Ansi, AnsiConsole, AnsiPrintStream and
AnsiMode, honouring
+ Maven's own color setting, for backward compatibility with code (e.g.
maven-shared-utils)
still calling the JAnsi API. The jansi artifact itself stays excluded
below, so a plugin that
declares org.fusesource.jansi:jansi gets these forwarding classes
instead of its own copy: that
is what keeps AnsiConsole.systemInstall()/systemUninstall() calls
routed through the single
@@ -189,11 +189,11 @@ under the License.
<exportedArtifact>org.slf4j:slf4j-api</exportedArtifact>
<!--
- | JAnsi is no longer a maven-core dependency (replaced by JLine, see
#11874), but stays excluded here:
+ | JAnsi is no longer a maven-core dependency (see #11874), but stays
excluded here:
| maven-jline exports forwarding classes for the JAnsi API (see
exportedPackages above), and excluding
| the real jansi artifact is what makes a plugin's own
org.fusesource.jansi:jansi dependency resolve to
| those forwarding classes instead of shadowing them with the real
AnsiConsole, which would install its
- | own System.out/System.err independently of the terminal Maven already
installed. See #13726, #13727.
+ | own System.out/System.err behind Maven's back. See #13726, #13727.
-->
<exportedArtifact>org.fusesource.jansi:jansi</exportedArtifact>
diff --git
a/maven-core/src/test/java/org/apache/maven/project/ExtensionDescriptorBuilderTest.java
b/maven-core/src/test/java/org/apache/maven/project/ExtensionDescriptorBuilderTest.java
index d94e84b855..f7ec69dbbf 100644
---
a/maven-core/src/test/java/org/apache/maven/project/ExtensionDescriptorBuilderTest.java
+++
b/maven-core/src/test/java/org/apache/maven/project/ExtensionDescriptorBuilderTest.java
@@ -80,7 +80,7 @@ public void testCompleteDescriptor() throws Exception {
/**
* maven-core's own {@code META-INF/maven/extension.xml} must keep
excluding {@code org.fusesource.jansi:jansi}
- * as an {@code exportedArtifact} even though jansi is no longer a
maven-core dependency (replaced by JLine, see
+ * as an {@code exportedArtifact} even though jansi is no longer a
maven-core dependency (see
* #11874): maven-jline exports forwarding classes for the JAnsi API (see
* {@code org.apache.maven.jline}{@code .*} and {@code
org.fusesource.jansi.*} in maven-jline), and it is the
* {@code exportedArtifact} exclusion that makes a plugin's own {@code
org.fusesource.jansi:jansi} dependency
diff --git a/maven-embedder/src/main/java/org/apache/maven/cli/MavenCli.java
b/maven-embedder/src/main/java/org/apache/maven/cli/MavenCli.java
index 7e9e4e0b12..2ec00edb7f 100644
--- a/maven-embedder/src/main/java/org/apache/maven/cli/MavenCli.java
+++ b/maven-embedder/src/main/java/org/apache/maven/cli/MavenCli.java
@@ -19,7 +19,6 @@
package org.apache.maven.cli;
import java.io.BufferedReader;
-import java.io.ByteArrayInputStream;
import java.io.Console;
import java.io.File;
import java.io.FileNotFoundException;
@@ -27,7 +26,6 @@
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
-import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
@@ -120,8 +118,6 @@
import org.eclipse.aether.DefaultRepositoryCache;
import org.eclipse.aether.repository.RepositoryPolicy;
import org.eclipse.aether.transfer.TransferListener;
-import org.jline.terminal.Terminal;
-import org.jline.terminal.impl.DumbTerminal;
import org.slf4j.ILoggerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -221,11 +217,7 @@ public static int main(String[] args, ClassWorld
classWorld) {
MavenCli cli = new MavenCli();
MessageUtils.systemInstall();
- MessageUtils.registerShutdownHook();
- int result = cli.doMain(new CliRequest(args, classWorld));
- MessageUtils.systemUninstall();
-
- return result;
+ return cli.doMain(new CliRequest(args, classWorld));
}
// TODO need to externalize CliRequest
@@ -234,34 +226,6 @@ public static int doMain(String[] args, ClassWorld
classWorld) {
return cli.doMain(new CliRequest(args, classWorld));
}
- /**
- * Installs a threadless, colour-capable "dumb" terminal that is not
attached to the process console, so that
- * an explicit {@code --color=yes} works; automatic detection still yields
plain output for it. Colour is
- * optional, so failure to create the terminal is not an error.
- *
- * @return the installed terminal, or {@code null} if it could not be
created
- */
- private static Terminal installEmbeddedTerminal() {
- try {
- Terminal dumb = new DumbTerminal(
- "Maven",
- Terminal.TYPE_DUMB_COLOR,
- new ByteArrayInputStream(new byte[0]),
- new OutputStream() {
- @Override
- public void write(int b) {
- // discard
- }
- },
- null);
- MessageUtils.systemInstall(dumb);
- return dumb;
- } catch (IOException e) {
- LoggerFactory.getLogger(MavenCli.class).debug("Could not create
terminal, continuing without colour", e);
- return null;
- }
- }
-
/**
* This supports painless invocation by the Verifier during embedded
execution of the core ITs.
* See <a
href="http://maven.apache.org/shared/maven-verifier/xref/org/apache/maven/it/Embedded3xLauncher.html">
@@ -281,39 +245,19 @@ public int doMain(String[] args, String workingDirectory,
PrintStream stdout, Pr
realms = Collections.emptySet();
}
- // Embedders call this method instead of main(), so nobody installed a
terminal; without one
- // MessageUtils.isColorEnabled() is always false, even for an explicit
--color=yes (#13357).
- // The dumb terminal keeps "auto" plain, and an already installed
terminal is left alone.
- Terminal embeddedTerminal = null;
try {
if (stdout != null) {
- MessageUtils.awaitTerminalInitialization();
System.setOut(stdout);
}
if (stderr != null) {
- MessageUtils.awaitTerminalInitialization();
System.setErr(stderr);
}
- if (MessageUtils.getTerminal() == null) {
- embeddedTerminal = installEmbeddedTerminal();
- }
-
CliRequest cliRequest = new CliRequest(args, classWorld);
cliRequest.workingDirectory = workingDirectory;
return doMain(cliRequest);
} finally {
- if (embeddedTerminal != null) {
- if (MessageUtils.getTerminal() == embeddedTerminal) {
- MessageUtils.systemInstall((Terminal) null);
- }
- try {
- embeddedTerminal.close();
- } catch (IOException e) {
- // ignore
- }
- }
if (classWorld != null) {
for (ClassRealm realm : new
ArrayList<>(classWorld.getRealms())) {
String realmId = realm.getId();
@@ -593,11 +537,8 @@ void logging(CliRequest cliRequest) {
|| cliRequest.commandLine.hasOption(CLIManager.LOG_FILE)) {
MessageUtils.setColorEnabled(false);
} else {
- // if the terminal is detected as dumb terminal, disable colors
- if (MessageUtils.getTerminal() != null
- &&
MessageUtils.getTerminal().getType().startsWith("dumb")) {
- MessageUtils.setColorEnabled(false);
- }
+ // auto: color only on a detected ANSI terminal; embedded use
(#13357) never detects one
+ MessageUtils.setColorEnabled(MessageUtils.isTty());
}
// LOG STREAMS
@@ -605,11 +546,6 @@ void logging(CliRequest cliRequest) {
File logFile = new
File(cliRequest.commandLine.getOptionValue(CLIManager.LOG_FILE));
logFile = 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));
@@ -620,19 +556,8 @@ void logging(CliRequest cliRequest) {
// Ignore
//
}
-
- // 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();
}
+ slf4jConfiguration.activate();
plexusLoggerManager = new Slf4jLoggerManager();
slf4jLogger = slf4jLoggerFactory.getLogger(this.getClass().getName());
@@ -678,7 +603,7 @@ private void commands(CliRequest cliRequest) throws
ExitException {
if (slf4jLogger.isDebugEnabled()) {
slf4jLogger.debug("Message scheme: {}",
(MessageUtils.isColorEnabled() ? "color" : "plain"));
- slf4jLogger.debug("Message terminal: {}",
MessageUtils.getTerminal());
+ slf4jLogger.debug("Message terminal: {}", MessageUtils.isTty() ?
"ansi" : "none");
if (MessageUtils.isColorEnabled()) {
MessageBuilder buff = builder();
buff.a("Message styles: ");
diff --git
a/maven-embedder/src/test/java/org/apache/maven/cli/MavenCliLoggingTest.java
b/maven-embedder/src/test/java/org/apache/maven/cli/MavenCliLoggingTest.java
deleted file mode 100644
index de46e5c7e8..0000000000
--- a/maven-embedder/src/test/java/org/apache/maven/cli/MavenCliLoggingTest.java
+++ /dev/null
@@ -1,235 +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.PrintStream;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.FutureTask;
-
-import org.apache.maven.cli.logging.impl.Slf4jSimpleConfiguration;
-import org.apache.maven.jline.FastTerminal;
-import org.apache.maven.jline.MessageUtils;
-import org.jline.terminal.Terminal;
-import org.jline.terminal.spi.TerminalExt;
-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.mockito.Mockito.mock;
-
-@Isolated("Changes JVM-wide streams, system properties, terminal state, and
logging configuration")
-class MavenCliLoggingTest {
- /**
- * When color is explicitly forced ({@code -color=always}), logging must
NOT wait for
- * terminal installation before caching {@code System.out}. Waiting causes
- * {@code AnsiConsole.systemInstall()} to wrap the stream before the
logger sees it; in a
- * non-TTY environment (CI, pipes) that wrapper strips ANSI codes even for
a dumb-color
- * terminal, defeating the purpose of {@code -color=always}.
- * <p>
- * Therefore the logger caches the stream that was active when {@code
logging()} was called
- * (the "early" stream), and continues to write to it even after terminal
installation
- * replaces {@code System.out}.
- */
- @Test
- void withColorForcedLoggerCachesEarlyStream() throws Exception {
- PrintStream originalOut = System.out;
- Terminal originalTerminal = MessageUtils.getTerminal();
- boolean originalColor;
- try {
- MessageUtils.systemInstall(mock(Terminal.class));
- originalColor = MessageUtils.isColorEnabled();
- } finally {
- MessageUtils.systemInstall(originalTerminal);
- }
- String cacheProperty = "org.slf4j.simpleLogger.cacheOutputStream";
- String fileProperty = "org.slf4j.simpleLogger.logFile";
- String originalCache = System.getProperty(cacheProperty);
- String originalFile = System.getProperty(fileProperty);
- 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(cacheProperty, "true");
- System.setProperty(fileProperty, "System.out");
- System.setOut(earlyStream);
- new Slf4jSimpleConfiguration().activate();
-
- FastTerminal terminal = new FastTerminal(
- () -> {
- buildingTerminal.countDown();
- if (!releaseTerminal.await(10, SECONDS)) {
- throw new IllegalStateException("Terminal
installation was not released");
- }
- return mock(TerminalExt.class);
- },
- installed -> System.setOut(terminalStream));
- MessageUtils.systemInstall(terminal);
- assertTrue(buildingTerminal.await(10, SECONDS));
-
- MavenCli cli = new MavenCli();
- CliRequest request = new CliRequest(new String[]
{"-Dstyle.color=always"}, null);
- cli.cli(request);
- cli.properties(request);
- FutureTask<Void> logging = new FutureTask<>(() -> {
- cli.logging(request);
- return null;
- });
- loggingThread = new Thread(logging, "logging-initialization-test");
- loggingThread.setDaemon(true);
- loggingThread.start();
- // With -color=always, logging() does NOT await terminal
initialization, so it
- // completes without blocking. Release the terminal after logging
finishes.
- logging.get(10, SECONDS);
- releaseTerminal.countDown();
- terminal.getTerminal();
-
- // The logger must have cached earlyStream (active when logging()
ran), not the
- // terminalStream that the installed callback set afterwards.
-
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 during
logging() with -color=always");
- assertFalse(
-
terminalOutput.toString(UTF_8.name()).contains("terminal-output-marker"),
- "Logger must not switch to the terminal stream when color
is forced");
- } finally {
- releaseTerminal.countDown();
- if (loggingThread != null) {
- loggingThread.join(10000);
- }
- System.setOut(originalOut);
- MessageUtils.systemInstall(originalTerminal);
- MessageUtils.setColorEnabled(originalColor);
- restoreProperty(cacheProperty, originalCache);
- restoreProperty(fileProperty, originalFile);
- new Slf4jSimpleConfiguration().activate();
- }
- }
-
- @Test
- void cachesOutputAfterTerminalInstallationWithColorDisabled() throws
Exception {
- cachesOutputAfterTerminalInstallation("never");
- }
-
- @Test
- void cachesOutputAfterTerminalInstallationInBatchMode() throws Exception {
- cachesOutputAfterTerminalInstallation("batch");
- }
-
- private void cachesOutputAfterTerminalInstallation(String color) throws
Exception {
- PrintStream originalOut = System.out;
- Terminal originalTerminal = MessageUtils.getTerminal();
- boolean originalColor;
- try {
- // isColorEnabled also requires a terminal, even when the color
flag is set.
- MessageUtils.systemInstall(mock(Terminal.class));
- originalColor = MessageUtils.isColorEnabled();
- } finally {
- MessageUtils.systemInstall(originalTerminal);
- }
- String cacheProperty = "org.slf4j.simpleLogger.cacheOutputStream";
- String fileProperty = "org.slf4j.simpleLogger.logFile";
- String originalCache = System.getProperty(cacheProperty);
- String originalFile = System.getProperty(fileProperty);
- CountDownLatch buildingTerminal = new CountDownLatch(1);
- CountDownLatch releaseTerminal = new CountDownLatch(1);
- CountDownLatch awaitingTerminalOrLoggingFinished = 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(cacheProperty, "true");
- System.setProperty(fileProperty, "System.out");
- System.setOut(earlyStream);
- new Slf4jSimpleConfiguration().activate();
-
- FastTerminal terminal =
- new FastTerminal(
- () -> {
- buildingTerminal.countDown();
- if (!releaseTerminal.await(10, SECONDS)) {
- throw new IllegalStateException("Terminal
installation was not released");
- }
- return mock(TerminalExt.class);
- },
- installed -> System.setOut(terminalStream)) {
- @Override
- public TerminalExt getTerminal() {
- awaitingTerminalOrLoggingFinished.countDown();
- return super.getTerminal();
- }
- };
- MessageUtils.systemInstall(terminal);
- 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<>(() -> {
- try {
- cli.logging(request);
- return null;
- } finally {
- awaitingTerminalOrLoggingFinished.countDown();
- }
- });
- loggingThread = new Thread(logging, "logging-initialization-test");
- loggingThread.setDaemon(true);
- loggingThread.start();
- assertTrue(awaitingTerminalOrLoggingFinished.await(10, SECONDS));
- releaseTerminal.countDown();
- logging.get(10, SECONDS);
- terminal.getTerminal();
-
-
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);
- }
- System.setOut(originalOut);
- MessageUtils.systemInstall(originalTerminal);
- MessageUtils.setColorEnabled(originalColor);
- restoreProperty(cacheProperty, originalCache);
- restoreProperty(fileProperty, originalFile);
- new Slf4jSimpleConfiguration().activate();
- }
- }
-
- private static void restoreProperty(String name, String value) {
- if (value == null) {
- System.clearProperty(name);
- } else {
- System.setProperty(name, value);
- }
- }
-}
diff --git
a/maven-embedder/src/test/java/org/apache/maven/cli/MavenCliTest.java
b/maven-embedder/src/test/java/org/apache/maven/cli/MavenCliTest.java
index 7633b8f293..6a5b4ae59e 100644
--- a/maven-embedder/src/test/java/org/apache/maven/cli/MavenCliTest.java
+++ b/maven-embedder/src/test/java/org/apache/maven/cli/MavenCliTest.java
@@ -41,8 +41,6 @@
import org.apache.maven.toolchain.building.ToolchainsBuildingRequest;
import org.apache.maven.toolchain.building.ToolchainsBuildingResult;
import org.codehaus.plexus.PlexusContainer;
-import org.jline.terminal.Terminal;
-import org.jline.terminal.impl.DumbTerminal;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
@@ -56,7 +54,6 @@
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
-import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
@@ -363,12 +360,6 @@ class StyleColors {
@BeforeEach
public void setUp() {
MessageUtils.systemInstall();
- MessageUtils.getTerminalWidth(); // wait for fast terminal
initialize
- }
-
- @AfterEach
- public void tearDown() {
- MessageUtils.systemUninstall();
}
@Test
@@ -486,7 +477,6 @@ void setUp() {
@AfterEach
void tearDown() {
- MessageUtils.systemInstall((Terminal) null);
MessageUtils.setColorEnabled(true);
}
@@ -501,14 +491,11 @@ private String embeddedVersionOutput(String... extraArgs)
{
}
@Test
- void colorYesEmitsAnsiAndLeavesNoTerminalBehind() {
- assertNull(MessageUtils.getTerminal());
-
+ void colorYesEmitsAnsi() {
String output = embeddedVersionOutput("--color=yes");
assertTrue(output.contains("Apache Maven"));
assertNotEquals(MessageUtils.stripAnsiCodes(output), output, "ANSI
escapes expected: " + output);
- assertNull(MessageUtils.getTerminal());
}
@Test
@@ -521,25 +508,6 @@ void colorNoAndAutoEmitNoAnsi() {
String auto = embeddedVersionOutput();
assertTrue(auto.contains("Apache Maven"));
assertEquals(MessageUtils.stripAnsiCodes(auto), auto);
- assertNull(MessageUtils.getTerminal());
- }
-
- @Test
- void installedTerminalIsLeftAlone() throws Exception {
- Terminal mine = new DumbTerminal(
- "test",
- Terminal.TYPE_DUMB,
- new ByteArrayInputStream(new byte[0]),
- new ByteArrayOutputStream(),
- null);
- MessageUtils.systemInstall(mine);
- try {
- embeddedVersionOutput("--color=yes");
- assertSame(mine, MessageUtils.getTerminal());
- } finally {
- MessageUtils.systemInstall((Terminal) null);
- mine.close();
- }
}
}
diff --git a/maven-jline/pom.xml b/maven-jline/pom.xml
index 3b91e6bc3b..d5381f7e3e 100644
--- a/maven-jline/pom.xml
+++ b/maven-jline/pom.xml
@@ -27,31 +27,14 @@ under the License.
</parent>
<artifactId>maven-jline</artifactId>
- <name>Maven 3 JLine integration</name>
- <description>Provides the JLine integration in Maven</description>
+ <name>Maven 3 Message Colors</name>
+ <description>Provides colorized (ANSI) message output in Maven</description>
<properties>
<moduleNameSuffix>jline</moduleNameSuffix>
</properties>
<dependencies>
- <dependency>
- <groupId>org.jline</groupId>
- <artifactId>jansi-core</artifactId>
- </dependency>
- <dependency>
- <groupId>org.jline</groupId>
- <artifactId>jline-terminal</artifactId>
- </dependency>
- <dependency>
- <groupId>org.jline</groupId>
- <artifactId>jline-terminal-jni</artifactId>
- </dependency>
- <dependency>
- <groupId>org.jline</groupId>
- <artifactId>jline-terminal-ffm</artifactId>
- <optional>true</optional>
- </dependency>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
diff --git a/maven-jline/src/main/java/org/apache/maven/jline/FastTerminal.java
b/maven-jline/src/main/java/org/apache/maven/jline/FastTerminal.java
deleted file mode 100644
index 1c4d9b124c..0000000000
--- a/maven-jline/src/main/java/org/apache/maven/jline/FastTerminal.java
+++ /dev/null
@@ -1,291 +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.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.jline.terminal.Attributes;
-import org.jline.terminal.Cursor;
-import org.jline.terminal.MouseEvent;
-import org.jline.terminal.Size;
-import org.jline.terminal.Terminal;
-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;
-
- public FastTerminal(Callable<Terminal> builder, Consumer<Terminal>
consumer) {
- this.terminal = new CompletableFuture<>();
- new Thread(
- () -> {
- try {
- Terminal term = builder.call();
- consumer.accept(term);
- terminal.complete(term);
- } catch (Exception e) {
- terminal.completeExceptionally(e);
- }
- },
- "fast-terminal-thread")
- .start();
- }
-
- public TerminalExt getTerminal() {
- try {
- return (TerminalExt) terminal.get();
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- @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() {
- return 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 int getWidth() {
- return getTerminal().getWidth();
- }
-
- @Override
- public int getHeight() {
- return getTerminal().getHeight();
- }
-
- @Override
- public Size getBufferSize() {
- return getTerminal().getBufferSize();
- }
-
- @Override
- public void flush() {
- getTerminal().flush();
- }
-
- @Override
- public String getType() {
- return 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();
- }
-
- @Override
- public String toString() {
- return getTerminal().toString();
- }
-}
diff --git
a/maven-jline/src/main/java/org/apache/maven/jline/JLineMessageBuilderFactory.java
b/maven-jline/src/main/java/org/apache/maven/jline/JLineMessageBuilderFactory.java
index ff17bd59da..1f50840a37 100644
---
a/maven-jline/src/main/java/org/apache/maven/jline/JLineMessageBuilderFactory.java
+++
b/maven-jline/src/main/java/org/apache/maven/jline/JLineMessageBuilderFactory.java
@@ -21,25 +21,31 @@
import javax.inject.Named;
import javax.inject.Singleton;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Locale;
import java.util.Map;
+import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.maven.message.MessageBuilder;
import org.apache.maven.message.MessageBuilderFactory;
import org.eclipse.sisu.Priority;
-import org.jline.utils.AttributedStringBuilder;
-import org.jline.utils.AttributedStyle;
-import org.jline.utils.StyleResolver;
+/**
+ * Message builder factory emitting ANSI colors. The class name is kept for
compatibility, JLine is not used anymore.
+ */
@Named
@Singleton
@Priority(10)
public class JLineMessageBuilderFactory implements MessageBuilderFactory {
- private final StyleResolver resolver;
- public JLineMessageBuilderFactory() {
- this.resolver = new MavenStyleResolver();
- }
+ static final String RESET = "\u001B[0m";
+
+ private static final List<String> COLORS =
+ Arrays.asList("black", "red", "green", "yellow", "blue",
"magenta", "cyan", "white");
+
+ private static final Map<String, String> STYLES = new
ConcurrentHashMap<>();
@Override
public boolean isColorEnabled() {
@@ -58,29 +64,144 @@ public MessageBuilder builder() {
@Override
public MessageBuilder builder(int size) {
- return new JlineMessageBuilder(resolver, size);
+ return new AnsiMessageBuilder(size);
+ }
+
+ /**
+ * Resolves a style to its ANSI escape sequence (empty if it has no
effect). A style is either a spec like
+ * {@code bold,f:red}, or a reference {@code .name:-default} looked up
from the {@code maven.style.name} or
+ * {@code style.name} system property, falling back to {@code default}.
+ */
+ static String resolve(String style) {
+ return STYLES.computeIfAbsent(style,
JLineMessageBuilderFactory::doResolve);
+ }
+
+ private static String doResolve(String style) {
+ String spec = style;
+ if (spec.startsWith(".")) {
+ int i = spec.indexOf(":-");
+ String name = i < 0 ? spec.substring(1) : spec.substring(1, i);
+ String def = i < 0 ? "" : spec.substring(i + 2);
+ spec = System.getProperty("maven.style." + name,
System.getProperty("style." + name, def));
+ }
+ // same order as JLine emitted (ITs match exact bytes): attributes
3-9, foreground, background, bold, faint
+ String[] slots = new String[5];
+ TreeSet<String> attributes = new TreeSet<>();
+ for (String item : spec.split(",")) {
+ String code = code(item.trim().toLowerCase(Locale.ROOT));
+ if (code == null) {
+ continue;
+ }
+ int colon = item.trim().indexOf(':');
+ if (colon > 0) {
+ String target = item.trim().substring(0,
colon).toLowerCase(Locale.ROOT);
+ slots[target.startsWith("f") ? 1 : 2] = code;
+ } else if (code.equals("1")) {
+ slots[3] = code;
+ } else if (code.equals("2")) {
+ slots[4] = code;
+ } else {
+ attributes.add(code);
+ }
+ }
+ slots[0] = attributes.isEmpty() ? null : String.join(";", attributes);
+ StringBuilder codes = new StringBuilder();
+ for (String slot : slots) {
+ if (slot != null) {
+ codes.append(codes.length() > 0 ? ";" : "").append(slot);
+ }
+ }
+ return codes.length() > 0 ? "\u001B[" + codes + "m" : "";
+ }
+
+ // ponytail: the subset of JLine's style syntax Maven styles use; unknown
items are ignored
+ private static String code(String item) {
+ switch (item) {
+ case "bold":
+ return "1";
+ case "faint":
+ return "2";
+ case "italic":
+ return "3";
+ case "underline":
+ return "4";
+ case "blink":
+ return "5";
+ case "inverse":
+ return "7";
+ case "conceal":
+ case "hidden":
+ return "8";
+ case "crossed-out":
+ return "9";
+ default:
+ }
+ int colon = item.indexOf(':');
+ if (colon < 0) {
+ return null;
+ }
+ String target = item.substring(0, colon);
+ boolean fg = target.equals("f") || target.equals("fg") ||
target.equals("foreground");
+ boolean bg = target.equals("b") || target.equals("bg") ||
target.equals("background");
+ return fg || bg ? color(item.substring(colon + 1), fg) : null;
+ }
+
+ private static String color(String color, boolean fg) {
+ if (color.equals("default")) {
+ return fg ? "39" : "49";
+ }
+ boolean bright = false;
+ if (color.startsWith("bright-")) {
+ bright = true;
+ color = color.substring("bright-".length());
+ } else if (color.startsWith("!")) {
+ bright = true;
+ color = color.substring(1);
+ }
+ int index = COLORS.indexOf(color);
+ if (index >= 0) {
+ return String.valueOf((fg ? 30 : 40) + (bright ? 60 : 0) + index);
+ }
+ try {
+ if (color.startsWith("#") || color.startsWith("x")) {
+ int rgb = Integer.parseInt(color.substring(1), 16);
+ return (fg ? "38" : "48") + ";2;" + (rgb >> 16 & 0xff) + ";" +
(rgb >> 8 & 0xff) + ";" + (rgb & 0xff);
+ }
+ return (fg ? "38" : "48") + ";5;" + (Integer.parseInt(color) &
0xff);
+ } catch (NumberFormatException e) {
+ return null;
+ }
}
- private static class JlineMessageBuilder implements MessageBuilder {
- private final StyleResolver styleResolver;
- private final AttributedStringBuilder builder;
+ private static class AnsiMessageBuilder implements MessageBuilder {
+ private final StringBuilder builder;
+ private boolean styled;
- private JlineMessageBuilder(StyleResolver styleResolver, int size) {
- this.styleResolver = styleResolver;
- this.builder = new AttributedStringBuilder(size);
+ private AnsiMessageBuilder(int size) {
+ this.builder = new StringBuilder(size);
}
@Override
public MessageBuilder style(String style) {
if (MessageUtils.isColorEnabled()) {
- builder.style(styleResolver.resolve(style));
+ String ansi = resolve(style);
+ if (!ansi.isEmpty()) {
+ if (styled) {
+ builder.append(RESET);
+ }
+ builder.append(ansi);
+ styled = true;
+ }
}
return this;
}
@Override
public MessageBuilder resetStyle() {
- builder.style(AttributedStyle.DEFAULT);
+ if (styled) {
+ builder.append(RESET);
+ styled = false;
+ }
return this;
}
@@ -105,12 +226,15 @@ public MessageBuilder append(char c) {
@Override
public MessageBuilder setLength(int length) {
builder.setLength(length);
+ if (length == 0) {
+ styled = false;
+ }
return this;
}
@Override
public String build() {
- return builder.toAnsi(MessageUtils.terminal);
+ return styled ? builder + RESET : builder.toString();
}
@Override
@@ -118,39 +242,4 @@ public String toString() {
return build();
}
}
-
- private static class MavenStyleResolver extends StyleResolver {
- private final Map<String, AttributedStyle> styles = new
ConcurrentHashMap<>();
-
- private MavenStyleResolver() {
- super(key -> {
- String v = System.getProperty("maven.style." + key);
- if (v == null) {
- v = System.getProperty("style." + key);
- }
- return v;
- });
- }
-
- @Override
- public AttributedStyle resolve(String spec) {
- return styles.computeIfAbsent(spec, this::doResolve);
- }
-
- @Override
- public AttributedStyle resolve(String spec, String defaultSpec) {
- return resolve(defaultSpec != null ? spec + ":-" + defaultSpec :
spec);
- }
-
- private AttributedStyle doResolve(String spec) {
- String def = null;
- int i = spec.indexOf(":-");
- if (i != -1) {
- String[] parts = spec.split(":-");
- spec = parts[0].trim();
- def = parts[1].trim();
- }
- return super.resolve(spec, def);
- }
- }
}
diff --git a/maven-jline/src/main/java/org/apache/maven/jline/MessageUtils.java
b/maven-jline/src/main/java/org/apache/maven/jline/MessageUtils.java
index 7295795c2c..249e189a9d 100644
--- a/maven-jline/src/main/java/org/apache/maven/jline/MessageUtils.java
+++ b/maven-jline/src/main/java/org/apache/maven/jline/MessageUtils.java
@@ -18,120 +18,106 @@
*/
package org.apache.maven.jline;
-import java.util.function.Consumer;
+import java.io.BufferedReader;
+import java.io.Console;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.lang.reflect.Method;
import org.apache.maven.message.MessageBuilder;
import org.apache.maven.message.MessageBuilderFactory;
-import org.jline.jansi.AnsiConsole;
-import org.jline.terminal.Terminal;
-import org.jline.terminal.TerminalBuilder;
+/**
+ * Colorized message support. Maven only needs ANSI colors in its log output,
so there is no terminal library here:
+ * styles are emitted as plain SGR escape sequences, and only when color is
enabled.
+ */
public class MessageUtils {
- static Terminal terminal;
static MessageBuilderFactory messageBuilderFactory = new
JLineMessageBuilderFactory();
- static boolean colorEnabled = true;
- static Thread shutdownHook;
- static final Object STARTUP_SHUTDOWN_MONITOR = new Object();
+ static volatile boolean tty;
+ static volatile boolean colorEnabled;
- public static void systemInstall(Terminal terminal) {
- MessageUtils.terminal = terminal;
+ /**
+ * Detects whether standard output is an ANSI capable terminal and enables
color accordingly. Only the CLI calls
+ * this; embedded use never does, so "auto" color stays off there.
+ */
+ public static void systemInstall() {
+ tty = detectAnsiTerminal();
+ colorEnabled = tty;
+ width = 0;
}
- public static void systemInstall() {
- systemInstall(null, null);
+ /**
+ * Returns {@code true} if {@link #systemInstall()} detected an ANSI
capable terminal on standard output.
+ */
+ public static boolean isTty() {
+ return tty;
+ }
+
+ public static void setColorEnabled(boolean enabled) {
+ colorEnabled = enabled;
}
- public static void systemInstall(Consumer<TerminalBuilder>
builderConsumer, Consumer<Terminal> terminalConsumer) {
- MessageUtils.terminal = new FastTerminal(
- () -> {
- TerminalBuilder builder = TerminalBuilder.builder()
- .name("Maven")
- .dumb(true)
- .systemOutput(TerminalBuilder.SystemOutput.SysOut)
- .color(true);
- if (builderConsumer != null) {
- builderConsumer.accept(builder);
- }
- return builder.build();
- },
- terminal -> {
- AnsiConsole.setTerminal(terminal);
- AnsiConsole.systemInstall();
- if (terminalConsumer != null) {
- terminalConsumer.accept(terminal);
- }
- });
+ public static boolean isColorEnabled() {
+ return colorEnabled;
}
/**
- * Waits for the terminal to finish installing on its background thread.
- * <p>
- * Terminal setup runs asynchronously and replaces {@code
System.out}/{@code System.err} along
- * the way. Call this before you redirect those streams yourself (for
example for the {@code -l}
- * log file), otherwise the late terminal install can overwrite your
redirection and logs end up
- * back on the console.
+ * Returns the terminal width in columns, or {@code -1} if unknown. Taken
from the {@code COLUMNS} environment
+ * variable if set, otherwise (on a detected non-Windows terminal) from
{@code stty size}. Computed once.
*/
- public static void awaitTerminalInitialization() {
- if (terminal instanceof FastTerminal) {
- ((FastTerminal) terminal).getTerminal();
+ public static int getTerminalWidth() {
+ int w = width;
+ if (w == 0) {
+ w = detectWidth();
+ width = w;
}
+ return w;
}
- public static void registerShutdownHook() {
- if (shutdownHook == null) {
- shutdownHook = new Thread(() -> {
- synchronized (MessageUtils.STARTUP_SHUTDOWN_MONITOR) {
- MessageUtils.doSystemUninstall();
- }
- });
- Runtime.getRuntime().addShutdownHook(shutdownHook);
- }
- }
+ static volatile int width; // 0 = not yet detected
- public static void systemUninstall() {
- doSystemUninstall();
- if (shutdownHook != null) {
- try {
- Runtime.getRuntime().removeShutdownHook(shutdownHook);
- } catch (IllegalStateException var3) {
- // ignore
- }
+ private static int detectWidth() {
+ int columns = parseWidth(System.getenv("COLUMNS"));
+ if (columns > 0) {
+ return columns;
}
- }
-
- private static void doSystemUninstall() {
+ if (!tty || System.getProperty("os.name", "").startsWith("Windows")) {
+ return -1;
+ }
+ // ponytail: read once, window resizes are not tracked; re-query
periodically if a consumer ever needs it
try {
- if (terminal instanceof FastTerminal) {
- // wait for the asynchronous systemInstall call before we
uninstall to ensure a consistent state
- ((FastTerminal) terminal).getTerminal();
+ Process p = new ProcessBuilder("stty", "size")
+ .redirectInput(new File("/dev/tty"))
+ .redirectError(new File("/dev/null"))
+ .start();
+ try (BufferedReader r = new BufferedReader(new
InputStreamReader(p.getInputStream()))) {
+ String size = r.readLine(); // "rows cols"
+ p.waitFor();
+ return size == null ? -1 :
parseWidth(size.substring(size.indexOf(' ') + 1));
}
- AnsiConsole.systemUninstall();
- } finally {
- terminal = null;
+ } catch (IOException e) {
+ return -1;
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ return -1;
}
}
- public static void setColorEnabled(boolean enabled) {
- colorEnabled = enabled;
- }
-
- public static boolean isColorEnabled() {
- return colorEnabled && terminal != null;
- }
-
- public static int getTerminalWidth() {
- return terminal != null ? terminal.getWidth() : -1;
+ static int parseWidth(String s) {
+ try {
+ int w = s == null ? -1 : Integer.parseInt(s.trim());
+ return w > 0 ? w : -1;
+ } catch (NumberFormatException e) {
+ return -1;
+ }
}
public static MessageBuilder builder() {
return messageBuilderFactory.builder();
}
- public static Terminal getTerminal() {
- return terminal;
- }
-
/**
* Remove any ANSI code from a message (colors or other escape sequences).
*
@@ -141,4 +127,33 @@ public static Terminal getTerminal() {
public static String stripAnsiCodes(String msg) {
return msg.replaceAll("\u001B\\[[;\\d]*[ -/]*[@-~]", "");
}
+
+ static boolean detectAnsiTerminal() {
+ if ("dumb".equals(System.getenv("TERM"))) {
+ return false;
+ }
+ Console console = System.console();
+ if (console == null) {
+ return false; // stdin or stdout is redirected
+ }
+ try {
+ // Java 22+ returns a console even when redirected; isTerminal()
tells the truth
+ Method isTerminal = Console.class.getMethod("isTerminal");
+ if (!(Boolean) isTerminal.invoke(console)) {
+ return false;
+ }
+ } catch (ReflectiveOperationException e) {
+ // Java < 22: a non-null console already means a terminal
+ }
+ if (System.getProperty("os.name", "").startsWith("Windows")) {
+ // ponytail: no native call to switch on VT processing, so trust
only consoles known to do ANSI already
+ // (Windows Terminal, ConEmu/Cmder, ANSICON, VS Code, mintty &
co); legacy conhost users use --color=always
+ return System.getenv("WT_SESSION") != null
+ || "ON".equals(System.getenv("ConEmuANSI"))
+ || System.getenv("ANSICON") != null
+ || "vscode".equals(System.getenv("TERM_PROGRAM"))
+ || System.getenv("TERM") != null;
+ }
+ return true;
+ }
}
diff --git a/maven-jline/src/main/java/org/fusesource/jansi/Ansi.java
b/maven-jline/src/main/java/org/fusesource/jansi/Ansi.java
index 820556d9c4..a584d56804 100644
--- a/maven-jline/src/main/java/org/fusesource/jansi/Ansi.java
+++ b/maven-jline/src/main/java/org/fusesource/jansi/Ansi.java
@@ -25,8 +25,7 @@
* <a href="https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences">ANSI
escape sequences</a>.
*
* This class comes from Jansi and is provided for backward compatibility
- * with maven-shared-utils, while Maven has migrated to JLine (into which
Jansi has been merged
- * since JLine 3.25.0).
+ * with maven-shared-utils; Maven itself no longer ships Jansi.
*
* @see AnsiConsole
*/
@@ -162,12 +161,14 @@ public interface Consumer {
void apply(Ansi ansi);
}
+ private static volatile boolean enabled = true;
+
public static boolean isEnabled() {
- return org.apache.maven.jline.MessageUtils.isColorEnabled() &&
org.jline.jansi.Ansi.isEnabled();
+ return org.apache.maven.jline.MessageUtils.isColorEnabled() && enabled;
}
public static void setEnabled(final boolean flag) {
- org.jline.jansi.Ansi.setEnabled(flag);
+ enabled = flag;
}
public static Ansi ansi() {
@@ -851,21 +852,59 @@ public Ansi apply(Consumer fun) {
}
/**
- * Uses the {@link org.jline.jansi.AnsiRenderer}
- * to generate the ANSI escape sequences for the supplied text.
+ * Renders Jansi markup, e.g. {@code @|bold,red text|@}, into ANSI escape
sequences.
*
* @param text text
* @return this
* @since 2.2
*/
public Ansi render(final String text) {
- a(new org.jline.jansi.Ansi().render(text).toString());
- return this;
+ int i = 0;
+ int begin;
+ while ((begin = text.indexOf("@|", i)) >= 0) {
+ int space = text.indexOf(' ', begin);
+ int end = text.indexOf("|@", begin);
+ if (space < 0 || end < 0 || space > end) {
+ break;
+ }
+ a(text.substring(i, begin));
+ for (String code : text.substring(begin + 2, space).split(",")) {
+ renderCode(code.trim().toUpperCase(java.util.Locale.ROOT));
+ }
+ a(text.substring(space + 1, end)).reset();
+ i = end + 2;
+ }
+ return a(text.substring(i));
+ }
+
+ private void renderCode(String code) {
+ boolean bg = code.startsWith("BG_");
+ String name = bg || code.startsWith("FG_") ? code.substring(3) : code;
+ for (Color color : Color.values()) {
+ if (color.name().equals(name)) {
+ if (bg) {
+ bg(color);
+ } else {
+ fg(color);
+ }
+ return;
+ }
+ }
+ for (Attribute attribute : Attribute.values()) {
+ if (attribute.name().equals(code) || attribute.name().equals(code
+ "_ON")) {
+ a(attribute);
+ return;
+ }
+ }
+ if (code.equals("BOLD")) {
+ bold();
+ } else if (code.equals("FAINT")) {
+ a(Attribute.INTENSITY_FAINT);
+ }
}
/**
- * String formats and renders the supplied arguments. Uses the {@link
org.jline.jansi.AnsiRenderer}
- * to generate the ANSI escape sequences.
+ * String formats and renders the supplied arguments.
*
* @param text format
* @param args arguments
@@ -873,8 +912,7 @@ public Ansi render(final String text) {
* @since 2.2
*/
public Ansi render(final String text, Object... args) {
- a(String.format(new org.jline.jansi.Ansi().render(text).toString(),
args));
- return this;
+ return render(String.format(text, args));
}
@Override
diff --git a/maven-jline/src/main/java/org/fusesource/jansi/AnsiConsole.java
b/maven-jline/src/main/java/org/fusesource/jansi/AnsiConsole.java
index f0b59a40b7..209c98490d 100644
--- a/maven-jline/src/main/java/org/fusesource/jansi/AnsiConsole.java
+++ b/maven-jline/src/main/java/org/fusesource/jansi/AnsiConsole.java
@@ -19,31 +19,34 @@
package org.fusesource.jansi;
/**
- * Forwards to {@link org.jline.jansi.AnsiConsole} instead of performing its
own install, so that code
- * calling the JAnsi API, such as maven-shared-utils, shares the single
console Maven itself installs
- * through {@code org.apache.maven.jline.MessageUtils} rather than racing it
for ownership of
- * {@code System.out}/{@code System.err}.
+ * Does not install anything: Maven never replaces {@code System.out}/{@code
System.err}, it only decides whether
+ * to emit colors (see {@code org.apache.maven.jline.MessageUtils}). Install
calls are just counted, so code calling
+ * the JAnsi API, such as maven-shared-utils, keeps working without racing
Maven for the console.
*
- * This class comes from Jansi and is provided for backward compatibility with
maven-shared-utils,
- * while Maven has migrated to JLine (into which Jansi has been merged since
JLine 3.25.0).
+ * This class comes from Jansi and is provided for backward compatibility with
maven-shared-utils;
+ * Maven itself no longer ships Jansi.
*/
@Deprecated
public class AnsiConsole {
private static final AnsiPrintStream OUT = new AnsiPrintStream();
+ private static int installed;
+
private AnsiConsole() {}
public static synchronized void systemInstall() {
- org.jline.jansi.AnsiConsole.systemInstall();
+ installed++;
}
public static synchronized boolean isInstalled() {
- return org.jline.jansi.AnsiConsole.isInstalled();
+ return installed > 0;
}
public static synchronized void systemUninstall() {
- org.jline.jansi.AnsiConsole.systemUninstall();
+ if (installed > 0) {
+ installed--;
+ }
}
public static AnsiPrintStream out() {
@@ -51,6 +54,6 @@ public static AnsiPrintStream out() {
}
public static int getTerminalWidth() {
- return org.jline.jansi.AnsiConsole.getTerminalWidth();
+ return org.apache.maven.jline.MessageUtils.getTerminalWidth();
}
}
diff --git a/maven-jline/src/main/java/org/fusesource/jansi/AnsiMode.java
b/maven-jline/src/main/java/org/fusesource/jansi/AnsiMode.java
index c295e4731c..29054b2be8 100644
--- a/maven-jline/src/main/java/org/fusesource/jansi/AnsiMode.java
+++ b/maven-jline/src/main/java/org/fusesource/jansi/AnsiMode.java
@@ -22,8 +22,8 @@
* Mirrors the real JAnsi {@code AnsiMode} enum so code compiled against
JAnsi, such as
* maven-shared-utils, keeps resolving against this type at runtime.
*
- * This class comes from Jansi and is provided for backward compatibility with
maven-shared-utils,
- * while Maven has migrated to JLine (into which Jansi has been merged since
JLine 3.25.0).
+ * This class comes from Jansi and is provided for backward compatibility with
maven-shared-utils;
+ * Maven itself no longer ships Jansi.
*/
@Deprecated
public enum AnsiMode {
diff --git
a/maven-jline/src/main/java/org/fusesource/jansi/AnsiPrintStream.java
b/maven-jline/src/main/java/org/fusesource/jansi/AnsiPrintStream.java
index d5e148bf4d..8ce283630f 100644
--- a/maven-jline/src/main/java/org/fusesource/jansi/AnsiPrintStream.java
+++ b/maven-jline/src/main/java/org/fusesource/jansi/AnsiPrintStream.java
@@ -22,13 +22,13 @@
import java.io.PrintStream;
/**
- * Forwards everything written to it to whatever {@code System.out} currently
is, which is the stream
- * JLine installed. Unlike real JAnsi, this stream does not decide for itself
whether to strip, force or
- * pass through ANSI escapes - that decision belongs to the terminal Maven
already set up - so
+ * Forwards everything written to it to whatever {@code System.out} currently
is, untouched by Maven.
+ * Unlike real JAnsi, this stream does not decide for itself whether to strip,
force or
+ * pass through ANSI escapes - that decision belongs to Maven's color setting
- so
* {@link #setMode} is a no-op.
*
- * This class comes from Jansi and is provided for backward compatibility with
maven-shared-utils,
- * while Maven has migrated to JLine (into which Jansi has been merged since
JLine 3.25.0).
+ * This class comes from Jansi and is provided for backward compatibility with
maven-shared-utils;
+ * Maven itself no longer ships Jansi.
*/
@Deprecated
public class AnsiPrintStream extends PrintStream {
@@ -59,7 +59,7 @@ public AnsiMode getMode() {
}
public void setMode(AnsiMode mode) {
- // no-op: the terminal Maven installed already decides whether ANSI is
forced, stripped or kept
+ // no-op: Maven's color setting decides whether ANSI is emitted at all
}
public int getTerminalWidth() {
diff --git
a/maven-jline/src/test/java/org/apache/maven/jline/FastTerminalTest.java
b/maven-jline/src/test/java/org/apache/maven/jline/FastTerminalTest.java
deleted file mode 100644
index 9751e937cb..0000000000
--- a/maven-jline/src/test/java/org/apache/maven/jline/FastTerminalTest.java
+++ /dev/null
@@ -1,94 +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.time.Duration;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import org.jline.terminal.Terminal;
-import org.jline.terminal.TerminalBuilder;
-import org.junit.jupiter.api.Test;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertSame;
-import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-/**
- * Tests that {@link FastTerminal#getTerminal()} waits for the background
setup to finish before it
- * returns. {@link MessageUtils#awaitTerminalInitialization()} relies on this
so the {@code -l} log
- * file redirection cannot be overwritten by the late terminal install
- * (see <a href="https://github.com/apache/maven/issues/12188">#12188</a>).
- */
-class FastTerminalTest {
-
- /** Safety net so a broken implementation fails fast instead of hanging
the build forever. */
- private static final Duration MAX_WAIT = Duration.ofSeconds(30);
-
- @Test
- void getTerminalBlocksUntilConsumerHasCompleted() throws Exception {
- Terminal dumb = TerminalBuilder.builder().dumb(true).build();
-
- CountDownLatch builderProceed = new CountDownLatch(1);
- AtomicBoolean consumerCompleted = new AtomicBoolean(false);
-
- FastTerminal fastTerminal = new FastTerminal(
- () -> {
- // pretend the terminal is slow to build, like it often is
on macOS
- builderProceed.await();
- return dumb;
- },
- terminal -> {
- // this is where AnsiConsole.systemInstall() and the
stream swap would happen
- consumerCompleted.set(true);
- });
-
- // the build is still blocked, so the consumer has not run yet
- assertFalse(consumerCompleted.get(), "consumer must not run before the
terminal is built");
-
- // let the setup finish
- builderProceed.countDown();
-
- // getTerminal() should only come back once the consumer is done
- assertTimeoutPreemptively(MAX_WAIT, fastTerminal::getTerminal);
- assertTrue(consumerCompleted.get(), "getTerminal() must block until
the consumer has completed");
-
- dumb.close();
- }
-
- @Test
- void getTerminalReturnsSameReadyTerminalOnRepeatedCalls() throws Exception
{
- Terminal dumb = TerminalBuilder.builder().dumb(true).build();
- AtomicInteger consumerInvocations = new AtomicInteger();
-
- FastTerminal fastTerminal = new FastTerminal(() -> dumb, terminal ->
consumerInvocations.incrementAndGet());
-
- assertTimeoutPreemptively(MAX_WAIT, () -> {
- assertSame(dumb, fastTerminal.getTerminal());
- // calling it again returns the same terminal without re-running
the setup
- assertSame(dumb, fastTerminal.getTerminal());
- });
- assertEquals(1, consumerInvocations.get(), "the consumer must run
exactly once");
-
- dumb.close();
- }
-}
diff --git
a/maven-jline/src/test/java/org/apache/maven/jline/MessageUtilsTest.java
b/maven-jline/src/test/java/org/apache/maven/jline/MessageUtilsTest.java
index 6106330c16..30b5ca9f36 100644
--- a/maven-jline/src/test/java/org/apache/maven/jline/MessageUtilsTest.java
+++ b/maven-jline/src/test/java/org/apache/maven/jline/MessageUtilsTest.java
@@ -18,32 +18,68 @@
*/
package org.apache.maven.jline;
-import org.jline.terminal.Terminal;
-import org.jline.terminal.TerminalBuilder;
+import org.apache.maven.message.MessageBuilder;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
-import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.assertEquals;
class MessageUtilsTest {
@AfterEach
void reset() {
- MessageUtils.terminal = null;
+ MessageUtils.setColorEnabled(false);
}
@Test
- void awaitTerminalInitializationIsNoOpWhenNoTerminalInstalled() {
- MessageUtils.terminal = null;
- assertDoesNotThrow(MessageUtils::awaitTerminalInitialization);
+ void parsesWidth() {
+ assertEquals(137, MessageUtils.parseWidth("137"));
+ assertEquals(137, MessageUtils.parseWidth(" 137\n"));
+ assertEquals(-1, MessageUtils.parseWidth("0"));
+ assertEquals(-1, MessageUtils.parseWidth("wide"));
+ assertEquals(-1, MessageUtils.parseWidth(null));
}
@Test
- void awaitTerminalInitializationIsNoOpForPlainTerminal() throws Exception {
- // a plain terminal (e.g. embedded use) has nothing to wait for and
must return at once
- try (Terminal terminal = TerminalBuilder.builder().dumb(true).build())
{
- MessageUtils.terminal = terminal;
- assertDoesNotThrow(MessageUtils::awaitTerminalInitialization);
+ void resolvesStyleSpecs() {
+ // byte-for-byte what JLine 3.30 emitted for the same specs
+ assertEquals("\u001B[31;1m",
JLineMessageBuilderFactory.resolve("bold,f:red"));
+ assertEquals("\u001B[36;1m",
JLineMessageBuilderFactory.resolve("f:cyan,bold"));
+ assertEquals("\u001B[4;31;44;1m",
JLineMessageBuilderFactory.resolve("bold,underline,f:red,bg:blue"));
+ assertEquals(
+ "\u001B[3;4;5;7;8;9;31;44;1;2m",
+ JLineMessageBuilderFactory.resolve(
+
"bold,faint,italic,underline,blink,inverse,conceal,crossed-out,f:red,bg:blue"));
+ assertEquals("\u001B[3;5;8m",
JLineMessageBuilderFactory.resolve("conceal,hidden,blink,italic"));
+ assertEquals("\u001B[90m",
JLineMessageBuilderFactory.resolve("f:bright-black"));
+ assertEquals("\u001B[38;5;208;44m",
JLineMessageBuilderFactory.resolve("bg:blue,fg:208"));
+ assertEquals("\u001B[38;2;255;0;16m",
JLineMessageBuilderFactory.resolve("f:#ff0010"));
+ assertEquals("",
JLineMessageBuilderFactory.resolve("nonsense,f:nocolor"));
+ }
+
+ @Test
+ void resolvesNamedStyleFromSystemPropertyOrDefault() {
+ assertEquals("\u001B[34;1m",
JLineMessageBuilderFactory.resolve(".test-unset:-bold,f:blue"));
+ System.setProperty("maven.style.test-set", "f:green");
+ try {
+ assertEquals("\u001B[32m",
JLineMessageBuilderFactory.resolve(".test-set:-bold,f:blue"));
+ } finally {
+ System.clearProperty("maven.style.test-set");
}
}
+
+ @Test
+ void builderEmitsAnsiOnlyWhenColorEnabled() {
+ MessageUtils.setColorEnabled(false);
+ assertEquals("a b c", MessageUtils.builder().a("a ").error("b").a("
c").build());
+
+ MessageUtils.setColorEnabled(true);
+ MessageBuilder mb = MessageUtils.builder().a("a ").error("b").a(" c");
+ assertEquals("a \u001B[31;1mb\u001B[0m c", mb.build());
+ assertEquals("a b c", MessageUtils.stripAnsiCodes(mb.build()));
+ // an unterminated style is reset at the end
+ assertEquals(
+ "\u001B[1mx\u001B[0m",
+ MessageUtils.builder().style("bold").a("x").build());
+ }
}
diff --git
a/maven-jline/src/test/java/org/fusesource/jansi/AnsiConsoleTest.java
b/maven-jline/src/test/java/org/fusesource/jansi/AnsiConsoleTest.java
index bac1816a1f..8020174e31 100644
--- a/maven-jline/src/test/java/org/fusesource/jansi/AnsiConsoleTest.java
+++ b/maven-jline/src/test/java/org/fusesource/jansi/AnsiConsoleTest.java
@@ -28,10 +28,10 @@
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
- * Verifies that this JAnsi compatibility shim shares its lifecycle with
{@link org.jline.jansi.AnsiConsole}
- * instead of running an install of its own (see #13726, #13727).
+ * Verifies that this JAnsi compatibility shim never installs anything of its
own (see #13726, #13727).
*/
class AnsiConsoleTest {
@@ -43,15 +43,17 @@ void uninstall() {
}
@Test
- void systemInstallAndUninstallDelegateToJLinesAnsiConsole() {
+ void systemInstallLeavesSystemOutAlone() {
+ PrintStream original = System.out;
assertFalse(AnsiConsole.isInstalled());
AnsiConsole.systemInstall();
- assertEquals(org.jline.jansi.AnsiConsole.isInstalled(),
AnsiConsole.isInstalled());
+ assertTrue(AnsiConsole.isInstalled());
+ assertSame(original, System.out);
AnsiConsole.systemUninstall();
assertFalse(AnsiConsole.isInstalled());
- assertEquals(org.jline.jansi.AnsiConsole.isInstalled(),
AnsiConsole.isInstalled());
+ assertSame(original, System.out);
}
@Test
@@ -75,8 +77,21 @@ void outReturnsTheSameInstanceEveryCall() {
}
@Test
- void getTerminalWidthDelegatesToJLinesAnsiConsole() {
- assertEquals(org.jline.jansi.AnsiConsole.getTerminalWidth(),
AnsiConsole.getTerminalWidth());
+ void getTerminalWidthDelegatesToMessageUtils() {
+ assertEquals(org.apache.maven.jline.MessageUtils.getTerminalWidth(),
AnsiConsole.getTerminalWidth());
+ }
+
+ @Test
+ void renderHonoursColorSetting() {
+ org.apache.maven.jline.MessageUtils.setColorEnabled(true);
+ try {
+ assertEquals(
+ "a \u001B[1;31mb\u001B[m c",
+ Ansi.ansi().render("a @|bold,red b|@ c").toString());
+ } finally {
+ org.apache.maven.jline.MessageUtils.setColorEnabled(false);
+ }
+ assertEquals("a b c", Ansi.ansi().render("a @|bold,red b|@
c").toString());
}
@Test
diff --git a/pom.xml b/pom.xml
index 405fbc9f0e..b33b157e90 100644
--- a/pom.xml
+++ b/pom.xml
@@ -158,7 +158,6 @@ under the License.
<checkstyle.violation.ignore>None</checkstyle.violation.ignore>
<checkstyle.excludes>**/package-info.java</checkstyle.excludes>
<project.build.outputTimestamp>2026-09-27T20:38:58Z</project.build.outputTimestamp>
- <jlineVersion>3.30.17</jlineVersion>
<!-- The JPMS module name elements used in the Automatic-Module-Name -->
<!-- Note: Maven 3 can never become "pure modular" thing, we leave that to
Maven 4+ -->
@@ -357,26 +356,6 @@ under the License.
<artifactId>plexus-interpolation</artifactId>
<version>${plexusInterpolationVersion}</version>
</dependency>
- <dependency>
- <groupId>org.jline</groupId>
- <artifactId>jansi-core</artifactId>
- <version>${jlineVersion}</version>
- </dependency>
- <dependency>
- <groupId>org.jline</groupId>
- <artifactId>jline-terminal</artifactId>
- <version>${jlineVersion}</version>
- </dependency>
- <dependency>
- <groupId>org.jline</groupId>
- <artifactId>jline-terminal-jni</artifactId>
- <version>${jlineVersion}</version>
- </dependency>
- <dependency>
- <groupId>org.jline</groupId>
- <artifactId>jline-terminal-ffm</artifactId>
- <version>${jlineVersion}</version>
- </dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
@@ -742,11 +721,7 @@ under the License.
</goals>
<configuration>
<rules>
- <enforceBytecodeVersion>
- <excludes>
- <exclude>org.jline:jline-terminal-ffm</exclude>
- </excludes>
- </enforceBytecodeVersion>
+ <enforceBytecodeVersion />
</rules>
<fail>true</fail>
</configuration>