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