From 8f85d87b5c2724665b203e82ce176c10ecb83953 Mon Sep 17 00:00:00 2001 From: Jason van Zyl Date: Mon, 26 Oct 2009 21:42:53 +0000 Subject: [PATCH] o another pass at cleaning up the MavenCli, it still needs work but at least I can see a pattern now for embedding git-svn-id: https://svn.apache.org/repos/asf/maven/maven-3/trunk@829988 13f79535-47bb-0310-9956-ffa450edef68 --- .../java/org/apache/maven/DefaultMaven.java | 11 +- .../cli/BatchModeMavenTransferListener.java | 1 - .../org/apache/maven/cli/Configuration.java | 39 -- .../cli/ConfigurationValidationResult.java | 56 -- .../maven/cli/DefaultConfiguration.java | 51 -- .../DefaultConfigurationValidationResult.java | 107 --- .../java/org/apache/maven/cli/MavenCli.java | 630 ++++++++---------- 7 files changed, 283 insertions(+), 612 deletions(-) delete mode 100644 maven-embedder/src/main/java/org/apache/maven/cli/Configuration.java delete mode 100644 maven-embedder/src/main/java/org/apache/maven/cli/ConfigurationValidationResult.java delete mode 100644 maven-embedder/src/main/java/org/apache/maven/cli/DefaultConfiguration.java delete mode 100644 maven-embedder/src/main/java/org/apache/maven/cli/DefaultConfigurationValidationResult.java diff --git a/maven-core/src/main/java/org/apache/maven/DefaultMaven.java b/maven-core/src/main/java/org/apache/maven/DefaultMaven.java index 047df19ea0..59d938211e 100644 --- a/maven-core/src/main/java/org/apache/maven/DefaultMaven.java +++ b/maven-core/src/main/java/org/apache/maven/DefaultMaven.java @@ -34,6 +34,8 @@ import org.apache.maven.execution.DefaultMavenExecutionResult; import org.apache.maven.execution.ExecutionEvent; import org.apache.maven.execution.ExecutionListener; import org.apache.maven.execution.MavenExecutionRequest; +import org.apache.maven.execution.MavenExecutionRequestPopulationException; +import org.apache.maven.execution.MavenExecutionRequestPopulator; import org.apache.maven.execution.MavenExecutionResult; import org.apache.maven.execution.MavenSession; import org.apache.maven.execution.ProjectDependencyGraph; @@ -76,6 +78,9 @@ public class DefaultMaven @Requirement protected PlexusContainer container; + @Requirement + MavenExecutionRequestPopulator populator; + private void fireEvent( MavenSession session, ExecutionEventCatapult catapult ) { ExecutionListener listener = session.getRequest().getExecutionListener(); @@ -94,12 +99,16 @@ public class DefaultMaven try { - result = doExecute( request ); + result = doExecute( populator.populateDefaults( request ) ); } catch ( OutOfMemoryError e ) { result = processResult( new DefaultMavenExecutionResult(), e ); } + catch ( MavenExecutionRequestPopulationException e ) + { + result = processResult( new DefaultMavenExecutionResult(), e ); + } return result; } diff --git a/maven-embedder/src/main/java/org/apache/maven/cli/BatchModeMavenTransferListener.java b/maven-embedder/src/main/java/org/apache/maven/cli/BatchModeMavenTransferListener.java index 837aa346cd..1ca2818799 100644 --- a/maven-embedder/src/main/java/org/apache/maven/cli/BatchModeMavenTransferListener.java +++ b/maven-embedder/src/main/java/org/apache/maven/cli/BatchModeMavenTransferListener.java @@ -24,7 +24,6 @@ import java.io.PrintStream; class BatchModeMavenTransferListener extends AbstractMavenTransferListener { - public BatchModeMavenTransferListener( PrintStream out ) { super( out ); diff --git a/maven-embedder/src/main/java/org/apache/maven/cli/Configuration.java b/maven-embedder/src/main/java/org/apache/maven/cli/Configuration.java deleted file mode 100644 index 05c9b614a8..0000000000 --- a/maven-embedder/src/main/java/org/apache/maven/cli/Configuration.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.apache.maven.cli; -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import java.io.File; -import java.net.URL; -import java.util.List; -import java.util.Properties; - -import org.codehaus.plexus.PlexusContainer; -import org.codehaus.plexus.classworlds.ClassWorld; -import org.codehaus.plexus.logging.Logger; - -public interface Configuration -{ - Configuration setUserSettingsFile( File userSettingsFile ); - - File getUserSettingsFile(); - - Configuration setGlobalSettingsFile( File globalSettingsFiles ); - - File getGlobalSettingsFile(); -} diff --git a/maven-embedder/src/main/java/org/apache/maven/cli/ConfigurationValidationResult.java b/maven-embedder/src/main/java/org/apache/maven/cli/ConfigurationValidationResult.java deleted file mode 100644 index a31b96aebe..0000000000 --- a/maven-embedder/src/main/java/org/apache/maven/cli/ConfigurationValidationResult.java +++ /dev/null @@ -1,56 +0,0 @@ -package org.apache.maven.cli; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.apache.maven.settings.Settings; - -/** - * @author Jason van Zyl - * TODO remove deprecated methods - */ -public interface ConfigurationValidationResult -{ - /** - * Whether both user and global settings are valid - */ - boolean isValid(); - - /** - * Parsed user settings. If there's any parse error, it can be retrieved through - * {@link #getUserSettingsException()} - */ - Settings getUserSettings(); - - /** - * Parsed global settings. If there's any parse error, it can be retrieved through - * {@link #getGlobalSettingsException()} - */ - Settings getGlobalSettings(); - - /** - * Any exception that happened during parsing user settings, or null if there were no errors. - */ - Exception getUserSettingsException(); - - /** - * Any exception that happened during parsing global settings, or null if there were no errors. - */ - Exception getGlobalSettingsException(); -} diff --git a/maven-embedder/src/main/java/org/apache/maven/cli/DefaultConfiguration.java b/maven-embedder/src/main/java/org/apache/maven/cli/DefaultConfiguration.java deleted file mode 100644 index 92bfc071ab..0000000000 --- a/maven-embedder/src/main/java/org/apache/maven/cli/DefaultConfiguration.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.apache.maven.cli; -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import java.io.File; - -public class DefaultConfiguration - implements Configuration -{ - private File userSettings; - - private File globalSettings; - - public Configuration setUserSettingsFile( File user ) - { - userSettings = user; - return this; - } - - public Configuration setGlobalSettingsFile( File global ) - { - globalSettings = global; - return this; - } - - public File getUserSettingsFile() - { - return userSettings; - } - - public File getGlobalSettingsFile() - { - return globalSettings; - } -} diff --git a/maven-embedder/src/main/java/org/apache/maven/cli/DefaultConfigurationValidationResult.java b/maven-embedder/src/main/java/org/apache/maven/cli/DefaultConfigurationValidationResult.java deleted file mode 100644 index 12f95c664f..0000000000 --- a/maven-embedder/src/main/java/org/apache/maven/cli/DefaultConfigurationValidationResult.java +++ /dev/null @@ -1,107 +0,0 @@ -package org.apache.maven.cli; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import java.io.FileNotFoundException; - -import org.apache.maven.settings.Settings; - -/** - * @author Jason van Zyl - */ -public class DefaultConfigurationValidationResult - implements ConfigurationValidationResult -{ - private Exception userSettingsException; - - private Exception globalSettingsException; - - private Settings userSettings, globalSettings; - - public boolean isValid() - { - return ( getUserSettingsException() == null ) && ( getGlobalSettingsException() == null ); - } - - public Exception getUserSettingsException() - { - return userSettingsException; - } - - public void setUserSettingsException( Exception e ) - { - this.userSettingsException = e; - } - - public Exception getGlobalSettingsException() - { - return globalSettingsException; - } - - public void setGlobalSettingsException( Exception e ) - { - this.globalSettingsException = e; - } - - public Settings getUserSettings() - { - return userSettings; - } - - public void setUserSettings( Settings settings ) - { - this.userSettings = settings; - } - - public Settings getGlobalSettings() - { - return globalSettings; - } - - public void setGlobalSettings( Settings globalSettings ) - { - this.globalSettings = globalSettings; - } - - public boolean isGlobalSettingsFileParses() - { - return getGlobalSettings() != null; - } - - public boolean isGlobalSettingsFilePresent() - { - return isSettingsFilePresent( getGlobalSettings(), getGlobalSettingsException() ); - } - - public boolean isUserSettingsFileParses() - { - return getUserSettings() != null; - } - - public boolean isUserSettingsFilePresent() - { - return isSettingsFilePresent( getUserSettings(), getUserSettingsException() ); - } - - private boolean isSettingsFilePresent( Settings settings, Throwable e ) - { - return ( settings != null ) || ( ( e != null ) && !( e instanceof FileNotFoundException ) ); - } -} diff --git a/maven-embedder/src/main/java/org/apache/maven/cli/MavenCli.java b/maven-embedder/src/main/java/org/apache/maven/cli/MavenCli.java index bff75775d5..ffb9a654bd 100644 --- a/maven-embedder/src/main/java/org/apache/maven/cli/MavenCli.java +++ b/maven-embedder/src/main/java/org/apache/maven/cli/MavenCli.java @@ -35,17 +35,12 @@ import org.apache.maven.exception.DefaultExceptionHandler; import org.apache.maven.exception.ExceptionHandler; import org.apache.maven.exception.ExceptionSummary; import org.apache.maven.execution.DefaultMavenExecutionRequest; -import org.apache.maven.execution.DefaultMavenExecutionResult; -import org.apache.maven.execution.MavenExecutionRequestPopulationException; import org.apache.maven.execution.MavenExecutionRequest; -import org.apache.maven.execution.MavenExecutionRequestPopulator; import org.apache.maven.execution.MavenExecutionResult; import org.apache.maven.model.building.ModelProcessor; import org.apache.maven.repository.ArtifactTransferListener; -import org.apache.maven.settings.Settings; import org.apache.maven.settings.building.DefaultSettingsBuildingRequest; import org.apache.maven.settings.building.SettingsBuilder; -import org.apache.maven.settings.building.SettingsBuildingException; import org.apache.maven.settings.building.SettingsBuildingRequest; import org.apache.maven.settings.building.SettingsBuildingResult; import org.apache.maven.settings.building.SettingsProblem; @@ -53,9 +48,7 @@ import org.codehaus.plexus.ContainerConfiguration; import org.codehaus.plexus.DefaultContainerConfiguration; import org.codehaus.plexus.DefaultPlexusContainer; import org.codehaus.plexus.PlexusContainer; -import org.codehaus.plexus.PlexusContainerException; import org.codehaus.plexus.classworlds.ClassWorld; -import org.codehaus.plexus.component.repository.exception.ComponentLifecycleException; import org.codehaus.plexus.component.repository.exception.ComponentLookupException; import org.codehaus.plexus.util.StringUtils; import org.codehaus.plexus.util.cli.CommandLineUtils; @@ -65,8 +58,10 @@ import org.sonatype.plexus.components.sec.dispatcher.SecDispatcher; import org.sonatype.plexus.components.sec.dispatcher.SecUtil; import org.sonatype.plexus.components.sec.dispatcher.model.SettingsSecurity; +// TODO: push all common bits back to plexus cli and prepare for transition to Guice. We don't need 50 ways to make CLIs + /** - * @author jason van zyl + * @author Jason van Zyl * @noinspection UseOfSystemOutOrSystemErr,ACCESS_STATIC_VIA_INSTANCE */ public class MavenCli @@ -79,16 +74,21 @@ public class MavenCli public static final File DEFAULT_USER_SETTINGS_FILE = new File( userMavenConfigurationHome, "settings.xml" ); - public static final File DEFAULT_GLOBAL_SETTINGS_FILE = - new File( System.getProperty( "maven.home", System.getProperty( "user.dir", "" ) ), "conf/settings.xml" ); + public static final File DEFAULT_GLOBAL_SETTINGS_FILE = new File( System.getProperty( "maven.home", System.getProperty( "user.dir", "" ) ), "conf/settings.xml" ); public static final File DEFAULT_USER_TOOLCHAINS_FILE = new File( userMavenConfigurationHome, "toolchains.xml" ); - private DefaultPlexusContainer container; - private PrintStreamLogger logger; private ModelProcessor modelProcessor; + + private Maven maven; + + private SettingsBuilder settingsBuilder; + + private DefaultSecDispatcher dispatcher; + + private enum Exit { EXIT_WITH_ERROR, EXIT_WITHOUT_ERROR } public static void main( String[] args ) { @@ -100,375 +100,252 @@ public class MavenCli /** @noinspection ConfusingMainMethod */ public static int main( String[] args, ClassWorld classWorld ) { - MavenCli cli = new MavenCli( classWorld ); - - return cli.doMain( args, null, System.out, System.err ); + MavenCli cli = new MavenCli(); + return cli.doMain( new CliRequest( args, classWorld ) ); } - public MavenCli() + // TODO: need to externalize CliRequest + public static int doMain( String[] args, ClassWorld classWorld ) { - this( null ); + MavenCli cli = new MavenCli(); + return cli.doMain( new CliRequest( args, classWorld ) ); } - - public MavenCli( ClassWorld classWorld ) - { - if ( classWorld == null ) - { - classWorld = new ClassWorld( "plexus.core", Thread.currentThread().getContextClassLoader() ); - } - - try - { - ContainerConfiguration cc = - new DefaultContainerConfiguration().setClassWorld( classWorld ).setName( "embedder" ); - - container = new DefaultPlexusContainer( cc ); - } - catch ( PlexusContainerException e ) - { - throw new IllegalStateException( "Could not start component container: " + e.getMessage(), e ); - } - - logger = new PrintStreamLogger( System.out ); - - container.setLoggerManager( new MavenLoggerManager( logger ) ); - customizeContainer( container ); - } - - protected void customizeContainer( PlexusContainer container ) - { - } - - public int doMain( String[] args, String workingDirectory, PrintStream stdout, PrintStream stderr ) + // TODO: need to externalize CliRequest + public int doMain( CliRequest cliRequest ) { - if ( stdout == null ) - { - stdout = System.out; - } - if ( stderr == null ) - { - stderr = System.err; - } - if ( workingDirectory == null ) - { - workingDirectory = System.getProperty( "user.dir" ); - } - - // ---------------------------------------------------------------------- - // Setup the command line parser - // ---------------------------------------------------------------------- - - CLIManager cliManager = new CLIManager(); - - CommandLine commandLine; try { - commandLine = cliManager.parse( args ); + initialize( cliRequest ); + // Need to process cli options first to get possible logging options + cli( cliRequest ); + logging( cliRequest ); + commands( cliRequest ); + container( cliRequest ); + settings( cliRequest ); + populateRequest( cliRequest ); + encryption( cliRequest ); + return execute( cliRequest ); } - catch ( ParseException e ) - { - stderr.println( "Unable to parse command line options: " + e.getMessage() ); - cliManager.displayHelp( stdout ); + catch( Exception e ) + { + CLIReportingUtils.showError( logger, "Error executing Maven.", e, cliRequest.showErrors ); + return 1; } - - boolean debug = commandLine.hasOption( CLIManager.DEBUG ); - - boolean quiet = !debug && commandLine.hasOption( CLIManager.QUIET ); - - boolean showErrors = debug || commandLine.hasOption( CLIManager.ERRORS ); - - // ---------------------------------------------------------------------- - // Process particular command line options - // ---------------------------------------------------------------------- - - if ( commandLine.hasOption( CLIManager.HELP ) ) + finally { - cliManager.displayHelp( stdout ); - - return 0; + if ( cliRequest.fileStream != null ) + { + cliRequest.fileStream.close(); + } } + } - if ( commandLine.hasOption( CLIManager.VERSION ) ) + private void initialize( CliRequest cliRequest ) + { + if ( cliRequest.workingDirectory == null ) { - CLIReportingUtils.showVersion( stdout ); - - return 0; - } - + cliRequest.workingDirectory = System.getProperty( "user.dir" ); + } + + // // Make sure the Maven home directory is an absolute path to save us from confusion with say drive-relative // Windows paths. + // String mavenHome = System.getProperty( "maven.home" ); + if ( mavenHome != null ) { System.setProperty( "maven.home", new File( mavenHome ).getAbsolutePath() ); - } - - PrintStream fileStream = null; - - if ( commandLine.hasOption( CLIManager.LOG_FILE ) ) + } + } + + // + // Logging needs to be handled in a standard way at the container level. + // + private void logging( CliRequest cliRequest ) + { + if ( cliRequest.stdout == null ) { - File logFile = new File( commandLine.getOptionValue( CLIManager.LOG_FILE ) ); - logFile = resolveFile( logFile, workingDirectory ); + cliRequest.stdout = System.out; + } + if ( cliRequest.stderr == null ) + { + cliRequest.stderr = System.err; + } + + logger = new PrintStreamLogger( System.out ); + + if ( cliRequest.commandLine.hasOption( CLIManager.LOG_FILE ) ) + { + File logFile = new File( cliRequest.commandLine.getOptionValue( CLIManager.LOG_FILE ) ); + logFile = resolveFile( logFile, cliRequest.workingDirectory ); try { - fileStream = new PrintStream( logFile ); - logger.setStream( fileStream ); + cliRequest.fileStream = new PrintStream( logFile ); + logger.setStream( cliRequest.fileStream ); } catch ( FileNotFoundException e ) { - stderr.println( e ); - logger.setStream( stdout ); + cliRequest.stderr.println( e ); + logger.setStream( cliRequest.stdout ); } } else { - logger.setStream( stdout ); - } - - // - - Maven maven; - - try - { - maven = container.lookup( Maven.class ); - - modelProcessor = createModelProcessor( container ); - } - catch ( ComponentLookupException e ) - { - CLIReportingUtils.showError( logger, "Unable to start the embedder: ", e, showErrors ); - - return 1; + logger.setStream( cliRequest.stdout ); } - Configuration configuration = buildEmbedderConfiguration( commandLine, workingDirectory ); + cliRequest.request.setExecutionListener( new ExecutionEventLogger( logger ) ); + } + + // + // Every bit of information taken from the CLI should be processed here. + // + private void cli( CliRequest request ) + { + CLIManager cliManager = new CLIManager(); + + try + { + request.commandLine = cliManager.parse( request.args ); + } + catch ( ParseException e ) + { + request.stderr.println( "Unable to parse command line options: " + e.getMessage() ); + cliManager.displayHelp( request.stdout ); + request.exit = Exit.EXIT_WITH_ERROR; + } + + request.debug = request.commandLine.hasOption( CLIManager.DEBUG ); + request.quiet = !request.debug && request.commandLine.hasOption( CLIManager.QUIET ); + request.showErrors = request.debug || request.commandLine.hasOption( CLIManager.ERRORS ); + + // TODO: these should be moved out of here. Wrong place. + // + if ( request.commandLine.hasOption( CLIManager.HELP ) ) + { + cliManager.displayHelp( request.stdout ); + request.exit = Exit.EXIT_WITHOUT_ERROR; + } + + if ( request.commandLine.hasOption( CLIManager.VERSION ) ) + { + CLIReportingUtils.showVersion( request.stdout ); + request.exit = Exit.EXIT_WITHOUT_ERROR; + } + } - MavenExecutionRequest request = new DefaultMavenExecutionRequest(); - - request.setGlobalSettingsFile( configuration.getGlobalSettingsFile() ); - request.setUserSettingsFile( configuration.getUserSettingsFile() ); - - populateProperties( request, commandLine ); - - Settings settings; - - try + private void commands( CliRequest cliRequest ) + { + if ( cliRequest.debug || cliRequest.commandLine.hasOption( CLIManager.SHOW_VERSION ) ) { - SettingsBuildingRequest settingsRequest = new DefaultSettingsBuildingRequest(); - settingsRequest.setGlobalSettingsFile( configuration.getGlobalSettingsFile() ); - settingsRequest.setUserSettingsFile( configuration.getUserSettingsFile() ); - settingsRequest.setSystemProperties( request.getSystemProperties() ); - settingsRequest.setUserProperties( request.getUserProperties() ); - - SettingsBuilder settingsBuilder = container.lookup( SettingsBuilder.class ); - - try - { - SettingsBuildingResult settingsResult = settingsBuilder.build( settingsRequest ); - - settings = settingsResult.getEffectiveSettings(); - - if ( !settingsResult.getProblems().isEmpty() && logger.isWarnEnabled() ) - { - logger.warn( "" ); - logger.warn( "Some problems were encountered while building the effective settings" ); - - for ( SettingsProblem problem : settingsResult.getProblems() ) - { - logger.warn( problem.getMessage() + " @ " + problem.getLocation() ); - } - - logger.warn( "" ); - } - } - finally - { - try - { - container.release( settingsBuilder ); - } - catch ( ComponentLifecycleException e ) - { - logger.debug( "Failed to release component: " + e.getMessage(), e ); - } - } - } - catch ( ComponentLookupException e ) - { - CLIReportingUtils.showError( logger, "Unable to lookup settings builder: ", e, showErrors ); - - return 1; - } - catch ( SettingsBuildingException e ) - { - CLIReportingUtils.showError( logger, "Failed to read settings: ", e, showErrors ); - - return 1; + CLIReportingUtils.showVersion( cliRequest.stdout ); } - try - { - MavenExecutionRequestPopulator requestPopulator = container.lookup( MavenExecutionRequestPopulator.class ); - - try - { - requestPopulator.populateFromSettings( request, settings ); - } - finally - { - try - { - container.release( requestPopulator ); - } - catch ( ComponentLifecycleException e ) - { - logger.debug( "Failed to release component: " + e.getMessage(), e ); - } - } - } - catch ( ComponentLookupException e ) - { - CLIReportingUtils.showError( logger, "Unable to lookup execution request populator: ", e, showErrors ); - - return 1; - } - catch ( MavenExecutionRequestPopulationException e ) - { - CLIReportingUtils.showError( logger, "Failed to process settings: ", e, showErrors ); - - return 1; - } - - populateRequest( request, commandLine, workingDirectory, debug, quiet, showErrors, stdout ); - - request.setExecutionListener( new ExecutionEventLogger( logger ) ); - - container.getLoggerManager().setThresholds( request.getLoggingLevel() ); - - if ( debug || commandLine.hasOption( CLIManager.SHOW_VERSION ) ) - { - CLIReportingUtils.showVersion( stdout ); - } - - if ( showErrors ) + if ( cliRequest.showErrors ) { logger.info( "Error stacktraces are turned on." ); } - if ( MavenExecutionRequest.CHECKSUM_POLICY_WARN.equals( request.getGlobalChecksumPolicy() ) ) + // + // TODO: move checksum policies to + // + if ( MavenExecutionRequest.CHECKSUM_POLICY_WARN.equals( cliRequest.request.getGlobalChecksumPolicy() ) ) { logger.info( "Disabling strict checksum verification on all artifact downloads." ); } - else if ( MavenExecutionRequest.CHECKSUM_POLICY_FAIL.equals( request.getGlobalChecksumPolicy() ) ) + else if ( MavenExecutionRequest.CHECKSUM_POLICY_FAIL.equals( cliRequest.request.getGlobalChecksumPolicy() ) ) { logger.info( "Enabling strict checksum verification on all artifact downloads." ); } - - if ( configuration.getGlobalSettingsFile() != null ) + } + + private void container( CliRequest cliRequest ) + throws Exception + { + if ( cliRequest.classWorld == null ) { - request.setGlobalSettingsFile( configuration.getGlobalSettingsFile() ); + cliRequest.classWorld = new ClassWorld( "plexus.core", Thread.currentThread().getContextClassLoader() ); } - if ( configuration.getUserSettingsFile() != null ) - { - request.setUserSettingsFile( configuration.getUserSettingsFile() ); - } + ContainerConfiguration cc = new DefaultContainerConfiguration() + .setClassWorld( cliRequest.classWorld ) + .setName( "maven" ); - try - { - if ( commandLine.hasOption( CLIManager.ENCRYPT_MASTER_PASSWORD ) ) - { - String passwd = commandLine.getOptionValue( CLIManager.ENCRYPT_MASTER_PASSWORD ); + DefaultPlexusContainer container = new DefaultPlexusContainer( cc ); - DefaultPlexusCipher cipher = new DefaultPlexusCipher(); + container.setLoggerManager( new MavenLoggerManager( new PrintStreamLogger( System.out ) ) ); - stdout.println( cipher.encryptAndDecorate( passwd, DefaultSecDispatcher.SYSTEM_PROPERTY_SEC_LOCATION ) ); - - return 0; - } - else if ( commandLine.hasOption( CLIManager.ENCRYPT_PASSWORD ) ) - { - String passwd = commandLine.getOptionValue( CLIManager.ENCRYPT_PASSWORD ); - - DefaultSecDispatcher dispatcher; - dispatcher = (DefaultSecDispatcher) container.lookup( SecDispatcher.class ); - String configurationFile = dispatcher.getConfigurationFile(); - if ( configurationFile.startsWith( "~" ) ) - { - configurationFile = System.getProperty( "user.home" ) + configurationFile.substring( 1 ); - } - String file = System.getProperty( DefaultSecDispatcher.SYSTEM_PROPERTY_SEC_LOCATION, configurationFile ); - container.release( dispatcher ); - - String master = null; - - SettingsSecurity sec = SecUtil.read( file, true ); - if ( sec != null ) - { - master = sec.getMaster(); - } - - if ( master == null ) - { - stderr.println( "Master password is not set in the setting security file" ); - - return 1; - } - - DefaultPlexusCipher cipher = new DefaultPlexusCipher(); - String masterPasswd = cipher.decryptDecorated( master, DefaultSecDispatcher.SYSTEM_PROPERTY_SEC_LOCATION ); - stdout.println( cipher.encryptAndDecorate( passwd, masterPasswd ) ); - - return 0; - } - } - catch ( Exception e ) - { - stderr.println( "FATAL ERROR: " + "Error encrypting password: " + e.getMessage() ); - - return 1; - } + container.getLoggerManager().setThresholds( cliRequest.request.getLoggingLevel() ); - MavenExecutionResult result = new DefaultMavenExecutionResult(); + customizeContainer( container ); - try - { - MavenExecutionRequestPopulator populator = container.lookup( MavenExecutionRequestPopulator.class ); - - request = populator.populateDefaults( request ); - } - catch ( MavenExecutionRequestPopulationException e ) - { - result.addException( e ); - } - catch ( ComponentLookupException e ) - { - result.addException( e ); - } + maven = container.lookup( Maven.class ); - result = maven.execute( request ); + modelProcessor = createModelProcessor( container ); - // The exception handling should be handled in Maven itself. + settingsBuilder = container.lookup( SettingsBuilder.class ); - try + dispatcher = (DefaultSecDispatcher) container.lookup( SecDispatcher.class ); + } + + protected void customizeContainer( PlexusContainer container ) + { + } + + // + // This should probably be a separate tool and not be baked into Maven. + // + private void encryption( CliRequest cliRequest ) + throws Exception + { + if ( cliRequest.commandLine.hasOption( CLIManager.ENCRYPT_MASTER_PASSWORD ) ) { - return processResult( request, result, showErrors ); + String passwd = cliRequest.commandLine.getOptionValue( CLIManager.ENCRYPT_MASTER_PASSWORD ); + + DefaultPlexusCipher cipher = new DefaultPlexusCipher(); + + cliRequest.stdout.println( cipher.encryptAndDecorate( passwd, DefaultSecDispatcher.SYSTEM_PROPERTY_SEC_LOCATION ) ); } - finally + else if ( cliRequest.commandLine.hasOption( CLIManager.ENCRYPT_PASSWORD ) ) { - if ( fileStream != null ) + String passwd = cliRequest.commandLine.getOptionValue( CLIManager.ENCRYPT_PASSWORD ); + + String configurationFile = dispatcher.getConfigurationFile(); + + if ( configurationFile.startsWith( "~" ) ) { - fileStream.close(); + configurationFile = System.getProperty( "user.home" ) + configurationFile.substring( 1 ); } + + String file = System.getProperty( DefaultSecDispatcher.SYSTEM_PROPERTY_SEC_LOCATION, configurationFile ); + + String master = null; + + SettingsSecurity sec = SecUtil.read( file, true ); + if ( sec != null ) + { + master = sec.getMaster(); + } + + if ( master == null ) + { + cliRequest.stderr.println( "Master password is not set in the setting security file." ); + } + + DefaultPlexusCipher cipher = new DefaultPlexusCipher(); + String masterPasswd = cipher.decryptDecorated( master, DefaultSecDispatcher.SYSTEM_PROPERTY_SEC_LOCATION ); + cliRequest.stdout.println( cipher.encryptAndDecorate( passwd, masterPasswd ) ); } } - - private int processResult( MavenExecutionRequest request, MavenExecutionResult result, boolean showErrors ) + + private int execute( CliRequest cliRequest ) { + MavenExecutionResult result = maven.execute( cliRequest.request ); + if ( result.hasExceptions() ) { ExceptionHandler handler = new DefaultExceptionHandler(); @@ -479,12 +356,12 @@ public class MavenCli { ExceptionSummary summary = handler.handleException( exception ); - logSummary( summary, references, "", showErrors ); + logSummary( summary, references, "", cliRequest.showErrors ); } logger.error( "" ); - if ( !showErrors ) + if ( !cliRequest.showErrors ) { logger.error( "To see the full stack trace of the errors, re-run Maven with the -e switch." ); } @@ -496,8 +373,7 @@ public class MavenCli if ( !references.isEmpty() ) { logger.error( "" ); - logger.error( "For more information about the errors and possible solutions" - + ", please read the following articles:" ); + logger.error( "For more information about the errors and possible solutions" + ", please read the following articles:" ); for ( Map.Entry entry : references.entrySet() ) { @@ -505,7 +381,7 @@ public class MavenCli } } - if ( MavenExecutionRequest.REACTOR_FAIL_NEVER.equals( request.getReactorFailureBehavior() ) ) + if ( MavenExecutionRequest.REACTOR_FAIL_NEVER.equals( cliRequest.request.getReactorFailureBehavior() ) ) { logger.info( "Build failures were ignored." ); @@ -553,20 +429,21 @@ public class MavenCli } } - protected ModelProcessor createModelProcessor( PlexusContainer container ) + protected ModelProcessor createModelProcessor( PlexusContainer container ) throws ComponentLookupException { - return container.lookup( ModelProcessor.class ); + return container.lookup( ModelProcessor.class ); } - private Configuration buildEmbedderConfiguration( CommandLine commandLine, String workingDirectory ) + private void settings( CliRequest cliRequest ) + throws Exception { File userSettingsFile; - if ( commandLine.hasOption( CLIManager.ALTERNATE_USER_SETTINGS ) ) + if ( cliRequest.commandLine.hasOption( CLIManager.ALTERNATE_USER_SETTINGS ) ) { - userSettingsFile = new File( commandLine.getOptionValue( CLIManager.ALTERNATE_USER_SETTINGS ) ); - userSettingsFile = resolveFile( userSettingsFile, workingDirectory ); + userSettingsFile = new File( cliRequest.commandLine.getOptionValue( CLIManager.ALTERNATE_USER_SETTINGS ) ); + userSettingsFile = resolveFile( userSettingsFile, cliRequest.workingDirectory ); } else { @@ -575,21 +452,41 @@ public class MavenCli File globalSettingsFile; - if ( commandLine.hasOption( CLIManager.ALTERNATE_GLOBAL_SETTINGS ) ) + if ( cliRequest.commandLine.hasOption( CLIManager.ALTERNATE_GLOBAL_SETTINGS ) ) { - globalSettingsFile = new File( commandLine.getOptionValue( CLIManager.ALTERNATE_GLOBAL_SETTINGS ) ); - globalSettingsFile = resolveFile( globalSettingsFile, workingDirectory ); + globalSettingsFile = new File( cliRequest.commandLine.getOptionValue( CLIManager.ALTERNATE_GLOBAL_SETTINGS ) ); + globalSettingsFile = resolveFile( globalSettingsFile, cliRequest.workingDirectory ); } else { globalSettingsFile = DEFAULT_GLOBAL_SETTINGS_FILE; } - Configuration configuration = new DefaultConfiguration() - .setUserSettingsFile( userSettingsFile ) - .setGlobalSettingsFile( globalSettingsFile ); + cliRequest.request.setGlobalSettingsFile( globalSettingsFile ); + cliRequest.request.setUserSettingsFile( userSettingsFile ); - return configuration; + populateProperties( cliRequest.request, cliRequest.commandLine ); + + SettingsBuildingRequest settingsRequest = new DefaultSettingsBuildingRequest(); + settingsRequest.setGlobalSettingsFile( globalSettingsFile ); + settingsRequest.setUserSettingsFile( userSettingsFile ); + settingsRequest.setSystemProperties( cliRequest.request.getSystemProperties() ); + settingsRequest.setUserProperties( cliRequest.request.getUserProperties() ); + + SettingsBuildingResult settingsResult = settingsBuilder.build( settingsRequest ); + + if ( !settingsResult.getProblems().isEmpty() && logger.isWarnEnabled() ) + { + logger.warn( "" ); + logger.warn( "Some problems were encountered while building the effective settings" ); + + for ( SettingsProblem problem : settingsResult.getProblems() ) + { + logger.warn( problem.getMessage() + " @ " + problem.getLocation() ); + } + + logger.warn( "" ); + } } private void populateProperties( MavenExecutionRequest request, CommandLine commandLine ) @@ -600,11 +497,16 @@ public class MavenCli request.setUserProperties( userProperties ); request.setSystemProperties( systemProperties ); } - - private MavenExecutionRequest populateRequest( MavenExecutionRequest request, CommandLine commandLine, - String workingDirectory, boolean debug, boolean quiet, - boolean showErrors, PrintStream stdout ) + + private MavenExecutionRequest populateRequest( CliRequest cliRequest ) { + MavenExecutionRequest request = cliRequest.request; + CommandLine commandLine = cliRequest.commandLine; + String workingDirectory = cliRequest.workingDirectory; + boolean debug = cliRequest.debug; + boolean quiet = cliRequest.quiet; + boolean showErrors = cliRequest.showErrors; + // ---------------------------------------------------------------------- // Now that we have everything that we need we will fire up plexus and // bring the maven component to life for use. @@ -617,8 +519,7 @@ public class MavenCli boolean pluginUpdateOverride = false; - if ( commandLine.hasOption( CLIManager.FORCE_PLUGIN_UPDATES ) - || commandLine.hasOption( CLIManager.FORCE_PLUGIN_UPDATES2 ) ) + if ( commandLine.hasOption( CLIManager.FORCE_PLUGIN_UPDATES ) || commandLine.hasOption( CLIManager.FORCE_PLUGIN_UPDATES2 ) ) { pluginUpdateOverride = true; } @@ -637,7 +538,7 @@ public class MavenCli // // ---------------------------------------------------------------------- - @SuppressWarnings( "unchecked" ) + @SuppressWarnings("unchecked") List goals = commandLine.getArgList(); boolean recursive = true; @@ -698,12 +599,12 @@ public class MavenCli if ( commandLine.hasOption( CLIManager.ACTIVATE_PROFILES ) ) { - String [] profileOptionValues = commandLine.getOptionValues( CLIManager.ACTIVATE_PROFILES ); + String[] profileOptionValues = commandLine.getOptionValues( CLIManager.ACTIVATE_PROFILES ); if ( profileOptionValues != null ) { for ( int i = 0; i < profileOptionValues.length; ++i ) { - StringTokenizer profileTokens = new StringTokenizer( profileOptionValues[i] , "," ); + StringTokenizer profileTokens = new StringTokenizer( profileOptionValues[i], "," ); while ( profileTokens.hasMoreTokens() ) { @@ -730,11 +631,11 @@ public class MavenCli if ( request.isInteractiveMode() ) { - transferListener = new ConsoleMavenTransferListener( stdout ); + transferListener = new ConsoleMavenTransferListener( cliRequest.stdout ); } else { - transferListener = new BatchModeMavenTransferListener( stdout ); + transferListener = new BatchModeMavenTransferListener( cliRequest.stdout ); } transferListener.setShowChecksumEvents( false ); @@ -778,16 +679,10 @@ public class MavenCli userToolchainsFile = MavenCli.DEFAULT_USER_TOOLCHAINS_FILE; } - request - .setBaseDirectory( baseDirectory ) - .setGoals( goals ) - .setSystemProperties( systemProperties ) - .setUserProperties( userProperties ) - .setReactorFailureBehavior( reactorFailureBehaviour ) // default: fail fast + request.setBaseDirectory( baseDirectory ).setGoals( goals ).setSystemProperties( systemProperties ).setUserProperties( userProperties ).setReactorFailureBehavior( reactorFailureBehaviour ) // default: fail fast .setRecursive( recursive ) // default: true .setShowErrors( showErrors ) // default: false - .setUsePluginUpdateOverride( pluginUpdateOverride ) - .addActiveProfiles( activeProfiles ) // optional + .setUsePluginUpdateOverride( pluginUpdateOverride ).addActiveProfiles( activeProfiles ) // optional .addInactiveProfiles( inactiveProfiles ) // optional .setLoggingLevel( loggingLevel ) // default: info .setTransferListener( transferListener ) // default: batch mode which goes along with interactive @@ -819,8 +714,8 @@ public class MavenCli else if ( request.getBaseDirectory() == null ) { request.setBaseDirectory( new File( System.getProperty( "user.dir" ) ) ); - } - + } + if ( commandLine.hasOption( CLIManager.RESUME_FROM ) ) { request.setResumeFrom( commandLine.getOptionValue( CLIManager.RESUME_FROM ) ); @@ -837,13 +732,11 @@ public class MavenCli { request.setMakeBehavior( MavenExecutionRequest.REACTOR_MAKE_UPSTREAM ); } - else if ( !commandLine.hasOption( CLIManager.ALSO_MAKE ) - && commandLine.hasOption( CLIManager.ALSO_MAKE_DEPENDENTS ) ) + else if ( !commandLine.hasOption( CLIManager.ALSO_MAKE ) && commandLine.hasOption( CLIManager.ALSO_MAKE_DEPENDENTS ) ) { request.setMakeBehavior( MavenExecutionRequest.REACTOR_MAKE_DOWNSTREAM ); } - else if ( commandLine.hasOption( CLIManager.ALSO_MAKE ) - && commandLine.hasOption( CLIManager.ALSO_MAKE_DEPENDENTS ) ) + else if ( commandLine.hasOption( CLIManager.ALSO_MAKE ) && commandLine.hasOption( CLIManager.ALSO_MAKE_DEPENDENTS ) ) { request.setMakeBehavior( MavenExecutionRequest.REACTOR_MAKE_BOTH ); } @@ -956,5 +849,28 @@ public class MavenCli // ---------------------------------------------------------------------- System.setProperty( name, value ); + } + + static class CliRequest + { + String[] args; + CommandLine commandLine; + PrintStream stdout; + PrintStream stderr; + ClassWorld classWorld; + String workingDirectory; + boolean debug; + boolean quiet; + boolean showErrors; + PrintStream fileStream; + MavenExecutionRequest request; + Exit exit; + + CliRequest( String[] args, ClassWorld classWorld ) + { + this.args = args; + this.classWorld = classWorld; + this.request = new DefaultMavenExecutionRequest(); + } } }