Skip to content

Commit

Permalink
Use module version of Console Launcher when on module path (#3847)
Browse files Browse the repository at this point in the history
+ Respect --disable-ansi-colors in --version output

Fixes #3827.

Co-authored-by: Christian Stein <[email protected]>
  • Loading branch information
marcphilipp and sormuras authored Jun 10, 2024
1 parent f1b2aae commit abf5ac3
Show file tree
Hide file tree
Showing 12 changed files with 131 additions and 29 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -99,4 +99,22 @@ public static Optional<String> getAttribute(Class<?> type, String name) {
return Optional.empty();
}
}

/**
* Get the module or implementation version for the supplied {@code type}.
* <p>
* The former is only available if the type is part of a versioned module on
* the module path; the latter only if the type is part of a JAR file with a
* manifest that contains an {@code Implementation-Version} attribute.
*
* @since 1.11
*/
@API(status = INTERNAL, since = "1.11")
public static Optional<String> getModuleOrImplementationVersion(Class<?> type) {
Optional<String> moduleVersion = ModuleUtils.getModuleVersion(type);
if (moduleVersion.isPresent()) {
return moduleVersion;
}
return getAttribute(type, Package::getImplementationVersion);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,23 +18,13 @@
import picocli.CommandLine.Option;
import picocli.CommandLine.Spec;

class OutputOptionsMixin {
class AnsiColorOptionMixin {

@Spec(MIXEE)
CommandSpec commandSpec;

@Option(names = "--disable-banner", description = "Disable print out of the welcome message.")
private boolean disableBanner;

@Option(names = "-disable-banner", hidden = true)
private boolean disableBanner2;

private boolean disableAnsiColors;

public boolean isDisableBanner() {
return disableBanner || disableBanner2;
}

public boolean isDisableAnsiColors() {
return disableAnsiColors;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/*
* Copyright 2015-2024 the original author or authors.
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v2.0 which
* accompanies this distribution and is available at
*
* https://www.eclipse.org/legal/epl-v20.html
*/

package org.junit.platform.console.options;

import picocli.CommandLine.Option;

class BannerOptionMixin {

@Option(names = "--disable-banner", description = "Disable print out of the welcome message.")
private boolean disableBanner;

@Option(names = "-disable-banner", hidden = true)
private boolean disableBanner2;

public boolean isDisableBanner() {
return disableBanner || disableBanner2;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,10 @@ abstract class BaseCommand<T> implements Callable<T> {
CommandSpec commandSpec;

@Mixin
OutputOptionsMixin outputOptions;
AnsiColorOptionMixin ansiColorOption;

@Mixin
BannerOptionMixin bannerOption;

@SuppressWarnings("unused")
@Option(names = { "-h", "--help" }, usageHelp = true, description = "Display help information.")
Expand Down Expand Up @@ -71,7 +74,7 @@ static CommandLine initialize(CommandLine commandLine) {
@Override
public final T call() {
PrintWriter out = getOut();
if (!outputOptions.isDisableBanner()) {
if (!bannerOption.isDisableBanner()) {
displayBanner(out);
}
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import static org.apiguardian.api.API.Status.INTERNAL;

import java.io.PrintWriter;
import java.util.Optional;

import org.apiguardian.api.API;
import org.junit.platform.console.tasks.ConsoleTestExecutor;
Expand All @@ -33,9 +34,9 @@ public CommandFacade(ConsoleTestExecutor.Factory consoleTestExecutorFactory) {
}

public CommandResult<?> run(PrintWriter out, PrintWriter err, String[] args) {
String version = ManifestVersionProvider.getImplementationVersion();
Optional<String> version = ManifestVersionProvider.getImplementationVersion();
System.setProperty("junit.docs.version",
version == null ? "current" : (version.endsWith("-SNAPSHOT") ? "snapshot" : version));
version.map(it -> it.endsWith("-SNAPSHOT") ? "snapshot" : it).orElse("current"));
return new MainCommand(consoleTestExecutorFactory).run(out, err, args);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ class DiscoverTestsCommand extends BaseCommand<Void> {
protected Void execute(PrintWriter out) {
TestDiscoveryOptions discoveryOptions = this.discoveryOptions.toTestDiscoveryOptions();
TestConsoleOutputOptions testOutputOptions = this.testOutputOptions.toTestConsoleOutputOptions();
testOutputOptions.setAnsiColorOutputDisabled(outputOptions.isDisableAnsiColors());
consoleTestExecutorFactory.create(discoveryOptions, testOutputOptions).discover(out);
testOutputOptions.setAnsiColorOutputDisabled(this.ansiColorOption.isDisableAnsiColors());
this.consoleTestExecutorFactory.create(discoveryOptions, testOutputOptions).discover(out);
return null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ TestDiscoveryOptions toTestDiscoveryOptions() {

TestConsoleOutputOptions toTestConsoleOutputOptions() {
TestConsoleOutputOptions testOutputOptions = this.testOutputOptions.toTestConsoleOutputOptions();
testOutputOptions.setAnsiColorOutputDisabled(outputOptions.isDisableAnsiColors());
testOutputOptions.setAnsiColorOutputDisabled(this.ansiColorOption.isDisableAnsiColors());
return testOutputOptions;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import picocli.CommandLine.Command;
import picocli.CommandLine.Help.ColorScheme;
import picocli.CommandLine.IExitCodeGenerator;
import picocli.CommandLine.Mixin;
import picocli.CommandLine.Model.CommandSpec;
import picocli.CommandLine.Option;
import picocli.CommandLine.Spec;
Expand Down Expand Up @@ -56,6 +57,9 @@ class MainCommand implements Callable<Object>, IExitCodeGenerator {
@Option(names = "--version", versionHelp = true, description = "Display version information.")
private boolean versionHelpRequested;

@Mixin
AnsiColorOptionMixin ansiColorOption;

@Unmatched
private final List<String> allParameters = new ArrayList<>();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,23 @@

package org.junit.platform.console.options;

import java.util.Optional;

import org.junit.platform.commons.util.PackageUtils;

import picocli.CommandLine;

class ManifestVersionProvider implements CommandLine.IVersionProvider {

public static String getImplementationVersion() {
return ManifestVersionProvider.class.getPackage().getImplementationVersion();
public static Optional<String> getImplementationVersion() {
return PackageUtils.getModuleOrImplementationVersion(ManifestVersionProvider.class);
}

@Override
public String[] getVersion() {
return new String[] { //
String.format("@|bold JUnit Platform Console Launcher %s|@", getImplementationVersion()), //
String.format("@|bold JUnit Platform Console Launcher %s|@",
getImplementationVersion().orElse("<unknown>")), //
"JVM: ${java.version} (${java.vendor} ${java.vm.name} ${java.vm.version})", //
"OS: ${os.name} ${os.version} ${os.arch}" //
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -186,12 +186,7 @@ default Optional<String> getVersion() {
if (standalone.isPresent()) {
return standalone;
}
String fallback = "DEVELOPMENT";
Optional<String> moduleVersion = ModuleUtils.getModuleVersion(getClass());
if (moduleVersion.isPresent()) {
return moduleVersion;
}
return Optional.of(PackageUtils.getAttribute(getClass(), Package::getImplementationVersion).orElse(fallback));
return Optional.of(PackageUtils.getModuleOrImplementationVersion(getClass()).orElse("DEVELOPMENT"));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,15 @@ private ThirdPartyJars() {
}

public static void copy(Path targetDir, String group, String artifact) throws Exception {
Path source = Stream.of(System.getProperty("thirdPartyJars").split(File.pathSeparator)) //
Path source = find(group, artifact);
Files.copy(source, targetDir.resolve(source.getFileName()), REPLACE_EXISTING);
}

public static Path find(String group, String artifact) {
return Stream.of(System.getProperty("thirdPartyJars").split(File.pathSeparator)) //
.filter(it -> it.replace(File.separator, "/").contains("/" + group + "/" + artifact + "/")) //
.map(Path::of) //
.findFirst() //
.orElseThrow(() -> new AssertionError("Failed to find JAR file for " + group + ":" + artifact));
Files.copy(source, targetDir.resolve(source.getFileName()), REPLACE_EXISTING);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

package platform.tooling.support.tests;

import static java.util.stream.Collectors.joining;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertLinesMatch;
Expand All @@ -22,6 +23,7 @@
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

import de.sormuras.bartholdy.Result;
import de.sormuras.bartholdy.jdk.Jar;
Expand All @@ -38,6 +40,7 @@
import platform.tooling.support.Helper;
import platform.tooling.support.MavenRepo;
import platform.tooling.support.Request;
import platform.tooling.support.ThirdPartyJars;

/**
* @since 1.4
Expand Down Expand Up @@ -83,6 +86,58 @@ void listAllObservableEngines() {
result.getOutput("out").lines());
}

@Test
void printVersionViaJar() {
var result = Request.builder() //
.setTool(new Java()) //
.setProject("standalone") //
.addArguments("-jar", MavenRepo.jar("junit-platform-console-standalone")) //
.addArguments("--version", "--disable-ansi-colors") //
.putEnvironment("CLICOLOR_FORCE", "1") // enable ANSI colors by default (see https://picocli.info/#_heuristics_for_enabling_ansi)
.build() //
.run();

assertEquals(0, result.getExitCode(), () -> getExitCodeMessage(result));

var version = Helper.version("junit-platform-console");
assertLinesMatch("""
JUnit Platform Console Launcher %s
JVM: .*
OS: .*
""".formatted(version).lines(), //
result.getOutputLines("out").stream());
}

@Test
void printVersionViaModule() {
var junitJars = Stream.of("junit-platform-console", "junit-platform-reporting", "junit-platform-engine",
"junit-platform-launcher", "junit-platform-commons") //
.map(MavenRepo::jar);
var thirdPartyJars = Stream.of(ThirdPartyJars.find("org.opentest4j", "opentest4j"));
var modulePath = Stream.concat(junitJars, thirdPartyJars) //
.map(String::valueOf) //
.collect(joining(File.pathSeparator));
var result = Request.builder() //
.setTool(new Java()) //
.setProject("standalone") //
.addArguments("--module-path", modulePath) //
.addArguments("--module", "org.junit.platform.console") //
.addArguments("--version", "--disable-ansi-colors") //
.putEnvironment("CLICOLOR_FORCE", "1") // enable ANSI colors by default (see https://picocli.info/#_heuristics_for_enabling_ansi)
.build() //
.run();

assertEquals(0, result.getExitCode(), () -> getExitCodeMessage(result));

var version = Helper.version("junit-platform-console");
assertLinesMatch("""
JUnit Platform Console Launcher %s
JVM: .*
OS: .*
""".formatted(version).lines(), //
result.getOutputLines("out").stream());
}

@Test
@Order(1)
void compile() throws Exception {
Expand Down

0 comments on commit abf5ac3

Please sign in to comment.