This is an automated email from the ASF dual-hosted git repository. slachiewicz pushed a commit to branch master in repository https://gitbox.apache.org/repos/asf/maven-surefire.git
commit 670f7c8cd1b0a9f7fb04e7c8cc05e04aa901c099 Author: Sylwester Lachiewicz <[email protected]> AuthorDate: Sun Nov 8 14:32:59 2026 +0000 Launch the forked JVM with ProcessBuilder The fork no longer goes through /bin/sh -c or cmd.exe /C: Surefire's own Commandline builds a ProcessBuilder, so the JVM is the direct child and the shell quoting rules never apply to the classpath or argLine. The quote-aware argLine splitting is kept (translateCommandline, copied from maven-shared-utils), and ShutdownHookUtils moves into surefire-api. Start failures surface as IOException instead of CommandLineException. Part of #3574. --- .../plugin/surefire/AbstractSurefireMojo.java | 4 +- .../booterclient/DefaultForkConfiguration.java | 4 +- .../plugin/surefire/booterclient/ForkStarter.java | 6 +- .../booterclient/lazytestprovider/Commandline.java | 35 +-- .../apache/maven/surefire/stream/EventDecoder.java | 2 +- .../booterclient/ForkConfigurationTest.java | 29 +-- .../lazytestprovider/CommandlineTest.java | 10 +- .../api/util/internal/ShutdownHookUtils.java | 44 ++++ .../apache/maven/surefire/booter/ForkedBooter.java | 2 +- .../surefire/booter/stream/CommandDecoder.java | 2 +- .../surefire/booter/ForkedBooterMockTest.java | 2 +- .../surefire/extensions/util/Commandline.java | 283 +++++++++++++++++++++ .../extensions/util/CommandlineExecutor.java | 12 +- .../extensions/CommandlineExecutorTest.java | 4 +- 14 files changed, 368 insertions(+), 71 deletions(-) diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/AbstractSurefireMojo.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/AbstractSurefireMojo.java index 9ed719ae7..e5011324b 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/AbstractSurefireMojo.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/AbstractSurefireMojo.java @@ -145,6 +145,8 @@ import static org.apache.maven.surefire.api.booter.ProviderParameterNames.RUN_ORDER_RANDOM_SEED_PROP; import static org.apache.maven.surefire.api.suite.RunResult.failure; import static org.apache.maven.surefire.api.suite.RunResult.noTestsRun; +import static org.apache.maven.surefire.api.util.internal.ShutdownHookUtils.addShutDownHook; +import static org.apache.maven.surefire.api.util.internal.ShutdownHookUtils.removeShutdownHook; import static org.apache.maven.surefire.booter.SystemUtils.endsWithJavaPath; import static org.apache.maven.surefire.booter.SystemUtils.isBuiltInJava9AtLeast; import static org.apache.maven.surefire.booter.SystemUtils.isJava9AtLeast; @@ -158,8 +160,6 @@ import static org.apache.maven.surefire.shared.lang3.StringUtils.split; import static org.apache.maven.surefire.shared.lang3.StringUtils.substringBeforeLast; import static org.apache.maven.surefire.shared.lang3.SystemUtils.IS_OS_WINDOWS; -import static org.apache.maven.surefire.shared.utils.cli.ShutdownHookUtils.addShutDownHook; -import static org.apache.maven.surefire.shared.utils.cli.ShutdownHookUtils.removeShutdownHook; /** * Abstract base class for running tests using Surefire. diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/DefaultForkConfiguration.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/DefaultForkConfiguration.java index dffe59d56..c590adde7 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/DefaultForkConfiguration.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/DefaultForkConfiguration.java @@ -37,7 +37,6 @@ import org.apache.maven.surefire.booter.StartupConfiguration; import org.apache.maven.surefire.booter.SurefireBooterForkException; import org.apache.maven.surefire.extensions.ForkNodeFactory; -import org.apache.maven.surefire.shared.utils.cli.CommandLineException; import static org.apache.maven.plugin.surefire.SurefireHelper.replaceForkThreadsInPath; import static org.apache.maven.plugin.surefire.SurefireHelper.replaceThreadNumberPlaceholders; @@ -178,7 +177,8 @@ public Commandline createCommandLine( resolveClasspath(cli, findStartClass(config), config, getWorkingDirectory(forkNumber), dumpLogDirectory); return cli; - } catch (CommandLineException e) { + } catch (IllegalArgumentException e) { + // unbalanced quotes in argLine or the debug line throw new SurefireBooterForkException(e.getLocalizedMessage(), e); } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/ForkStarter.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/ForkStarter.java index 76826121a..0e3b1b286 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/ForkStarter.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/ForkStarter.java @@ -114,12 +114,12 @@ import static org.apache.maven.surefire.api.util.internal.ConcurrencyUtils.runIfZeroCountDown; import static org.apache.maven.surefire.api.util.internal.DaemonThreadFactory.newDaemonThread; import static org.apache.maven.surefire.api.util.internal.DaemonThreadFactory.newDaemonThreadFactory; +import static org.apache.maven.surefire.api.util.internal.ShutdownHookUtils.addShutDownHook; +import static org.apache.maven.surefire.api.util.internal.ShutdownHookUtils.removeShutdownHook; import static org.apache.maven.surefire.api.util.internal.StringUtils.NL; import static org.apache.maven.surefire.booter.SystemPropertyManager.writePropertiesFile; import static org.apache.maven.surefire.booter.SystemUtils.forkedJvmPidOf; import static org.apache.maven.surefire.booter.SystemUtils.toJdkHomeFromJre; -import static org.apache.maven.surefire.shared.utils.cli.ShutdownHookUtils.addShutDownHook; -import static org.apache.maven.surefire.shared.utils.cli.ShutdownHookUtils.removeShutdownHook; /** * Starts the fork or runs in-process. @@ -670,7 +670,7 @@ private RunResult fork( err.disable(); } } catch (Exception e) { - // CommandLineException from pipes and IOException from sockets + // IOException from the process start, the pipes or the sockets runResult = failure(reporter.getGlobalRunStatistics().getRunResult(), e); String cliErr = e.getLocalizedMessage(); Throwable cause = e.getCause(); diff --git a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/Commandline.java b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/Commandline.java index d1f06052f..64db74a6c 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/Commandline.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/Commandline.java @@ -18,21 +18,16 @@ */ package org.apache.maven.plugin.surefire.booterclient.lazytestprovider; -import java.util.Arrays; import java.util.Collection; import java.util.Collections; -import java.util.HashSet; -import java.util.Set; +import java.util.Map; import java.util.concurrent.ConcurrentLinkedDeque; /** - * A {@link org.apache.maven.surefire.shared.utils.cli.Commandline} implementation. - * - * @author Andreas Gudian + * The forked JVM's command line: the environment of this JVM without the excluded variables, plus the added ones. */ -public class Commandline extends org.apache.maven.surefire.shared.utils.cli.Commandline { +public class Commandline extends org.apache.maven.surefire.extensions.util.Commandline { private final Collection<String> excludedEnvironmentVariables; - private final Set<String> addedEnvironmentVariables; /** * For testing purposes only. @@ -43,29 +38,13 @@ public Commandline() { public Commandline(String[] excludedEnvironmentVariables) { this.excludedEnvironmentVariables = new ConcurrentLinkedDeque<>(); - this.addedEnvironmentVariables = new HashSet<>(); Collections.addAll(this.excludedEnvironmentVariables, excludedEnvironmentVariables); } @Override - public void addEnvironment(String name, String value) { - super.addEnvironment(name, value); - addedEnvironmentVariables.add(name); - } - - @Override - public String[] getEnvironmentVariables() { - String[] envs = super.getEnvironmentVariables(); - Set<String> result = new HashSet<>(Arrays.asList(envs)); - result.addAll(addedEnvironmentVariables); - return excludedEnvironmentVariables.isEmpty() - ? result.toArray(new String[0]) - : result.stream() - .filter(env -> { - String varName = - env != null && env.contains("=") ? env.substring(0, env.indexOf('=')) : env; - return !excludedEnvironmentVariables.contains(varName); - }) - .toArray(String[]::new); + protected Map<String, String> environment() { + Map<String, String> env = super.environment(); + env.keySet().removeAll(excludedEnvironmentVariables); + return env; } } diff --git a/maven-surefire-common/src/main/java/org/apache/maven/surefire/stream/EventDecoder.java b/maven-surefire-common/src/main/java/org/apache/maven/surefire/stream/EventDecoder.java index 2f641778a..8904bfc5a 100644 --- a/maven-surefire-common/src/main/java/org/apache/maven/surefire/stream/EventDecoder.java +++ b/maven-surefire-common/src/main/java/org/apache/maven/surefire/stream/EventDecoder.java @@ -72,7 +72,7 @@ import static org.apache.maven.surefire.api.stream.SegmentType.RUN_MODE; import static org.apache.maven.surefire.api.stream.SegmentType.STRING_ENCODING; import static org.apache.maven.surefire.api.stream.SegmentType.TEST_RUN_ID; -import static org.apache.maven.surefire.shared.utils.cli.ShutdownHookUtils.addShutDownHook; +import static org.apache.maven.surefire.api.util.internal.ShutdownHookUtils.addShutDownHook; public class EventDecoder extends AbstractStreamDecoder<Event, ForkedProcessEventType, SegmentType> { private static final int DEBUG_SINK_BUFFER_SIZE = 64 * 1024; diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/ForkConfigurationTest.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/ForkConfigurationTest.java index fbd602519..1324872c1 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/ForkConfigurationTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/ForkConfigurationTest.java @@ -140,8 +140,7 @@ protected void resolveClasspath( ClassLoaderConfiguration clc = new ClassLoaderConfiguration(true, true); StartupConfiguration startup = new StartupConfiguration("cls", cpConfig, clc, ALL, providerJpmsArgs); - org.apache.maven.surefire.shared.utils.cli.Commandline cli = - config.createCommandLine(startup, 1, getTempDirectory()); + Commandline cli = config.createCommandLine(startup, 1, getTempDirectory()); assertThat(cli.getEnvironmentVariables()) .contains("key1=val1", "key2=val2", "key3=val3") @@ -195,16 +194,14 @@ protected void resolveClasspath( ClassLoaderConfiguration clc = new ClassLoaderConfiguration(true, true); StartupConfiguration startup = new StartupConfiguration("cls", cpConfig, clc, ALL, providerJpmsArgs); - org.apache.maven.surefire.shared.utils.cli.Commandline cliFork1 = - config.createCommandLine(startup, 1, getTempDirectory()); + Commandline cliFork1 = config.createCommandLine(startup, 1, getTempDirectory()); assertThat(cliFork1.getEnvironmentVariables()) .contains("FORK_ID=1") .doesNotContain("PATH=") .doesNotHaveDuplicates(); - org.apache.maven.surefire.shared.utils.cli.Commandline cliFork2 = - config.createCommandLine(startup, 2, getTempDirectory()); + Commandline cliFork2 = config.createCommandLine(startup, 2, getTempDirectory()); assertThat(cliFork2.getEnvironmentVariables()) .contains("FORK_ID=2") @@ -245,8 +242,7 @@ public void testCliArgs() throws Exception { ClassLoaderConfiguration clc = new ClassLoaderConfiguration(true, true); StartupConfiguration startup = new StartupConfiguration("cls", cpConfig, clc, ALL, providerJpmsArgs); - org.apache.maven.surefire.shared.utils.cli.Commandline cli = - config.createCommandLine(startup, 1, getTempDirectory()); + Commandline cli = config.createCommandLine(startup, 1, getTempDirectory()); String cliAsString = cli.toString(); assertThat(cliAsString).contains("arg1"); @@ -321,8 +317,7 @@ protected void resolveClasspath( assertThat(startup.isShadefire()).isFalse(); - org.apache.maven.surefire.shared.utils.cli.Commandline cli = - config.createCommandLine(startup, 1, getTempDirectory()); + Commandline cli = config.createCommandLine(startup, 1, getTempDirectory()); assertThat(cli.toString()).contains("-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005"); } @@ -341,8 +336,7 @@ public void testCreateCommandLine_UseSystemClassLoaderForkOnce_ShouldConstructMa StartupConfiguration startup = new StartupConfiguration("", cpConfig, clc, ALL, Collections.<String[]>emptyList()); - org.apache.maven.surefire.shared.utils.cli.Commandline cli = - config.createCommandLine(startup, 1, getTempDirectory()); + Commandline cli = config.createCommandLine(startup, 1, getTempDirectory()); String line = join(" ", cli.getCommandline()); assertTrue(line.contains("-jar")); @@ -361,8 +355,7 @@ public void testArglineWithNewline() throws IOException, SurefireBooterForkExcep StartupConfiguration startup = new StartupConfiguration("", cpConfig, clc, ALL, Collections.<String[]>emptyList()); - org.apache.maven.surefire.shared.utils.cli.Commandline commandLine = - config.createCommandLine(startup, 1, getTempDirectory()); + Commandline commandLine = config.createCommandLine(startup, 1, getTempDirectory()); assertThat(commandLine.toString()).contains(IS_OS_WINDOWS ? "abc def" : "'abc' 'def'"); } @@ -377,12 +370,11 @@ public void testCurrentWorkingDirectoryPropagationIncludingForkNumberExpansion() StartupConfiguration startup = new StartupConfiguration("", cpConfig, clc, ALL, Collections.<String[]>emptyList()); ForkConfiguration config = getForkConfiguration(cwd.getCanonicalFile()); - org.apache.maven.surefire.shared.utils.cli.Commandline commandLine = - config.createCommandLine(startup, 1, getTempDirectory()); + Commandline commandLine = config.createCommandLine(startup, 1, getTempDirectory()); File forkDirectory = new File(basedir, "fork_1"); - String shellWorkDir = commandLine.getShell().getWorkingDirectory().getCanonicalPath(); + String shellWorkDir = commandLine.getWorkingDirectory().getCanonicalPath(); assertEquals(shellWorkDir, forkDirectory.getCanonicalPath()); } @@ -500,8 +492,7 @@ public void testRelativeClasspathElementResolvedAgainstWorkingDirectory() new StartupConfiguration("", cpConfig, clc, ALL, Collections.<String[]>emptyList()); ForkConfiguration config = getForkConfiguration(workingDir.getCanonicalFile()); - org.apache.maven.surefire.shared.utils.cli.Commandline cli = - config.createCommandLine(startup, 1, getTempDirectory()); + Commandline cli = config.createCommandLine(startup, 1, getTempDirectory()); // The command line must use -jar (manifest-only JAR mode) String line = join(" ", cli.getCommandline()); diff --git a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/CommandlineTest.java b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/CommandlineTest.java index af93c64dc..b6f2354e3 100644 --- a/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/CommandlineTest.java +++ b/maven-surefire-common/src/test/java/org/apache/maven/plugin/surefire/booterclient/lazytestprovider/CommandlineTest.java @@ -18,7 +18,6 @@ */ package org.apache.maven.plugin.surefire.booterclient.lazytestprovider; -import org.apache.maven.surefire.shared.utils.cli.CommandLineException; import org.junit.jupiter.api.Test; import static org.apache.maven.surefire.shared.lang3.SystemUtils.IS_OS_WINDOWS; @@ -43,10 +42,13 @@ public void shouldGetEnvironmentVariables() { } @Test - public void shouldExecute() throws CommandLineException { + public void shouldExecute() throws Exception { Commandline cli = new Commandline(); - cli.getShell().setWorkingDirectory(System.getProperty("user.dir")); - cli.getShell().setExecutable(IS_OS_WINDOWS ? "dir" : "ls"); + cli.setWorkingDirectory(System.getProperty("user.dir")); + cli.setExecutable(IS_OS_WINDOWS ? "cmd.exe" : "ls"); + if (IS_OS_WINDOWS) { + cli.addArguments("/c", "dir"); + } cli.execute(); } } diff --git a/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/ShutdownHookUtils.java b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/ShutdownHookUtils.java new file mode 100644 index 000000000..e9765f0b1 --- /dev/null +++ b/surefire-api/src/main/java/org/apache/maven/surefire/api/util/internal/ShutdownHookUtils.java @@ -0,0 +1,44 @@ +/* + * 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.surefire.api.util.internal; + +/** + * Registers and removes JVM shutdown hooks, ignoring the failures that are harmless at that point: the JVM is + * already shutting down, or a security manager forbids it. + */ +public final class ShutdownHookUtils { + + private ShutdownHookUtils() {} + + public static void addShutDownHook(Thread hook) { + try { + Runtime.getRuntime().addShutdownHook(hook); + } catch (IllegalStateException | SecurityException ignore) { + // the JVM is shutting down, or hooks are not allowed + } + } + + public static void removeShutdownHook(Thread hook) { + try { + Runtime.getRuntime().removeShutdownHook(hook); + } catch (IllegalStateException | SecurityException ignore) { + // the JVM is shutting down, or hooks are not allowed + } + } +} diff --git a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/ForkedBooter.java b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/ForkedBooter.java index 85ca891d3..d03437f40 100644 --- a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/ForkedBooter.java +++ b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/ForkedBooter.java @@ -53,9 +53,9 @@ import org.apache.maven.surefire.api.provider.SurefireProvider; import org.apache.maven.surefire.api.report.StackTraceProvider; import org.apache.maven.surefire.api.testset.TestSetFailedException; +import org.apache.maven.surefire.api.util.internal.ShutdownHookUtils; import org.apache.maven.surefire.booter.spi.LegacyMasterProcessChannelProcessorFactory; import org.apache.maven.surefire.booter.spi.SurefireMasterProcessChannelProcessorFactory; -import org.apache.maven.surefire.shared.utils.cli.ShutdownHookUtils; import org.apache.maven.surefire.spi.MasterProcessChannelProcessorFactory; import static java.lang.Thread.currentThread; diff --git a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/stream/CommandDecoder.java b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/stream/CommandDecoder.java index 41dffc26c..6968b877b 100644 --- a/surefire-booter/src/main/java/org/apache/maven/surefire/booter/stream/CommandDecoder.java +++ b/surefire-booter/src/main/java/org/apache/maven/surefire/booter/stream/CommandDecoder.java @@ -48,7 +48,7 @@ import static org.apache.maven.surefire.api.stream.SegmentType.DATA_STRING; import static org.apache.maven.surefire.api.stream.SegmentType.END_OF_FRAME; import static org.apache.maven.surefire.api.stream.SegmentType.STRING_ENCODING; -import static org.apache.maven.surefire.shared.utils.cli.ShutdownHookUtils.addShutDownHook; +import static org.apache.maven.surefire.api.util.internal.ShutdownHookUtils.addShutDownHook; public class CommandDecoder extends AbstractStreamDecoder<Command, MasterProcessCommand, SegmentType> { private static final int DEBUG_SINK_BUFFER_SIZE = 64 * 1024; diff --git a/surefire-booter/src/test/java/org/apache/maven/surefire/booter/ForkedBooterMockTest.java b/surefire-booter/src/test/java/org/apache/maven/surefire/booter/ForkedBooterMockTest.java index b02b87f6a..f0a30706e 100644 --- a/surefire-booter/src/test/java/org/apache/maven/surefire/booter/ForkedBooterMockTest.java +++ b/surefire-booter/src/test/java/org/apache/maven/surefire/booter/ForkedBooterMockTest.java @@ -42,13 +42,13 @@ import org.apache.maven.surefire.api.booter.MasterProcessChannelDecoder; import org.apache.maven.surefire.api.booter.MasterProcessChannelEncoder; import org.apache.maven.surefire.api.fork.ForkNodeArguments; +import org.apache.maven.surefire.api.util.internal.ShutdownHookUtils; import org.apache.maven.surefire.api.util.internal.WritableBufferedByteChannel; import org.apache.maven.surefire.booter.spi.AbstractMasterProcessChannelProcessorFactory; import org.apache.maven.surefire.booter.spi.CommandChannelDecoder; import org.apache.maven.surefire.booter.spi.EventChannelEncoder; import org.apache.maven.surefire.booter.spi.LegacyMasterProcessChannelProcessorFactory; import org.apache.maven.surefire.booter.spi.SurefireMasterProcessChannelProcessorFactory; -import org.apache.maven.surefire.shared.utils.cli.ShutdownHookUtils; import org.apache.maven.surefire.spi.MasterProcessChannelProcessorFactory; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; diff --git a/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/util/Commandline.java b/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/util/Commandline.java new file mode 100644 index 000000000..e013bf9ca --- /dev/null +++ b/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/util/Commandline.java @@ -0,0 +1,283 @@ +/* + * 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.surefire.extensions.util; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.StringTokenizer; + +/** + * The command line of a process Surefire starts: an executable, its arguments, the environment and the working + * directory, started with {@link ProcessBuilder}. The process is a direct child; there is no shell in between. + */ +public class Commandline { + private static final boolean WINDOWS = + System.getProperty("os.name", "").toLowerCase(java.util.Locale.ROOT).startsWith("windows"); + + private String executable; + private final List<String> arguments = new ArrayList<>(); + private final Map<String, String> addedEnvironment = new LinkedHashMap<>(); + private File workingDirectory; + + public Commandline() {} + + /** + * @param commandLine the executable followed by its arguments, split like a shell would, see + * {@link #translateCommandline(String)} + */ + public Commandline(String commandLine) { + String[] parts = translateCommandline(commandLine); + if (parts.length > 0) { + executable = parts[0]; + arguments.addAll(java.util.Arrays.asList(parts).subList(1, parts.length)); + } + } + + public void setExecutable(String executable) { + this.executable = executable; + } + + public String getExecutable() { + return executable; + } + + public Argument createArg() { + return new Argument(); + } + + public void addArgument(String argument) { + arguments.add(argument); + } + + public void addArguments(String... args) { + Collections.addAll(arguments, args); + } + + /** + * @return the arguments, without the executable + */ + public String[] getArguments() { + return arguments.toArray(new String[0]); + } + + /** + * @return the executable followed by the arguments + */ + public String[] getCommandline() { + List<String> all = new ArrayList<>(arguments.size() + 1); + all.add(executable); + all.addAll(arguments); + return all.toArray(new String[0]); + } + + public void setWorkingDirectory(String path) { + this.workingDirectory = path == null ? null : new File(path); + } + + public void setWorkingDirectory(File workingDirectory) { + this.workingDirectory = workingDirectory; + } + + public File getWorkingDirectory() { + return workingDirectory; + } + + public void addEnvironment(String name, String value) { + addedEnvironment.put(name, value); + } + + /** + * The environment the process gets: the environment of this JVM, with {@link #addEnvironment added} variables + * overriding it. Subclasses may remove variables. + * + * @return a mutable copy + */ + protected Map<String, String> environment() { + Map<String, String> env = new LinkedHashMap<>(System.getenv()); + env.putAll(addedEnvironment); + return env; + } + + /** + * @return the environment of the process as {@code NAME=value} entries + */ + public String[] getEnvironmentVariables() { + Map<String, String> env = environment(); + String[] result = new String[env.size()]; + int i = 0; + for (Map.Entry<String, String> e : env.entrySet()) { + result[i++] = e.getKey() + "=" + e.getValue(); + } + return result; + } + + public ProcessBuilder toProcessBuilder() { + ProcessBuilder builder = new ProcessBuilder(getCommandline()); + builder.directory(workingDirectory); + Map<String, String> env = builder.environment(); + env.clear(); + env.putAll(environment()); + return builder; + } + + public Process execute() throws IOException { + return toProcessBuilder().start(); + } + + /** + * The command line as text, each item quoted: single quotes on Unix, double quotes on Windows. + */ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + for (String item : getCommandline()) { + if (sb.length() > 0) { + sb.append(' '); + } + if (WINDOWS) { + sb.append('"') + .append(item == null ? "" : item.replace("\"", "\\\"")) + .append('"'); + } else { + sb.append('\'') + .append(item == null ? "" : item.replace("'", "'\"'\"'")) + .append('\''); + } + } + return sb.toString(); + } + + /** + * Splits a command line into arguments like a shell would: whitespace separates, single or double quotes + * group, a backslash escapes the next character. + * + * @throws IllegalArgumentException on unbalanced quotes + */ + public static String[] translateCommandline(String toProcess) { + if (toProcess == null || toProcess.isEmpty()) { + return new String[0]; + } + + final int normal = 0; + final int inQuote = 1; + final int inDoubleQuote = 2; + boolean inEscape = false; + int state = normal; + final StringTokenizer tok = new StringTokenizer(toProcess, "\"' \\", true); + List<String> tokens = new ArrayList<>(); + StringBuilder current = new StringBuilder(); + + while (tok.hasMoreTokens()) { + String nextTok = tok.nextToken(); + switch (state) { + case inQuote: + if ("'".equals(nextTok)) { + if (inEscape) { + current.append(nextTok); + inEscape = false; + } else { + state = normal; + } + } else { + current.append(nextTok); + inEscape = "\\".equals(nextTok); + } + break; + case inDoubleQuote: + if ("\"".equals(nextTok)) { + if (inEscape) { + current.append(nextTok); + inEscape = false; + } else { + state = normal; + } + } else { + current.append(nextTok); + inEscape = "\\".equals(nextTok); + } + break; + default: + if ("'".equals(nextTok)) { + if (inEscape) { + inEscape = false; + current.append(nextTok); + } else { + state = inQuote; + } + } else if ("\"".equals(nextTok)) { + if (inEscape) { + inEscape = false; + current.append(nextTok); + } else { + state = inDoubleQuote; + } + } else if (" ".equals(nextTok)) { + if (current.length() != 0) { + tokens.add(current.toString()); + current.setLength(0); + } + } else { + current.append(nextTok); + inEscape = "\\".equals(nextTok); + } + break; + } + } + + if (current.length() != 0) { + tokens.add(current.toString()); + } + + if (state == inQuote || state == inDoubleQuote) { + throw new IllegalArgumentException("unbalanced quotes in " + toProcess); + } + + return tokens.toArray(new String[0]); + } + + /** + * One argument being added, as {@code createArg().setValue(..)} or {@code setLine(..)}. + */ + public final class Argument { + private Argument() {} + + public void setValue(String value) { + arguments.add(value); + } + + public void setFile(File file) { + arguments.add(file.getAbsolutePath()); + } + + /** + * @param line a line split into arguments like a shell would + * @throws IllegalArgumentException on unbalanced quotes + */ + public void setLine(String line) { + if (line != null) { + Collections.addAll(arguments, translateCommandline(line)); + } + } + } +} diff --git a/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/util/CommandlineExecutor.java b/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/util/CommandlineExecutor.java index d2ea07e57..73dc4d453 100644 --- a/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/util/CommandlineExecutor.java +++ b/surefire-extensions-api/src/main/java/org/apache/maven/surefire/extensions/util/CommandlineExecutor.java @@ -19,12 +19,10 @@ package org.apache.maven.surefire.extensions.util; import java.io.Closeable; +import java.io.IOException; -import org.apache.maven.surefire.shared.utils.cli.CommandLineException; -import org.apache.maven.surefire.shared.utils.cli.Commandline; - -import static org.apache.maven.surefire.shared.utils.cli.ShutdownHookUtils.addShutDownHook; -import static org.apache.maven.surefire.shared.utils.cli.ShutdownHookUtils.removeShutdownHook; +import static org.apache.maven.surefire.api.util.internal.ShutdownHookUtils.addShutDownHook; +import static org.apache.maven.surefire.api.util.internal.ShutdownHookUtils.removeShutdownHook; /** * Programming model with this class: @@ -51,7 +49,7 @@ * { * lineConsumerThread.disable(); * } - * catch ( CommandLineException e ) + * catch ( IOException e ) * { * // handle the exceptions * } @@ -72,7 +70,7 @@ public CommandlineExecutor(Commandline cli, CountdownCloseable endOfStreamsCount this.endOfStreamsCountdown = endOfStreamsCountdown; } - public CommandlineStreams execute() throws CommandLineException { + public CommandlineStreams execute() throws IOException { process = cli.execute(); shutdownHook = new ProcessHook(process); addShutDownHook(shutdownHook); diff --git a/surefire-extensions-api/src/test/java/org/apache/maven/plugin/surefire/extensions/CommandlineExecutorTest.java b/surefire-extensions-api/src/test/java/org/apache/maven/plugin/surefire/extensions/CommandlineExecutorTest.java index d7d4946f9..185215fc5 100644 --- a/surefire-extensions-api/src/test/java/org/apache/maven/plugin/surefire/extensions/CommandlineExecutorTest.java +++ b/surefire-extensions-api/src/test/java/org/apache/maven/plugin/surefire/extensions/CommandlineExecutorTest.java @@ -22,11 +22,11 @@ import java.nio.file.Paths; import org.apache.maven.surefire.extensions.EventHandler; +import org.apache.maven.surefire.extensions.util.Commandline; import org.apache.maven.surefire.extensions.util.CommandlineExecutor; import org.apache.maven.surefire.extensions.util.CommandlineStreams; import org.apache.maven.surefire.extensions.util.CountdownCloseable; import org.apache.maven.surefire.extensions.util.LineConsumerThread; -import org.apache.maven.surefire.shared.utils.cli.Commandline; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -78,7 +78,7 @@ void tearDown() throws Exception { @Test void shouldExecuteNativeCommand() throws Exception { Closeable closer = mock(Closeable.class); - Commandline cli = new Commandline(IS_OS_WINDOWS ? "dir" : "ls -la"); + Commandline cli = new Commandline(IS_OS_WINDOWS ? "cmd.exe /c dir" : "ls -la"); cli.setWorkingDirectory( Paths.get(baseDir, "target", "CommandlineExecutorTest").toFile()); CountdownCloseable countdownCloseable = new CountdownCloseable(closer, 1);
