View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.maven.cli;
20  
21  import java.io.BufferedReader;
22  import java.io.Console;
23  import java.io.File;
24  import java.io.FileNotFoundException;
25  import java.io.FileOutputStream;
26  import java.io.IOException;
27  import java.io.InputStream;
28  import java.io.InputStreamReader;
29  import java.io.PrintStream;
30  import java.nio.charset.StandardCharsets;
31  import java.nio.file.Files;
32  import java.nio.file.Path;
33  import java.nio.file.Paths;
34  import java.util.ArrayList;
35  import java.util.Collections;
36  import java.util.HashSet;
37  import java.util.LinkedHashMap;
38  import java.util.List;
39  import java.util.ListIterator;
40  import java.util.Map;
41  import java.util.Map.Entry;
42  import java.util.Objects;
43  import java.util.Properties;
44  import java.util.ServiceLoader;
45  import java.util.Set;
46  import java.util.StringTokenizer;
47  import java.util.regex.Matcher;
48  import java.util.regex.Pattern;
49  import java.util.stream.Stream;
50  
51  import com.google.inject.AbstractModule;
52  import org.apache.commons.cli.CommandLine;
53  import org.apache.commons.cli.Option;
54  import org.apache.commons.cli.ParseException;
55  import org.apache.commons.cli.UnrecognizedOptionException;
56  import org.apache.maven.BuildAbort;
57  import org.apache.maven.InternalErrorException;
58  import org.apache.maven.Maven;
59  import org.apache.maven.api.services.MessageBuilder;
60  import org.apache.maven.building.FileSource;
61  import org.apache.maven.building.Problem;
62  import org.apache.maven.building.Source;
63  import org.apache.maven.cli.configuration.ConfigurationProcessor;
64  import org.apache.maven.cli.configuration.SettingsXmlConfigurationProcessor;
65  import org.apache.maven.cli.event.DefaultEventSpyContext;
66  import org.apache.maven.cli.event.ExecutionEventLogger;
67  import org.apache.maven.cli.internal.BootstrapCoreExtensionManager;
68  import org.apache.maven.cli.internal.extension.model.CoreExtension;
69  import org.apache.maven.cli.internal.extension.model.io.xpp3.CoreExtensionsXpp3Reader;
70  import org.apache.maven.cli.logging.Slf4jConfiguration;
71  import org.apache.maven.cli.logging.Slf4jConfigurationFactory;
72  import org.apache.maven.cli.logging.Slf4jLoggerManager;
73  import org.apache.maven.cli.logging.Slf4jStdoutLogger;
74  import org.apache.maven.cli.transfer.ConsoleMavenTransferListener;
75  import org.apache.maven.cli.transfer.QuietMavenTransferListener;
76  import org.apache.maven.cli.transfer.SimplexTransferListener;
77  import org.apache.maven.cli.transfer.Slf4jMavenTransferListener;
78  import org.apache.maven.eventspy.internal.EventSpyDispatcher;
79  import org.apache.maven.exception.DefaultExceptionHandler;
80  import org.apache.maven.exception.ExceptionHandler;
81  import org.apache.maven.exception.ExceptionSummary;
82  import org.apache.maven.execution.DefaultMavenExecutionRequest;
83  import org.apache.maven.execution.ExecutionListener;
84  import org.apache.maven.execution.MavenExecutionRequest;
85  import org.apache.maven.execution.MavenExecutionRequestPopulationException;
86  import org.apache.maven.execution.MavenExecutionRequestPopulator;
87  import org.apache.maven.execution.MavenExecutionResult;
88  import org.apache.maven.execution.scope.internal.MojoExecutionScopeModule;
89  import org.apache.maven.extension.internal.CoreExports;
90  import org.apache.maven.extension.internal.CoreExtensionEntry;
91  import org.apache.maven.jline.MessageUtils;
92  import org.apache.maven.lifecycle.LifecycleExecutionException;
93  import org.apache.maven.model.building.ModelProcessor;
94  import org.apache.maven.model.interpolation.ModelInterpolator;
95  import org.apache.maven.model.root.RootLocator;
96  import org.apache.maven.project.MavenProject;
97  import org.apache.maven.properties.internal.EnvironmentUtils;
98  import org.apache.maven.properties.internal.SystemProperties;
99  import org.apache.maven.session.scope.internal.SessionScopeModule;
100 import org.apache.maven.toolchain.building.DefaultToolchainsBuildingRequest;
101 import org.apache.maven.toolchain.building.ToolchainsBuilder;
102 import org.apache.maven.toolchain.building.ToolchainsBuildingResult;
103 import org.codehaus.plexus.ContainerConfiguration;
104 import org.codehaus.plexus.DefaultContainerConfiguration;
105 import org.codehaus.plexus.DefaultPlexusContainer;
106 import org.codehaus.plexus.PlexusConstants;
107 import org.codehaus.plexus.PlexusContainer;
108 import org.codehaus.plexus.classworlds.ClassWorld;
109 import org.codehaus.plexus.classworlds.realm.ClassRealm;
110 import org.codehaus.plexus.classworlds.realm.NoSuchRealmException;
111 import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
112 import org.codehaus.plexus.interpolation.AbstractValueSource;
113 import org.codehaus.plexus.interpolation.InterpolationException;
114 import org.codehaus.plexus.interpolation.StringSearchInterpolator;
115 import org.codehaus.plexus.logging.LoggerManager;
116 import org.codehaus.plexus.util.StringUtils;
117 import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
118 import org.eclipse.aether.DefaultRepositoryCache;
119 import org.eclipse.aether.repository.RepositoryPolicy;
120 import org.eclipse.aether.transfer.TransferListener;
121 import org.slf4j.ILoggerFactory;
122 import org.slf4j.Logger;
123 import org.slf4j.LoggerFactory;
124 import org.sonatype.plexus.components.cipher.DefaultPlexusCipher;
125 import org.sonatype.plexus.components.sec.dispatcher.DefaultSecDispatcher;
126 import org.sonatype.plexus.components.sec.dispatcher.SecDispatcher;
127 import org.sonatype.plexus.components.sec.dispatcher.SecUtil;
128 import org.sonatype.plexus.components.sec.dispatcher.model.SettingsSecurity;
129 
130 import static org.apache.maven.cli.CLIManager.COLOR;
131 import static org.apache.maven.cli.ResolveFile.resolveFile;
132 import static org.apache.maven.jline.MessageUtils.builder;
133 
134 // TODO push all common bits back to plexus cli and prepare for transition to Guice. We don't need 50 ways to make CLIs
135 
136 /**
137  * @author Jason van Zyl
138  */
139 public class MavenCli {
140     public static final String LOCAL_REPO_PROPERTY = "maven.repo.local";
141 
142     public static final String MULTIMODULE_PROJECT_DIRECTORY = "maven.multiModuleProjectDirectory";
143 
144     public static final String USER_HOME = System.getProperty("user.home");
145 
146     public static final File USER_MAVEN_CONFIGURATION_HOME = new File(USER_HOME, ".m2");
147 
148     public static final File DEFAULT_USER_TOOLCHAINS_FILE = new File(USER_MAVEN_CONFIGURATION_HOME, "toolchains.xml");
149 
150     public static final File DEFAULT_GLOBAL_TOOLCHAINS_FILE =
151             new File(System.getProperty("maven.conf"), "toolchains.xml");
152 
153     private static final String EXT_CLASS_PATH = "maven.ext.class.path";
154 
155     private static final String DOT_MVN = ".mvn";
156 
157     private static final String PROJECT_EXTENSIONS_FILENAME = DOT_MVN + "/extensions.xml";
158 
159     private static final File USER_EXTENSIONS_FILE = new File(USER_MAVEN_CONFIGURATION_HOME, "extensions.xml");
160 
161     public static final File GLOBAL_EXTENSIONS_FILE = new File(System.getProperty("maven.conf"), "extensions.xml");
162 
163     private static final String MVN_MAVEN_CONFIG = DOT_MVN + "/maven.config";
164 
165     /**
166      * One "distinguished" env variable that we want to make into non-prefixed property, if present.
167      *
168      * @see ModelInterpolator
169      * @since 3.10.0
170      */
171     private static final String MAVEN_REPO_CENTRAL_ENV = "env.MAVEN_REPO_CENTRAL";
172 
173     public static final String STYLE_COLOR_PROPERTY = "style.color";
174 
175     private ClassWorld classWorld;
176 
177     private LoggerManager plexusLoggerManager;
178 
179     private ILoggerFactory slf4jLoggerFactory;
180 
181     private Logger slf4jLogger;
182 
183     private EventSpyDispatcher eventSpyDispatcher;
184 
185     private ModelProcessor modelProcessor;
186 
187     private Maven maven;
188 
189     private MavenExecutionRequestPopulator executionRequestPopulator;
190 
191     private ToolchainsBuilder toolchainsBuilder;
192 
193     private DefaultSecDispatcher dispatcher;
194 
195     private Map<String, ConfigurationProcessor> configurationProcessors;
196 
197     private CLIManager cliManager;
198 
199     private static final Pattern NEXT_LINE = Pattern.compile("\r?\n");
200 
201     public MavenCli() {
202         this(null);
203     }
204 
205     // This supports painless invocation by the Verifier during embedded execution of the core ITs
206     public MavenCli(ClassWorld classWorld) {
207         this.classWorld = classWorld;
208     }
209 
210     public static void main(String[] args) {
211         int result = main(args, null);
212 
213         System.exit(result);
214     }
215 
216     public static int main(String[] args, ClassWorld classWorld) {
217         MavenCli cli = new MavenCli();
218 
219         MessageUtils.systemInstall();
220         return cli.doMain(new CliRequest(args, classWorld));
221     }
222 
223     // TODO need to externalize CliRequest
224     public static int doMain(String[] args, ClassWorld classWorld) {
225         MavenCli cli = new MavenCli();
226         return cli.doMain(new CliRequest(args, classWorld));
227     }
228 
229     /**
230      * This supports painless invocation by the Verifier during embedded execution of the core ITs.
231      * See <a href="http://maven.apache.org/shared/maven-verifier/xref/org/apache/maven/it/Embedded3xLauncher.html">
232      * <code>Embedded3xLauncher</code> in <code>maven-verifier</code></a>
233      */
234     public int doMain(String[] args, String workingDirectory, PrintStream stdout, PrintStream stderr) {
235         PrintStream oldout = System.out;
236         PrintStream olderr = System.err;
237 
238         final Set<String> realms;
239         if (classWorld != null) {
240             realms = new HashSet<>();
241             for (ClassRealm realm : classWorld.getRealms()) {
242                 realms.add(realm.getId());
243             }
244         } else {
245             realms = Collections.emptySet();
246         }
247 
248         try {
249             if (stdout != null) {
250                 System.setOut(stdout);
251             }
252             if (stderr != null) {
253                 System.setErr(stderr);
254             }
255 
256             CliRequest cliRequest = new CliRequest(args, classWorld);
257             cliRequest.workingDirectory = workingDirectory;
258 
259             return doMain(cliRequest);
260         } finally {
261             if (classWorld != null) {
262                 for (ClassRealm realm : new ArrayList<>(classWorld.getRealms())) {
263                     String realmId = realm.getId();
264                     if (!realms.contains(realmId)) {
265                         try {
266                             classWorld.disposeRealm(realmId);
267                         } catch (NoSuchRealmException ignored) {
268                             // can't happen
269                         }
270                     }
271                 }
272             }
273             System.setOut(oldout);
274             System.setErr(olderr);
275         }
276     }
277 
278     // TODO need to externalize CliRequest
279     public int doMain(CliRequest cliRequest) {
280         PlexusContainer localContainer = null;
281         try {
282             initialize(cliRequest);
283             cli(cliRequest);
284             properties(cliRequest);
285             setupGuiceClassLoading();
286             logging(cliRequest);
287             informativeCommands(cliRequest);
288             version(cliRequest);
289             localContainer = container(cliRequest);
290             commands(cliRequest);
291             configure(cliRequest);
292             toolchains(cliRequest);
293             populateRequest(cliRequest);
294             encryption(cliRequest);
295             return execute(cliRequest);
296         } catch (ExitException e) {
297             return e.exitCode;
298         } catch (UnrecognizedOptionException e) {
299             // pure user error, suppress stack trace
300             return 1;
301         } catch (BuildAbort e) {
302             CLIReportingUtils.showError(slf4jLogger, "ABORTED", e, cliRequest.showErrors);
303 
304             return 2;
305         } catch (Exception e) {
306             CLIReportingUtils.showError(slf4jLogger, "Error executing Maven.", e, cliRequest.showErrors);
307 
308             return 1;
309         } finally {
310             if (localContainer != null) {
311                 localContainer.dispose();
312             }
313         }
314     }
315 
316     void initialize(CliRequest cliRequest) throws ExitException {
317         if (cliRequest.workingDirectory == null) {
318             cliRequest.workingDirectory = System.getProperty("user.dir");
319         }
320 
321         if (cliRequest.multiModuleProjectDirectory == null) {
322             String basedirProperty = System.getProperty(MULTIMODULE_PROJECT_DIRECTORY);
323             if (basedirProperty == null) {
324                 System.err.format("-D%s system property is not set.", MULTIMODULE_PROJECT_DIRECTORY);
325                 throw new ExitException(1);
326             }
327             File basedir = basedirProperty != null ? new File(basedirProperty) : new File("");
328             // Resolve lexically rather than through getCanonicalFile(), which asks the OS to resolve the path
329             // and can substitute it with a different one when a segment is a symlink, junction, or (on Windows)
330             // a mapped network drive, corrupting the reactor root that every relative module/parent path is
331             // later resolved against (MNG-11167).
332             cliRequest.multiModuleProjectDirectory =
333                     getCanonicalPath(basedir.toPath()).toFile();
334         }
335 
336         // We need to locate the top level project which may be pointed at using
337         // the -f/--file option.  However, the command line isn't parsed yet, so
338         // we need to iterate through the args to find it and act upon it.
339         Path topDirectory = Paths.get(cliRequest.workingDirectory);
340         boolean isAltFile = false;
341         for (String arg : cliRequest.args) {
342             if (isAltFile) {
343                 // this is the argument following -f/--file
344                 Path path = topDirectory.resolve(stripLeadingAndTrailingQuotes(arg));
345                 if (Files.isDirectory(path)) {
346                     topDirectory = path;
347                 } else if (Files.isRegularFile(path)) {
348                     topDirectory = path.getParent();
349                     if (!Files.isDirectory(topDirectory)) {
350                         System.err.println("Directory " + topDirectory
351                                 + " extracted from the -f/--file command-line argument " + arg + " does not exist");
352                         throw new ExitException(1);
353                     }
354                 } else {
355                     System.err.println(
356                             "POM file " + arg + " specified with the -f/--file command line argument does not exist");
357                     throw new ExitException(1);
358                 }
359                 break;
360             } else {
361                 // Check if this is the -f/--file option
362                 isAltFile = arg.equals("-f") || arg.equals("--file");
363             }
364         }
365         topDirectory = getCanonicalPath(topDirectory);
366         cliRequest.request.setTopDirectory(topDirectory);
367         // We're very early in the process, and we don't have the container set up yet,
368         // so we rely on the JDK services to eventually look up a custom RootLocator.
369         // This is used to compute {@code session.rootDirectory} but all {@code project.rootDirectory}
370         // properties will be computed through the RootLocator found in the container.
371         RootLocator rootLocator =
372                 ServiceLoader.load(RootLocator.class).iterator().next();
373         cliRequest.request.setRootDirectory(rootLocator.findRoot(topDirectory));
374 
375         //
376         // Make sure the Maven home directory is an absolute path to save us from confusion with say drive-relative
377         // Windows paths.
378         //
379         String mavenHome = System.getProperty("maven.home");
380 
381         if (mavenHome != null) {
382             System.setProperty("maven.home", new File(mavenHome).getAbsolutePath());
383         }
384     }
385 
386     void cli(CliRequest cliRequest) throws Exception {
387         //
388         // Parsing errors can happen during the processing of the arguments and we prefer not having to check if
389         // the logger is null and construct this so we can use an SLF4J logger everywhere.
390         //
391         slf4jLogger = new Slf4jStdoutLogger();
392 
393         cliManager = new CLIManager();
394 
395         CommandLine mavenConfig = null;
396         try {
397             File configFile = new File(cliRequest.multiModuleProjectDirectory, MVN_MAVEN_CONFIG);
398 
399             if (configFile.isFile()) {
400                 try (Stream<String> lines = Files.lines(configFile.toPath(), StandardCharsets.UTF_8)) {
401                     String[] args = lines.filter(arg -> !arg.isEmpty() && !arg.startsWith("#"))
402                             .toArray(String[]::new);
403                     mavenConfig = cliManager.parse(args);
404                     List<?> unrecognized = mavenConfig.getArgList();
405                     if (!unrecognized.isEmpty()) {
406                         // This file can only contain options, not args (goals or phases)
407                         throw new ParseException("Unrecognized maven.config file entries: " + unrecognized);
408                     }
409                 }
410             }
411         } catch (ParseException e) {
412             System.err.println("Unable to parse maven.config file options: " + e.getMessage());
413             cliManager.displayHelp(System.out);
414             throw e;
415         }
416 
417         try {
418             CommandLine mavenCli = cliManager.parse(cliRequest.args);
419             if (mavenConfig == null) {
420                 cliRequest.commandLine = mavenCli;
421             } else {
422                 cliRequest.commandLine = cliMerge(mavenConfig, mavenCli);
423             }
424         } catch (ParseException e) {
425             System.err.println("Unable to parse command line options: " + e.getMessage());
426             cliManager.displayHelp(System.out);
427             throw e;
428         }
429 
430         // check for presence of unsupported command line options
431         try {
432             if (cliRequest.commandLine.hasOption("llr")) {
433                 throw new UnrecognizedOptionException("Option '-llr' is not supported starting with Maven 3.9.1");
434             }
435         } catch (ParseException e) {
436             System.err.println("Unsupported options: " + e.getMessage());
437             cliManager.displayHelp(System.out);
438             throw e;
439         }
440     }
441 
442     private void informativeCommands(CliRequest cliRequest) throws ExitException {
443         if (cliRequest.commandLine.hasOption(CLIManager.HELP)) {
444             cliManager.displayHelp(System.out);
445             throw new ExitException(0);
446         }
447 
448         if (cliRequest.commandLine.hasOption(CLIManager.VERSION)) {
449             if (cliRequest.commandLine.hasOption(CLIManager.QUIET)) {
450                 System.out.println(CLIReportingUtils.showVersionMinimal());
451             } else {
452                 System.out.println(CLIReportingUtils.showVersion());
453             }
454             throw new ExitException(0);
455         }
456     }
457 
458     private CommandLine cliMerge(CommandLine mavenConfig, CommandLine mavenCli) {
459         CommandLine.Builder commandLineBuilder = new CommandLine.Builder();
460 
461         // the args are easy, CLI only since maven.config file can only contain options
462         for (String arg : mavenCli.getArgs()) {
463             commandLineBuilder.addArg(arg);
464         }
465 
466         /* Although this looks wrong in terms of order Commons CLI stores the value of options in
467          * an array and when a value is potentionally overriden it is added to the array. The single
468          * arg option value is retrieved and instead of returning values[values.length-1] it returns
469          * values[0] which means that the original value instead of the overridden one is returned
470          * (first wins). With properties values are truely overriden since at the end a map is used
471          * to merge which means last wins.
472          *
473          * TODO Report this behavioral bug with Commons CLI
474          */
475         // now add all options, except for user properties with CLI first then maven.config file
476         List<Option> setPropertyOptions = new ArrayList<>();
477         for (Option opt : mavenCli.getOptions()) {
478             if (String.valueOf(CLIManager.SET_USER_PROPERTY).equals(opt.getOpt())) {
479                 setPropertyOptions.add(opt);
480             } else {
481                 commandLineBuilder.addOption(opt);
482             }
483         }
484         for (Option opt : mavenConfig.getOptions()) {
485             commandLineBuilder.addOption(opt);
486         }
487         // finally add the CLI user properties
488         for (Option opt : setPropertyOptions) {
489             commandLineBuilder.addOption(opt);
490         }
491         return commandLineBuilder.build();
492     }
493 
494     /**
495      * Sets up Guice class loading mode to CHILD, if not already set.
496      * Default Guice class loading mode uses a terminally deprecated JDK memory-access classes.
497      */
498     void setupGuiceClassLoading() {
499         if (System.getProperty("guice_custom_class_loading", "").trim().isEmpty()) {
500             System.setProperty("guice_custom_class_loading", "CHILD");
501         }
502     }
503 
504     /**
505      * configure logging
506      */
507     void logging(CliRequest cliRequest) {
508         // LOG LEVEL
509         cliRequest.debug = cliRequest.commandLine.hasOption(CLIManager.DEBUG);
510         cliRequest.quiet = !cliRequest.debug && cliRequest.commandLine.hasOption(CLIManager.QUIET);
511         cliRequest.showErrors = cliRequest.debug || cliRequest.commandLine.hasOption(CLIManager.ERRORS);
512 
513         slf4jLoggerFactory = LoggerFactory.getILoggerFactory();
514         Slf4jConfiguration slf4jConfiguration = Slf4jConfigurationFactory.getConfiguration(slf4jLoggerFactory);
515 
516         if (cliRequest.debug) {
517             cliRequest.request.setLoggingLevel(MavenExecutionRequest.LOGGING_LEVEL_DEBUG);
518             slf4jConfiguration.setRootLoggerLevel(Slf4jConfiguration.Level.DEBUG);
519         } else if (cliRequest.quiet) {
520             cliRequest.request.setLoggingLevel(MavenExecutionRequest.LOGGING_LEVEL_ERROR);
521             slf4jConfiguration.setRootLoggerLevel(Slf4jConfiguration.Level.ERROR);
522         }
523         // else fall back to default log level specified in conf
524         // see https://issues.apache.org/jira/browse/MNG-2570
525 
526         // LOG COLOR
527         String styleColor = cliRequest.getUserProperties().getProperty(STYLE_COLOR_PROPERTY, "auto");
528         styleColor = cliRequest.commandLine.getOptionValue(COLOR, styleColor);
529         if ("always".equals(styleColor) || "yes".equals(styleColor) || "force".equals(styleColor)) {
530             MessageUtils.setColorEnabled(true);
531         } else if ("never".equals(styleColor) || "no".equals(styleColor) || "none".equals(styleColor)) {
532             MessageUtils.setColorEnabled(false);
533         } else if (!"auto".equals(styleColor) && !"tty".equals(styleColor) && !"if-tty".equals(styleColor)) {
534             throw new IllegalArgumentException(
535                     "Invalid color configuration value '" + styleColor + "'. Supported are 'auto', 'always', 'never'.");
536         } else if (cliRequest.commandLine.hasOption(CLIManager.BATCH_MODE)
537                 || cliRequest.commandLine.hasOption(CLIManager.LOG_FILE)) {
538             MessageUtils.setColorEnabled(false);
539         } else {
540             // auto: color only on a detected ANSI terminal; embedded use (#13357) never detects one
541             MessageUtils.setColorEnabled(MessageUtils.isTty());
542         }
543 
544         // LOG STREAMS
545         if (cliRequest.commandLine.hasOption(CLIManager.LOG_FILE)) {
546             File logFile = new File(cliRequest.commandLine.getOptionValue(CLIManager.LOG_FILE));
547             logFile = resolveFile(logFile, cliRequest.workingDirectory);
548 
549             // redirect stdout and stderr to file
550             try {
551                 PrintStream ps = new PrintStream(new FileOutputStream(logFile));
552                 System.setOut(ps);
553                 System.setErr(ps);
554             } catch (FileNotFoundException e) {
555                 //
556                 // Ignore
557                 //
558             }
559         }
560         slf4jConfiguration.activate();
561 
562         plexusLoggerManager = new Slf4jLoggerManager();
563         slf4jLogger = slf4jLoggerFactory.getLogger(this.getClass().getName());
564     }
565 
566     private void version(CliRequest cliRequest) {
567         if (cliRequest.debug || cliRequest.commandLine.hasOption(CLIManager.SHOW_VERSION)) {
568             System.out.println(CLIReportingUtils.showVersion());
569         }
570     }
571 
572     private void commands(CliRequest cliRequest) throws ExitException {
573         if (cliRequest.showErrors) {
574             slf4jLogger.info("Error stacktraces are turned on.");
575         }
576 
577         if (MavenExecutionRequest.CHECKSUM_POLICY_WARN.equals(cliRequest.request.getGlobalChecksumPolicy())) {
578             slf4jLogger.info("Disabling strict checksum verification on all artifact downloads.");
579         } else if (MavenExecutionRequest.CHECKSUM_POLICY_FAIL.equals(cliRequest.request.getGlobalChecksumPolicy())) {
580             slf4jLogger.info("Enabling strict checksum verification on all artifact downloads.");
581         }
582 
583         // If no goals/phases were specified and there is no POM in the current directory,
584         // print usage (like `mvn -h`) and exit successfully instead of failing with
585         // "No goals have been specified for this build."
586         // When a POM is present the default goal (if any) may apply, so let Maven proceed normally.
587         // Skip this check for encryption commands (--encrypt-password, --encrypt-master-password)
588         // which also have no goals and no POM, but are handled later by encryption().
589         // Also skip when -f/--file is specified: the alternate POM existence is validated later,
590         // and the working directory may legitimately have no pom.xml.
591         List<String> goals = cliRequest.commandLine.getArgList();
592         if (goals.isEmpty()
593                 && modelProcessor != null
594                 && !cliRequest.commandLine.hasOption(CLIManager.ALTERNATE_POM_FILE)
595                 && !cliRequest.commandLine.hasOption(CLIManager.ENCRYPT_PASSWORD)
596                 && !cliRequest.commandLine.hasOption(CLIManager.ENCRYPT_MASTER_PASSWORD)) {
597             File pom = modelProcessor.locatePom(new File(cliRequest.workingDirectory));
598             if (!pom.isFile()) {
599                 cliManager.displayHelp(System.out);
600                 throw new ExitException(0);
601             }
602         }
603 
604         if (slf4jLogger.isDebugEnabled()) {
605             slf4jLogger.debug("Message scheme: {}", (MessageUtils.isColorEnabled() ? "color" : "plain"));
606             slf4jLogger.debug("Message terminal: {}", MessageUtils.isTty() ? "ansi" : "none");
607             if (MessageUtils.isColorEnabled()) {
608                 MessageBuilder buff = builder();
609                 buff.a("Message styles: ");
610                 buff.a(builder().trace("trace")).a(' ');
611                 buff.a(builder().debug("debug")).a(' ');
612                 buff.a(builder().info("info")).a(' ');
613                 buff.a(builder().warning("warning")).a(' ');
614                 buff.a(builder().error("error")).a(' ');
615                 buff.success("success").a(' ');
616                 buff.failure("failure").a(' ');
617                 buff.strong("strong").a(' ');
618                 buff.mojo("mojo").a(' ');
619                 buff.project("project");
620                 slf4jLogger.debug(buff.toString());
621             }
622         }
623     }
624 
625     // Needed to make this method package visible to make writing a unit test possible
626     // Maybe it's better to move some of those methods to separate class (SoC).
627     void properties(CliRequest cliRequest) throws ExitException {
628         try {
629             populateProperties(cliRequest, cliRequest.systemProperties, cliRequest.userProperties);
630 
631             StringSearchInterpolator interpolator =
632                     createInterpolator(cliRequest, cliRequest.systemProperties, cliRequest.userProperties);
633             CommandLine.Builder commandLineBuilder = new CommandLine.Builder();
634             for (Option option : cliRequest.commandLine.getOptions()) {
635                 if (!String.valueOf(CLIManager.SET_USER_PROPERTY).equals(option.getOpt())) {
636                     List<String> values = option.getValuesList();
637                     for (ListIterator<String> it = values.listIterator(); it.hasNext(); ) {
638                         it.set(interpolator.interpolate(it.next()));
639                     }
640                 }
641                 commandLineBuilder.addOption(option);
642             }
643             for (String arg : cliRequest.commandLine.getArgList()) {
644                 commandLineBuilder.addArg(interpolator.interpolate(arg));
645             }
646             cliRequest.commandLine = commandLineBuilder.build();
647         } catch (InterpolationException e) {
648             String message = "ERROR: Could not interpolate properties and/or arguments: " + e.getMessage();
649             System.err.println(message);
650             throw new ExitException(1); // user error
651         } catch (IllegalUseOfUndefinedProperty e) {
652             String message = "ERROR: Illegal use of undefined property: " + e.property;
653             System.err.println(message);
654             try {
655                 cliRequest.request.getRootDirectory();
656             } catch (IllegalStateException ex) {
657                 System.err.println();
658                 System.err.println(RootLocator.UNABLE_TO_FIND_ROOT_PROJECT_MESSAGE);
659             }
660             throw new ExitException(1); // user error
661         }
662     }
663 
664     PlexusContainer container(CliRequest cliRequest) throws Exception {
665         if (cliRequest.classWorld == null) {
666             cliRequest.classWorld =
667                     new ClassWorld("plexus.core", Thread.currentThread().getContextClassLoader());
668         }
669 
670         ClassRealm coreRealm = cliRequest.classWorld.getClassRealm("plexus.core");
671         if (coreRealm == null) {
672             coreRealm = cliRequest.classWorld.getRealms().iterator().next();
673         }
674 
675         List<File> extClassPath = parseExtClasspath(cliRequest);
676 
677         CoreExtensionEntry coreEntry = CoreExtensionEntry.discoverFrom(coreRealm);
678         List<CoreExtensionEntry> extensions =
679                 loadCoreExtensions(cliRequest, coreRealm, coreEntry.getExportedArtifacts());
680 
681         ClassRealm containerRealm = setupContainerRealm(cliRequest.classWorld, coreRealm, extClassPath, extensions);
682 
683         ContainerConfiguration cc = new DefaultContainerConfiguration()
684                 .setClassWorld(cliRequest.classWorld)
685                 .setRealm(containerRealm)
686                 .setClassPathScanning(PlexusConstants.SCANNING_INDEX)
687                 .setAutoWiring(true)
688                 .setJSR250Lifecycle(true)
689                 .setVisibilityPredicateSupplierTransformer(s -> () -> {
690                     if (BootstrapCoreExtensionManager.isContextRealmCoreExtensionRealm()) {
691                         return null;
692                     } else {
693                         return s.get();
694                     }
695                 })
696                 .setName("maven");
697 
698         Set<String> exportedArtifacts = new HashSet<>(coreEntry.getExportedArtifacts());
699         Set<String> exportedPackages = new HashSet<>(coreEntry.getExportedPackages());
700         for (CoreExtensionEntry extension : extensions) {
701             exportedArtifacts.addAll(extension.getExportedArtifacts());
702             exportedPackages.addAll(extension.getExportedPackages());
703         }
704 
705         final CoreExports exports = new CoreExports(containerRealm, exportedArtifacts, exportedPackages);
706 
707         DefaultPlexusContainer container = new DefaultPlexusContainer(cc, new AbstractModule() {
708             @Override
709             protected void configure() {
710                 bind(ILoggerFactory.class).toInstance(slf4jLoggerFactory);
711                 bind(CoreExports.class).toInstance(exports);
712             }
713         });
714 
715         // NOTE: To avoid inconsistencies, we'll use the TCCL exclusively for lookups
716         container.setLookupRealm(null);
717         Thread.currentThread().setContextClassLoader(container.getContainerRealm());
718 
719         container.setLoggerManager(plexusLoggerManager);
720 
721         for (CoreExtensionEntry extension : extensions) {
722             container.discoverComponents(
723                     extension.getClassRealm(),
724                     new SessionScopeModule(container),
725                     new MojoExecutionScopeModule(container));
726         }
727 
728         customizeContainer(container);
729 
730         container.getLoggerManager().setThresholds(cliRequest.request.getLoggingLevel());
731 
732         eventSpyDispatcher = container.lookup(EventSpyDispatcher.class);
733 
734         DefaultEventSpyContext eventSpyContext = new DefaultEventSpyContext();
735         Map<String, Object> data = eventSpyContext.getData();
736         data.put("plexus", container);
737         data.put("workingDirectory", cliRequest.workingDirectory);
738         data.put("systemProperties", cliRequest.systemProperties);
739         data.put("userProperties", cliRequest.userProperties);
740         data.put("versionProperties", CLIReportingUtils.getBuildProperties());
741         eventSpyDispatcher.init(eventSpyContext);
742 
743         // refresh logger in case container got customized by spy
744         slf4jLogger = slf4jLoggerFactory.getLogger(this.getClass().getName());
745 
746         maven = container.lookup(Maven.class);
747 
748         executionRequestPopulator = container.lookup(MavenExecutionRequestPopulator.class);
749 
750         modelProcessor = createModelProcessor(container);
751 
752         configurationProcessors = container.lookupMap(ConfigurationProcessor.class);
753 
754         toolchainsBuilder = container.lookup(ToolchainsBuilder.class);
755 
756         dispatcher = (DefaultSecDispatcher) container.lookup(SecDispatcher.class, "maven");
757 
758         return container;
759     }
760 
761     private List<CoreExtensionEntry> loadCoreExtensions(
762             CliRequest cliRequest, ClassRealm containerRealm, Set<String> providedArtifacts) throws Exception {
763         if (cliRequest.multiModuleProjectDirectory == null) {
764             return Collections.emptyList();
765         }
766 
767         File projectExtensionsFile = new File(cliRequest.multiModuleProjectDirectory, PROJECT_EXTENSIONS_FILENAME);
768         if (!projectExtensionsFile.isFile() && !USER_EXTENSIONS_FILE.isFile() && !GLOBAL_EXTENSIONS_FILE.isFile()) {
769             return Collections.emptyList();
770         }
771 
772         List<CoreExtension> projectExtensions = null;
773         List<CoreExtension> userExtensions = null;
774         List<CoreExtension> globalExtensions = null;
775         if (projectExtensionsFile.isFile()) {
776             projectExtensions = readCoreExtensionsDescriptor(projectExtensionsFile.toPath());
777         }
778         if (USER_EXTENSIONS_FILE.isFile()) {
779             userExtensions = readCoreExtensionsDescriptor(USER_EXTENSIONS_FILE.toPath());
780         }
781         if (GLOBAL_EXTENSIONS_FILE.isFile()) {
782             globalExtensions = readCoreExtensionsDescriptor(GLOBAL_EXTENSIONS_FILE.toPath());
783         }
784 
785         if ((projectExtensions == null || projectExtensions.isEmpty())
786                 && (userExtensions == null || userExtensions.isEmpty())
787                 && (globalExtensions == null || globalExtensions.isEmpty())) {
788             return Collections.emptyList();
789         }
790 
791         Map<Path, List<CoreExtension>> configuredCoreExtensions = new LinkedHashMap<>();
792         if (projectExtensions != null && !projectExtensions.isEmpty()) {
793             configuredCoreExtensions.put(projectExtensionsFile.toPath(), projectExtensions);
794         }
795         if (userExtensions != null && !userExtensions.isEmpty()) {
796             configuredCoreExtensions.put(USER_EXTENSIONS_FILE.toPath(), userExtensions);
797         }
798         if (globalExtensions != null && !globalExtensions.isEmpty()) {
799             configuredCoreExtensions.put(GLOBAL_EXTENSIONS_FILE.toPath(), globalExtensions);
800         }
801         // mediate versions
802         List<CoreExtension> extensions = selectCoreExtensions(configuredCoreExtensions);
803 
804         ContainerConfiguration cc = new DefaultContainerConfiguration() //
805                 .setClassWorld(cliRequest.classWorld) //
806                 .setRealm(containerRealm) //
807                 .setClassPathScanning(PlexusConstants.SCANNING_INDEX) //
808                 .setAutoWiring(true) //
809                 .setJSR250Lifecycle(true) //
810                 .setName("maven");
811 
812         DefaultPlexusContainer container = new DefaultPlexusContainer(cc, new AbstractModule() {
813             @Override
814             protected void configure() {
815                 bind(ILoggerFactory.class).toInstance(slf4jLoggerFactory);
816             }
817         });
818 
819         try {
820             container.setLookupRealm(null);
821 
822             container.setLoggerManager(plexusLoggerManager);
823 
824             container.getLoggerManager().setThresholds(cliRequest.request.getLoggingLevel());
825 
826             Thread.currentThread().setContextClassLoader(container.getContainerRealm());
827 
828             executionRequestPopulator = container.lookup(MavenExecutionRequestPopulator.class);
829 
830             configurationProcessors = container.lookupMap(ConfigurationProcessor.class);
831 
832             configure(cliRequest);
833 
834             MavenExecutionRequest request = DefaultMavenExecutionRequest.copy(cliRequest.request);
835 
836             request = populateRequest(cliRequest, request);
837 
838             request = executionRequestPopulator.populateDefaults(request);
839 
840             BootstrapCoreExtensionManager resolver = container.lookup(BootstrapCoreExtensionManager.class);
841 
842             return Collections.unmodifiableList(resolver.loadCoreExtensions(request, providedArtifacts, extensions));
843 
844         } finally {
845             executionRequestPopulator = null;
846             container.dispose();
847         }
848     }
849 
850     List<CoreExtension> readCoreExtensionsDescriptor(Path extensionsFile) throws IOException {
851         CoreExtensionsXpp3Reader parser = new CoreExtensionsXpp3Reader();
852         try (BufferedReader is = Files.newBufferedReader(extensionsFile, StandardCharsets.UTF_8)) {
853             return parser.read(is).getExtensions();
854         } catch (IOException | XmlPullParserException e) {
855             throw new IOException(
856                     "Unable to parse core extensions descriptor " + extensionsFile + ": " + e.getMessage(), e);
857         }
858     }
859 
860     private List<CoreExtension> selectCoreExtensions(Map<Path, List<CoreExtension>> configuredCoreExtensions) {
861         slf4jLogger.debug("Configured core extensions (in precedence order):");
862         for (Map.Entry<Path, List<CoreExtension>> source : configuredCoreExtensions.entrySet()) {
863             slf4jLogger.debug("* Source file: {}", source.getKey());
864             for (CoreExtension extension : source.getValue()) {
865                 slf4jLogger.debug("  - {} -> {}", extension.getId(), source.getKey());
866             }
867         }
868 
869         LinkedHashMap<String, CoreExtension> selectedExtensions = new LinkedHashMap<>();
870         List<String> conflicts = new ArrayList<>();
871         for (Map.Entry<Path, List<CoreExtension>> coreExtensions : configuredCoreExtensions.entrySet()) {
872             for (CoreExtension coreExtension : coreExtensions.getValue()) {
873                 String key = coreExtension.getGroupId() + ":" + coreExtension.getArtifactId();
874                 CoreExtension conflict = selectedExtensions.putIfAbsent(key, coreExtension);
875                 if (conflict != null && !Objects.equals(coreExtension.getVersion(), conflict.getVersion())) {
876                     conflicts.add(String.format(
877                             "Conflicting extension %s: %s vs %s in %s",
878                             key, coreExtension.getVersion(), conflict.getVersion(), coreExtensions.getKey()));
879                 }
880             }
881         }
882         if (!conflicts.isEmpty()) {
883             slf4jLogger.warn("Found {} extension conflict(s):", conflicts.size());
884             for (String conflict : conflicts) {
885                 slf4jLogger.warn("* {}", conflict);
886             }
887             slf4jLogger.warn("");
888             slf4jLogger.warn(
889                     "Order of core extensions precedence is project > user > installation. Selected extensions are:");
890             for (CoreExtension extension : selectedExtensions.values()) {
891                 slf4jLogger.warn("* {}", extension.getId());
892             }
893         }
894 
895         slf4jLogger.debug("Selected core extensions (in loading order):");
896         for (CoreExtension source : selectedExtensions.values()) {
897             slf4jLogger.debug("* {}: ", source.getId());
898         }
899         return new ArrayList<>(selectedExtensions.values());
900     }
901 
902     private ClassRealm setupContainerRealm(
903             ClassWorld classWorld, ClassRealm coreRealm, List<File> extClassPath, List<CoreExtensionEntry> extensions)
904             throws Exception {
905         if (!extClassPath.isEmpty() || !extensions.isEmpty()) {
906             ClassRealm extRealm = classWorld.newRealm("maven.ext", null);
907 
908             extRealm.setParentRealm(coreRealm);
909 
910             slf4jLogger.debug("Populating class realm {}", extRealm.getId());
911 
912             for (File file : extClassPath) {
913                 slf4jLogger.debug("  Included {}", file);
914 
915                 extRealm.addURL(file.toURI().toURL());
916             }
917 
918             for (CoreExtensionEntry entry : reverse(extensions)) {
919                 Set<String> exportedPackages = entry.getExportedPackages();
920                 ClassRealm realm = entry.getClassRealm();
921                 for (String exportedPackage : exportedPackages) {
922                     extRealm.importFrom(realm, exportedPackage);
923                 }
924                 if (exportedPackages.isEmpty()) {
925                     // sisu uses realm imports to establish component visibility
926                     extRealm.importFrom(realm, realm.getId());
927                 }
928             }
929 
930             return extRealm;
931         }
932 
933         return coreRealm;
934     }
935 
936     private static <T> List<T> reverse(List<T> list) {
937         List<T> copy = new ArrayList<>(list);
938         Collections.reverse(copy);
939         return copy;
940     }
941 
942     private List<File> parseExtClasspath(CliRequest cliRequest) {
943         String extClassPath = cliRequest.userProperties.getProperty(EXT_CLASS_PATH);
944         if (extClassPath == null) {
945             extClassPath = cliRequest.systemProperties.getProperty(EXT_CLASS_PATH);
946         }
947 
948         List<File> jars = new ArrayList<>();
949 
950         if (StringUtils.isNotEmpty(extClassPath)) {
951             for (String jar : StringUtils.split(extClassPath, File.pathSeparator)) {
952                 File file = resolveFile(new File(jar), cliRequest.workingDirectory);
953 
954                 slf4jLogger.debug("  Included {}", file);
955 
956                 jars.add(file);
957             }
958         }
959 
960         return jars;
961     }
962 
963     /**
964      * Reads a password from the console and, when there is none because the streams are redirected, from the first
965      * line of the given input.
966      *
967      * @param console the console, or {@code null} if the streams are redirected
968      * @param in the input to read the first line from when there is no console
969      * @param prompt the prompt shown by the console; it is not shown when the password is read from the input, as
970      *               the caller is then not interactive and the prompt would only pollute its output
971      * @return the password, never empty
972      * @throws IOException if the input cannot be read
973      * @throws IllegalStateException if no password could be read, so that an empty one is not encrypted
974      */
975     static String readPassword(Console console, InputStream in, String prompt) throws IOException {
976         String password;
977         if (console != null) {
978             char[] chars = console.readPassword(prompt);
979             password = (chars == null) ? null : String.copyValueOf(chars);
980 
981             if (chars != null) {
982                 // Sun/Oracle advises to empty the char array
983                 java.util.Arrays.fill(chars, ' ');
984             }
985         } else {
986             // do not close the reader, that would close the standard input
987             password = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8)).readLine();
988         }
989 
990         if (password == null || password.isEmpty()) {
991             throw new IllegalStateException("No password was provided");
992         }
993 
994         return password;
995     }
996 
997     //
998     // This should probably be a separate tool and not be baked into Maven.
999     //
1000     private void encryption(CliRequest cliRequest) throws Exception {
1001         if (cliRequest.commandLine.hasOption(CLIManager.ENCRYPT_MASTER_PASSWORD)) {
1002             String passwd = cliRequest.commandLine.getOptionValue(CLIManager.ENCRYPT_MASTER_PASSWORD);
1003 
1004             if (passwd == null) {
1005                 passwd = readPassword(System.console(), System.in, "Master password: ");
1006             }
1007 
1008             DefaultPlexusCipher cipher = new DefaultPlexusCipher();
1009 
1010             System.out.println(cipher.encryptAndDecorate(passwd, DefaultSecDispatcher.SYSTEM_PROPERTY_SEC_LOCATION));
1011 
1012             throw new ExitException(0);
1013         } else if (cliRequest.commandLine.hasOption(CLIManager.ENCRYPT_PASSWORD)) {
1014             String passwd = cliRequest.commandLine.getOptionValue(CLIManager.ENCRYPT_PASSWORD);
1015 
1016             if (passwd == null) {
1017                 passwd = readPassword(System.console(), System.in, "Password: ");
1018             }
1019 
1020             String configurationFile = dispatcher.getConfigurationFile();
1021 
1022             if (configurationFile.startsWith("~")) {
1023                 configurationFile = System.getProperty("user.home") + configurationFile.substring(1);
1024             }
1025 
1026             String file = System.getProperty(DefaultSecDispatcher.SYSTEM_PROPERTY_SEC_LOCATION, configurationFile);
1027 
1028             String master = null;
1029 
1030             SettingsSecurity sec = SecUtil.read(file, true);
1031             if (sec != null) {
1032                 master = sec.getMaster();
1033             }
1034 
1035             if (master == null) {
1036                 throw new IllegalStateException("Master password is not set in the setting security file: " + file);
1037             }
1038 
1039             DefaultPlexusCipher cipher = new DefaultPlexusCipher();
1040             String masterPasswd = cipher.decryptDecorated(master, DefaultSecDispatcher.SYSTEM_PROPERTY_SEC_LOCATION);
1041             System.out.println(cipher.encryptAndDecorate(passwd, masterPasswd));
1042 
1043             throw new ExitException(0);
1044         }
1045     }
1046 
1047     private int execute(CliRequest cliRequest) throws MavenExecutionRequestPopulationException {
1048         MavenExecutionRequest request = executionRequestPopulator.populateDefaults(cliRequest.request);
1049         request.setRepositoryCache(new DefaultRepositoryCache()); // reset caches
1050 
1051         eventSpyDispatcher.onEvent(request);
1052 
1053         MavenExecutionResult result = maven.execute(request);
1054 
1055         eventSpyDispatcher.onEvent(result);
1056 
1057         eventSpyDispatcher.close();
1058 
1059         if (result.hasExceptions()) {
1060             ExceptionHandler handler = new DefaultExceptionHandler();
1061 
1062             Map<String, String> references = new LinkedHashMap<>();
1063 
1064             MavenProject project = null;
1065 
1066             for (Throwable exception : result.getExceptions()) {
1067                 ExceptionSummary summary = handler.handleException(exception);
1068 
1069                 logSummary(summary, references, "", cliRequest.showErrors);
1070 
1071                 if (project == null && exception instanceof LifecycleExecutionException) {
1072                     project = ((LifecycleExecutionException) exception).getProject();
1073                 }
1074             }
1075 
1076             slf4jLogger.error("");
1077 
1078             if (!cliRequest.showErrors) {
1079                 slf4jLogger.error(
1080                         "To see the full stack trace of the errors, re-run Maven with the {} switch.",
1081                         builder().strong("-e"));
1082             }
1083             if (!slf4jLogger.isDebugEnabled()) {
1084                 slf4jLogger.error(
1085                         "Re-run Maven using the {} switch to enable full debug logging.",
1086                         builder().strong("-X"));
1087             }
1088 
1089             if (!references.isEmpty()) {
1090                 slf4jLogger.error("");
1091                 slf4jLogger.error("For more information about the errors and possible solutions"
1092                         + ", please read the following articles:");
1093 
1094                 for (Map.Entry<String, String> entry : references.entrySet()) {
1095                     slf4jLogger.error("{} {}", builder().strong(entry.getValue()), entry.getKey());
1096                 }
1097             }
1098 
1099             if (project != null
1100                     && !project.equals(result.getTopologicallySortedProjects().get(0))) {
1101                 slf4jLogger.error("");
1102                 slf4jLogger.error("After correcting the problems, you can resume the build with the command");
1103                 slf4jLogger.error(builder()
1104                         .a("  ")
1105                         .strong("mvn <args> -rf " + getResumeFrom(result.getTopologicallySortedProjects(), project))
1106                         .toString());
1107             }
1108 
1109             if (MavenExecutionRequest.REACTOR_FAIL_NEVER.equals(cliRequest.request.getReactorFailureBehavior())) {
1110                 slf4jLogger.info("Build failures were ignored.");
1111 
1112                 return 0;
1113             } else {
1114                 return 1;
1115             }
1116         } else {
1117             return 0;
1118         }
1119     }
1120 
1121     /**
1122      * A helper method to determine the value to resume the build with {@code -rf} taking into account the
1123      * edge case where multiple modules in the reactor have the same artifactId.
1124      * <p>
1125      * {@code -rf :artifactId} will pick up the first module which matches, but when multiple modules in the
1126      * reactor have the same artifactId, effective failed module might be later in build reactor.
1127      * This means that developer will either have to type groupId or wait for build execution of all modules
1128      * which were fine, but they are still before one which reported errors.
1129      * <p>Then the returned value is {@code groupId:artifactId} when there is a name clash and
1130      * {@code :artifactId} if there is no conflict.
1131      *
1132      * @param mavenProjects Maven projects which are part of build execution.
1133      * @param failedProject Project which has failed.
1134      * @return Value for -rf flag to resume build exactly from place where it failed ({@code :artifactId} in
1135      *    general and {@code groupId:artifactId} when there is a name clash).
1136      */
1137     private String getResumeFrom(List<MavenProject> mavenProjects, MavenProject failedProject) {
1138         for (MavenProject buildProject : mavenProjects) {
1139             if (failedProject.getArtifactId().equals(buildProject.getArtifactId())
1140                     && !failedProject.equals(buildProject)) {
1141                 return failedProject.getGroupId() + ":" + failedProject.getArtifactId();
1142             }
1143         }
1144         return ":" + failedProject.getArtifactId();
1145     }
1146 
1147     private void logSummary(
1148             ExceptionSummary summary, Map<String, String> references, String indent, boolean showErrors) {
1149         String referenceKey = "";
1150 
1151         if (StringUtils.isNotEmpty(summary.getReference())) {
1152             referenceKey = references.get(summary.getReference());
1153             if (referenceKey == null) {
1154                 referenceKey = "[Help " + (references.size() + 1) + "]";
1155                 references.put(summary.getReference(), referenceKey);
1156             }
1157         }
1158 
1159         String msg = summary.getMessage();
1160 
1161         if (StringUtils.isNotEmpty(referenceKey)) {
1162             if (msg.indexOf('\n') < 0) {
1163                 msg += " -> " + builder().strong(referenceKey);
1164             } else {
1165                 msg += "\n-> " + builder().strong(referenceKey);
1166             }
1167         }
1168 
1169         String[] lines = NEXT_LINE.split(msg);
1170         String currentColor = "";
1171 
1172         for (int i = 0; i < lines.length; i++) {
1173             // add eventual current color inherited from previous line
1174             String line = currentColor + lines[i];
1175 
1176             // look for last ANSI escape sequence to check if nextColor
1177             Matcher matcher = LAST_ANSI_SEQUENCE.matcher(line);
1178             String nextColor = "";
1179             if (matcher.find()) {
1180                 nextColor = matcher.group(1);
1181                 if (ANSI_RESET.equals(nextColor)) {
1182                     // last ANSI escape code is reset: no next color
1183                     nextColor = "";
1184                 }
1185             }
1186 
1187             // effective line, with indent and reset if end is colored
1188             line = indent + line + ("".equals(nextColor) ? "" : ANSI_RESET);
1189 
1190             if ((i == lines.length - 1) && (showErrors || (summary.getException() instanceof InternalErrorException))) {
1191                 slf4jLogger.error(line, summary.getException());
1192             } else {
1193                 slf4jLogger.error(line);
1194             }
1195 
1196             currentColor = nextColor;
1197         }
1198 
1199         indent += "  ";
1200 
1201         for (ExceptionSummary child : summary.getChildren()) {
1202             logSummary(child, references, indent, showErrors);
1203         }
1204     }
1205 
1206     private static final Pattern LAST_ANSI_SEQUENCE = Pattern.compile("(\u001B\\[[;\\d]*[ -/]*[@-~])[^\u001B]*$");
1207 
1208     private static final String ANSI_RESET = "\u001B\u005Bm";
1209 
1210     private void configure(CliRequest cliRequest) throws Exception {
1211         //
1212         // This is not ideal but there are events specifically for configuration from the CLI which I don't
1213         // believe are really valid but there are ITs which assert the right events are published so this
1214         // needs to be supported so the EventSpyDispatcher needs to be put in the CliRequest so that
1215         // it can be accessed by configuration processors.
1216         //
1217         cliRequest.request.setEventSpyDispatcher(eventSpyDispatcher);
1218 
1219         //
1220         // We expect at most 2 implementations to be available. The SettingsXmlConfigurationProcessor implementation
1221         // is always available in the core and likely always will be, but we may have another ConfigurationProcessor
1222         // present supplied by the user. The rule is that we only allow the execution of one ConfigurationProcessor.
1223         // If there is more than one then we execute the one supplied by the user, otherwise we execute the
1224         // the default SettingsXmlConfigurationProcessor.
1225         //
1226         int userSuppliedConfigurationProcessorCount = configurationProcessors.size() - 1;
1227 
1228         if (userSuppliedConfigurationProcessorCount == 0) {
1229             //
1230             // Our settings.xml source is historically how we have configured Maven from the CLI so we are going to
1231             // have to honour its existence forever. So let's run it.
1232             //
1233             configurationProcessors.get(SettingsXmlConfigurationProcessor.HINT).process(cliRequest);
1234         } else if (userSuppliedConfigurationProcessorCount == 1) {
1235             //
1236             // Run the user supplied ConfigurationProcessor
1237             //
1238             for (Entry<String, ConfigurationProcessor> entry : configurationProcessors.entrySet()) {
1239                 String hint = entry.getKey();
1240                 if (!hint.equals(SettingsXmlConfigurationProcessor.HINT)) {
1241                     ConfigurationProcessor configurationProcessor = entry.getValue();
1242                     configurationProcessor.process(cliRequest);
1243                 }
1244             }
1245         } else if (userSuppliedConfigurationProcessorCount > 1) {
1246             //
1247             // There are too many ConfigurationProcessors so we don't know which one to run so report the error.
1248             //
1249             StringBuilder sb = new StringBuilder(String.format(
1250                     "\nThere can only be one user supplied ConfigurationProcessor, there are %s:\n\n",
1251                     userSuppliedConfigurationProcessorCount));
1252             for (Entry<String, ConfigurationProcessor> entry : configurationProcessors.entrySet()) {
1253                 String hint = entry.getKey();
1254                 if (!hint.equals(SettingsXmlConfigurationProcessor.HINT)) {
1255                     ConfigurationProcessor configurationProcessor = entry.getValue();
1256                     sb.append(String.format(
1257                             "%s\n", configurationProcessor.getClass().getName()));
1258                 }
1259             }
1260             sb.append("\n");
1261             throw new Exception(sb.toString());
1262         }
1263     }
1264 
1265     void toolchains(CliRequest cliRequest) throws Exception {
1266         File userToolchainsFile;
1267 
1268         if (cliRequest.commandLine.hasOption(CLIManager.ALTERNATE_USER_TOOLCHAINS)) {
1269             userToolchainsFile = new File(cliRequest.commandLine.getOptionValue(CLIManager.ALTERNATE_USER_TOOLCHAINS));
1270             userToolchainsFile = resolveFile(userToolchainsFile, cliRequest.workingDirectory);
1271 
1272             if (!userToolchainsFile.isFile()) {
1273                 throw new FileNotFoundException(
1274                         "The specified user toolchains file does not exist: " + userToolchainsFile);
1275             }
1276         } else {
1277             userToolchainsFile = DEFAULT_USER_TOOLCHAINS_FILE;
1278         }
1279 
1280         File globalToolchainsFile;
1281 
1282         if (cliRequest.commandLine.hasOption(CLIManager.ALTERNATE_GLOBAL_TOOLCHAINS)) {
1283             globalToolchainsFile =
1284                     new File(cliRequest.commandLine.getOptionValue(CLIManager.ALTERNATE_GLOBAL_TOOLCHAINS));
1285             globalToolchainsFile = resolveFile(globalToolchainsFile, cliRequest.workingDirectory);
1286 
1287             if (!globalToolchainsFile.isFile()) {
1288                 throw new FileNotFoundException(
1289                         "The specified global toolchains file does not exist: " + globalToolchainsFile);
1290             }
1291         } else {
1292             globalToolchainsFile = DEFAULT_GLOBAL_TOOLCHAINS_FILE;
1293         }
1294 
1295         cliRequest.request.setGlobalToolchainsFile(globalToolchainsFile);
1296         cliRequest.request.setUserToolchainsFile(userToolchainsFile);
1297 
1298         DefaultToolchainsBuildingRequest toolchainsRequest = new DefaultToolchainsBuildingRequest();
1299         if (globalToolchainsFile.isFile()) {
1300             toolchainsRequest.setGlobalToolchainsSource(new FileSource(globalToolchainsFile));
1301         }
1302         if (userToolchainsFile.isFile()) {
1303             toolchainsRequest.setUserToolchainsSource(new FileSource(userToolchainsFile));
1304         }
1305 
1306         eventSpyDispatcher.onEvent(toolchainsRequest);
1307 
1308         slf4jLogger.debug(
1309                 "Reading global toolchains from {}",
1310                 getLocation(toolchainsRequest.getGlobalToolchainsSource(), globalToolchainsFile));
1311         slf4jLogger.debug(
1312                 "Reading user toolchains from {}",
1313                 getLocation(toolchainsRequest.getUserToolchainsSource(), userToolchainsFile));
1314 
1315         ToolchainsBuildingResult toolchainsResult = toolchainsBuilder.build(toolchainsRequest);
1316 
1317         eventSpyDispatcher.onEvent(toolchainsResult);
1318 
1319         executionRequestPopulator.populateFromToolchains(cliRequest.request, toolchainsResult.getEffectiveToolchains());
1320 
1321         if (!toolchainsResult.getProblems().isEmpty() && slf4jLogger.isWarnEnabled()) {
1322             slf4jLogger.warn("");
1323             slf4jLogger.warn("Some problems were encountered while building the effective toolchains");
1324 
1325             for (Problem problem : toolchainsResult.getProblems()) {
1326                 slf4jLogger.warn("{} @ {}", problem.getMessage(), problem.getLocation());
1327             }
1328 
1329             slf4jLogger.warn("");
1330         }
1331     }
1332 
1333     private Object getLocation(Source source, File defaultLocation) {
1334         if (source != null) {
1335             return source.getLocation();
1336         }
1337         return defaultLocation;
1338     }
1339 
1340     private MavenExecutionRequest populateRequest(CliRequest cliRequest) {
1341         return populateRequest(cliRequest, cliRequest.request);
1342     }
1343 
1344     @SuppressWarnings("checkstyle:methodlength")
1345     private MavenExecutionRequest populateRequest(CliRequest cliRequest, MavenExecutionRequest request) {
1346         CommandLine commandLine = cliRequest.commandLine;
1347         String workingDirectory = cliRequest.workingDirectory;
1348         boolean quiet = cliRequest.quiet;
1349         boolean showErrors = cliRequest.showErrors;
1350 
1351         String[] deprecatedOptions = {"up", "npu", "cpu", "npr"};
1352         for (String deprecatedOption : deprecatedOptions) {
1353             if (commandLine.hasOption(deprecatedOption)) {
1354                 slf4jLogger.warn(
1355                         "Command line option -{} is deprecated and will be removed in future Maven versions.",
1356                         deprecatedOption);
1357             }
1358         }
1359 
1360         // ----------------------------------------------------------------------
1361         // Now that we have everything that we need we will fire up plexus and
1362         // bring the maven component to life for use.
1363         // ----------------------------------------------------------------------
1364 
1365         if (commandLine.hasOption(CLIManager.BATCH_MODE)) {
1366             request.setInteractiveMode(false);
1367         }
1368 
1369         boolean noSnapshotUpdates = false;
1370         if (commandLine.hasOption(CLIManager.SUPRESS_SNAPSHOT_UPDATES)) {
1371             noSnapshotUpdates = true;
1372         }
1373 
1374         boolean updateSnapshots = false;
1375         if (commandLine.hasOption(CLIManager.UPDATE_SNAPSHOTS)) {
1376             updateSnapshots = true;
1377         }
1378 
1379         String artifactsUpdatePolicy = null;
1380         String metadataUpdatePolicy = null;
1381         if (commandLine.hasOption(CLIManager.UPDATE_ARTIFACTS)) {
1382             artifactsUpdatePolicy = RepositoryPolicy.UPDATE_POLICY_ALWAYS;
1383         }
1384         if (artifactsUpdatePolicy == null && commandLine.hasOption(CLIManager.ARTIFACTS_UPDATE_POLICY)) {
1385             artifactsUpdatePolicy = commandLine.getOptionValue(CLIManager.ARTIFACTS_UPDATE_POLICY);
1386         }
1387         if (commandLine.hasOption(CLIManager.UPDATE_METADATA)) {
1388             metadataUpdatePolicy = RepositoryPolicy.UPDATE_POLICY_ALWAYS;
1389         }
1390         if (metadataUpdatePolicy == null && commandLine.hasOption(CLIManager.METADATA_UPDATE_POLICY)) {
1391             metadataUpdatePolicy = commandLine.getOptionValue(CLIManager.METADATA_UPDATE_POLICY);
1392         }
1393 
1394         // ----------------------------------------------------------------------
1395         //
1396         // ----------------------------------------------------------------------
1397 
1398         List<String> goals = commandLine.getArgList();
1399 
1400         boolean recursive = true;
1401 
1402         // this is the default behavior.
1403         String reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_FAST;
1404 
1405         if (commandLine.hasOption(CLIManager.NON_RECURSIVE)) {
1406             recursive = false;
1407         }
1408 
1409         if (commandLine.hasOption(CLIManager.FAIL_FAST)) {
1410             reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_FAST;
1411         } else if (commandLine.hasOption(CLIManager.FAIL_AT_END)) {
1412             reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_AT_END;
1413         } else if (commandLine.hasOption(CLIManager.FAIL_NEVER)) {
1414             reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_NEVER;
1415         }
1416 
1417         if (commandLine.hasOption(CLIManager.OFFLINE)) {
1418             request.setOffline(true);
1419         }
1420 
1421         String globalChecksumPolicy = null;
1422 
1423         if (commandLine.hasOption(CLIManager.CHECKSUM_FAILURE_POLICY)) {
1424             globalChecksumPolicy = MavenExecutionRequest.CHECKSUM_POLICY_FAIL;
1425         } else if (commandLine.hasOption(CLIManager.CHECKSUM_WARNING_POLICY)) {
1426             globalChecksumPolicy = MavenExecutionRequest.CHECKSUM_POLICY_WARN;
1427         }
1428 
1429         File baseDirectory = new File(workingDirectory, "").getAbsoluteFile();
1430 
1431         // ----------------------------------------------------------------------
1432         // Profile Activation
1433         // ----------------------------------------------------------------------
1434 
1435         List<String> activeProfiles = new ArrayList<>();
1436 
1437         List<String> inactiveProfiles = new ArrayList<>();
1438 
1439         performProfileActivation(commandLine, activeProfiles, inactiveProfiles);
1440 
1441         TransferListener transferListener;
1442 
1443         if (quiet || cliRequest.commandLine.hasOption(CLIManager.NO_TRANSFER_PROGRESS)) {
1444             transferListener = new QuietMavenTransferListener();
1445         } else if (request.isInteractiveMode() && !cliRequest.commandLine.hasOption(CLIManager.LOG_FILE)) {
1446             //
1447             // If we're logging to a file then we don't want the console transfer listener as it will spew
1448             // download progress all over the place
1449             //
1450             transferListener = getConsoleTransferListener(cliRequest.commandLine.hasOption(CLIManager.DEBUG));
1451         } else {
1452             transferListener = getBatchTransferListener();
1453         }
1454 
1455         ExecutionListener executionListener = new ExecutionEventLogger();
1456         if (eventSpyDispatcher != null) {
1457             executionListener = eventSpyDispatcher.chainListener(executionListener);
1458         }
1459 
1460         String alternatePomFile = null;
1461         if (commandLine.hasOption(CLIManager.ALTERNATE_POM_FILE)) {
1462             alternatePomFile = commandLine.getOptionValue(CLIManager.ALTERNATE_POM_FILE);
1463         }
1464 
1465         request.setBaseDirectory(baseDirectory)
1466                 .setGoals(goals)
1467                 .setSystemProperties(cliRequest.systemProperties)
1468                 .setUserProperties(cliRequest.userProperties)
1469                 .setReactorFailureBehavior(reactorFailureBehaviour) // default: fail fast
1470                 .setRecursive(recursive) // default: true
1471                 .setShowErrors(showErrors) // default: false
1472                 .addActiveProfiles(activeProfiles) // optional
1473                 .addInactiveProfiles(inactiveProfiles) // optional
1474                 .setExecutionListener(executionListener)
1475                 .setTransferListener(transferListener) // default: batch mode which goes along with interactive
1476                 .setUpdateSnapshots(updateSnapshots) // default: false
1477                 .setNoSnapshotUpdates(noSnapshotUpdates) // default: false
1478                 .setArtifactsUpdatePolicy(artifactsUpdatePolicy) // default: null
1479                 .setMetadataUpdatePolicy(metadataUpdatePolicy) // default: null
1480                 .setGlobalChecksumPolicy(globalChecksumPolicy) // default: warn
1481                 .setMultiModuleProjectDirectory(cliRequest.multiModuleProjectDirectory);
1482 
1483         if (alternatePomFile != null) {
1484             File pom = resolveFile(new File(alternatePomFile), workingDirectory);
1485             if (pom.isDirectory()) {
1486                 pom = new File(pom, "pom.xml");
1487             }
1488 
1489             request.setPom(pom);
1490         } else if (modelProcessor != null) {
1491             File pom = modelProcessor.locatePom(baseDirectory);
1492 
1493             if (pom.isFile()) {
1494                 request.setPom(pom);
1495             }
1496         }
1497 
1498         if ((request.getPom() != null) && (request.getPom().getParentFile() != null)) {
1499             request.setBaseDirectory(request.getPom().getParentFile());
1500         }
1501 
1502         if (commandLine.hasOption(CLIManager.RESUME_FROM)) {
1503             request.setResumeFrom(commandLine.getOptionValue(CLIManager.RESUME_FROM));
1504         }
1505 
1506         if (commandLine.hasOption(CLIManager.PROJECT_LIST)) {
1507             String[] projectOptionValues = commandLine.getOptionValues(CLIManager.PROJECT_LIST);
1508 
1509             List<String> inclProjects = new ArrayList<>();
1510             List<String> exclProjects = new ArrayList<>();
1511 
1512             if (projectOptionValues != null) {
1513                 for (String projectOptionValue : projectOptionValues) {
1514                     StringTokenizer projectTokens = new StringTokenizer(projectOptionValue, ",");
1515 
1516                     while (projectTokens.hasMoreTokens()) {
1517                         String projectAction = projectTokens.nextToken().trim();
1518 
1519                         if (projectAction.startsWith("-") || projectAction.startsWith("!")) {
1520                             exclProjects.add(projectAction.substring(1));
1521                         } else if (projectAction.startsWith("+")) {
1522                             inclProjects.add(projectAction.substring(1));
1523                         } else {
1524                             inclProjects.add(projectAction);
1525                         }
1526                     }
1527                 }
1528             }
1529 
1530             request.setSelectedProjects(inclProjects);
1531             request.setExcludedProjects(exclProjects);
1532         }
1533 
1534         if (commandLine.hasOption(CLIManager.ALSO_MAKE) && !commandLine.hasOption(CLIManager.ALSO_MAKE_DEPENDENTS)) {
1535             request.setMakeBehavior(MavenExecutionRequest.REACTOR_MAKE_UPSTREAM);
1536         } else if (!commandLine.hasOption(CLIManager.ALSO_MAKE)
1537                 && commandLine.hasOption(CLIManager.ALSO_MAKE_DEPENDENTS)) {
1538             request.setMakeBehavior(MavenExecutionRequest.REACTOR_MAKE_DOWNSTREAM);
1539         } else if (commandLine.hasOption(CLIManager.ALSO_MAKE)
1540                 && commandLine.hasOption(CLIManager.ALSO_MAKE_DEPENDENTS)) {
1541             request.setMakeBehavior(MavenExecutionRequest.REACTOR_MAKE_BOTH);
1542         }
1543 
1544         String localRepoProperty = request.getUserProperties().getProperty(MavenCli.LOCAL_REPO_PROPERTY);
1545 
1546         // TODO Investigate why this can also be a Java system property and not just a Maven user property like
1547         // other properties
1548         if (localRepoProperty == null) {
1549             localRepoProperty = request.getSystemProperties().getProperty(MavenCli.LOCAL_REPO_PROPERTY);
1550         }
1551 
1552         if (localRepoProperty != null) {
1553             request.setLocalRepositoryPath(localRepoProperty);
1554         }
1555 
1556         request.setCacheNotFound(true);
1557         request.setCacheTransferError(false);
1558         request.setIgnoreTransitiveRepositories(commandLine.hasOption(CLIManager.IGNORE_TRANSITIVE_REPOSITORIES));
1559 
1560         //
1561         // Builder, concurrency and parallelism
1562         //
1563         // We preserve the existing methods for builder selection which is to look for various inputs in the threading
1564         // configuration. We don't have an easy way to allow a pluggable builder to provide its own configuration
1565         // parameters but this is sufficient for now. Ultimately we want components like Builders to provide a way to
1566         // extend the command line to accept its own configuration parameters.
1567         //
1568         final String threadConfiguration =
1569                 commandLine.hasOption(CLIManager.THREADS) ? commandLine.getOptionValue(CLIManager.THREADS) : null;
1570 
1571         if (threadConfiguration != null) {
1572             int degreeOfConcurrency = calculateDegreeOfConcurrency(threadConfiguration);
1573             if (degreeOfConcurrency > 1) {
1574                 request.setBuilderId("multithreaded");
1575                 request.setDegreeOfConcurrency(degreeOfConcurrency);
1576             }
1577         }
1578 
1579         //
1580         // Allow the builder to be overridden by the user if requested. The builders are now pluggable.
1581         //
1582         if (commandLine.hasOption(CLIManager.BUILDER)) {
1583             request.setBuilderId(commandLine.getOptionValue(CLIManager.BUILDER));
1584         }
1585 
1586         return request;
1587     }
1588 
1589     int calculateDegreeOfConcurrency(String originalThreadConfiguration) {
1590         String threadConfiguration = originalThreadConfiguration.trim();
1591         if (threadConfiguration.endsWith("C")) {
1592             threadConfiguration = threadConfiguration.substring(0, threadConfiguration.length() - 1);
1593 
1594             try {
1595                 float coreMultiplier = Float.parseFloat(threadConfiguration);
1596 
1597                 if (coreMultiplier <= 0.0f) {
1598                     throw new IllegalArgumentException("Invalid threads core multiplier value: '" + threadConfiguration
1599                             + "C'. Value must be positive.");
1600                 }
1601 
1602                 int procs = Runtime.getRuntime().availableProcessors();
1603                 int threads = (int) (coreMultiplier * procs);
1604                 return threads == 0 ? 1 : threads;
1605             } catch (NumberFormatException e) {
1606                 throw new IllegalArgumentException(
1607                         "Invalid threads core multiplier value: '" + threadConfiguration
1608                                 + "C'. Supported are int and float values ending with C.",
1609                         e);
1610             }
1611         } else {
1612             try {
1613                 int threads = Integer.parseInt(threadConfiguration);
1614 
1615                 if (threads <= 0) {
1616                     throw new IllegalArgumentException(
1617                             "Invalid threads value: '" + threadConfiguration + "'. Value must be positive.");
1618                 }
1619 
1620                 return threads;
1621             } catch (NumberFormatException e) {
1622                 throw new IllegalArgumentException(
1623                         "Invalid threads value: '" + threadConfiguration + "'. Supported are integer values.");
1624             }
1625         }
1626     }
1627 
1628     // Visible for testing
1629     static void performProfileActivation(
1630             final CommandLine commandLine, final List<String> activeProfiles, final List<String> inactiveProfiles) {
1631         if (commandLine.hasOption(CLIManager.ACTIVATE_PROFILES)) {
1632             String[] profileOptionValues = commandLine.getOptionValues(CLIManager.ACTIVATE_PROFILES);
1633             if (profileOptionValues != null) {
1634                 for (String profileOptionValue : profileOptionValues) {
1635                     StringTokenizer profileTokens = new StringTokenizer(profileOptionValue, ",");
1636 
1637                     while (profileTokens.hasMoreTokens()) {
1638                         String profileId = profileTokens.nextToken().trim();
1639                         boolean active = true;
1640 
1641                         if (profileId.startsWith("-") || profileId.startsWith("!")) {
1642                             active = false;
1643                             profileId = profileId.substring(1);
1644                         } else if (profileId.startsWith("+")) {
1645                             profileId = profileId.substring(1);
1646                         }
1647 
1648                         // "?id" is an optional profile in Maven 4; Maven 3 never fails on a missing profile,
1649                         // so the prefix only has to be removed
1650                         if (profileId.startsWith("?")) {
1651                             profileId = profileId.substring(1);
1652                         }
1653 
1654                         if (profileId.isEmpty()) {
1655                             continue;
1656                         }
1657 
1658                         if (active) {
1659                             activeProfiles.add(profileId);
1660                         } else {
1661                             inactiveProfiles.add(profileId);
1662                         }
1663                     }
1664                 }
1665             }
1666         }
1667     }
1668 
1669     // ----------------------------------------------------------------------
1670     // Properties handling
1671     // ----------------------------------------------------------------------
1672 
1673     static void populateProperties(CliRequest cliRequest, Properties systemProperties, Properties userProperties)
1674             throws InterpolationException {
1675 
1676         // ----------------------------------------------------------------------
1677         // Options that are set on the command line become system properties
1678         // and therefore are set in the session properties. System properties
1679         // are most dominant.
1680         // ----------------------------------------------------------------------
1681 
1682         Properties cliProperties = new Properties();
1683         if (cliRequest.commandLine.hasOption(CLIManager.SET_USER_PROPERTY)) {
1684             String[] defStrs = cliRequest.commandLine.getOptionValues(CLIManager.SET_USER_PROPERTY);
1685 
1686             if (defStrs != null) {
1687                 String name;
1688                 String value;
1689                 for (String property : defStrs) {
1690                     int i = property.indexOf('=');
1691                     if (i <= 0) {
1692                         name = property.trim();
1693                         value = "true";
1694                     } else {
1695                         name = property.substring(0, i).trim();
1696                         value = property.substring(i + 1);
1697                     }
1698                     cliProperties.setProperty(name, value);
1699                 }
1700             }
1701         }
1702 
1703         EnvironmentUtils.addEnvVars(systemProperties);
1704         SystemProperties.addSystemProperties(systemProperties);
1705 
1706         // one distinguished env variable: MAVEN_REPO_CENTRAL; if present, we make it into property
1707         if (systemProperties.containsKey(MAVEN_REPO_CENTRAL_ENV)) {
1708             systemProperties.put(
1709                     ModelInterpolator.MAVEN_REPO_CENTRAL_KEY, systemProperties.getProperty(MAVEN_REPO_CENTRAL_ENV));
1710         }
1711 
1712         StringSearchInterpolator interpolator = createInterpolator(cliRequest, cliProperties, systemProperties);
1713         for (Map.Entry<Object, Object> e : cliProperties.entrySet()) {
1714             String name = (String) e.getKey();
1715             String value = interpolator.interpolate((String) e.getValue());
1716             userProperties.setProperty(name, value);
1717         }
1718 
1719         systemProperties.putAll(userProperties);
1720 
1721         // ----------------------------------------------------------------------
1722         // I'm leaving the setting of system properties here as not to break
1723         // the SystemPropertyProfileActivator. This won't harm embedding. jvz.
1724         // ----------------------------------------------------------------------
1725         userProperties.forEach((k, v) -> System.setProperty((String) k, (String) v));
1726 
1727         // ----------------------------------------------------------------------
1728         // Properties containing info about the currently running version of Maven
1729         // These override any corresponding properties set on the command line
1730         // ----------------------------------------------------------------------
1731 
1732         Properties buildProperties = CLIReportingUtils.getBuildProperties();
1733 
1734         String mavenVersion = buildProperties.getProperty(CLIReportingUtils.BUILD_VERSION_PROPERTY);
1735         systemProperties.setProperty("maven.version", mavenVersion);
1736 
1737         String mavenBuildVersion = CLIReportingUtils.createMavenVersionString(buildProperties);
1738         systemProperties.setProperty("maven.build.version", mavenBuildVersion);
1739     }
1740 
1741     protected static StringSearchInterpolator createInterpolator(CliRequest cliRequest, Properties... properties) {
1742         StringSearchInterpolator interpolator = new StringSearchInterpolator();
1743         interpolator.addValueSource(new AbstractValueSource(false) {
1744             @Override
1745             public Object getValue(String expression) {
1746                 if ("session.topDirectory".equals(expression)) {
1747                     Path topDirectory = cliRequest.request.getTopDirectory();
1748                     if (topDirectory != null) {
1749                         return topDirectory.toString();
1750                     } else {
1751                         throw new IllegalUseOfUndefinedProperty(expression);
1752                     }
1753                 } else if ("session.rootDirectory".equals(expression)) {
1754                     try {
1755                         return cliRequest.request.getRootDirectory();
1756                     } catch (IllegalStateException e) {
1757                         throw new IllegalUseOfUndefinedProperty(expression);
1758                     }
1759                 }
1760                 return null;
1761             }
1762         });
1763         interpolator.addValueSource(new AbstractValueSource(false) {
1764             @Override
1765             public Object getValue(String expression) {
1766                 for (Properties props : properties) {
1767                     Object val = props.getProperty(expression);
1768                     if (val != null) {
1769                         return val;
1770                     }
1771                 }
1772                 return null;
1773             }
1774         });
1775         return interpolator;
1776     }
1777 
1778     private static String stripLeadingAndTrailingQuotes(String str) {
1779         final int length = str.length();
1780         if (length > 1
1781                 && str.startsWith("\"")
1782                 && str.endsWith("\"")
1783                 && str.substring(1, length - 1).indexOf('"') == -1) {
1784             str = str.substring(1, length - 1);
1785         }
1786 
1787         return str;
1788     }
1789 
1790     private static Path getCanonicalPath(Path path) {
1791         return path.toAbsolutePath().normalize();
1792     }
1793 
1794     static class ExitException extends Exception {
1795         int exitCode;
1796 
1797         ExitException(int exitCode) {
1798             this.exitCode = exitCode;
1799         }
1800     }
1801 
1802     static class IllegalUseOfUndefinedProperty extends IllegalArgumentException {
1803         final String property;
1804 
1805         IllegalUseOfUndefinedProperty(String property) {
1806             this.property = property;
1807         }
1808     }
1809 
1810     //
1811     // Customizations available via the CLI
1812     //
1813 
1814     protected TransferListener getConsoleTransferListener(boolean printResourceNames) {
1815         return new SimplexTransferListener(new ConsoleMavenTransferListener(System.out, printResourceNames));
1816     }
1817 
1818     protected TransferListener getBatchTransferListener() {
1819         return new Slf4jMavenTransferListener();
1820     }
1821 
1822     protected void customizeContainer(PlexusContainer container) {}
1823 
1824     protected ModelProcessor createModelProcessor(PlexusContainer container) throws ComponentLookupException {
1825         return container.lookup(ModelProcessor.class);
1826     }
1827 }