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