Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import java.util.Optional;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Pattern;

import org.aesh.command.Command;
import org.aesh.command.CommandResult;
Expand All @@ -46,6 +47,9 @@

public abstract class CamelCommand implements Command<CommandInvocation>, CommandTree.ParsedCommandAware {

// an ANSI escape code (CSI), such as the colors of the Jansi Ansi builder
private static final Pattern ANSI_CODE = Pattern.compile("\\x1B\\[[0-9;:?]*[ -/]*[@-~]");

// the model of the options of this command, and the tree it runs in (set when the command line is built)
private ProcessedCommand<?, ?> processedCommand;
private CommandTree tree;
Expand Down Expand Up @@ -327,7 +331,9 @@ protected Printer printer() {
* CLI that runs the command in its own JVM and keeps its output (see {@link CliRunner}).
*/
protected void printColored(Object text) {
if (printsToConsole()) {
if (printsToConsole() && stripsColorsItself()) {
printer().print(withoutColors(text));
} else if (printsToConsole()) {
AnsiConsole.out().print(text);
} else {
printer().print(String.valueOf(text));
Expand All @@ -338,7 +344,9 @@ protected void printColored(Object text) {
* Prints a line with colors (ANSI escape codes), see {@link #printColored(Object)}.
*/
protected void printlnColored(Object text) {
if (printsToConsole()) {
if (printsToConsole() && stripsColorsItself()) {
printer().println(withoutColors(text));
} else if (printsToConsole()) {
AnsiConsole.out().println(text);
} else {
printer().println(String.valueOf(text));
Expand All @@ -352,7 +360,24 @@ protected void printlnColored(Object text) {
* (CAMEL-26911).
*/
protected boolean colorsStripped() {
return printsToConsole() && AnsiConsole.out().getMode() == AnsiMode.Strip;
return printsToConsole() && (stripsColorsItself() || AnsiConsole.out().getMode() == AnsiMode.Strip);
}

/**
* Whether the command leaves out the colors itself, instead of the console. When the output is not a terminal, the
* console would leave them out too, but finding that out builds a JLine terminal, which costs more than most
* commands take to print (CAMEL-26937). Not when the console is told how to print the colors
* ({@code -Djansi.mode}).
*/
Comment thread
davsclaus marked this conversation as resolved.
Resolved
private static boolean stripsColorsItself() {
return !EnvironmentHelper.hasTerminal()
&& System.getProperty(AnsiConsole.JANSI_MODE) == null
&& System.getProperty(AnsiConsole.JANSI_OUT_MODE) == null;
}

// the text without the ANSI escape codes of its colors
private static String withoutColors(Object text) {
return ANSI_CODE.matcher(String.valueOf(text)).replaceAll("");
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@
import org.apache.camel.dsl.jbang.core.common.Plugin;
import org.apache.camel.dsl.jbang.core.common.PluginHelper;
import org.apache.camel.dsl.jbang.core.common.PluginType;
import org.apache.camel.dsl.jbang.run.common.CliLogging;
import org.apache.camel.dsl.jbang.run.common.Printer;
import org.apache.camel.util.json.JsonObject;

Expand Down Expand Up @@ -110,7 +111,12 @@ public class CamelJBangMain implements Command<CommandInvocation> {
// the plugins whose commands were added, to add them to a new command line too
private final List<Plugin> plugins = new CopyOnWriteArrayList<>();

/**
* The main method of the CLI that JBang runs (camel-jbang-main/dist/CamelJBang.java).
*/
public static void run(String... args) {
// before anything creates a logger
CliLogging.install();
run(new CamelJBangMain(), args);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
import org.apache.camel.dsl.jbang.core.common.CommandLineHelper;
import org.apache.camel.dsl.jbang.core.common.EnvironmentHelper;
import org.apache.camel.dsl.jbang.core.common.JsonOutput;
import org.apache.camel.dsl.jbang.run.common.CliLogging;
import org.apache.camel.dsl.jbang.run.common.Printer;
import org.apache.camel.dsl.jbang.run.common.RuntimeUtil;
import org.apache.camel.main.download.DependencyDownloaderClassLoader;
Expand Down Expand Up @@ -253,6 +254,7 @@ private Integer startService(
URL logConfig = InfraRun.class.getClassLoader().getResource("log4j2-infra.properties");
if (logConfig != null) {
Configurator.reconfigure(logConfig.toURI());
CliLogging.loggingConfigured();
}
String prefix = "";
if (testServiceImplementation != null) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/*
* 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.camel.dsl.jbang.core.commands;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;

import org.apache.camel.dsl.jbang.core.common.EnvironmentHelper;
import org.jline.jansi.Ansi;
import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assumptions.assumeFalse;

/**
* Without a terminal, a command prints its colored text without the colors itself, as the console would, without
* building the JLine terminal that the console needs to find that out (CAMEL-26937).
*/
class CamelCommandColorsTest {

@Test
void coloredTextWithoutTerminalIsPrintedWithoutColors() throws Exception {
assumeFalse(EnvironmentHelper.hasTerminal(), "runs without a terminal");

String out = printToConsole(new ColoredCommand(new CamelJBangMain()));

assertThat(out).isEqualTo("red and bold" + System.lineSeparator() + "plain");
}

@Test
void consoleStripsTheColorsWithoutTerminal() {
assumeFalse(EnvironmentHelper.hasTerminal(), "runs without a terminal");

assertThat(new ColoredCommand(new CamelJBangMain()).colorsStripped()).isTrue();
}

private static String printToConsole(CamelCommand command) throws Exception {
PrintStream previous = System.out;
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
System.setOut(new PrintStream(bytes, true, StandardCharsets.UTF_8));
try {
command.doCall();
} finally {
System.setOut(previous);
}
return bytes.toString(StandardCharsets.UTF_8);
}

private static final class ColoredCommand extends CamelCommand {

ColoredCommand(CamelJBangMain main) {
super(main);
}

@Override
public Integer doCall() {
printlnColored(Ansi.ansi().fgRed().a("red").reset().a(" and ").bold().a("bold").reset());
printColored(Ansi.ansi().a("plain"));
return 0;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
/*
* 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.camel.dsl.jbang.run.common;

import java.util.Deque;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;

import org.slf4j.ILoggerFactory;
import org.slf4j.IMarkerFactory;
import org.slf4j.Logger;
import org.slf4j.helpers.NOP_FallbackServiceProvider;
import org.slf4j.helpers.SubstituteLogger;
import org.slf4j.spi.MDCAdapter;
import org.slf4j.spi.SLF4JServiceProvider;

/**
* The SLF4J provider of a Camel CLI started from the command line: its loggers log nothing until the CLI configures the
* logging ({@link RuntimeUtil#configureLog}), and then log with the SLF4J provider on the classpath (log4j).
* <p/>
* Most commands, such as camel ps or camel get, turn the logging off, and something that only creates a logger (a
* static logger of a class of Camel) then made log4j start, which is about a third of such a command (CAMEL-26937).
* Log4j already logged nothing until the CLI configured it (CAMEL-26429), so the commands log as before. The main
* method of the CLI installs it, see {@link CliLogging#install()}.
*/
public final class CliLoggerProvider implements SLF4JServiceProvider {

private final CliLoggerFactory loggerFactory = new CliLoggerFactory();
private final MDCAdapter mdcAdapter = new CliMDCAdapter(this);
private final Supplier<SLF4JServiceProvider> delegateFinder;
private volatile SLF4JServiceProvider delegate;

/**
* The provider that SLF4J creates, as the system property {@code slf4j.provider} names it.
*/
public CliLoggerProvider() {
this(CliLoggerProvider::findProvider);
}

CliLoggerProvider(Supplier<SLF4JServiceProvider> delegateFinder) {
this.delegateFinder = delegateFinder;
}

/**
* The CLI configured the logging: from now on the loggers log with the provider on the classpath.
*/
void configured() {
loggerFactory.delegateTo(delegate().getLoggerFactory());
}

@Override
public void initialize() {
// SLF4J chose this provider, as something asked for a logger
CliLogging.bound(this::configured);
}

@Override
public ILoggerFactory getLoggerFactory() {
return loggerFactory;
}

@Override
public IMarkerFactory getMarkerFactory() {
return delegate().getMarkerFactory();
}

@Override
public MDCAdapter getMDCAdapter() {
// SLF4J asks for it when it chooses the provider, before anything logs
return mdcAdapter;
}

@Override
public String getRequestedApiVersion() {
return "2.0.99";
}

// the provider on the classpath, which is found as SLF4J would without this one
private SLF4JServiceProvider delegate() {
SLF4JServiceProvider answer = delegate;
if (answer == null) {
synchronized (this) {
answer = delegate;
if (answer == null) {
answer = delegateFinder.get();
answer.initialize();
delegate = answer;
}
}
}
return answer;
}

private static SLF4JServiceProvider findProvider() {
ClassLoader cl = CliLoggerProvider.class.getClassLoader();
for (SLF4JServiceProvider provider : ServiceLoader.load(SLF4JServiceProvider.class, cl)) {
if (!(provider instanceof CliLoggerProvider)) {
return provider;
}
}
return new NOP_FallbackServiceProvider();
}

/**
* The loggers created before the logging is configured stand in for the loggers of the provider on the classpath,
* which they log with once it is.
*/
static final class CliLoggerFactory implements ILoggerFactory {

private final Map<String, SubstituteLogger> loggers = new ConcurrentHashMap<>();
private volatile ILoggerFactory delegate;

@Override
public Logger getLogger(String name) {
ILoggerFactory factory = delegate;
if (factory != null) {
return factory.getLogger(name);
}
synchronized (this) {
factory = delegate;
if (factory != null) {
return factory.getLogger(name);
}
// a substitute logger without a delegate logs nothing
return loggers.computeIfAbsent(name, n -> new SubstituteLogger(n, null, true));
}
}

synchronized void delegateTo(ILoggerFactory factory) {
if (delegate == null) {
loggers.forEach((name, logger) -> logger.setDelegate(factory.getLogger(name)));
delegate = factory;
}
}
}

/**
* The MDC of the provider on the classpath, which its layouts read, created when something first uses the MDC.
*/
static final class CliMDCAdapter implements MDCAdapter {

private final CliLoggerProvider provider;

CliMDCAdapter(CliLoggerProvider provider) {
this.provider = provider;
}

private MDCAdapter adapter() {
return provider.delegate().getMDCAdapter();
}

@Override
public void put(String key, String val) {
adapter().put(key, val);
}

@Override
public String get(String key) {
return adapter().get(key);
}

@Override
public void remove(String key) {
adapter().remove(key);
}

@Override
public void clear() {
adapter().clear();
}

@Override
public Map<String, String> getCopyOfContextMap() {
return adapter().getCopyOfContextMap();
}

@Override
public void setContextMap(Map<String, String> contextMap) {
adapter().setContextMap(contextMap);
}

@Override
public void pushByKey(String key, String value) {
adapter().pushByKey(key, value);
}

@Override
public String popByKey(String key) {
return adapter().popByKey(key);
}

@Override
public Deque<String> getCopyOfDequeByKey(String key) {
return adapter().getCopyOfDequeByKey(key);
}

@Override
public void clearDequeByKey(String key) {
adapter().clearDequeByKey(key);
}
}
}
Loading
Loading